utils.py 207 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891
  1. # Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import copy
  16. import functools
  17. import inspect
  18. import os
  19. import warnings
  20. from collections.abc import Callable
  21. from contextlib import contextmanager
  22. from dataclasses import dataclass
  23. from typing import TYPE_CHECKING, Any, Optional, cast
  24. import torch
  25. import torch.distributed as dist
  26. from torch import nn
  27. from ..cache_utils import (
  28. Cache,
  29. DynamicCache,
  30. EncoderDecoderCache,
  31. QuantizedCache,
  32. StaticCache,
  33. )
  34. from ..dynamic_module_utils import (
  35. check_python_requirements,
  36. get_cached_module_file,
  37. get_class_in_module,
  38. resolve_trust_remote_code,
  39. )
  40. from ..integrations.deepspeed import is_deepspeed_zero3_enabled
  41. from ..integrations.fsdp import is_fsdp_managed_module
  42. from ..masking_utils import create_masks_for_generate
  43. from ..tokenization_python import ExtensionsTrie
  44. from ..utils import (
  45. ModelOutput,
  46. TransformersKwargs,
  47. is_accelerate_available,
  48. logging,
  49. )
  50. from ..utils.generic import is_flash_attention_requested
  51. from .candidate_generator import (
  52. AssistantVocabTranslatorCache,
  53. AssistedCandidateGenerator,
  54. AssistedCandidateGeneratorDifferentTokenizers,
  55. CandidateGenerator,
  56. EarlyExitCandidateGenerator,
  57. PromptLookupCandidateGenerator,
  58. UniversalSpeculativeDecodingGenerator,
  59. _prepare_attention_mask,
  60. _prepare_position_ids,
  61. _prepare_token_type_ids,
  62. )
  63. from .configuration_utils import (
  64. ALL_STATIC_CACHE_IMPLEMENTATIONS,
  65. DEPRECATED_STATIC_CACHE_IMPLEMENTATIONS,
  66. STATIC_CACHE_IMPLEMENTATIONS,
  67. GenerationConfig,
  68. GenerationMode,
  69. )
  70. from .continuous_batching import ContinuousMixin
  71. from .logits_process import (
  72. EncoderNoRepeatNGramLogitsProcessor,
  73. EncoderRepetitionPenaltyLogitsProcessor,
  74. EpsilonLogitsWarper,
  75. EtaLogitsWarper,
  76. ExponentialDecayLengthPenalty,
  77. ForcedBOSTokenLogitsProcessor,
  78. ForcedEOSTokenLogitsProcessor,
  79. InfNanRemoveLogitsProcessor,
  80. LogitNormalization,
  81. LogitsProcessorList,
  82. MinLengthLogitsProcessor,
  83. MinNewTokensLengthLogitsProcessor,
  84. MinPLogitsWarper,
  85. NoBadWordsLogitsProcessor,
  86. NoRepeatNGramLogitsProcessor,
  87. PrefixConstrainedLogitsProcessor,
  88. RepetitionPenaltyLogitsProcessor,
  89. SequenceBiasLogitsProcessor,
  90. SuppressTokensAtBeginLogitsProcessor,
  91. SuppressTokensLogitsProcessor,
  92. TemperatureLogitsWarper,
  93. TopHLogitsWarper,
  94. TopKLogitsWarper,
  95. TopPLogitsWarper,
  96. TypicalLogitsWarper,
  97. UnbatchedClassifierFreeGuidanceLogitsProcessor,
  98. )
  99. from .stopping_criteria import (
  100. ConfidenceCriteria,
  101. EosTokenCriteria,
  102. MaxLengthCriteria,
  103. MaxTimeCriteria,
  104. StoppingCriteria,
  105. StoppingCriteriaList,
  106. StopStringCriteria,
  107. )
  108. if TYPE_CHECKING:
  109. from .._typing import GenerativePreTrainedModel
  110. from ..modeling_utils import PreTrainedModel
  111. from ..tokenization_utils_base import PreTrainedTokenizerBase
  112. from .streamers import BaseStreamer
  113. logger = logging.get_logger(__name__)
  114. if is_accelerate_available():
  115. from accelerate.hooks import AlignDevicesHook, add_hook_to_module
  116. # Variable names used to hold the cache at generation time
  117. ALL_CACHE_NAMES = [
  118. "past_key_values", # default
  119. "cache_params", # mamba-based models
  120. "state", # rwkv
  121. "mems", # xlnet
  122. "past_buckets_states", # reformer
  123. ]
  124. GENERATION_MODES_MAPPING = {
  125. GenerationMode.SAMPLE: "_sample",
  126. GenerationMode.GREEDY_SEARCH: "_sample",
  127. GenerationMode.BEAM_SEARCH: "_beam_search",
  128. GenerationMode.BEAM_SAMPLE: "_beam_search",
  129. GenerationMode.ASSISTED_GENERATION: "_assisted_decoding",
  130. # Deprecated methods
  131. GenerationMode.DOLA_GENERATION: "transformers-community/dola",
  132. GenerationMode.CONTRASTIVE_SEARCH: "transformers-community/contrastive-search",
  133. GenerationMode.GROUP_BEAM_SEARCH: "transformers-community/group-beam-search",
  134. GenerationMode.CONSTRAINED_BEAM_SEARCH: "transformers-community/constrained-beam-search",
  135. }
  136. @dataclass
  137. class GenerateDecoderOnlyOutput(ModelOutput):
  138. """
  139. Outputs of decoder-only generation models, when using non-beam methods.
  140. Args:
  141. sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  142. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  143. if all batches finished early due to the `eos_token_id`.
  144. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  145. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  146. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  147. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  148. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  149. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  150. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  151. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  152. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  153. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  154. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  155. hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  156. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  157. `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
  158. past_key_values (`Cache`, *optional*, returned when `use_cache=True`):
  159. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  160. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  161. """
  162. sequences: torch.LongTensor
  163. scores: tuple[torch.FloatTensor] | None = None
  164. logits: tuple[torch.FloatTensor] | None = None
  165. attentions: tuple[tuple[torch.FloatTensor]] | None = None
  166. hidden_states: tuple[tuple[torch.FloatTensor]] | None = None
  167. past_key_values: Cache | None = None
  168. @dataclass
  169. class GenerateEncoderDecoderOutput(ModelOutput):
  170. """
  171. Outputs of encoder-decoder generation models, when using non-beam methods.
  172. Args:
  173. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  174. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  175. if all batches finished early due to the `eos_token_id`.
  176. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  177. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  178. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  179. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  180. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  181. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  182. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  183. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  184. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
  185. Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
  186. sequence_length, sequence_length)`.
  187. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
  188. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  189. shape `(batch_size, sequence_length, hidden_size)`.
  190. decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  191. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  192. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  193. cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  194. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  195. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  196. decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  197. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  198. `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
  199. past_key_values (`Cache`, *optional*, returned when `use_cache=True`):
  200. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  201. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  202. """
  203. sequences: torch.LongTensor
  204. scores: tuple[torch.FloatTensor] | None = None
  205. logits: tuple[torch.FloatTensor] | None = None
  206. encoder_attentions: tuple[torch.FloatTensor] | None = None
  207. encoder_hidden_states: tuple[torch.FloatTensor] | None = None
  208. decoder_attentions: tuple[tuple[torch.FloatTensor]] | None = None
  209. cross_attentions: tuple[tuple[torch.FloatTensor]] | None = None
  210. decoder_hidden_states: tuple[tuple[torch.FloatTensor]] | None = None
  211. past_key_values: Cache | None = None
  212. @dataclass
  213. class GenerateBeamDecoderOnlyOutput(ModelOutput):
  214. """
  215. Outputs of decoder-only generation models, when using beam methods.
  216. Args:
  217. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  218. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  219. if all batches finished early due to the `eos_token_id`.
  220. sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
  221. Final beam scores of the generated `sequences`.
  222. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  223. Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  224. of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
  225. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
  226. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  227. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  228. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  229. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  230. each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  231. beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
  232. Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
  233. `(batch_size*num_return_sequences, sequence_length)`.
  234. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  235. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  236. `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
  237. hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  238. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  239. `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
  240. past_key_values (`Cache`, *optional*, returned when `use_cache=True`):
  241. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  242. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  243. """
  244. sequences: torch.LongTensor
  245. sequences_scores: torch.FloatTensor | None = None
  246. scores: tuple[torch.FloatTensor] | None = None
  247. logits: tuple[torch.FloatTensor] | None = None
  248. beam_indices: torch.LongTensor | None = None
  249. attentions: tuple[tuple[torch.FloatTensor]] | None = None
  250. hidden_states: tuple[tuple[torch.FloatTensor]] | None = None
  251. past_key_values: Cache | None = None
  252. @dataclass
  253. class GenerateBeamEncoderDecoderOutput(ModelOutput):
  254. """
  255. Outputs of encoder-decoder generation models, when using beam methods.
  256. Args:
  257. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  258. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  259. if all batches finished early due to the `eos_token_id`.
  260. sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
  261. Final beam scores of the generated `sequences`.
  262. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  263. Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  264. of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
  265. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
  266. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  267. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  268. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  269. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  270. each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  271. beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
  272. Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
  273. `(batch_size*num_return_sequences, sequence_length)`.
  274. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
  275. Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
  276. sequence_length, sequence_length)`.
  277. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
  278. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  279. shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
  280. decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  281. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  282. `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
  283. sequence_length)`.
  284. cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  285. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  286. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  287. decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  288. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  289. `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
  290. past_key_values (`Cache`, *optional*, returned when `use_cache=True`):
  291. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  292. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  293. """
  294. sequences: torch.LongTensor
  295. sequences_scores: torch.FloatTensor | None = None
  296. scores: tuple[torch.FloatTensor] | None = None
  297. logits: tuple[torch.FloatTensor] | None = None
  298. beam_indices: torch.LongTensor | None = None
  299. encoder_attentions: tuple[torch.FloatTensor] | None = None
  300. encoder_hidden_states: tuple[torch.FloatTensor] | None = None
  301. decoder_attentions: tuple[tuple[torch.FloatTensor]] | None = None
  302. cross_attentions: tuple[tuple[torch.FloatTensor]] | None = None
  303. decoder_hidden_states: tuple[tuple[torch.FloatTensor]] | None = None
  304. past_key_values: Cache | None = None
  305. # Typing shortcuts
  306. GenerateNonBeamOutput = GenerateDecoderOnlyOutput | GenerateEncoderDecoderOutput
  307. GenerateBeamOutput = GenerateBeamDecoderOnlyOutput | GenerateBeamEncoderDecoderOutput
  308. GenerateOutput = GenerateNonBeamOutput | GenerateBeamOutput
  309. class GenerationMixin(ContinuousMixin):
  310. """
  311. A class containing all functions for auto-regressive text generation, to be used as a mixin in model classes.
  312. Inheriting from this class causes the model to have special generation-related behavior, such as loading a
  313. `GenerationConfig` at initialization time or ensuring `generate`-related tests are run in `transformers` CI.
  314. A model class should inherit from `GenerationMixin` to enable calling methods like `generate`, or when it
  315. has defined a custom `generate` method that relies on `GenerationMixin`, directly or indirectly, which
  316. approximately shares the same interface to public methods like `generate`. Three examples:
  317. - `LlamaForCausalLM` should inherit from `GenerationMixin` to enable calling `generate` and other public
  318. methods in the mixin;
  319. - `BlipForQuestionAnswering` has a custom `generate` method that approximately shares the same interface as
  320. `GenerationMixin.generate` (it has a few extra arguments, and the same output). That function also calls
  321. `GenerationMixin.generate` indirectly, through an inner model. As such, `BlipForQuestionAnswering` should
  322. inherit from `GenerationMixin` to benefit from all generation-related automation in our codebase;
  323. - `BarkModel` has a custom `generate` method and one of its inner models calls `GenerationMixin.generate`.
  324. However, its `generate` does not share the same interface as `GenerationMixin.generate`. In this case,
  325. `BarkModel` should NOT inherit from `GenerationMixin`, as it breaks the `generate` interface.
  326. The class exposes [`~generation.GenerationMixin.generate`], which can be used for:
  327. - *greedy decoding* if `num_beams=1` and `do_sample=False`
  328. - *multinomial sampling* if `num_beams=1` and `do_sample=True`
  329. - *beam-search decoding* if `num_beams>1` and `do_sample=False`
  330. - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
  331. - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
  332. To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
  333. """
  334. # Should be overwritten by models that can generate non-text output
  335. output_modalities = ("text",)
  336. def adjust_generation_fn(
  337. self: "GenerativePreTrainedModel",
  338. generation_config,
  339. from_auto_class,
  340. from_pipeline,
  341. pretrained_model_name_or_path,
  342. cache_dir,
  343. force_download,
  344. proxies,
  345. local_files_only,
  346. token,
  347. revision,
  348. subfolder,
  349. trust_remote_code,
  350. **kwargs,
  351. ):
  352. if self.can_generate() and generation_config is not None:
  353. self.generation_config = self.generation_config.from_dict(generation_config.to_dict())
  354. elif self.can_generate() and pretrained_model_name_or_path is not None:
  355. repo_loading_kwargs = {
  356. "cache_dir": cache_dir,
  357. "force_download": force_download,
  358. "proxies": proxies,
  359. "local_files_only": local_files_only,
  360. "token": token,
  361. "revision": revision,
  362. "subfolder": subfolder,
  363. **kwargs,
  364. }
  365. # Load generation config
  366. try:
  367. self.generation_config = GenerationConfig.from_pretrained(
  368. pretrained_model_name_or_path,
  369. _from_auto=from_auto_class,
  370. _from_pipeline=from_pipeline,
  371. **repo_loading_kwargs,
  372. )
  373. except OSError:
  374. # `self` already has a generation config created from model config, but model config will
  375. # not contain any generation-specific params. These are popped at config's `__init__`.
  376. # Thus we have to load from `config.json` and create a generation config from it (for BART)
  377. logger.info(
  378. "Generation config file not found, using a generation config created from the model config."
  379. )
  380. self.generation_config = GenerationConfig.from_pretrained(
  381. pretrained_model_name_or_path,
  382. config_file_name="config.json",
  383. _from_auto=from_auto_class,
  384. _from_pipeline=from_pipeline,
  385. _from_model_config=True,
  386. **repo_loading_kwargs,
  387. )
  388. # Load custom generate function if `pretrained_model_name_or_path` defines it (and override `generate`)
  389. if hasattr(self, "load_custom_generate") and trust_remote_code:
  390. try:
  391. custom_generate = self.load_custom_generate(
  392. pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **repo_loading_kwargs
  393. )
  394. self.generate = functools.partial(custom_generate, model=self)
  395. except OSError: # there is no custom generate function
  396. pass
  397. def load_custom_generate(
  398. self,
  399. pretrained_model_name_or_path: str | os.PathLike | None = None,
  400. trust_remote_code: bool | None = None,
  401. **kwargs,
  402. ) -> Callable:
  403. """
  404. Loads and returns a custom generate function, given a model repo.
  405. Args:
  406. pretrained_model_name_or_path (`str` or `os.PathLike`):
  407. Can be either:
  408. - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
  409. - A path to a *directory* containing model weights saved using
  410. [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
  411. trust_remote_code (`bool`, *optional*):
  412. Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
  413. should only be set to `True` for repositories you trust and in which you have read the code, as it will
  414. execute code present on the Hub on your local machine.
  415. **kwargs:
  416. Additional keyword arguments for remote code loading.
  417. Raises:
  418. OSError: If `pretrained_model_name_or_path` does not contain a `custom_generate` subdirectory.
  419. Returns:
  420. A callable that can be used to generate text.
  421. """
  422. # Fetches the generate.py file from the model repo. If it doesn't exist, a file in `.no_exist` cache directory
  423. # is created (preventing future hub requests), and an OSError is raised.
  424. try:
  425. module = get_cached_module_file(
  426. pretrained_model_name_or_path, module_file="custom_generate/generate.py", **kwargs
  427. )
  428. except OSError:
  429. raise OSError(
  430. f"`{pretrained_model_name_or_path}` does not contain a `custom_generate` subdirectory with a "
  431. "`generate.py` file, can't load the custom generate function."
  432. )
  433. # Handle opt-in `trust_remote_code` and related exceptions
  434. is_local_code = os.path.exists(pretrained_model_name_or_path)
  435. error_message = (
  436. f"The repository `{pretrained_model_name_or_path}` contains custom generation code that will override "
  437. "the default `generate` method."
  438. )
  439. resolve_trust_remote_code(
  440. trust_remote_code,
  441. pretrained_model_name_or_path,
  442. has_local_code=is_local_code,
  443. has_remote_code=not is_local_code,
  444. error_message=error_message,
  445. )
  446. # Load the custom generate function
  447. check_python_requirements(
  448. pretrained_model_name_or_path, requirements_file="custom_generate/requirements.txt", **kwargs
  449. )
  450. custom_generate_function = get_class_in_module("generate", module)
  451. return custom_generate_function
  452. def prepare_inputs_for_generation(
  453. self: "GenerativePreTrainedModel",
  454. input_ids: torch.LongTensor,
  455. next_sequence_length: int | None = None,
  456. past_key_values: Cache | None = None,
  457. attention_mask: torch.LongTensor | None = None,
  458. inputs_embeds: torch.FloatTensor | None = None,
  459. is_first_iteration: bool | None = False,
  460. **kwargs,
  461. ):
  462. """
  463. Prepare the model inputs for generation. Notable steps include selecting the correct input key and cloning when appropriate,
  464. creating position_ids from the attention_mask when missing, slicing inputs and converting 2D attention masks to 4D for
  465. compilable caches, and finally forwarding all additional keyword arguments unchanged to the model's forward pass.
  466. See the forward pass in the model documentation for expected arguments (different models might have different
  467. requirements for e.g. `past_key_values`). This function should work as is for most LLMs.
  468. """
  469. # Instantiate output
  470. model_inputs = {}
  471. # 1. Prepare base model inputs
  472. input_ids_key = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  473. # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.
  474. if not self.config.is_encoder_decoder and inputs_embeds is not None and is_first_iteration:
  475. model_inputs[input_ids_key] = None
  476. prompt_embeds = (
  477. inputs_embeds[:, -next_sequence_length:, :] if next_sequence_length is not None else inputs_embeds
  478. )
  479. model_inputs["inputs_embeds"] = prompt_embeds.clone(memory_format=torch.contiguous_format)
  480. batch_size, sequence_length = prompt_embeds.shape[:2]
  481. else:
  482. # `clone` calls in this function ensure a consistent stride. See #32227
  483. input_ids = input_ids[:, -next_sequence_length:] if next_sequence_length is not None else input_ids
  484. model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
  485. batch_size, sequence_length = input_ids.shape[:2] # we slice here as some models may have them 3D
  486. # 2. Add important inputs
  487. if past_key_values is not None:
  488. model_inputs["past_key_values"] = past_key_values
  489. position_ids_key = "decoder_position_ids" if self.config.is_encoder_decoder else "position_ids"
  490. if (position_ids := kwargs.pop(position_ids_key, None)) is not None:
  491. model_inputs[position_ids_key] = position_ids
  492. if (token_type_ids := kwargs.pop("token_type_ids", None)) is not None:
  493. model_inputs["token_type_ids"] = token_type_ids
  494. # 3. Slice model inputs if it's an input that should have the same length as `input_ids`
  495. for model_input_name in [position_ids_key, "token_type_ids", "mm_token_type_ids"]:
  496. model_input = model_inputs.get(model_input_name)
  497. if model_input is not None and model_input.shape[-1] != sequence_length:
  498. # Input can be 2D or 3D, and we always slice on `seq-length` (last dim)
  499. model_input = model_input[..., -sequence_length:].clone(memory_format=torch.contiguous_format)
  500. model_inputs[model_input_name] = model_input
  501. # 4. Create 4D attention mask is we are using a compilable cache (important for performant compiled forward
  502. # pass)
  503. encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None
  504. attention_mask_key = "decoder_attention_mask" if self.config.is_encoder_decoder else "attention_mask"
  505. attention_mask = (
  506. kwargs.pop("decoder_attention_mask", None) if self.config.is_encoder_decoder else attention_mask
  507. )
  508. if (
  509. isinstance(past_key_values, Cache)
  510. and past_key_values.is_compileable
  511. and attention_mask is not None
  512. and attention_mask.ndim == 2
  513. ):
  514. # Some models may overwrite the general one
  515. causal_mask_creation_function = getattr(self, "create_masks_for_generate", create_masks_for_generate)
  516. attention_mask = causal_mask_creation_function(
  517. config=self.config,
  518. # we only need batch size, seq_length, dtype and device here - so we pass a 0-sized tensor with only the metadata
  519. inputs_embeds=torch.empty((batch_size, sequence_length, 0), dtype=self.dtype, device=input_ids.device),
  520. attention_mask=attention_mask,
  521. past_key_values=model_inputs.get("past_key_values"),
  522. position_ids=model_inputs.get(position_ids_key),
  523. # The following kwargs are not used in the main function - only on a few models with overloaded `create_masks_for_generate`
  524. token_type_ids=model_inputs.get("token_type_ids"),
  525. mm_token_type_ids=model_inputs.get("mm_token_type_ids"),
  526. is_first_iteration=is_first_iteration,
  527. )
  528. if attention_mask is not None:
  529. model_inputs[attention_mask_key] = attention_mask
  530. if encoder_attention_mask is not None:
  531. model_inputs["attention_mask"] = encoder_attention_mask
  532. # 5. Forward ALL kwargs that are uninitialized, e.g. `use_cache` (except a few exceptions)
  533. kwargs_to_avoid_forwarding = ("labels", "next_sequence_length")
  534. for key, value in kwargs.items():
  535. if key not in model_inputs and key not in kwargs_to_avoid_forwarding:
  536. model_inputs[key] = value
  537. # BC for remote code models only: create `cache_position` on the fly here, as we don't want to maintain them in kwargs
  538. # between `forward`s
  539. if self.is_remote_code() and "cache_position" in set(inspect.signature(self.forward).parameters):
  540. logger.warning_once(
  541. "The remote code model you are currently using seems to expect `cache_position`. This arg has been "
  542. "removed from the Transformers library, and will stop being created in `generate` even for remote code models "
  543. "in a future release. Please open a PR on the remote code hub repo to remove any usage of `cache_position`."
  544. )
  545. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  546. cache_position = torch.arange(sequence_length, device=input_ids.device) + past_seen_tokens
  547. model_inputs["cache_position"] = cache_position
  548. return model_inputs
  549. def _prepare_model_inputs(
  550. self: "GenerativePreTrainedModel",
  551. inputs: torch.Tensor | None,
  552. bos_token_id: torch.Tensor | None,
  553. model_kwargs: dict[str, torch.Tensor],
  554. ) -> tuple[torch.Tensor, str | None, dict[str, torch.Tensor]]:
  555. """
  556. This function extracts the model-specific `inputs` for generation.
  557. """
  558. # 1. retrieve all kwargs that are non-None or non-model input related.
  559. # some encoder-decoder models have different names for model and encoder
  560. if (
  561. self.config.is_encoder_decoder
  562. and hasattr(self, "encoder")
  563. and self.encoder.main_input_name != self.main_input_name
  564. ):
  565. input_name = self.encoder.main_input_name
  566. else:
  567. input_name = self.main_input_name
  568. # 2. check whether model_input_name is passed as kwarg
  569. # if yes and `inputs` is None use kwarg inputs
  570. inputs_kwarg = model_kwargs.pop(input_name, None)
  571. if inputs_kwarg is not None and inputs is not None:
  572. raise ValueError(
  573. f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
  574. f"Make sure to either pass {inputs} or {input_name}=..."
  575. )
  576. elif inputs_kwarg is not None:
  577. inputs = inputs_kwarg
  578. # 3. In the presence of `inputs_embeds` for text models:
  579. # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
  580. # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
  581. # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
  582. # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
  583. # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
  584. if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
  585. if model_kwargs["inputs_embeds"] is None:
  586. model_kwargs.pop("inputs_embeds")
  587. elif not self.config.is_encoder_decoder:
  588. has_inputs_embeds_forwarding = "inputs_embeds" in set(
  589. inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
  590. )
  591. if not has_inputs_embeds_forwarding:
  592. raise ValueError(
  593. f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
  594. "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
  595. "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
  596. )
  597. # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
  598. # the attention mask) can rely on the actual model input.
  599. model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
  600. inputs, bos_token_id, model_kwargs=model_kwargs
  601. )
  602. inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
  603. else:
  604. if inputs is not None:
  605. raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
  606. inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
  607. # 4. if `inputs` is still None, try to create `input_ids` from BOS token
  608. inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
  609. return inputs, input_name, model_kwargs
  610. def _maybe_initialize_input_ids_for_generation(
  611. self: "GenerativePreTrainedModel",
  612. inputs: torch.Tensor | None,
  613. bos_token_id: torch.Tensor | None,
  614. model_kwargs: dict[str, torch.Tensor],
  615. ) -> torch.LongTensor:
  616. """Initializes input ids for generation, if necessary."""
  617. if inputs is not None:
  618. return inputs
  619. encoder_outputs = model_kwargs.get("encoder_outputs")
  620. last_hidden_state = getattr(encoder_outputs, "last_hidden_state", None)
  621. if self.config.is_encoder_decoder and last_hidden_state is not None:
  622. # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
  623. shape = last_hidden_state.size()[:-1]
  624. return torch.ones(shape, dtype=torch.long, device=self.device) * -100
  625. # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
  626. # soft-prompting or in multimodal implementations built on top of decoder-only language models.
  627. batch_size = 1
  628. for value in model_kwargs.values():
  629. if isinstance(value, torch.Tensor):
  630. batch_size = value.shape[0]
  631. break
  632. if "inputs_embeds" in model_kwargs:
  633. return torch.ones(
  634. (batch_size, 0),
  635. dtype=torch.long,
  636. # Use the device of the existing tensor to avoid any potential `meta` device isssue, which is likely
  637. # linked to the offloading behavior (keeping it on meta device). See PR #44848. Previously, it used
  638. # `self.device`.
  639. device=self.device if self.device.type != "meta" else model_kwargs["inputs_embeds"].device,
  640. )
  641. if bos_token_id is None:
  642. raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
  643. return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id
  644. def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
  645. """
  646. Tries to infer position ids given attention mask and past kv cache length. All instances when
  647. `position_ids=None` should call this method.
  648. """
  649. # `input_ids` may be present in the model kwargs, instead of being the main input (e.g. multimodal model)
  650. if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
  651. inputs_tensor = model_kwargs["input_ids"]
  652. seq_length = inputs_tensor.shape[1]
  653. if (attention_mask := model_kwargs.get("attention_mask")) is not None:
  654. position_ids = attention_mask.long().cumsum(-1) - 1
  655. # We need this as otherwise padding tokens appear as -1 in position
  656. position_ids = position_ids.masked_fill(attention_mask == 0, 0)
  657. else:
  658. past_length = 0
  659. if (cache := model_kwargs.get("past_key_values")) is not None:
  660. past_length = cache.get_seq_length()
  661. position_ids = torch.arange(seq_length + past_length, dtype=torch.long, device=inputs_tensor.device)
  662. position_ids = position_ids.unsqueeze(0)
  663. return position_ids
  664. def _prepare_attention_mask_for_generation(
  665. self,
  666. inputs_tensor: torch.Tensor,
  667. generation_config: GenerationConfig,
  668. model_kwargs: dict[str, Any],
  669. ) -> torch.LongTensor:
  670. pad_token_id = generation_config._pad_token_tensor
  671. eos_token_id = generation_config._eos_token_tensor
  672. # `input_ids` may be present in the model kwargs, instead of being the main input (e.g. multimodal model)
  673. if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
  674. inputs_tensor = model_kwargs["input_ids"]
  675. # No information for attention mask inference -> return default attention mask
  676. default_attention_mask = torch.ones(inputs_tensor.shape[:2], dtype=torch.long, device=inputs_tensor.device)
  677. if pad_token_id is None:
  678. return default_attention_mask
  679. is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
  680. if not is_input_ids:
  681. return default_attention_mask
  682. is_pad_token_in_inputs = (pad_token_id is not None) and (torch.isin(inputs_tensor, pad_token_id).any())
  683. is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or ~(
  684. torch.isin(eos_token_id, pad_token_id).any()
  685. )
  686. can_infer_attention_mask = is_pad_token_in_inputs * is_pad_token_not_equal_to_eos_token_id
  687. attention_mask_from_padding = inputs_tensor.ne(pad_token_id).long()
  688. attention_mask = (
  689. attention_mask_from_padding * can_infer_attention_mask + default_attention_mask * ~can_infer_attention_mask
  690. )
  691. return attention_mask
  692. def _prepare_encoder_decoder_kwargs_for_generation(
  693. self: "GenerativePreTrainedModel",
  694. inputs_tensor: torch.Tensor,
  695. model_kwargs,
  696. model_input_name: str | None,
  697. generation_config: GenerationConfig,
  698. ) -> dict[str, Any]:
  699. # 1. get encoder
  700. encoder = self.get_encoder()
  701. # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device
  702. # as the inputs.
  703. if hasattr(self, "hf_device_map"):
  704. if hasattr(encoder, "_hf_hook"):
  705. encoder._hf_hook.io_same_device = True
  706. else:
  707. add_hook_to_module(encoder, AlignDevicesHook(io_same_device=True))
  708. # 2. Prepare encoder args and encoder kwargs from model kwargs and generation config.
  709. irrelevant_prefix = ["decoder_", "cross_attn", "use_cache", "past_key_values", "cache_params"]
  710. encoder_kwargs = {
  711. argument: value
  712. for argument, value in model_kwargs.items()
  713. if not any(argument.startswith(p) for p in irrelevant_prefix)
  714. }
  715. encoder_signature = set(inspect.signature(encoder.forward).parameters)
  716. encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
  717. if not encoder_accepts_wildcard:
  718. encoder_kwargs = {
  719. argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
  720. }
  721. encoder_kwargs["output_attentions"] = generation_config.output_attentions
  722. encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states
  723. # 3. make sure that encoder returns `ModelOutput`
  724. model_input_name = model_input_name if model_input_name is not None else self.main_input_name
  725. encoder_kwargs["return_dict"] = True
  726. encoder_kwargs[model_input_name] = inputs_tensor
  727. model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs)
  728. return model_kwargs
  729. def _prepare_decoder_input_ids_for_generation(
  730. self: "GenerativePreTrainedModel",
  731. batch_size: int,
  732. model_input_name: str,
  733. model_kwargs: dict[str, torch.Tensor],
  734. decoder_start_token_id: torch.Tensor,
  735. device: torch.device | None = None,
  736. ) -> tuple[torch.LongTensor, dict[str, torch.Tensor]]:
  737. """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
  738. # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
  739. # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
  740. if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
  741. decoder_input_ids = model_kwargs.pop("decoder_input_ids")
  742. elif "input_ids" in model_kwargs and model_input_name != "input_ids":
  743. decoder_input_ids = model_kwargs.pop("input_ids")
  744. else:
  745. decoder_input_ids = None
  746. # 2. `decoder_start_token_id` must have shape (batch_size, 1)
  747. if device is None:
  748. device = self.device
  749. if decoder_start_token_id.ndim == 1:
  750. if decoder_start_token_id.shape[0] != batch_size:
  751. raise ValueError(
  752. f"`decoder_start_token_id` expected to have length {batch_size} but got {decoder_start_token_id.shape[0]}"
  753. )
  754. decoder_start_token_id = decoder_start_token_id.view(-1, 1)
  755. else:
  756. decoder_start_token_id = (
  757. torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id
  758. )
  759. # 3. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
  760. # no user input -> use decoder_start_token_id as decoder_input_ids
  761. if decoder_input_ids is None:
  762. decoder_input_ids = decoder_start_token_id
  763. # exception: Donut checkpoints have task-specific decoder starts and don't expect a BOS token. Note that the
  764. # original checkpoints can't be detected through `self.__class__.__name__.lower()`, needing custom logic.
  765. # See: https://github.com/huggingface/transformers/pull/31470
  766. elif "donut" in self.__class__.__name__.lower() or (
  767. self.config.model_type == "vision-encoder-decoder" and "donut" in self.config.encoder.model_type.lower()
  768. ):
  769. pass
  770. elif self.config.model_type == "whisper":
  771. pass
  772. # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
  773. # decoder_attention_mask if provided)
  774. elif (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item():
  775. decoder_input_ids = torch.cat([decoder_start_token_id, decoder_input_ids], dim=-1)
  776. if "decoder_attention_mask" in model_kwargs:
  777. decoder_attention_mask = model_kwargs["decoder_attention_mask"]
  778. decoder_attention_mask = torch.cat(
  779. (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
  780. dim=-1,
  781. )
  782. model_kwargs["decoder_attention_mask"] = decoder_attention_mask
  783. return decoder_input_ids, model_kwargs
  784. @staticmethod
  785. def _expand_inputs_for_generation(
  786. expand_size: int = 1,
  787. is_encoder_decoder: bool = False,
  788. input_ids: torch.LongTensor | None = None,
  789. **model_kwargs,
  790. ) -> tuple[torch.LongTensor, dict[str, Any]]:
  791. """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
  792. # Do not call torch.repeat_interleave if expand_size is 1 because it clones
  793. # the input tensor and thus requires more memory although no change is applied
  794. if expand_size == 1:
  795. return input_ids, model_kwargs
  796. def _expand_dict_for_generation(dict_to_expand):
  797. for key in dict_to_expand:
  798. if dict_to_expand[key] is not None and isinstance(dict_to_expand[key], torch.Tensor):
  799. dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
  800. return dict_to_expand
  801. if input_ids is not None:
  802. input_ids = input_ids.repeat_interleave(expand_size, dim=0)
  803. model_kwargs = _expand_dict_for_generation(model_kwargs)
  804. if is_encoder_decoder:
  805. if model_kwargs.get("encoder_outputs") is None:
  806. raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
  807. model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
  808. return input_ids, model_kwargs
  809. def _update_model_kwargs_for_generation(
  810. self,
  811. outputs: ModelOutput,
  812. model_kwargs: dict[str, Any],
  813. is_encoder_decoder: bool = False,
  814. num_new_tokens: int = 1,
  815. ) -> dict[str, Any]:
  816. """
  817. Update the model kwargs to account for the `num_new_tokens` new tokens that were just generated.
  818. That is, update the `attention_mask`, `position_ids`, and `token_type_ids` to account for the
  819. new tokens of the total sequence.
  820. Note that this function never slices inputs, this is performed in `prepare_inputs_for_generation`.
  821. """
  822. # update past_key_values keeping its naming used in model code
  823. for possible_cache_name in ALL_CACHE_NAMES:
  824. if possible_cache_name in outputs:
  825. # TODO (joao): remove output/input mismatch when these old models (xlnet, reformer) are deprecated
  826. if possible_cache_name in ("past_buckets_states", "mems"):
  827. cache_name = "past_key_values"
  828. else:
  829. cache_name = possible_cache_name
  830. model_kwargs[cache_name] = getattr(outputs, possible_cache_name)
  831. break
  832. # update token_type_ids with last value
  833. if (token_type_ids := model_kwargs.get("token_type_ids")) is not None:
  834. model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -num_new_tokens:]], dim=-1)
  835. # update mm_token_type_ids with zeros (only-text)
  836. if (mm_token_type_ids := model_kwargs.get("mm_token_type_ids")) is not None:
  837. model_kwargs["mm_token_type_ids"] = torch.cat(
  838. [mm_token_type_ids, mm_token_type_ids.new_zeros((mm_token_type_ids.shape[0], num_new_tokens))], dim=-1
  839. )
  840. # Position ids (2D or 3D sometimes)
  841. position_ids_key = "position_ids" if not is_encoder_decoder else "decoder_position_ids"
  842. if (position_ids := model_kwargs.get(position_ids_key)) is not None:
  843. # We want to expand to the same number of dims which is not always the same
  844. required_dim = [1] * (position_ids.dim() - 1) + [-1]
  845. next_position_ids = (
  846. torch.arange(num_new_tokens, dtype=position_ids.dtype, device=position_ids.device).view(*required_dim)
  847. + position_ids[..., -1:]
  848. + 1
  849. )
  850. next_position_ids = torch.cat([position_ids, next_position_ids], dim=-1)
  851. model_kwargs[position_ids_key] = next_position_ids
  852. # 2D attention mask (always 2D here)
  853. attention_mask_key = "attention_mask" if not is_encoder_decoder else "decoder_attention_mask"
  854. if (attention_mask := model_kwargs.get(attention_mask_key)) is not None:
  855. model_kwargs[attention_mask_key] = torch.cat(
  856. [attention_mask, attention_mask.new_ones((attention_mask.shape[0], num_new_tokens))], dim=-1
  857. )
  858. return model_kwargs
  859. def _get_candidate_generator(
  860. self: "GenerativePreTrainedModel",
  861. generation_config: GenerationConfig,
  862. input_ids: torch.LongTensor,
  863. inputs_tensor: torch.Tensor,
  864. logits_processor: LogitsProcessorList,
  865. model_kwargs: dict[str, Any],
  866. assistant_model: Optional["PreTrainedModel"] = None,
  867. target_tokenizer: Optional["PreTrainedTokenizerBase"] = None,
  868. assistant_tokenizer: Optional["PreTrainedTokenizerBase"] = None,
  869. ) -> CandidateGenerator:
  870. """
  871. Returns the candidate generator to be used in `assisted_generation`
  872. """
  873. different_tokenizers = all(v is not None for v in (assistant_model, target_tokenizer, assistant_tokenizer))
  874. if generation_config.assistant_early_exit is not None:
  875. candidate_generator = EarlyExitCandidateGenerator(
  876. input_ids=input_ids,
  877. assistant_model=self,
  878. generation_config=generation_config,
  879. model_kwargs=model_kwargs,
  880. inputs_tensor=inputs_tensor,
  881. logits_processor=logits_processor,
  882. )
  883. elif generation_config.prompt_lookup_num_tokens is not None:
  884. candidate_generator = PromptLookupCandidateGenerator(
  885. eos_token_id=generation_config._eos_token_tensor,
  886. num_output_tokens=generation_config.prompt_lookup_num_tokens,
  887. max_matching_ngram_size=generation_config.max_matching_ngram_size or 2,
  888. max_length=generation_config.max_length,
  889. logits_processor=logits_processor,
  890. vocab_size=self.config.get_text_config().vocab_size,
  891. )
  892. elif different_tokenizers:
  893. assistant_model = cast("PreTrainedModel", assistant_model)
  894. target_tokenizer = cast("PreTrainedTokenizerBase", target_tokenizer)
  895. assistant_tokenizer = cast("PreTrainedTokenizerBase", assistant_tokenizer)
  896. if generation_config.do_sample is True:
  897. atm_translator = AssistantVocabTranslatorCache.get_translator(
  898. target_tokenizer,
  899. assistant_tokenizer,
  900. self.config.get_text_config().vocab_size,
  901. assistant_model=assistant_model,
  902. assistant_prune_lm_head=True, # prune LM head of assistant model
  903. )
  904. # Since we prune the LM head, we cannot use the repetition penalty on the assistant model due to mismatches between token ids and logits index
  905. assistant_model.generation_config.repetition_penalty = None
  906. candidate_generator = UniversalSpeculativeDecodingGenerator(
  907. input_ids=input_ids,
  908. assistant_model=assistant_model,
  909. generation_config=generation_config,
  910. model_kwargs=model_kwargs,
  911. inputs_tensor=inputs_tensor,
  912. logits_processor=logits_processor,
  913. target_tokenizer=target_tokenizer,
  914. assistant_tokenizer=assistant_tokenizer,
  915. atm_translator=atm_translator,
  916. )
  917. elif generation_config.do_sample is False:
  918. candidate_generator = AssistedCandidateGeneratorDifferentTokenizers(
  919. input_ids=input_ids,
  920. assistant_model=assistant_model,
  921. generation_config=generation_config,
  922. model_kwargs=model_kwargs,
  923. inputs_tensor=inputs_tensor,
  924. logits_processor=logits_processor,
  925. target_tokenizer=target_tokenizer,
  926. assistant_tokenizer=assistant_tokenizer,
  927. )
  928. else:
  929. raise ValueError(
  930. f"Invalid value for `do_sample`: expected a boolean, got {type(generation_config.do_sample).__name__}"
  931. )
  932. else:
  933. candidate_generator = AssistedCandidateGenerator(
  934. input_ids=input_ids,
  935. assistant_model=assistant_model,
  936. generation_config=generation_config,
  937. model_kwargs=model_kwargs,
  938. inputs_tensor=inputs_tensor,
  939. logits_processor=logits_processor,
  940. )
  941. return candidate_generator
  942. def _get_logits_processor(
  943. self: "GenerativePreTrainedModel",
  944. generation_config: GenerationConfig,
  945. input_ids_seq_length: int | None = None,
  946. encoder_input_ids: torch.LongTensor | None = None,
  947. prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], list[int]] | None = None,
  948. logits_processor: LogitsProcessorList | None = None,
  949. device: str | None = None,
  950. model_kwargs: dict[str, Any] | None = None,
  951. negative_prompt_ids: torch.Tensor | None = None,
  952. negative_prompt_attention_mask: torch.Tensor | None = None,
  953. ) -> LogitsProcessorList:
  954. """
  955. This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
  956. instances used to modify the scores of the language model head.
  957. """
  958. # instantiate processors list
  959. processors = LogitsProcessorList()
  960. if logits_processor is None:
  961. logits_processor = []
  962. if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1:
  963. processors.append(
  964. UnbatchedClassifierFreeGuidanceLogitsProcessor(
  965. generation_config.guidance_scale,
  966. self,
  967. unconditional_ids=negative_prompt_ids,
  968. unconditional_attention_mask=negative_prompt_attention_mask,
  969. use_cache=generation_config.use_cache,
  970. )
  971. )
  972. if generation_config.sequence_bias is not None:
  973. processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))
  974. if (
  975. generation_config.encoder_repetition_penalty is not None
  976. and generation_config.encoder_repetition_penalty != 1.0
  977. ):
  978. if encoder_input_ids is not None and len(encoder_input_ids.shape) == 2:
  979. processors.append(
  980. EncoderRepetitionPenaltyLogitsProcessor(
  981. penalty=generation_config.encoder_repetition_penalty,
  982. encoder_input_ids=encoder_input_ids,
  983. )
  984. )
  985. else:
  986. warnings.warn(
  987. "Passing `encoder_repetition_penalty` requires some form of `input_ids` to be passed to "
  988. "`generate`, ignoring the argument.",
  989. UserWarning,
  990. )
  991. if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
  992. processors.append(RepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
  993. if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
  994. processors.append(NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
  995. if (
  996. generation_config.encoder_no_repeat_ngram_size is not None
  997. and generation_config.encoder_no_repeat_ngram_size > 0
  998. ):
  999. if encoder_input_ids is not None and len(encoder_input_ids.shape) == 2:
  1000. processors.append(
  1001. EncoderNoRepeatNGramLogitsProcessor(
  1002. generation_config.encoder_no_repeat_ngram_size,
  1003. encoder_input_ids,
  1004. )
  1005. )
  1006. else:
  1007. warnings.warn(
  1008. "Passing `encoder_no_repeat_ngram_size` requires some form of `input_ids` to be passed to "
  1009. "`generate`, ignoring the argument.",
  1010. UserWarning,
  1011. )
  1012. if generation_config.bad_words_ids is not None:
  1013. processors.append(
  1014. NoBadWordsLogitsProcessor(
  1015. generation_config.bad_words_ids,
  1016. generation_config._eos_token_tensor,
  1017. )
  1018. )
  1019. if (
  1020. generation_config.min_length is not None
  1021. and getattr(generation_config, "_eos_token_tensor", None) is not None
  1022. and generation_config.min_length > 0
  1023. ):
  1024. processors.append(
  1025. MinLengthLogitsProcessor(
  1026. generation_config.min_length,
  1027. generation_config._eos_token_tensor,
  1028. device=device,
  1029. )
  1030. )
  1031. if (
  1032. generation_config.min_new_tokens is not None
  1033. and getattr(generation_config, "_eos_token_tensor", None) is not None
  1034. and generation_config.min_new_tokens > 0
  1035. ):
  1036. processors.append(
  1037. MinNewTokensLengthLogitsProcessor(
  1038. input_ids_seq_length,
  1039. generation_config.min_new_tokens,
  1040. generation_config._eos_token_tensor,
  1041. device=device,
  1042. )
  1043. )
  1044. if prefix_allowed_tokens_fn is not None:
  1045. processors.append(
  1046. PrefixConstrainedLogitsProcessor(
  1047. prefix_allowed_tokens_fn,
  1048. generation_config.num_beams,
  1049. )
  1050. )
  1051. if generation_config.forced_bos_token_id is not None:
  1052. processors.append(
  1053. ForcedBOSTokenLogitsProcessor(
  1054. generation_config.forced_bos_token_id,
  1055. )
  1056. )
  1057. if generation_config.forced_eos_token_id is not None:
  1058. processors.append(
  1059. ForcedEOSTokenLogitsProcessor(
  1060. generation_config.max_length,
  1061. generation_config.forced_eos_token_id,
  1062. device=device,
  1063. )
  1064. )
  1065. if generation_config.remove_invalid_values is True:
  1066. processors.append(InfNanRemoveLogitsProcessor())
  1067. if generation_config.exponential_decay_length_penalty is not None:
  1068. processors.append(
  1069. ExponentialDecayLengthPenalty(
  1070. generation_config.exponential_decay_length_penalty,
  1071. generation_config._eos_token_tensor,
  1072. input_ids_seq_length,
  1073. )
  1074. )
  1075. if generation_config.suppress_tokens is not None:
  1076. processors.append(
  1077. SuppressTokensLogitsProcessor(
  1078. generation_config.suppress_tokens,
  1079. device=device,
  1080. )
  1081. )
  1082. if generation_config.begin_suppress_tokens is not None:
  1083. begin_index = input_ids_seq_length
  1084. begin_index = (
  1085. begin_index
  1086. if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
  1087. else begin_index + 1
  1088. )
  1089. processors.append(
  1090. SuppressTokensAtBeginLogitsProcessor(
  1091. generation_config.begin_suppress_tokens,
  1092. begin_index,
  1093. device=device,
  1094. )
  1095. )
  1096. # TODO (joao): find a strategy to specify the order of the processors
  1097. processors = self._merge_criteria_processor_list(processors, logits_processor)
  1098. # Processors previously known as `LogitsWarpers`, only applied with sampling strategies
  1099. if generation_config.do_sample:
  1100. # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
  1101. # better score (i.e. keep len(list(generation_config._eos_token_tensor)) + 1)
  1102. if generation_config.num_beams is not None and generation_config.num_beams > 1:
  1103. if isinstance(generation_config._eos_token_tensor, list):
  1104. min_tokens_to_keep = len(generation_config._eos_token_tensor) + 1
  1105. elif isinstance(generation_config._eos_token_tensor, torch.Tensor):
  1106. min_tokens_to_keep = generation_config._eos_token_tensor.shape[0] + 1
  1107. else:
  1108. min_tokens_to_keep = 2
  1109. else:
  1110. min_tokens_to_keep = 1
  1111. # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
  1112. # all samplers can be found in `generation_utils_samplers.py`
  1113. if generation_config.temperature is not None and generation_config.temperature != 1.0:
  1114. processors.append(TemperatureLogitsWarper(generation_config.temperature))
  1115. if generation_config.top_h is not None:
  1116. processors.append(TopHLogitsWarper(top_h=generation_config.top_h))
  1117. if generation_config.top_k is not None and generation_config.top_k != 0:
  1118. processors.append(
  1119. TopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep)
  1120. )
  1121. if generation_config.top_p is not None and generation_config.top_p < 1.0:
  1122. processors.append(
  1123. TopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep)
  1124. )
  1125. if generation_config.min_p is not None:
  1126. # Applied after temperature scaling (see https://github.com/ggerganov/llama.cpp/pull/3841#issuecomment-2073826084)
  1127. processors.append(
  1128. MinPLogitsWarper(min_p=generation_config.min_p, min_tokens_to_keep=min_tokens_to_keep)
  1129. )
  1130. if generation_config.typical_p is not None and generation_config.typical_p < 1.0:
  1131. processors.append(
  1132. TypicalLogitsWarper(mass=generation_config.typical_p, min_tokens_to_keep=min_tokens_to_keep)
  1133. )
  1134. if generation_config.epsilon_cutoff is not None and 0.0 < generation_config.epsilon_cutoff < 1.0:
  1135. processors.append(
  1136. EpsilonLogitsWarper(
  1137. epsilon=generation_config.epsilon_cutoff, min_tokens_to_keep=min_tokens_to_keep
  1138. )
  1139. )
  1140. if generation_config.eta_cutoff is not None and 0.0 < generation_config.eta_cutoff < 1.0:
  1141. processors.append(
  1142. EtaLogitsWarper(
  1143. epsilon=generation_config.eta_cutoff, min_tokens_to_keep=min_tokens_to_keep, device=device
  1144. )
  1145. )
  1146. # Watermarking should be after all logits processing is finished (see #34630)
  1147. if generation_config.watermarking_config is not None:
  1148. processors.append(
  1149. generation_config.watermarking_config.construct_processor(
  1150. self.config.get_text_config().vocab_size, device
  1151. )
  1152. )
  1153. # `LogitNormalization` should always be the last logit processor, when present
  1154. if generation_config.renormalize_logits is True:
  1155. processors.append(LogitNormalization())
  1156. return processors
  1157. def _get_stopping_criteria(
  1158. self: "GenerativePreTrainedModel",
  1159. generation_config: GenerationConfig,
  1160. stopping_criteria: StoppingCriteriaList | None,
  1161. tokenizer: Optional["PreTrainedTokenizerBase"] = None,
  1162. ) -> StoppingCriteriaList:
  1163. criteria = StoppingCriteriaList()
  1164. if generation_config.max_length is not None:
  1165. max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
  1166. criteria.append(
  1167. MaxLengthCriteria(
  1168. max_length=generation_config.max_length,
  1169. max_position_embeddings=max_position_embeddings,
  1170. )
  1171. )
  1172. if generation_config.max_time is not None:
  1173. criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))
  1174. if generation_config.stop_strings is not None:
  1175. if tokenizer is None:
  1176. raise ValueError(
  1177. "There are one or more stop strings, either in the arguments to `generate` or in the "
  1178. "model's generation config, but we could not locate a tokenizer. When generating with "
  1179. "stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`."
  1180. )
  1181. criteria.append(StopStringCriteria(stop_strings=generation_config.stop_strings, tokenizer=tokenizer))
  1182. if generation_config._eos_token_tensor is not None:
  1183. criteria.append(EosTokenCriteria(eos_token_id=generation_config._eos_token_tensor))
  1184. if (
  1185. generation_config.is_assistant
  1186. and generation_config.assistant_confidence_threshold is not None
  1187. and generation_config.assistant_confidence_threshold > 0
  1188. ):
  1189. criteria.append(
  1190. ConfidenceCriteria(assistant_confidence_threshold=generation_config.assistant_confidence_threshold)
  1191. )
  1192. criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)
  1193. return criteria
  1194. def _merge_criteria_processor_list(
  1195. self,
  1196. default_list: LogitsProcessorList | StoppingCriteriaList,
  1197. custom_list: LogitsProcessorList | StoppingCriteriaList,
  1198. ) -> LogitsProcessorList | StoppingCriteriaList:
  1199. """
  1200. Merge user-defined processors/criteria with the ones instantiated inside `generate`. In case the same
  1201. processor/criteria is present on both lists, use the user-defined one.
  1202. (Note: up to v4.49.0, this function threw an exception is the same logit processor was found twice.)
  1203. """
  1204. if len(custom_list) == 0:
  1205. return default_list
  1206. final_list = type(default_list)()
  1207. for default in default_list:
  1208. using_custom = False
  1209. for custom in custom_list:
  1210. if type(custom) is type(default):
  1211. object_type = "stopping criteria" if isinstance(custom, StoppingCriteria) else "logits processor"
  1212. logger.warning_once(
  1213. f"A custom {object_type} of type {type(custom)} has been passed to `.generate()`, but it "
  1214. f"was also created in `.generate()`, given its parameterization. The custom {type(custom)} "
  1215. f"will take precedence. Please check the docstring of {type(custom)} to see related "
  1216. "`.generate()` flags."
  1217. )
  1218. final_list.append(custom)
  1219. using_custom = True
  1220. break
  1221. if not using_custom:
  1222. final_list.append(default)
  1223. for custom in custom_list:
  1224. if custom not in final_list:
  1225. final_list.append(custom)
  1226. return final_list
  1227. def compute_transition_scores(
  1228. self: "GenerativePreTrainedModel",
  1229. sequences: torch.Tensor,
  1230. scores: tuple[torch.Tensor],
  1231. beam_indices: torch.Tensor | None = None,
  1232. normalize_logits: bool = False,
  1233. ) -> torch.Tensor:
  1234. """
  1235. Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
  1236. used). This is a convenient method to quickly obtain the scores of the selected tokens at generation time.
  1237. Parameters:
  1238. sequences (`torch.LongTensor`):
  1239. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
  1240. shorter if all batches finished early due to the `eos_token_id`.
  1241. scores (`tuple(torch.FloatTensor)`):
  1242. Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  1243. of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
  1244. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
  1245. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  1246. beam_indices (`torch.LongTensor`, *optional*):
  1247. Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
  1248. `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
  1249. generate-time.
  1250. normalize_logits (`bool`, *optional*, defaults to `False`):
  1251. Whether to normalize the logits (which, for legacy reasons, may be unnormalized).
  1252. Return:
  1253. `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
  1254. the transition scores (logits)
  1255. Examples:
  1256. ```python
  1257. >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
  1258. >>> import numpy as np
  1259. >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
  1260. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1261. >>> tokenizer.pad_token_id = tokenizer.eos_token_id
  1262. >>> inputs = tokenizer(["Today is"], return_tensors="pt")
  1263. >>> # Example 1: Print the scores for each token generated with Greedy Search
  1264. >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
  1265. >>> transition_scores = model.compute_transition_scores(
  1266. ... outputs.sequences, outputs.scores, normalize_logits=True
  1267. ... )
  1268. >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
  1269. >>> # encoder-decoder models, like BART or T5.
  1270. >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
  1271. >>> generated_tokens = outputs.sequences[:, input_length:]
  1272. >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
  1273. ... # | token | token string | log probability | probability
  1274. ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
  1275. | 262 | the | -1.414 | 24.33%
  1276. | 1110 | day | -2.609 | 7.36%
  1277. | 618 | when | -2.010 | 13.40%
  1278. | 356 | we | -1.859 | 15.58%
  1279. | 460 | can | -2.508 | 8.14%
  1280. >>> # Example 2: Reconstruct the sequence scores from Beam Search
  1281. >>> outputs = model.generate(
  1282. ... **inputs,
  1283. ... max_new_tokens=5,
  1284. ... num_beams=4,
  1285. ... num_return_sequences=4,
  1286. ... return_dict_in_generate=True,
  1287. ... output_scores=True,
  1288. ... )
  1289. >>> transition_scores = model.compute_transition_scores(
  1290. ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
  1291. ... )
  1292. >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
  1293. >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
  1294. >>> # use case, you might want to recompute it with `normalize_logits=True`.
  1295. >>> # Tip 2: the output length does NOT include the input length
  1296. >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
  1297. >>> length_penalty = model.generation_config.length_penalty
  1298. >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
  1299. >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
  1300. True
  1301. ```"""
  1302. # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
  1303. # to a beam search approach were the first (and only) beam is always selected
  1304. if beam_indices is None:
  1305. beam_indices = torch.arange(scores[0].shape[0]).view(-1, 1).to(sequences.device)
  1306. beam_indices = beam_indices.expand(-1, len(scores))
  1307. # 2. reshape scores as [batch_size*vocab_size, # generation steps] with # generation steps being
  1308. # seq_len - input_length
  1309. stacked_scores: torch.Tensor = torch.stack(scores).reshape(len(scores), -1).transpose(0, 1)
  1310. # 3. Optionally normalize the logits (across the vocab dimension)
  1311. if normalize_logits:
  1312. stacked_scores = stacked_scores.reshape(
  1313. -1, self.config.get_text_config().vocab_size, stacked_scores.shape[-1]
  1314. )
  1315. stacked_scores = torch.nn.functional.log_softmax(stacked_scores, dim=1)
  1316. stacked_scores = stacked_scores.reshape(-1, stacked_scores.shape[-1])
  1317. # 4. cut beam_indices to longest beam length
  1318. beam_indices_mask = beam_indices < 0
  1319. max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max()
  1320. beam_indices = beam_indices.clone()[:, :max_beam_length]
  1321. beam_indices_mask = beam_indices_mask[:, :max_beam_length]
  1322. # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
  1323. beam_indices[beam_indices_mask] = 0
  1324. # 6. multiply beam_indices with vocab size to gather correctly from scores
  1325. beam_sequence_indices = beam_indices * self.config.get_text_config().vocab_size
  1326. # 7. Define which indices contributed to scores
  1327. cut_idx = sequences.shape[-1] - max_beam_length
  1328. indices = sequences[:, cut_idx:] + beam_sequence_indices
  1329. # 8. Compute scores
  1330. transition_scores = stacked_scores.gather(0, indices)
  1331. # 9. Mask out transition_scores of beams that stopped early
  1332. transition_scores[beam_indices_mask] = 0
  1333. return transition_scores
  1334. def _validate_generation_mode(
  1335. self: "GenerativePreTrainedModel", generation_mode, generation_config, generation_mode_kwargs
  1336. ):
  1337. if generation_mode == GenerationMode.BEAM_SEARCH and "streamer" in generation_mode_kwargs:
  1338. raise ValueError(
  1339. "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
  1340. )
  1341. if generation_mode == GenerationMode.ASSISTED_GENERATION:
  1342. if generation_config.num_return_sequences > 1:
  1343. raise ValueError(
  1344. "num_return_sequences has to be 1 when doing assisted generate, "
  1345. f"but is {generation_config.num_return_sequences}."
  1346. )
  1347. if self._is_stateful:
  1348. # In assisted generation we need the ability to confirm whether the model would pick certain tokens,
  1349. # which is not possible with stateful models (they can't reset to a previous subset of generated text)
  1350. raise ValueError(
  1351. f"assisted generation is not supported with stateful models, such as {self.__class__.__name__}"
  1352. )
  1353. if (assistant_model := generation_mode_kwargs.get("assistant_model")) is not None:
  1354. if self.config.is_encoder_decoder and not assistant_model.config.is_encoder_decoder:
  1355. attributes_to_check = ["encoder_attention_heads", "encoder_ffn_dim", "encoder_layers"]
  1356. attributes_to_check = [attr for attr in dir(assistant_model.config) if attr in attributes_to_check]
  1357. are_equal = all(
  1358. getattr(self.config, attr) == getattr(assistant_model.config, attr) for attr in attributes_to_check
  1359. )
  1360. if not are_equal:
  1361. raise ValueError(
  1362. "The main model and the assistant don't have compatible encoder-dependent input shapes. "
  1363. "Ensure you load the assistant with the correct encoder-decoder class, e.g. `AutoModelForSpeechSeq2Seq` for Whisper."
  1364. )
  1365. doc_reference = (
  1366. "(see https://huggingface.co/docs/transformers/en/generation_strategies#universal-assisted-decoding)"
  1367. )
  1368. if self.config.get_text_config().vocab_size == assistant_model.config.get_text_config().vocab_size:
  1369. if "assistant_tokenizer" in generation_mode_kwargs:
  1370. raise ValueError(
  1371. f"`assistant_tokenizer` is not required when the main and assistant models use the same tokenizer. Please omit `assistant_tokenizer` from `generate()` {doc_reference}."
  1372. )
  1373. else:
  1374. if "tokenizer" not in generation_mode_kwargs or "assistant_tokenizer" not in generation_mode_kwargs:
  1375. raise ValueError(
  1376. f"The main and assistant models have different tokenizers. Please provide `tokenizer` and `assistant_tokenizer` to `generate()` {doc_reference}."
  1377. )
  1378. def _validate_model_kwargs(self: "GenerativePreTrainedModel", model_kwargs: dict[str, Any]):
  1379. """Validates model kwargs for generation. Generate argument typos will also be caught here."""
  1380. # Excludes arguments that are handled before calling any model function
  1381. if self.config.is_encoder_decoder:
  1382. for key in ["decoder_input_ids"]:
  1383. model_kwargs.pop(key, None)
  1384. unused_model_args = []
  1385. model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
  1386. # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
  1387. # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
  1388. if "kwargs" in model_args or "model_kwargs" in model_args:
  1389. model_args |= set(inspect.signature(self.forward).parameters)
  1390. # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`
  1391. if self.config.is_encoder_decoder:
  1392. base_model = getattr(self, self.base_model_prefix, None)
  1393. # allow encoder kwargs
  1394. encoder = getattr(self, "encoder", None)
  1395. # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.
  1396. # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`
  1397. # TODO: A better way to handle this.
  1398. if encoder is None and base_model is not None:
  1399. encoder = getattr(base_model, "encoder", None)
  1400. if encoder is not None:
  1401. encoder_model_args = set(inspect.signature(encoder.forward).parameters)
  1402. model_args |= encoder_model_args
  1403. # allow decoder kwargs
  1404. decoder = getattr(self, "decoder", None)
  1405. if decoder is None and base_model is not None:
  1406. decoder = getattr(base_model, "decoder", None)
  1407. if decoder is not None:
  1408. decoder_model_args = set(inspect.signature(decoder.forward).parameters)
  1409. model_args |= {f"decoder_{x}" for x in decoder_model_args}
  1410. # TransformersKwargs are model-agnostic attention and generation arguments such as 'output_attentions'
  1411. for key, value in model_kwargs.items():
  1412. if (
  1413. value is not None
  1414. and key not in model_args
  1415. and key not in TransformersKwargs.__optional_keys__
  1416. and key != "debug_io"
  1417. ):
  1418. unused_model_args.append(key)
  1419. if unused_model_args:
  1420. raise ValueError(
  1421. f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
  1422. " generate arguments will also show up in this list)"
  1423. )
  1424. def _validate_generated_length(
  1425. self: "GenerativePreTrainedModel", generation_config, input_ids_length, has_default_max_length
  1426. ):
  1427. """Performs validation related to the resulting generated length"""
  1428. # 1. Max length warnings related to poor parameterization
  1429. if has_default_max_length and generation_config.max_new_tokens is None:
  1430. # 20 is the default max_length of the generation config
  1431. warnings.warn(
  1432. f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
  1433. "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
  1434. "generation.",
  1435. UserWarning,
  1436. )
  1437. if input_ids_length >= generation_config.max_length:
  1438. input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  1439. raise ValueError(
  1440. f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
  1441. f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
  1442. " increasing `max_length` or, better yet, setting `max_new_tokens`."
  1443. )
  1444. # 2. Min length warnings due to unfeasible parameter combinations
  1445. min_length_error_suffix = (
  1446. " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "
  1447. "increase the maximum length."
  1448. )
  1449. if has_default_max_length:
  1450. min_length_error_suffix += (
  1451. f" Note that `max_length` is set to {generation_config.max_length}, its default value."
  1452. )
  1453. if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
  1454. warnings.warn(
  1455. f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"
  1456. f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
  1457. UserWarning,
  1458. )
  1459. if generation_config.min_new_tokens is not None:
  1460. min_length = generation_config.min_new_tokens + input_ids_length
  1461. if min_length > generation_config.max_length:
  1462. warnings.warn(
  1463. f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "
  1464. f"added to the prompt length ({input_ids_length}), is larger than"
  1465. f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
  1466. UserWarning,
  1467. )
  1468. def _prepare_generated_length(
  1469. self: "GenerativePreTrainedModel",
  1470. generation_config,
  1471. has_default_max_length,
  1472. has_default_min_length,
  1473. model_input_name,
  1474. input_ids_length,
  1475. inputs_tensor,
  1476. ):
  1477. """Prepared max and min length in generation configs to avoid clashes between similar attributes"""
  1478. if generation_config.max_new_tokens is not None:
  1479. if not has_default_max_length and generation_config.max_length is not None:
  1480. logger.warning(
  1481. f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
  1482. f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
  1483. "Please refer to the documentation for more information. "
  1484. "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
  1485. )
  1486. generation_config.max_length = generation_config.max_new_tokens + input_ids_length
  1487. # If both `inputs_embeds` and `input_ids` are passed, we correct length with `inputs_tensor.shape`
  1488. # We need to get max_length = inputs_embeds_len + max_new_tokens
  1489. elif (
  1490. model_input_name == "inputs_embeds"
  1491. and input_ids_length != inputs_tensor.shape[1]
  1492. and not self.config.is_encoder_decoder
  1493. and not has_default_max_length
  1494. ):
  1495. generation_config.max_length -= inputs_tensor.shape[1]
  1496. elif has_default_max_length: # by default let's always generate 20 new tokens
  1497. generation_config.max_length = generation_config.max_length + input_ids_length
  1498. max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
  1499. if max_position_embeddings is not None:
  1500. generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
  1501. # same for min length
  1502. if generation_config.min_new_tokens is not None:
  1503. if not has_default_min_length:
  1504. logger.warning(
  1505. f"Both `min_new_tokens` (={generation_config.min_new_tokens}) and `min_length`(="
  1506. f"{generation_config.min_length}) seem to have been set. `min_new_tokens` will take precedence. "
  1507. "Please refer to the documentation for more information. "
  1508. "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
  1509. )
  1510. generation_config.min_length = generation_config.min_new_tokens + input_ids_length
  1511. elif (
  1512. model_input_name == "inputs_embeds"
  1513. and input_ids_length != inputs_tensor.shape[1]
  1514. and not self.config.is_encoder_decoder
  1515. ):
  1516. generation_config.min_length = max(generation_config.min_length - inputs_tensor.shape[1], 0)
  1517. return generation_config
  1518. def _prepare_generation_config(
  1519. self: "GenerativePreTrainedModel",
  1520. generation_config: GenerationConfig | None,
  1521. **kwargs: Any,
  1522. ) -> tuple[GenerationConfig, dict]:
  1523. """
  1524. Prepares the base generation config, then applies any generation configuration options from kwargs. This
  1525. function handles retrocompatibility with respect to configuration files.
  1526. """
  1527. # parameterization priority:
  1528. # user-defined kwargs or `generation_config` > `self.generation_config` > global default values
  1529. # TODO (joao): per-model generation config classes.
  1530. generation_config_provided = generation_config is not None
  1531. if generation_config is None:
  1532. # Users may modify `model.config` to control generation. This is a legacy behavior and is not supported anymore
  1533. if len(self.config._get_generation_parameters()) > 0:
  1534. raise ValueError(
  1535. "You have modified the pretrained model configuration to control generation "
  1536. f"We detected the following values set - {self.config._get_generation_parameters()}. "
  1537. "This strategy to control generation is not supported anymore. Please use and modify `model.generation_config` "
  1538. "(see https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )",
  1539. )
  1540. generation_config = GenerationConfig()
  1541. # `torch.export.export` usually raises an exception if it is called
  1542. # with ``strict=True``. deepcopy can only be processed if ``strict=False``.
  1543. generation_config = copy.deepcopy(generation_config)
  1544. # First set values from the loaded `self.generation_config`, then set default values (BC)
  1545. #
  1546. # Only update values that are `None`, i.e. these values were not explicitly set by users to `generate()`,
  1547. # or values that are not present in the current config, i.e. custom entries that were set via `**kwargs`.
  1548. # Thus we use the specific kwargs `defaults_only=True` (`None` values only) and `allow_custom_entries=True`
  1549. # (custom entries are carried over).
  1550. global_defaults = self.generation_config._get_default_generation_params()
  1551. generation_config.update(**self.generation_config.to_dict(), defaults_only=True, allow_custom_entries=True)
  1552. generation_config.update(**global_defaults, defaults_only=True)
  1553. # Finally, if there are any kwargs, update config with it -> highest priority at the end
  1554. model_kwargs = generation_config.update(**kwargs)
  1555. # Related to #40039: prior to this PR, models with sliding window attention were forced to have
  1556. # `cache_implementation="hybrid"` (the static sliding window cache). For these models, we now want to use
  1557. # the dynamic sliding window cache by default, so we UNSET `cache_implementation` if it is a default value.
  1558. # (if we're inside this branch, then it is because we're using default values from the Hub)
  1559. if generation_config.cache_implementation == "hybrid":
  1560. generation_config.cache_implementation = None
  1561. # It doesn't make sense to allow kwargs and `generation_config`, that should be mutually exclusive
  1562. if generation_config_provided and set(kwargs.keys()) - set(model_kwargs.keys()):
  1563. generation_kwargs = set(kwargs.keys()) - set(model_kwargs.keys())
  1564. logger.warning_once(
  1565. f"Passing `generation_config` together with generation-related "
  1566. f"arguments=({generation_kwargs}) is deprecated and will be removed in future versions. "
  1567. "Please pass either a `generation_config` object OR all generation "
  1568. "parameters explicitly, but not both.",
  1569. )
  1570. # Finally keep output_xxx args in `model_kwargs` so it can be passed to `forward`
  1571. output_attentions = generation_config.output_attentions
  1572. output_hidden_states = generation_config.output_hidden_states
  1573. model_kwargs.update({"output_attentions": output_attentions} if output_attentions else {})
  1574. model_kwargs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
  1575. return generation_config, model_kwargs
  1576. def _prepare_static_cache(
  1577. self: "GenerativePreTrainedModel", cache_implementation: str, batch_size: int, max_cache_len: int, model_kwargs
  1578. ) -> Cache:
  1579. """
  1580. Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a
  1581. new `generate` call requires a larger cache or uses a different batch size.
  1582. Returns the resulting cache object.
  1583. """
  1584. offload_cache = "offloaded" in cache_implementation
  1585. cache_to_check: StaticCache | None = None
  1586. if hasattr(self, "_cache"):
  1587. if isinstance(self._cache, EncoderDecoderCache):
  1588. cache_to_check = self._cache.self_attention_cache
  1589. elif isinstance(self._cache, StaticCache):
  1590. cache_to_check = self._cache
  1591. need_new_cache = (
  1592. cache_to_check is None
  1593. or cache_to_check.offloading != offload_cache
  1594. or cache_to_check.max_batch_size != batch_size
  1595. or cache_to_check.max_cache_len < max_cache_len
  1596. )
  1597. encoder_decoder_cache = getattr(self, "_cache", None)
  1598. if isinstance(encoder_decoder_cache, EncoderDecoderCache):
  1599. need_new_cache = (
  1600. need_new_cache
  1601. or encoder_decoder_cache.cross_attention_cache.max_cache_len
  1602. != model_kwargs["encoder_outputs"][0].shape[1]
  1603. )
  1604. if need_new_cache:
  1605. self_attention_cache_kwargs = {
  1606. "config": self.config.get_text_config(decoder=True),
  1607. "max_cache_len": max_cache_len,
  1608. "offloading": offload_cache,
  1609. }
  1610. self._cache = StaticCache(**self_attention_cache_kwargs)
  1611. if self.config.is_encoder_decoder:
  1612. cross_attention_cache_kwargs = {
  1613. "config": self.config.get_text_config(decoder=True),
  1614. "max_cache_len": model_kwargs["encoder_outputs"][0].shape[1],
  1615. "offloading": offload_cache,
  1616. }
  1617. self._cache = EncoderDecoderCache(self._cache, StaticCache(**cross_attention_cache_kwargs))
  1618. else:
  1619. self._cache.reset()
  1620. return self._cache
  1621. @classmethod
  1622. def _supports_default_dynamic_cache(cls: type["GenerativePreTrainedModel"]) -> bool:
  1623. """
  1624. Return `True` if current model can use a `DynamicCache` instance when initializing the `past_key_values`.
  1625. """
  1626. # NOTE: remove xlnet/reformer when the models are deprecated, non-standard model architecture/cache name
  1627. unsupported_model_names = (
  1628. "reformer",
  1629. "minimax",
  1630. "xlnet",
  1631. "olmohybrid", # olmo_hybrid cannot use linear attention cache for now as it uses split k,q,v conv states
  1632. "rwkv",
  1633. "xlstm",
  1634. )
  1635. # name clash between minimax and minimax m2, so we add this "or"
  1636. return "minimaxm2" in cls.__name__.lower() or all(
  1637. unsupported_name not in cls.__name__.lower() for unsupported_name in unsupported_model_names
  1638. )
  1639. def _prepare_cache_for_generation(
  1640. self: "GenerativePreTrainedModel",
  1641. generation_config: GenerationConfig,
  1642. model_kwargs: dict,
  1643. generation_mode: GenerationMode,
  1644. batch_size: int,
  1645. max_cache_length: int,
  1646. ) -> bool:
  1647. """
  1648. Prepares the cache for generation (if applicable), given `generate`'s parameterization. If a cache is
  1649. instantiated, writes it to `model_kwargs`, under the name expected by the model.
  1650. """
  1651. # TODO @raushan, unify cache arg naming for all models
  1652. is_linear_attn_cache = "mamba" in self.__class__.__name__.lower()
  1653. cache_name = "past_key_values" if not is_linear_attn_cache else "cache_params"
  1654. # Quick escape route 1: if the user specifies a cache, we only need to check for conflicting `generate` arguments
  1655. user_defined_cache = model_kwargs.get(cache_name)
  1656. if user_defined_cache is not None:
  1657. if generation_config.cache_implementation is not None:
  1658. raise ValueError(
  1659. f"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a "
  1660. "Cache object) is unsupported. Please use only one of the two."
  1661. )
  1662. if isinstance(user_defined_cache, tuple):
  1663. raise ValueError(
  1664. "Passing a tuple of `past_key_values` is not supported anymore. Please use a `Cache` instance."
  1665. )
  1666. return
  1667. # Quick escape route 2: if the user specifies no cache is to be used. (conflicting arguments are handled in
  1668. # `generation_config.validate()`)
  1669. if generation_config.use_cache is False:
  1670. return
  1671. # Quick escape route 3: model that supply it in `prepare_inputs_for_generation` (mamba, zamba, ...)
  1672. if not self._supports_default_dynamic_cache():
  1673. if generation_config.cache_implementation is not None:
  1674. logger.warning_once(
  1675. "This model does not support `Cache` instances. `cache_implementation` (set to "
  1676. f"{generation_config.cache_implementation}) will be ignored.",
  1677. )
  1678. return
  1679. # Otherwise we NEED to prepare a cache, based on `generation_config.cache_implementation`
  1680. # Assisted decoding and contrastive search require cache rollback, which is incompatible with sliding layers.
  1681. # To handle this, we skip passing the model config to DynamicCache (forcing a full-layer cache).
  1682. # The "dynamic_full" option is a shortcut for generate() users to avoid sliding layers on their own.
  1683. if generation_mode in (GenerationMode.ASSISTED_GENERATION, GenerationMode.CONTRASTIVE_SEARCH):
  1684. if generation_config.cache_implementation is not None:
  1685. logger.warning_once(
  1686. "An assistant model is provided, using a dynamic cache instead of a cache of type="
  1687. f"'{generation_config.cache_implementation}'."
  1688. )
  1689. generation_config.cache_implementation = "dynamic_full"
  1690. dynamic_cache_kwargs = {}
  1691. # linear attention models always need to pass the config, otherwise it will use an Attention cache for the LinearAttention layers
  1692. is_linear_attention = any(
  1693. x in ("mamba", "conv", "linear_attention")
  1694. for x in (getattr(self.config.get_text_config(decoder=True), "layer_types", []) or [])
  1695. )
  1696. if generation_config.cache_implementation != "dynamic_full" or is_linear_attention:
  1697. dynamic_cache_kwargs["config"] = self.config.get_text_config(decoder=True)
  1698. if generation_config.cache_implementation == "offloaded":
  1699. dynamic_cache_kwargs["offloading"] = True
  1700. if generation_config.cache_implementation in ALL_STATIC_CACHE_IMPLEMENTATIONS:
  1701. if generation_config.cache_implementation in DEPRECATED_STATIC_CACHE_IMPLEMENTATIONS:
  1702. logger.warning_once(
  1703. f"Using `cache_implementation='{generation_config.cache_implementation}' is deprecated "
  1704. f"and will be removed in v5.13. Please only use one of {STATIC_CACHE_IMPLEMENTATIONS}, "
  1705. "and the layer structure will be inferred automatically."
  1706. )
  1707. model_kwargs[cache_name] = self._prepare_static_cache(
  1708. cache_implementation=generation_config.cache_implementation,
  1709. batch_size=max(generation_config.num_beams, generation_config.num_return_sequences) * batch_size,
  1710. max_cache_len=max_cache_length,
  1711. model_kwargs=model_kwargs,
  1712. )
  1713. elif generation_config.cache_implementation == "quantized":
  1714. if self.config.is_encoder_decoder or not self._supports_default_dynamic_cache():
  1715. raise ValueError(
  1716. "This model does not support the quantized cache. If you want your model to support quantized "
  1717. "cache, please open an issue and tag @zucchini-nlp."
  1718. )
  1719. cache_config = generation_config.cache_config if generation_config.cache_config is not None else {}
  1720. cache_config.setdefault("config", self.config.get_text_config(decoder=True))
  1721. backend = cache_config.pop("backend", "quanto")
  1722. model_kwargs[cache_name] = QuantizedCache(backend=backend, **cache_config)
  1723. # i.e. `cache_implementation` in [None, "dynamic", "offloaded", "dynamic_full"]
  1724. # TODO: prepare linear cache from a single API, instead of creating in modeling code
  1725. else:
  1726. model_kwargs[cache_name] = DynamicCache(**dynamic_cache_kwargs)
  1727. if (
  1728. self.config.is_encoder_decoder
  1729. and cache_name in model_kwargs
  1730. and not isinstance(model_kwargs[cache_name], EncoderDecoderCache)
  1731. ):
  1732. model_kwargs[cache_name] = EncoderDecoderCache(
  1733. model_kwargs[cache_name], # self-attention cache
  1734. DynamicCache(**dynamic_cache_kwargs), # cross-attention cache
  1735. )
  1736. def _supports_logits_to_keep(self: "GenerativePreTrainedModel") -> bool:
  1737. """
  1738. Return True if the current model supports the keyword argument `logits_to_keep` in forward()
  1739. to save memory. Checking it in this way allows to avoid using a new model attribute.
  1740. """
  1741. return "logits_to_keep" in set(inspect.signature(self.forward).parameters.keys())
  1742. def _prepare_special_tokens(
  1743. self: "GenerativePreTrainedModel",
  1744. generation_config: GenerationConfig,
  1745. kwargs_has_attention_mask: bool | None = None,
  1746. device: torch.device | str | None = None,
  1747. ):
  1748. """
  1749. Prepares the special tokens for generation, overwriting the generation config with their processed versions
  1750. converted to tensor.
  1751. Note that `generation_config` is changed in place and stops being serializable after this method is called.
  1752. That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
  1753. function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
  1754. """
  1755. # Convert special tokens to tensors
  1756. def _tensor_or_none(token, device=None):
  1757. if token is None:
  1758. return token
  1759. device = device if device is not None else self.device
  1760. if isinstance(token, torch.Tensor):
  1761. return token.to(device)
  1762. return torch.tensor(token, device=device, dtype=torch.long)
  1763. bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
  1764. eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
  1765. pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
  1766. decoder_start_token_tensor = _tensor_or_none(generation_config.decoder_start_token_id, device=device)
  1767. # for BC we also try to get `decoder_start_token_id` or `bos_token_id` (#30892)
  1768. if self.config.is_encoder_decoder:
  1769. decoder_start_token_tensor = (
  1770. decoder_start_token_tensor if decoder_start_token_tensor is not None else bos_token_tensor
  1771. )
  1772. # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
  1773. if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
  1774. eos_token_tensor = eos_token_tensor.unsqueeze(0)
  1775. # Set pad token if unset (and there are conditions to do so)
  1776. if pad_token_tensor is None and eos_token_tensor is not None:
  1777. if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
  1778. logger.warning(
  1779. "The attention mask and the pad token id were not set. As a consequence, you may observe "
  1780. "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
  1781. )
  1782. pad_token_tensor = eos_token_tensor[0]
  1783. logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
  1784. # Sanity checks/warnings
  1785. if self.config.is_encoder_decoder and decoder_start_token_tensor is None:
  1786. raise ValueError(
  1787. "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
  1788. )
  1789. if eos_token_tensor is not None and torch.isin(eos_token_tensor, pad_token_tensor).any():
  1790. if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
  1791. logger.warning_once(
  1792. "The attention mask is not set and cannot be inferred from input because pad token is same as "
  1793. "eos token. As a consequence, you may observe unexpected behavior. Please pass your input's "
  1794. "`attention_mask` to obtain reliable results."
  1795. )
  1796. if eos_token_tensor is not None and (
  1797. torch.is_floating_point(eos_token_tensor) or (eos_token_tensor < 0).any()
  1798. ):
  1799. logger.warning(
  1800. f"`eos_token_id` should consist of positive integers, but is {eos_token_tensor}. Your generation "
  1801. "will not stop until the maximum length is reached. Depending on other flags, it may even crash."
  1802. )
  1803. # Update generation config with the updated special tokens tensors
  1804. # NOTE: this must be written into a different attribute name than the one holding the original special tokens
  1805. # (in their non-tensor form), in order to enable end-to-end compilation. See
  1806. # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
  1807. generation_config._bos_token_tensor = bos_token_tensor
  1808. generation_config._eos_token_tensor = eos_token_tensor
  1809. generation_config._pad_token_tensor = pad_token_tensor
  1810. generation_config._decoder_start_token_tensor = decoder_start_token_tensor
  1811. def _valid_auto_compile_criteria(
  1812. self: "GenerativePreTrainedModel", model_kwargs: dict[str, Any], generation_config: GenerationConfig
  1813. ) -> bool:
  1814. """
  1815. Determines whether to trigger auto-compilation of the model's forward pass at generation time.
  1816. """
  1817. # Override: honor `disable_compile` flag
  1818. if generation_config.disable_compile:
  1819. return False
  1820. cache = model_kwargs.get("past_key_values", model_kwargs.get("cache_params"))
  1821. # Base logic
  1822. valid_hardware = self.device.type in ["cuda", "xpu"] or bool(
  1823. generation_config.compile_config is not None and generation_config.compile_config._compile_all_devices
  1824. )
  1825. # Note: for some models that only use linear attention (e.g. Mamba), even a DynamicCache is compileable since all
  1826. # layers are, but we don't want to ALWAYS compile when calling `generate`, so we check the type
  1827. using_compilable_cache = cache is not None and cache.is_compileable and type(cache) is not DynamicCache
  1828. can_compile = valid_hardware and using_compilable_cache
  1829. # Exception 1: Some quantization methods do not support compilation
  1830. if getattr(self, "hf_quantizer", None) is not None:
  1831. can_compile &= self.hf_quantizer.is_compileable
  1832. if hasattr(self, "hf_device_map"):
  1833. all_model_devices = set(self.hf_device_map.values())
  1834. # Exception 2: Don't compile if the model is using CPU offload (as of April 2025, this results in a crash)
  1835. has_cpu_offload = "cpu" in all_model_devices and len(all_model_devices) > 1
  1836. can_compile &= not has_cpu_offload
  1837. # Exception 3: Disk offload is not supported for compilation
  1838. has_disk_offload = "disk" in all_model_devices
  1839. can_compile &= not has_disk_offload
  1840. # If the user has manually specified compilation options, but compilation is not possible, let's warn
  1841. # them
  1842. if generation_config.compile_config is not None and not can_compile:
  1843. logger.warning_once(
  1844. "You have set `compile_config`, but we are unable to meet the criteria for compilation. Compilation "
  1845. "will be skipped."
  1846. )
  1847. if can_compile:
  1848. # Finally: if we can compile, disable tokenizers parallelism
  1849. os.environ["TOKENIZERS_PARALLELISM"] = "0"
  1850. # If we use FA and a static cache, we cannot compile with fullgraph
  1851. if is_flash_attention_requested(self.config):
  1852. # only raise warning if the user passed an explicit compile-config
  1853. if generation_config.compile_config is not None and generation_config.compile_config.fullgraph:
  1854. logger.warning_once(
  1855. "When using Flash Attention and a static cache, you cannot use the option `CompileConfig(fullgraph=True)` as "
  1856. "FA introduces graph breaks. We overrode the option with `fullgraph=False`."
  1857. )
  1858. generation_config.compile_config.fullgraph = False
  1859. return can_compile
  1860. @contextmanager
  1861. def _optimize_model_for_decode(self: "GenerativePreTrainedModel"):
  1862. original_experts_implementation = self.config._experts_implementation
  1863. # On non-CPU devices, 'batched_mm' can trade off a bit of memory (by duplicating selected experts weights)
  1864. # for much better speed during decoding, especially for smaller inputs. On CPU, grouped_mm is usually better.
  1865. if original_experts_implementation == "grouped_mm" and self.device.type != "cpu":
  1866. logger.info_once(
  1867. "We will be switching to 'batched_mm' for the decoding stage as it is much more performant than 'grouped_mm' on smaller inputs. "
  1868. "If you experience any issues with this, please open an issue on the Hugging Face Transformers GitHub repository.",
  1869. )
  1870. self.set_experts_implementation("batched_mm")
  1871. try:
  1872. yield
  1873. finally:
  1874. if original_experts_implementation == "grouped_mm" and self.device.type != "cpu":
  1875. self.set_experts_implementation(original_experts_implementation)
  1876. def _get_deprecated_gen_repo(
  1877. self,
  1878. generation_mode: GenerationMode,
  1879. trust_remote_code: bool,
  1880. custom_generate: str | None = None,
  1881. ) -> str | None:
  1882. """
  1883. Returns the Hub repo for a deprecated generation mode, if any.
  1884. """
  1885. if custom_generate is not None or "/" not in (repo := GENERATION_MODES_MAPPING[generation_mode]):
  1886. return None
  1887. logger.warning_once(
  1888. f"{generation_mode.name.replace('_', ' ').title()} was moved to a `custom_generate` repo: https://hf.co/{repo}. "
  1889. f"To prevent loss of backward compatibility, add `custom_generate='{repo}'` "
  1890. "to your `generate` call before v4.62.0."
  1891. )
  1892. if not trust_remote_code:
  1893. raise ValueError(
  1894. f"{generation_mode.name.replace('_', ' ').title()} requires `trust_remote_code=True` in your `generate` call, "
  1895. f"since it loads https://hf.co/{repo}."
  1896. )
  1897. return repo
  1898. def _extract_generation_mode_kwargs(
  1899. self,
  1900. custom_generate,
  1901. kwargs,
  1902. synced_gpus,
  1903. assistant_model,
  1904. streamer,
  1905. ) -> dict[str, Any]:
  1906. """
  1907. Extracts and returns the generation mode related keyword arguments from the provided kwargs.
  1908. """
  1909. generation_mode_kwargs = {
  1910. "tokenizer": kwargs.pop("tokenizer", None),
  1911. "assistant_tokenizer": kwargs.pop("assistant_tokenizer", None),
  1912. "assistant_model": assistant_model,
  1913. "streamer": streamer,
  1914. }
  1915. world_size = dist.get_world_size() if dist.is_available() and dist.is_initialized() else 1 # type: ignore
  1916. generation_mode_kwargs["synced_gpus"] = (
  1917. (is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)) and world_size > 1
  1918. if synced_gpus is None
  1919. else synced_gpus
  1920. )
  1921. generation_mode_kwargs = {k: v for k, v in generation_mode_kwargs.items() if v is not None}
  1922. # Custom_generate callables can have their own set of arguments
  1923. # To extract them, we compare the signature with the standard _sample method
  1924. if isinstance(custom_generate, Callable):
  1925. usual_mode_kwargs = inspect.signature(GenerationMixin._sample).parameters.keys()
  1926. custom_generate_kwargs = inspect.signature(custom_generate).parameters.keys()
  1927. new_custom_keys = custom_generate_kwargs - usual_mode_kwargs
  1928. generation_mode_kwargs = {k: kwargs.pop(k) for k in new_custom_keys if k in kwargs}
  1929. return generation_mode_kwargs
  1930. @torch.no_grad()
  1931. def generate(
  1932. self: "GenerativePreTrainedModel",
  1933. inputs: torch.Tensor | None = None,
  1934. generation_config: GenerationConfig | None = None,
  1935. logits_processor: LogitsProcessorList | None = None,
  1936. stopping_criteria: StoppingCriteriaList | None = None,
  1937. prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], list[int]] | None = None,
  1938. synced_gpus: bool | None = None,
  1939. assistant_model: Optional["PreTrainedModel"] = None,
  1940. streamer: Optional["BaseStreamer"] = None,
  1941. negative_prompt_ids: torch.Tensor | None = None,
  1942. negative_prompt_attention_mask: torch.Tensor | None = None,
  1943. custom_generate: str | Callable | None = None,
  1944. **kwargs,
  1945. ) -> GenerateOutput | torch.LongTensor:
  1946. r"""
  1947. Generates sequences of token ids for models with a language modeling head.
  1948. <Tip warning={true}>
  1949. Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
  1950. model's default generation configuration. You can override any `generation_config` by passing the corresponding
  1951. parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
  1952. For an overview of generation strategies and code examples, check out the [following
  1953. guide](../generation_strategies).
  1954. </Tip>
  1955. Parameters:
  1956. inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
  1957. The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
  1958. method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
  1959. should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
  1960. `input_ids`, `input_values`, `input_features`, or `pixel_values`.
  1961. generation_config ([`~generation.GenerationConfig`], *optional*):
  1962. The generation configuration to be used as base parametrization for the generation call. `**kwargs`
  1963. passed to generate matching the attributes of `generation_config` will override them. If
  1964. `generation_config` is not provided, the default will be used, which has the following loading
  1965. priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
  1966. configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
  1967. default values, whose documentation should be checked to parameterize generation.
  1968. logits_processor (`LogitsProcessorList`, *optional*):
  1969. Custom logits processors that complement the default logits processors built from arguments and
  1970. generation config. If a logit processor is passed that is already created with the arguments or a
  1971. generation config an error is thrown. This feature is intended for advanced users.
  1972. stopping_criteria (`StoppingCriteriaList`, *optional*):
  1973. Custom stopping criteria that complements the default stopping criteria built from arguments and a
  1974. generation config. If a stopping criteria is passed that is already created with the arguments or a
  1975. generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
  1976. sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
  1977. intended for advanced users.
  1978. prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`, *optional*):
  1979. If provided, this function constraints the beam search to allowed tokens only at each step. If not
  1980. provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
  1981. `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
  1982. on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
  1983. for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
  1984. Retrieval](https://huggingface.co/papers/2010.00904).
  1985. synced_gpus (`bool`, *optional*):
  1986. Whether to continue running the while loop until max_length. Unless overridden, this flag will be set
  1987. to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid
  1988. deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.
  1989. assistant_model (`PreTrainedModel`, *optional*):
  1990. An assistant model that can be used to accelerate generation. The assistant model must have the exact
  1991. same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model
  1992. is much faster than running generation with the model you're calling generate from. As such, the
  1993. assistant model should be much smaller.
  1994. streamer (`BaseStreamer`, *optional*):
  1995. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  1996. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  1997. negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1998. The negative prompt needed for some processors such as CFG. The batch size must match the input batch
  1999. size. This is an experimental feature, subject to breaking API changes in future versions.
  2000. negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  2001. Attention_mask for `negative_prompt_ids`.
  2002. custom_generate (`str` or `Callable`, *optional*):
  2003. One of the following:
  2004. - `str` (Hugging Face Hub repository name): runs the custom `generate` function defined at
  2005. `custom_generate/generate.py` in that repository instead of the standard `generate` method. The
  2006. repository fully replaces the generation logic, and the return type may differ.
  2007. - `str` (local repository path): same as above but from a local path, `trust_remote_code` not required.
  2008. - `Callable`: `generate` will perform the usual input preparation steps, then call the provided callable to
  2009. run the decoding loop.
  2010. For more information, see [the docs](../../generation_strategies#custom-generation-methods).
  2011. kwargs (`dict[str, Any]`, *optional*):
  2012. Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
  2013. forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
  2014. specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
  2015. Return:
  2016. [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
  2017. or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.
  2018. If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
  2019. [`~utils.ModelOutput`] types are:
  2020. - [`~generation.GenerateDecoderOnlyOutput`],
  2021. - [`~generation.GenerateBeamDecoderOnlyOutput`]
  2022. If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
  2023. [`~utils.ModelOutput`] types are:
  2024. - [`~generation.GenerateEncoderDecoderOutput`],
  2025. - [`~generation.GenerateBeamEncoderDecoderOutput`]
  2026. """
  2027. # 0.a. If requested, load an arbitrary generation recipe from the Hub and run it instead
  2028. trust_remote_code = kwargs.pop("trust_remote_code", None)
  2029. if custom_generate is not None and isinstance(custom_generate, str):
  2030. # Get all `generate` arguments in a single variable. Custom functions are responsible for handling them:
  2031. # they receive the same inputs as `generate`, with `model` instead of `self` and excluding the arguments to
  2032. # trigger the custom generation. They can access to methods from `GenerationMixin` through `model`.
  2033. global_keys_to_exclude = {
  2034. "self",
  2035. "kwargs",
  2036. "global_keys_to_exclude",
  2037. "trust_remote_code",
  2038. "custom_generate",
  2039. }
  2040. generate_arguments = {key: value for key, value in locals().items() if key not in global_keys_to_exclude}
  2041. generate_arguments.update(kwargs)
  2042. custom_generate_function = self.load_custom_generate(
  2043. custom_generate, trust_remote_code=trust_remote_code, **kwargs
  2044. )
  2045. return custom_generate_function(model=self, **generate_arguments)
  2046. # 0.b. If requested, switched to continuous batching generation
  2047. if kwargs.get("cache_implementation") == "paged":
  2048. logger.warning(
  2049. "Detected cache_implementation=paged: switching to continuous batching. You should consider using "
  2050. "generate_batch directly instead."
  2051. )
  2052. # generate_batch expects a list of lists of ints, so we create it from the inputs or input_ids
  2053. inputs = inputs if inputs is not None else kwargs.get("input_ids")
  2054. if inputs is None:
  2055. raise ValueError("inputs or input_ids must be provided for CB generation.")
  2056. if inputs.dim() == 1:
  2057. inputs = inputs.unsqueeze(0).tolist()
  2058. elif inputs.dim() == 2:
  2059. inputs = inputs.tolist()
  2060. else:
  2061. raise ValueError(f"inputs must be a 1D or 2D tensor, got {inputs.dim() = }")
  2062. # some arguments are not supported for continuous batching
  2063. if stopping_criteria is not None:
  2064. raise NotImplementedError(
  2065. f"stopping_criteria is not supported for continuous batching. Got {stopping_criteria = }"
  2066. )
  2067. if prefix_allowed_tokens_fn is not None:
  2068. raise NotImplementedError(
  2069. f"prefix_allowed_tokens_fn is not supported for continuous batching. Got {prefix_allowed_tokens_fn = }"
  2070. )
  2071. if assistant_model is not None:
  2072. raise NotImplementedError(
  2073. f"assistant_model is not supported for continuous batching. Got {assistant_model = }"
  2074. )
  2075. if streamer is not None: # TODO: actually this could be supported
  2076. raise NotImplementedError(f"streaming is not supported for continuous batching. Got {streamer = }")
  2077. if negative_prompt_ids is not None:
  2078. raise NotImplementedError(
  2079. f"negative_prompt_ids is not supported for continuous batching. Got {negative_prompt_ids = }"
  2080. )
  2081. if negative_prompt_attention_mask is not None:
  2082. raise NotImplementedError(
  2083. f"negative_prompt_attention_mask is not supported for continuous batching. Got {negative_prompt_attention_mask = }"
  2084. )
  2085. # others are ignored
  2086. if synced_gpus is not None:
  2087. logger.warning(f"synced_gpus is not ignored for continuous batching. Got {synced_gpus = }")
  2088. num_return_sequences = kwargs.get("num_return_sequences", 1)
  2089. num_beams = kwargs.get("num_beams", 1)
  2090. if num_return_sequences > 1 or num_beams > 1: # FIXME: remove this once CB supports it (which is planned)
  2091. logger.warning(
  2092. f"num_return_sequences and num_beams are not supported for continuous batching yet. "
  2093. f"Got {num_return_sequences = } and {num_beams = }. "
  2094. )
  2095. # switch to CB
  2096. outputs = self.generate_batch(
  2097. inputs=inputs,
  2098. generation_config=self._prepare_generation_config(generation_config, **kwargs)[0],
  2099. **kwargs,
  2100. )
  2101. sequences = [
  2102. outputs[f"req_{i}"].prompt_ids + outputs[f"req_{i}"].generated_tokens for i in range(len(outputs))
  2103. ]
  2104. # To use the same indexing (outputs[0]) as the regular generate method, we unsqueeze the tensor
  2105. sequences_as_tensor = torch.tensor(sequences, dtype=torch.long, device=self.device)
  2106. sequences_as_tensor = sequences_as_tensor.unsqueeze(0)
  2107. return sequences_as_tensor
  2108. # 1. Handle kwargs, `generation_config`, validate them and obtain generation mode
  2109. generation_mode_kwargs = self._extract_generation_mode_kwargs(
  2110. custom_generate,
  2111. kwargs,
  2112. synced_gpus,
  2113. assistant_model,
  2114. streamer,
  2115. )
  2116. # Check length values before updating the config with defaults. We'll use it later to define the final min/max length (# 6)
  2117. has_default_max_length = (
  2118. kwargs.get("max_length") is None
  2119. and (generation_config is None or generation_config.max_length is None)
  2120. and self.generation_config.max_length is None
  2121. )
  2122. has_default_min_length = (
  2123. kwargs.get("min_length") is None
  2124. and (generation_config is None or generation_config.min_length is None)
  2125. and self.generation_config.min_length is None
  2126. )
  2127. generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
  2128. generation_mode = generation_config.get_generation_mode(assistant_model)
  2129. deprecated_mode_repo = self._get_deprecated_gen_repo(generation_mode, trust_remote_code, custom_generate)
  2130. if isinstance(custom_generate, Callable):
  2131. decoding_method = custom_generate
  2132. elif deprecated_mode_repo is None:
  2133. # type() required to access the unbound class-level method
  2134. decoding_method = getattr(type(self), GENERATION_MODES_MAPPING[generation_mode])
  2135. self._validate_model_kwargs(model_kwargs.copy())
  2136. self._validate_generation_mode(generation_mode, generation_config, generation_mode_kwargs)
  2137. # Deprecation-related step: set Hub repo for deprecated strategies.
  2138. # NOTE: This must come after initializing generation_config, since we need it to determine if this is a deprecated mode.
  2139. # It must also be before any preparation steps, since Hub repos expect to be loaded before preparation steps.
  2140. # TODO joao, manuel: remove this in v4.62.0
  2141. if deprecated_mode_repo is not None:
  2142. return GenerationMixin.generate(
  2143. self,
  2144. inputs=inputs,
  2145. generation_config=generation_config,
  2146. logits_processor=logits_processor,
  2147. stopping_criteria=stopping_criteria,
  2148. prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
  2149. assistant_model=assistant_model,
  2150. negative_prompt_ids=negative_prompt_ids,
  2151. negative_prompt_attention_mask=negative_prompt_attention_mask,
  2152. custom_generate=deprecated_mode_repo,
  2153. trust_remote_code=trust_remote_code,
  2154. **generation_mode_kwargs,
  2155. **kwargs,
  2156. )
  2157. # 2. Set generation parameters if not already defined
  2158. logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
  2159. stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
  2160. accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
  2161. kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
  2162. # 3. Define model inputs
  2163. inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
  2164. inputs, generation_config.bos_token_id, model_kwargs
  2165. )
  2166. # Some generation modes (e.g. assisted) need `inputs_tensor` to rerun encoder.forward()
  2167. if "inputs_tensor" in inspect.signature(decoding_method).parameters.keys():
  2168. generation_mode_kwargs["inputs_tensor"] = inputs_tensor
  2169. batch_size = inputs_tensor.shape[0]
  2170. device = inputs_tensor.device
  2171. self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=device)
  2172. # decoder-only models must use left-padding for batched generation.
  2173. if not self.config.is_encoder_decoder:
  2174. # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
  2175. # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
  2176. if generation_config._pad_token_tensor is not None and batch_size > 1 and len(inputs_tensor.shape) == 2:
  2177. # When an attention mask is provided, use it to detect right-padding (more reliable than
  2178. # checking token ids, which can produce false positives when pad_token_id == eos_token_id
  2179. # or pad_token_id == bos_token_id, as is the case for Qwen3 and other models).
  2180. attention_mask = model_kwargs.get("attention_mask", None)
  2181. if attention_mask is not None and attention_mask.shape == inputs_tensor.shape:
  2182. # Right-padding means there are zeros (masked positions) at the end of some sequences
  2183. has_right_padding = torch.any(attention_mask[:, -1] == 0).item()
  2184. else:
  2185. # Fallback: check if the last token is a pad token (original heuristic)
  2186. has_right_padding = torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor) > 0
  2187. if has_right_padding:
  2188. logger.warning(
  2189. "A decoder-only architecture is being used, but right-padding was detected! For correct "
  2190. "generation results, please set `padding_side='left'` when initializing the tokenizer."
  2191. )
  2192. # 4. Define other model kwargs
  2193. # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
  2194. # generating the first new token or not, and we only want to use the embeddings for the first new token)
  2195. if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
  2196. generation_config.use_cache = True
  2197. if not kwargs_has_attention_mask and not self.config.is_encoder_decoder and accepts_attention_mask:
  2198. model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
  2199. inputs_tensor, generation_config, model_kwargs
  2200. )
  2201. elif kwargs_has_attention_mask:
  2202. # TODO (joao): generalize this check with other types of inputs
  2203. if model_input_name == "input_ids" and len(model_kwargs["attention_mask"].shape) > 2:
  2204. raise ValueError("`attention_mask` passed to `generate` must be 2D.")
  2205. kwargs_has_position_ids = model_kwargs.get("position_ids", None) is not None
  2206. accepts_position_ids = "position_ids" in set(inspect.signature(self.forward).parameters.keys())
  2207. if not kwargs_has_position_ids and accepts_position_ids and not self.config.is_encoder_decoder:
  2208. model_kwargs["position_ids"] = self._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
  2209. if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
  2210. # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
  2211. model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
  2212. inputs_tensor, model_kwargs, model_input_name, generation_config
  2213. )
  2214. # 5. Prepare `input_ids` which will be used for auto-regressive generation
  2215. if self.config.is_encoder_decoder:
  2216. input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
  2217. batch_size=batch_size,
  2218. model_input_name=model_input_name,
  2219. model_kwargs=model_kwargs,
  2220. decoder_start_token_id=generation_config._decoder_start_token_tensor,
  2221. device=inputs_tensor.device,
  2222. )
  2223. else:
  2224. input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
  2225. # Expand inputs depending on the generation mode
  2226. input_ids, model_kwargs = self._expand_inputs_for_generation(
  2227. input_ids=input_ids,
  2228. expand_size=max(generation_config.num_beams, generation_config.num_return_sequences),
  2229. is_encoder_decoder=self.config.is_encoder_decoder,
  2230. **model_kwargs,
  2231. )
  2232. if generation_config.token_healing:
  2233. input_ids = self.heal_tokens(input_ids, generation_mode_kwargs.get("tokenizer"))
  2234. if streamer is not None:
  2235. streamer.put(input_ids.cpu())
  2236. # 6. Prepare `max_length` depending on other stopping criteria.
  2237. input_ids_length = input_ids.shape[1]
  2238. generation_config = self._prepare_generated_length(
  2239. generation_config=generation_config,
  2240. has_default_max_length=has_default_max_length,
  2241. has_default_min_length=has_default_min_length,
  2242. model_input_name=model_input_name,
  2243. inputs_tensor=inputs_tensor,
  2244. input_ids_length=input_ids_length,
  2245. )
  2246. # If the model supports `logits_to_keep` in forward(), set it to 1 to avoid computing the whole
  2247. # logit matrix. This can save a lot of memory during the first forward pass. Note that assisted decoding
  2248. # dynamically overrides this value as it can need more than the last token logits
  2249. if self._supports_logits_to_keep() and "logits_to_keep" not in model_kwargs:
  2250. model_kwargs["logits_to_keep"] = 1
  2251. self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
  2252. # 7. Prepare the cache.
  2253. # - `model_kwargs` may be updated in place with a cache as defined by the parameters in `generation_config`.
  2254. # - different models have a different cache name expected by the model (default = "past_key_values")
  2255. # - `max_length`, prepared above, is used to determine the maximum cache length
  2256. max_cache_length = generation_config.max_length - 1
  2257. if (
  2258. inputs_tensor.shape[1] != input_ids_length
  2259. and model_input_name == "inputs_embeds"
  2260. and not self.config.is_encoder_decoder
  2261. ):
  2262. max_cache_length += inputs_tensor.shape[1]
  2263. self._prepare_cache_for_generation(
  2264. generation_config, model_kwargs, generation_mode, batch_size, max_cache_length
  2265. )
  2266. if self.device.type != input_ids.device.type:
  2267. warnings.warn(
  2268. "You are calling .generate() with the `input_ids` being on a device type different"
  2269. f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
  2270. f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
  2271. " Please make sure that you have put `input_ids` to the"
  2272. f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
  2273. " running `.generate()`.",
  2274. UserWarning,
  2275. )
  2276. # 8. Prepare logits processors and stopping criteria
  2277. prepared_logits_processor = self._get_logits_processor(
  2278. generation_config=generation_config,
  2279. input_ids_seq_length=input_ids_length,
  2280. encoder_input_ids=inputs_tensor,
  2281. prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
  2282. logits_processor=logits_processor,
  2283. device=inputs_tensor.device,
  2284. model_kwargs=model_kwargs,
  2285. negative_prompt_ids=negative_prompt_ids,
  2286. negative_prompt_attention_mask=negative_prompt_attention_mask,
  2287. )
  2288. prepared_stopping_criteria = self._get_stopping_criteria(
  2289. generation_config=generation_config,
  2290. stopping_criteria=stopping_criteria,
  2291. tokenizer=generation_mode_kwargs.get("tokenizer"),
  2292. )
  2293. # Set model_kwargs `use_cache` so we can use it later in forward runs
  2294. model_kwargs["use_cache"] = generation_config.use_cache
  2295. # 9. Call generation mode
  2296. result = decoding_method(
  2297. self,
  2298. input_ids,
  2299. logits_processor=prepared_logits_processor,
  2300. stopping_criteria=prepared_stopping_criteria,
  2301. generation_config=generation_config,
  2302. **generation_mode_kwargs,
  2303. **model_kwargs,
  2304. )
  2305. return result
  2306. def _has_unfinished_sequences(self, this_peer_finished: bool, synced_gpus: bool, device: torch.device) -> bool:
  2307. """
  2308. Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is
  2309. fed through `this_peer_finished`. ZeRO stage 3-friendly.
  2310. """
  2311. if synced_gpus:
  2312. # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
  2313. # The following logic allows an early break if all peers finished generating their sequence
  2314. this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0, device=device)
  2315. # send 0.0 if we finished, 1.0 otherwise
  2316. dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM) # type: ignore
  2317. # did all peers finish? the reduced sum will be 0.0 then
  2318. if this_peer_finished_flag.item() == 0.0:
  2319. return False
  2320. elif this_peer_finished:
  2321. return False
  2322. return True
  2323. def heal_tokens(
  2324. self, input_ids: torch.LongTensor, tokenizer: Optional["PreTrainedTokenizerBase"] = None
  2325. ) -> torch.LongTensor:
  2326. r"""
  2327. Generates sequences of token ids for models with a language modeling head.
  2328. Parameters:
  2329. input_ids (`torch.LongTensor`): The sequence used as a prompt for the generation.
  2330. tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used to decode the input ids.
  2331. Return:
  2332. `torch.LongTensor` where each sequence has its tail token replaced with its appropriate extension.
  2333. """
  2334. if tokenizer is None:
  2335. raise ValueError(
  2336. " When generating with token healing, you must pass the model's tokenizer to the `tokenizer` "
  2337. "argument of `generate`."
  2338. )
  2339. bos_token_id, pad_token_id = tokenizer.bos_token_id, tokenizer.pad_token_id
  2340. vocab_trie = ExtensionsTrie(tokenizer.get_vocab())
  2341. generation_config = GenerationConfig(max_new_tokens=1, pad_token_id=pad_token_id)
  2342. # assumption: leading/trailing whitespace is not meaningful, so the prompts are
  2343. # stripped before re-tokenizing to desensitize generation to whitespace artefacts
  2344. prompts = [p.strip() for p in tokenizer.decode(input_ids, skip_special_tokens=True)]
  2345. input_ids = tokenizer(
  2346. prompts,
  2347. return_tensors="pt",
  2348. padding=True,
  2349. ).input_ids.to(input_ids.device)
  2350. # replace bos with pad to not condition healing on it
  2351. input_ids = torch.where(input_ids == bos_token_id, pad_token_id, input_ids)
  2352. # the latter code assumes the input_ids is not empty, input_id has to be checked if contains elements
  2353. if input_ids.numel() == 0:
  2354. return input_ids
  2355. tail_ids = input_ids[:, -1].tolist()
  2356. # tail tokens are used for a prefix search, thus, whitespaces are replaced with
  2357. # their tokenization (e.g. 'Ġ') to enable search for tokens prefixed with a whitespace
  2358. if tokenizer.convert_tokens_to_ids(" ") is not None:
  2359. space_tok = tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids(" "))[0]
  2360. tail_toks = (cast(str, tokenizer.decode(t)).replace(" ", space_tok) for t in tail_ids)
  2361. else:
  2362. tail_toks = (cast(str, tokenizer.decode(t)) for t in tail_ids)
  2363. for batch_idx, (tail_id, tail_tok) in enumerate(zip(tail_ids, tail_toks)):
  2364. batch_ids = input_ids[batch_idx]
  2365. if torch.all(batch_ids == pad_token_id).item():
  2366. continue # skip empty sequences (all pad ids)
  2367. # apply bias for alternatives (extensions) to the tail token
  2368. """
  2369. seq_bias key has to be tuple with int so have to use
  2370. tokenizer function to convert str to int
  2371. """
  2372. seq_bias = {
  2373. (tokenizer.convert_tokens_to_ids(alt_tok),): 10.0 for alt_tok in vocab_trie.extensions(prefix=tail_tok)
  2374. }
  2375. if len(seq_bias) == 1:
  2376. continue # skip if there are no token alternatives to heal with
  2377. # slightly favor original token to limit aggressive healing e.g. 'http' -> 'https'
  2378. seq_bias[(tail_id,)] += 1.0
  2379. generation_config.update(sequence_bias=seq_bias)
  2380. trimmed_ids = batch_ids[:-1]
  2381. """
  2382. the latter code assumes trimmed_ids is not empty
  2383. so have to check the its element count
  2384. """
  2385. if trimmed_ids.numel() == 0:
  2386. continue
  2387. # if the prompt is a single (non-pad) token, regenerate from bos
  2388. if len(batch_ids[batch_ids != pad_token_id]) == 1:
  2389. trimmed_ids[-1] = bos_token_id
  2390. input_ids[batch_idx] = self.generate(trimmed_ids.unsqueeze(0), generation_config=generation_config)
  2391. return input_ids
  2392. def _sample(
  2393. self: "GenerativePreTrainedModel",
  2394. input_ids: torch.LongTensor,
  2395. logits_processor: LogitsProcessorList,
  2396. stopping_criteria: StoppingCriteriaList,
  2397. generation_config: GenerationConfig,
  2398. synced_gpus: bool = False,
  2399. streamer: Optional["BaseStreamer"] = None,
  2400. **model_kwargs,
  2401. ) -> GenerateNonBeamOutput | torch.LongTensor:
  2402. r"""
  2403. Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and
  2404. can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2405. Parameters:
  2406. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  2407. The sequence used as a prompt for the generation.
  2408. logits_processor (`LogitsProcessorList`):
  2409. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  2410. used to modify the prediction scores of the language modeling head applied at each generation step.
  2411. stopping_criteria (`StoppingCriteriaList`):
  2412. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  2413. used to tell if the generation loop should stop.
  2414. generation_config ([`~generation.GenerationConfig`]):
  2415. The generation configuration to be used as parametrization of the decoding method.
  2416. synced_gpus (`bool`):
  2417. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  2418. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  2419. streamer (`BaseStreamer`, *optional*):
  2420. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  2421. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  2422. model_kwargs:
  2423. Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
  2424. an encoder-decoder model the kwargs should include `encoder_outputs`.
  2425. Return:
  2426. [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:
  2427. A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  2428. [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  2429. `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
  2430. `model.config.is_encoder_decoder=True`.
  2431. """
  2432. # init values
  2433. pad_token_id = generation_config._pad_token_tensor
  2434. output_attentions = generation_config.output_attentions
  2435. output_hidden_states = generation_config.output_hidden_states
  2436. output_scores = generation_config.output_scores
  2437. output_logits = generation_config.output_logits
  2438. return_dict_in_generate = generation_config.return_dict_in_generate
  2439. has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
  2440. do_sample = generation_config.do_sample
  2441. # init attention / hidden states / scores tuples
  2442. scores = () if (return_dict_in_generate and output_scores) else None
  2443. raw_logits = () if (return_dict_in_generate and output_logits) else None
  2444. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  2445. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  2446. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  2447. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  2448. if return_dict_in_generate and self.config.is_encoder_decoder:
  2449. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2450. encoder_hidden_states = (
  2451. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2452. )
  2453. # keep track of which sequences are already finished
  2454. batch_size = input_ids.shape[0]
  2455. this_peer_finished = False
  2456. unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
  2457. model_forward = (
  2458. self.get_compiled_call(generation_config.compile_config)
  2459. if self._valid_auto_compile_criteria(model_kwargs, generation_config)
  2460. else self.__call__
  2461. )
  2462. prefill_consumed = False
  2463. outputs = self._prefill(
  2464. input_ids,
  2465. generation_config,
  2466. model_kwargs,
  2467. is_first_iteration=not generation_config.is_assistant,
  2468. )
  2469. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  2470. if prefill_consumed:
  2471. next_sequence_length = 1 if model_kwargs["use_cache"] else None
  2472. model_inputs = self.prepare_inputs_for_generation(
  2473. input_ids, next_sequence_length=next_sequence_length, **model_kwargs
  2474. )
  2475. with self._optimize_model_for_decode():
  2476. outputs = model_forward(**model_inputs, return_dict=True)
  2477. prefill_consumed = True
  2478. model_kwargs = self._update_model_kwargs_for_generation(
  2479. outputs,
  2480. model_kwargs,
  2481. is_encoder_decoder=self.config.is_encoder_decoder,
  2482. )
  2483. if synced_gpus and this_peer_finished:
  2484. continue
  2485. # Copy is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
  2486. # (the clone itself is always small)
  2487. next_token_logits = outputs.logits[:, -1, :].to(copy=True, dtype=torch.float32, device=input_ids.device)
  2488. # pre-process distribution
  2489. next_token_scores = logits_processor(input_ids, next_token_logits)
  2490. # Store scores, attentions and hidden_states when required
  2491. if return_dict_in_generate:
  2492. if output_scores:
  2493. scores += (next_token_scores,)
  2494. if output_logits:
  2495. raw_logits += (next_token_logits,)
  2496. if output_attentions:
  2497. decoder_attentions += (
  2498. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  2499. )
  2500. if self.config.is_encoder_decoder:
  2501. cross_attentions += (outputs.cross_attentions,)
  2502. if output_hidden_states:
  2503. decoder_hidden_states += (
  2504. (outputs.decoder_hidden_states,)
  2505. if self.config.is_encoder_decoder
  2506. else (outputs.hidden_states,)
  2507. )
  2508. # token selection
  2509. if do_sample:
  2510. probs = nn.functional.softmax(next_token_scores, dim=-1)
  2511. # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
  2512. next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
  2513. else:
  2514. next_tokens = torch.argmax(next_token_scores, dim=-1)
  2515. # finished sentences should have their next token be a padding token
  2516. if has_eos_stopping_criteria:
  2517. next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
  2518. # update generated ids, model inputs, and length for next step
  2519. input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
  2520. if streamer is not None:
  2521. streamer.put(next_tokens.cpu())
  2522. unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
  2523. this_peer_finished = unfinished_sequences.max() == 0
  2524. # This is needed to properly delete outputs.logits which may be very large for first iteration
  2525. # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
  2526. del outputs
  2527. if streamer is not None:
  2528. streamer.end()
  2529. if return_dict_in_generate:
  2530. cache = None
  2531. if any(cache_key in model_kwargs for cache_key in ALL_CACHE_NAMES):
  2532. cache_key = next(cache_key for cache_key in ALL_CACHE_NAMES if cache_key in model_kwargs)
  2533. cache = model_kwargs[cache_key]
  2534. if self.config.is_encoder_decoder:
  2535. return GenerateEncoderDecoderOutput(
  2536. sequences=input_ids,
  2537. scores=scores,
  2538. logits=raw_logits,
  2539. encoder_attentions=encoder_attentions,
  2540. encoder_hidden_states=encoder_hidden_states,
  2541. decoder_attentions=decoder_attentions,
  2542. cross_attentions=cross_attentions,
  2543. decoder_hidden_states=decoder_hidden_states,
  2544. past_key_values=cache,
  2545. )
  2546. else:
  2547. return GenerateDecoderOnlyOutput(
  2548. sequences=input_ids,
  2549. scores=scores,
  2550. logits=raw_logits,
  2551. attentions=decoder_attentions,
  2552. hidden_states=decoder_hidden_states,
  2553. past_key_values=cache,
  2554. )
  2555. else:
  2556. return input_ids
  2557. @staticmethod
  2558. def _flatten_beam_dim(tensor: torch.Tensor) -> torch.Tensor:
  2559. """[batch_size, num_beams, ...] -> [batch_size * num_beams, ...]"""
  2560. shape = list(tensor.shape)
  2561. return torch.reshape(tensor, [shape[0] * shape[1]] + shape[2:])
  2562. @staticmethod
  2563. def _unflatten_beam_dim(tensor: torch.Tensor, batch_size: int, num_beams: int) -> torch.Tensor:
  2564. """[batch_size * num_beams, ...] -> [batch_size, num_beams, ...]"""
  2565. shape = list(tensor.shape)
  2566. return torch.reshape(tensor, [batch_size, num_beams] + shape[1:])
  2567. @staticmethod
  2568. def _gather_beams(tensor: torch.Tensor, beam_indices: torch.Tensor) -> torch.Tensor:
  2569. """
  2570. Gathers the beam slices indexed by beam_indices into new beam array.
  2571. Args:
  2572. tensor (`torch.Tensor`): A tensor containing data to be gathered. The tensor is a 2D or a 3D tensor
  2573. with the two first dimensions depicting the batch and the beam dimensions.
  2574. beam_indices (`torch.Tensor` of shape `(batch_size, num_beams_to_select)`): The indices of the beams to
  2575. select .
  2576. Returns:
  2577. A tensor with the selected beams
  2578. """
  2579. # `take_along_dim` requires its indices arg to have the same number of dims as `input`
  2580. while len(beam_indices.shape) < len(tensor.shape):
  2581. beam_indices = beam_indices.unsqueeze(-1)
  2582. gathered_tensor = torch.take_along_dim(input=tensor, indices=beam_indices, dim=1)
  2583. return gathered_tensor
  2584. @staticmethod
  2585. def _check_early_stop_heuristic(
  2586. is_early_stop_heuristic_unsatisfied: torch.Tensor,
  2587. running_beam_scores: torch.Tensor,
  2588. beam_scores: torch.Tensor,
  2589. is_sent_finished: torch.Tensor,
  2590. cur_len: int,
  2591. max_length: int,
  2592. decoder_prompt_len: int,
  2593. early_stopping: bool | str,
  2594. length_penalty: float,
  2595. ):
  2596. """
  2597. Determine whether early stopping is possible by checking if the best possible score of running beams
  2598. could still improve upon the finished ones.
  2599. Mechanism:
  2600. - Without a length penalty, beam scores typically decrease as more tokens are generated.
  2601. So, if the *best possible* score from any running beam is already worse than the *worst* finished beam,
  2602. we can safely stop early.
  2603. - With a length penalty, scores may increase with longer sequences. In this case, we use heuristics
  2604. to estimate the best possible score — though this estimate may not always be correct — and stop
  2605. if no further improvement seems likely.
  2606. We apply different heuristics depending on the value of `early_stopping`:
  2607. 1. `early_stopping == False`:
  2608. -> Use a heuristic that assumes the best score comes from the current length minus the decoder prompt length.
  2609. -> See detailed discussion: https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
  2610. 2. `early_stopping == "never"`:
  2611. -> Estimate the best score using either `max_length` or `cur_len`, depending on the sign of `length_penalty`.
  2612. -> A positive length penalty favors longer sequences, so we use `max_length` in that case.
  2613. NOTE: the canonical beam search implementation can be replicated with `early_stopping="never"` and
  2614. `length_penalty=0.0`, which are NOT the default flags. The default behavior was empirically found to produce
  2615. better sequences (prior to 2022), and changing it is BC breaking.
  2616. """
  2617. if early_stopping == "never" and length_penalty > 0.0:
  2618. best_hypothetical_length = max_length - decoder_prompt_len
  2619. else:
  2620. best_hypothetical_length = cur_len - decoder_prompt_len
  2621. best_possible_running_score = running_beam_scores[:, :1] / (best_hypothetical_length**length_penalty)
  2622. worst_finished_score = torch.where(is_sent_finished, torch.min(beam_scores, dim=1, keepdim=True)[0], -1.0e9)
  2623. return is_early_stop_heuristic_unsatisfied & torch.any(
  2624. best_possible_running_score > worst_finished_score, dim=-1, keepdim=True
  2625. )
  2626. @staticmethod
  2627. def _beam_search_has_unfinished_sequences(
  2628. is_early_stop_heuristic_unsatisfied: torch.Tensor,
  2629. is_sent_finished: torch.Tensor,
  2630. next_token_hits_stopping_criteria: torch.Tensor,
  2631. early_stopping: bool | str,
  2632. ):
  2633. """
  2634. Beam Search stopping condition -- halts the generation loop if any of these conditions becomes False
  2635. """
  2636. # a. Can the open beams improve the top completed scores?
  2637. improvement_possible = torch.any(is_early_stop_heuristic_unsatisfied)
  2638. # b. Is there still a beam without fully completed sequences? This is only relevant if early_stopping is
  2639. # enabled, where we want to finish as soon as all beams have a completed sequence.
  2640. exists_open_beam = ~(torch.all(is_sent_finished) & (early_stopping is True))
  2641. # c. Have we hit a stopping criteria with all running sequences and have no way to continue? e.g. we have
  2642. # reached `max_length``
  2643. valid_continuations = ~torch.all(next_token_hits_stopping_criteria)
  2644. return improvement_possible & exists_open_beam & valid_continuations
  2645. def _get_top_k_continuations(
  2646. self,
  2647. accumulated_log_probs: torch.Tensor,
  2648. running_sequences: torch.Tensor,
  2649. running_beam_indices: torch.Tensor,
  2650. cur_len: int,
  2651. decoder_prompt_len: int,
  2652. do_sample: bool,
  2653. beams_to_keep: int,
  2654. num_beams: int,
  2655. vocab_size: int,
  2656. batch_size: int,
  2657. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  2658. """
  2659. Get top-K continuations given the accumulated log probs on the next token.
  2660. A few notes to understand what's going on:
  2661. 1. Each item in batch has `num_beams` * `vocab_size` candidate continuations. For each item, get the
  2662. top K [K = (number of EOS tokens + 1) * `num_beams`] candidates with the highest accumulated
  2663. log-probabilities, or sample them without replacement using the accumulated scores
  2664. 2. We gather the top K (as opposed to `num_beams`, or any number lower than K) here so that we have at
  2665. least `num_beams` sequences remaining to continue the live beam search.
  2666. 3. Note that other stopping criteria might result in impossible to continue beams, i.e. all continuations
  2667. selected in this step hit the stopping criteria.
  2668. """
  2669. # TODO (joao): This function should take an optional beam scorer function, to manipulate the scores after
  2670. # token selection. The function should be an argument exposed, so that custom scoring functions can be
  2671. # defined.
  2672. # Gather the top K scores from _all_ beams.
  2673. if do_sample:
  2674. topk_indices = torch.multinomial(
  2675. nn.functional.softmax(accumulated_log_probs, dim=-1), num_samples=beams_to_keep
  2676. )
  2677. topk_log_probs = torch.gather(input=accumulated_log_probs, dim=1, index=topk_indices)
  2678. else:
  2679. topk_log_probs, topk_indices = torch.topk(accumulated_log_probs, k=beams_to_keep)
  2680. # Gather K top beams, recover the beam index by floor division and token id by modulo division
  2681. topk_current_beam_indices = topk_indices // vocab_size
  2682. topk_running_beam_indices = self._gather_beams(running_beam_indices, topk_current_beam_indices)
  2683. topk_running_sequences = self._gather_beams(running_sequences, topk_current_beam_indices)
  2684. topk_ids = topk_indices % vocab_size
  2685. # Update sequences for the K top-k new sequences.
  2686. topk_running_sequences[:, :, cur_len] = topk_ids
  2687. # we want to store the beam indices with batch information -> real beam index = beam index % num beams
  2688. batch_offset = torch.arange(batch_size, device=topk_ids.device).view(-1, 1) * num_beams
  2689. batch_modified_indices = topk_current_beam_indices + batch_offset
  2690. topk_running_beam_indices[:, :, cur_len - decoder_prompt_len] = batch_modified_indices
  2691. return topk_log_probs, topk_running_sequences, topk_running_beam_indices
  2692. def _get_running_beams_for_next_iteration(
  2693. self,
  2694. topk_log_probs: torch.Tensor,
  2695. topk_running_sequences: torch.Tensor,
  2696. topk_running_beam_indices: torch.Tensor,
  2697. next_token_hits_stopping_criteria: torch.Tensor,
  2698. num_beams: int,
  2699. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  2700. """
  2701. Given the top-K continuations, their scores, and whether they hit a stopping criteria, select the
  2702. best non-finished beams to continue beam search in the next iteration.
  2703. """
  2704. # To prevent these just finished sequences from being used in subsequent iterations, set their log probs
  2705. # to a very large negative value
  2706. topk_running_log_probs = topk_log_probs + next_token_hits_stopping_criteria.to(torch.float32) * -1.0e9
  2707. next_topk_indices = torch.topk(topk_running_log_probs, k=num_beams)[1]
  2708. running_sequences = self._gather_beams(topk_running_sequences, next_topk_indices)
  2709. running_beam_scores = self._gather_beams(topk_running_log_probs, next_topk_indices)
  2710. running_beam_indices = self._gather_beams(topk_running_beam_indices, next_topk_indices)
  2711. return running_sequences, running_beam_scores, running_beam_indices
  2712. def _update_finished_beams(
  2713. self,
  2714. sequences: torch.Tensor,
  2715. topk_running_sequences: torch.Tensor,
  2716. beam_scores: torch.Tensor,
  2717. topk_log_probs: torch.Tensor,
  2718. beam_indices: torch.Tensor,
  2719. topk_running_beam_indices: torch.Tensor,
  2720. is_early_stop_heuristic_unsatisfied: torch.Tensor,
  2721. is_sent_finished: torch.Tensor,
  2722. next_token_hits_stopping_criteria: torch.Tensor,
  2723. top_num_beam_mask: torch.Tensor,
  2724. num_beams: int,
  2725. cur_len: int,
  2726. decoder_prompt_len: int,
  2727. length_penalty: float,
  2728. early_stopping: bool | str,
  2729. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
  2730. """
  2731. Updates the finished beams if (and only if) there are new completed sequences that have a higher score than
  2732. the current finished sequences.
  2733. """
  2734. # Only the top `num_beam` sequences can be considered for the final returned sequences. Remember: the
  2735. # remaining sequences only exist as a backup to ensure that we have at least `num_beams` sequences to
  2736. # continue.
  2737. did_top_num_beams_just_finished = next_token_hits_stopping_criteria & top_num_beam_mask[None, :]
  2738. # Further process topk logits for the finished beams
  2739. # - add length penalty
  2740. topk_log_probs = topk_log_probs / ((cur_len + 1 - decoder_prompt_len) ** length_penalty)
  2741. # - make sure no scores can be added anymore if beam is full and early stopping is on
  2742. beams_in_batch_are_full = torch.all(is_sent_finished, axis=-1, keepdims=True) & (early_stopping is True)
  2743. topk_log_probs += beams_in_batch_are_full.to(torch.float32) * -1.0e9
  2744. # - make sure no scores can be added anymore if improvement is not possible
  2745. topk_log_probs += (~is_early_stop_heuristic_unsatisfied).to(torch.float32) * -1.0e9
  2746. # - make sure still running sequences cannot be chosen as finalized beam
  2747. topk_log_probs += (~did_top_num_beams_just_finished) * -1.0e9
  2748. # Get finalized `num_beam` sequences for the next generation step -- combine the previous finalized
  2749. # data with the new finalized sequences (if any, non-finalized sequences have a very large negative score
  2750. # in this step), and keep the best `num_beams` sequences.
  2751. merged_sequences = torch.cat((sequences, topk_running_sequences), dim=1)
  2752. merged_scores = torch.cat((beam_scores, topk_log_probs), dim=1)
  2753. merged_beam_indices = torch.cat((beam_indices, topk_running_beam_indices), dim=1)
  2754. merged_is_sent_finished = torch.cat((is_sent_finished, did_top_num_beams_just_finished), dim=1)
  2755. topk_merged_indices = torch.topk(merged_scores, k=num_beams)[1]
  2756. sequences = self._gather_beams(merged_sequences, topk_merged_indices)
  2757. beam_scores = self._gather_beams(merged_scores, topk_merged_indices)
  2758. beam_indices = self._gather_beams(merged_beam_indices, topk_merged_indices)
  2759. is_sent_finished = self._gather_beams(merged_is_sent_finished, topk_merged_indices)
  2760. return sequences, beam_scores, beam_indices, is_sent_finished
  2761. # end of auxiliary functions for beam search
  2762. def _beam_search(
  2763. self: "GenerativePreTrainedModel",
  2764. input_ids: torch.LongTensor,
  2765. logits_processor: LogitsProcessorList,
  2766. stopping_criteria: StoppingCriteriaList,
  2767. generation_config: GenerationConfig,
  2768. synced_gpus: bool = False,
  2769. **model_kwargs,
  2770. ) -> GenerateBeamOutput | torch.LongTensor:
  2771. r"""
  2772. Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
  2773. can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2774. If it's the first time you're diving into Beam Search, we recommend you read the following blog post:
  2775. https://huggingface.co/blog/how-to-generate (especially the beam search section).
  2776. You can recompute the sequence scores from the individual scores using the `compute_transition_scores` function
  2777. (https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationMixin.compute_transition_scores)
  2778. Parameters:
  2779. input_ids (`torch.LongTensor` of shape `(batch_size*num_beams, sequence_length)`):
  2780. The sequence used as a prompt for the generation.
  2781. logits_processor (`LogitsProcessorList`):
  2782. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  2783. used to modify the prediction scores of the language modeling head applied at each generation step.
  2784. stopping_criteria (`StoppingCriteriaList`:
  2785. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  2786. used to tell if the generation loop should stop.
  2787. generation_config ([`~generation.GenerationConfig`]):
  2788. The generation configuration to be used as parametrization of the decoding method.
  2789. synced_gpus (`bool`):
  2790. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  2791. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  2792. model_kwargs:
  2793. Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
  2794. an encoder-decoder model the kwargs should include `encoder_outputs`.
  2795. Return:
  2796. [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
  2797. `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  2798. [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  2799. `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
  2800. `model.config.is_encoder_decoder=True`.
  2801. """
  2802. # 1. init beam_search values
  2803. pad_token_id = generation_config._pad_token_tensor
  2804. eos_token_id = generation_config._eos_token_tensor
  2805. output_attentions = generation_config.output_attentions
  2806. output_hidden_states = generation_config.output_hidden_states
  2807. output_scores = generation_config.output_scores
  2808. output_logits = generation_config.output_logits
  2809. return_dict_in_generate = generation_config.return_dict_in_generate
  2810. do_sample = generation_config.do_sample
  2811. early_stopping = generation_config.early_stopping
  2812. length_penalty = generation_config.length_penalty
  2813. max_length = generation_config.max_length
  2814. num_beams = generation_config.num_beams
  2815. num_return_sequences = generation_config.num_return_sequences
  2816. batch_size_unflattened, cur_len = input_ids.shape[:2]
  2817. batch_size = batch_size_unflattened // num_beams
  2818. # TODO (joao): standardize special cases
  2819. if self.__class__.__name__ == "MoshiDepthDecoder":
  2820. vocab_size = self.config.audio_vocab_size
  2821. elif self.__class__.__name__ == "ImageGPTForCausalImageModeling":
  2822. vocab_size = self.get_output_embeddings().out_features
  2823. elif self.__class__.__name__ == "BarkSemanticModel":
  2824. vocab_size = self.config.output_vocab_size
  2825. else:
  2826. vocab_size = self.config.get_text_config().vocab_size
  2827. decoder_prompt_len = cur_len
  2828. this_peer_finished = False
  2829. # At each beam search step, we want to keep top K [K = (number of EOS tokens + 1) * `num_beams`] candidates
  2830. # with the highest log-probabilities, or sample K continuations without replacement. We gather the top K
  2831. # (as opposed to `num_beams`, or any number lower than K) so that we have at least `num_beams` sequences
  2832. # non-finished to continue the live beam search, in case the top `num_beams` all select an EOS token.
  2833. n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
  2834. beams_to_keep = max(2, 1 + n_eos_tokens) * num_beams
  2835. top_num_beam_mask = torch.cat(
  2836. (torch.ones((num_beams), dtype=torch.bool), torch.zeros((beams_to_keep - num_beams), dtype=torch.bool)),
  2837. dim=0,
  2838. ).to(input_ids.device)
  2839. # (joao) feature lost in the refactor. Probably won't implement, hurts readability with minimal gains (there
  2840. # are newer low-memory alternatives like the offloaded cache)
  2841. sequential = generation_config.low_memory
  2842. if sequential:
  2843. raise ValueError(
  2844. "`low_memory=True` is not supported after the beam search refactor. Please check the discussion in "
  2845. "#35802 *after the PR got merged*, and add a comment there if your questions are not yet answered."
  2846. )
  2847. # 2. init output tuples
  2848. all_scores = () if (return_dict_in_generate and output_scores) else None
  2849. raw_logits = () if (return_dict_in_generate and output_logits) else None
  2850. beam_indices = () if (return_dict_in_generate and output_logits) else None
  2851. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  2852. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  2853. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  2854. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  2855. if return_dict_in_generate and self.config.is_encoder_decoder:
  2856. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2857. encoder_hidden_states = (
  2858. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2859. )
  2860. # 3. init running tensors and static-shaped placeholders
  2861. # per batch, beam-item holding current token in loop and completed sequences
  2862. output_fill_value = pad_token_id or eos_token_id[0] if eos_token_id is not None else -1
  2863. running_sequences = torch.full(
  2864. (batch_size, num_beams, max_length),
  2865. fill_value=output_fill_value,
  2866. dtype=torch.int64,
  2867. device=input_ids.device,
  2868. )
  2869. running_sequences[:, :, :cur_len] = self._unflatten_beam_dim(input_ids, batch_size, num_beams)
  2870. sequences = running_sequences.detach().clone()
  2871. # per batch, beam-item score, logprobs
  2872. # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
  2873. # of the first beam are considered to avoid sampling the exact same tokens across all beams.
  2874. running_beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
  2875. running_beam_scores[:, 1:] = -1e9
  2876. beam_scores = torch.full((batch_size, num_beams), fill_value=-1e9, dtype=torch.float, device=input_ids.device)
  2877. # per batch, beam-item state bit indicating if sentence has finished.
  2878. is_sent_finished = torch.zeros((batch_size, num_beams), dtype=torch.bool, device=input_ids.device)
  2879. # per batch state bit indicating if there is a possibility to improve the best finished sentence.
  2880. is_early_stop_heuristic_unsatisfied = torch.ones((batch_size, 1), dtype=torch.bool, device=input_ids.device)
  2881. # per batch, beam-item state bit indicating if there are valid continuations.
  2882. next_token_hits_stopping_criteria = torch.zeros(
  2883. (batch_size, num_beams), dtype=torch.bool, device=input_ids.device
  2884. )
  2885. # per batch selected beam indices
  2886. running_beam_indices = torch.full(
  2887. (batch_size, num_beams, max_length - cur_len), fill_value=-1, dtype=torch.int32, device=input_ids.device
  2888. )
  2889. beam_indices = running_beam_indices.detach().clone()
  2890. flat_running_sequences = input_ids
  2891. prefill_consumed = False
  2892. model_outputs = self._prefill(
  2893. input_ids,
  2894. generation_config,
  2895. model_kwargs,
  2896. is_first_iteration=not generation_config.is_assistant,
  2897. )
  2898. # 4. run the generation loop
  2899. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  2900. if prefill_consumed:
  2901. # a. Forward current tokens, obtain the logits
  2902. flat_running_sequences = self._flatten_beam_dim(running_sequences[:, :, :cur_len])
  2903. next_sequence_length = 1 if model_kwargs["use_cache"] else None
  2904. model_inputs = self.prepare_inputs_for_generation(
  2905. flat_running_sequences, next_sequence_length=next_sequence_length, **model_kwargs
  2906. )
  2907. model_outputs = self(**model_inputs, return_dict=True)
  2908. prefill_consumed = True
  2909. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  2910. model_kwargs = self._update_model_kwargs_for_generation(
  2911. model_outputs,
  2912. model_kwargs,
  2913. is_encoder_decoder=self.config.is_encoder_decoder,
  2914. )
  2915. if synced_gpus and this_peer_finished:
  2916. continue
  2917. # Copy is needed to avoid keeping a hanging ref
  2918. logits = model_outputs.logits[:, -1, :].to(copy=True, dtype=torch.float32, device=input_ids.device)
  2919. # b. Compute log probs -- get log probabilities from logits, process logits with processors (*e.g.*
  2920. # `temperature`, ...), and add new logprobs to existing running logprobs scores.
  2921. log_probs = nn.functional.log_softmax(logits, dim=-1)
  2922. log_probs = logits_processor(flat_running_sequences, log_probs)
  2923. # Store logits, attentions and hidden_states when required
  2924. if return_dict_in_generate:
  2925. if output_logits:
  2926. raw_logits += (logits.clone(),)
  2927. if return_dict_in_generate and output_scores:
  2928. all_scores += (log_probs.clone(),)
  2929. if output_attentions:
  2930. decoder_attentions += (
  2931. (model_outputs.decoder_attentions,)
  2932. if self.config.is_encoder_decoder
  2933. else (model_outputs.attentions,)
  2934. )
  2935. if self.config.is_encoder_decoder:
  2936. cross_attentions += (model_outputs.cross_attentions,)
  2937. if output_hidden_states:
  2938. decoder_hidden_states += (
  2939. (model_outputs.decoder_hidden_states,)
  2940. if self.config.is_encoder_decoder
  2941. else (model_outputs.hidden_states,)
  2942. )
  2943. # This is needed to properly delete logits which may be very large for first iteration
  2944. # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
  2945. del model_outputs
  2946. log_probs = self._unflatten_beam_dim(log_probs, batch_size, num_beams)
  2947. log_probs = log_probs + running_beam_scores[:, :, None]
  2948. log_probs = torch.reshape(log_probs, (batch_size, num_beams * vocab_size))
  2949. # c. Retrieve top-K continuations, i.e. select the next token (greedy or sampling) and then keep the best
  2950. # continuations among all beams based on the accumulated scores.
  2951. topk_log_probs, topk_running_sequences, topk_running_beam_indices = self._get_top_k_continuations(
  2952. accumulated_log_probs=log_probs,
  2953. running_sequences=running_sequences,
  2954. running_beam_indices=running_beam_indices,
  2955. cur_len=cur_len,
  2956. decoder_prompt_len=decoder_prompt_len,
  2957. do_sample=do_sample,
  2958. beams_to_keep=beams_to_keep,
  2959. num_beams=num_beams,
  2960. vocab_size=vocab_size,
  2961. batch_size=batch_size,
  2962. )
  2963. # d. Check which running sequences have finished
  2964. next_token_hits_stopping_criteria = stopping_criteria(
  2965. self._flatten_beam_dim(topk_running_sequences[:, :, : cur_len + 1]), # remove unfilled token indexes
  2966. all_scores,
  2967. )
  2968. next_token_hits_stopping_criteria = self._unflatten_beam_dim(
  2969. next_token_hits_stopping_criteria, batch_size, beams_to_keep
  2970. )
  2971. # e. Get the non-finished running `num_beams` sequences for the next generation step
  2972. running_sequences, running_beam_scores, running_beam_indices = self._get_running_beams_for_next_iteration(
  2973. topk_log_probs=topk_log_probs,
  2974. topk_running_sequences=topk_running_sequences,
  2975. topk_running_beam_indices=topk_running_beam_indices,
  2976. next_token_hits_stopping_criteria=next_token_hits_stopping_criteria,
  2977. num_beams=num_beams,
  2978. )
  2979. # f. Update the completed beams if a new high score in a finished sequence is found
  2980. sequences, beam_scores, beam_indices, is_sent_finished = self._update_finished_beams(
  2981. sequences=sequences,
  2982. topk_running_sequences=topk_running_sequences,
  2983. beam_scores=beam_scores,
  2984. topk_log_probs=topk_log_probs,
  2985. beam_indices=beam_indices,
  2986. topk_running_beam_indices=topk_running_beam_indices,
  2987. is_early_stop_heuristic_unsatisfied=is_early_stop_heuristic_unsatisfied,
  2988. is_sent_finished=is_sent_finished,
  2989. next_token_hits_stopping_criteria=next_token_hits_stopping_criteria,
  2990. top_num_beam_mask=top_num_beam_mask,
  2991. num_beams=num_beams,
  2992. cur_len=cur_len,
  2993. decoder_prompt_len=decoder_prompt_len,
  2994. length_penalty=length_penalty,
  2995. early_stopping=early_stopping,
  2996. )
  2997. # g. Prepare remaining data for the next iteration, including computing the stopping condition for
  2998. # beam search as a whole (as opposed to individual beams, i.e. `stopping_criteria`)
  2999. # pluck the cache from the beam indices that will be used in the next iteration
  3000. # NOTE: we need to check if `self._reorder_cache` exists for special models like RAG, RecurrentGemma etc.
  3001. if model_kwargs.get("past_key_values") is not None:
  3002. beam_idx = self._flatten_beam_dim(running_beam_indices[..., cur_len - decoder_prompt_len])
  3003. if hasattr(self, "_reorder_cache"):
  3004. model_kwargs["past_key_values"] = self._reorder_cache(model_kwargs["past_key_values"], beam_idx)
  3005. else:
  3006. model_kwargs["past_key_values"].reorder_cache(beam_idx)
  3007. cur_len = cur_len + 1
  3008. is_early_stop_heuristic_unsatisfied = self._check_early_stop_heuristic(
  3009. is_early_stop_heuristic_unsatisfied=is_early_stop_heuristic_unsatisfied,
  3010. running_beam_scores=running_beam_scores,
  3011. beam_scores=beam_scores,
  3012. is_sent_finished=is_sent_finished,
  3013. cur_len=cur_len,
  3014. max_length=max_length,
  3015. decoder_prompt_len=decoder_prompt_len,
  3016. early_stopping=early_stopping,
  3017. length_penalty=length_penalty,
  3018. )
  3019. this_peer_finished = not self._beam_search_has_unfinished_sequences(
  3020. is_early_stop_heuristic_unsatisfied,
  3021. is_sent_finished,
  3022. next_token_hits_stopping_criteria,
  3023. early_stopping,
  3024. )
  3025. # 5. prepare outputs
  3026. # Take best beams for each batch (the score is sorted in descending order)
  3027. sequences = self._flatten_beam_dim(sequences[:, :num_return_sequences, :])
  3028. beam_scores = self._flatten_beam_dim(beam_scores[:, :num_return_sequences])
  3029. beam_indices = self._flatten_beam_dim(beam_indices[:, :num_return_sequences, :])
  3030. # Crop the static-shaped tensors to the actual size.
  3031. # `beam_indices` is initialized with -1s, and is updated with the beam index of the generated token at each
  3032. # step. We can use it to detect the generated length, which may be != `cur_len` (e.g. selected beam is from a
  3033. # previous decoding iteration)
  3034. max_generated_length = ((beam_indices + 1).bool()).sum(dim=1).max()
  3035. output_length = decoder_prompt_len + max_generated_length
  3036. sequences = sequences[:, :output_length]
  3037. beam_indices = beam_indices[:, :max_generated_length]
  3038. if return_dict_in_generate:
  3039. if not output_scores:
  3040. beam_scores = None
  3041. cache = None
  3042. if any(cache_key in model_kwargs for cache_key in ALL_CACHE_NAMES):
  3043. cache_key = next(cache_key for cache_key in ALL_CACHE_NAMES if cache_key in model_kwargs)
  3044. cache = model_kwargs[cache_key]
  3045. if self.config.is_encoder_decoder:
  3046. return GenerateBeamEncoderDecoderOutput(
  3047. sequences=sequences,
  3048. sequences_scores=beam_scores,
  3049. scores=all_scores,
  3050. logits=raw_logits,
  3051. beam_indices=beam_indices,
  3052. encoder_attentions=encoder_attentions,
  3053. encoder_hidden_states=encoder_hidden_states,
  3054. decoder_attentions=decoder_attentions,
  3055. cross_attentions=cross_attentions,
  3056. decoder_hidden_states=decoder_hidden_states,
  3057. past_key_values=cache,
  3058. )
  3059. else:
  3060. return GenerateBeamDecoderOnlyOutput(
  3061. sequences=sequences,
  3062. sequences_scores=beam_scores,
  3063. scores=all_scores,
  3064. logits=raw_logits,
  3065. beam_indices=beam_indices,
  3066. attentions=decoder_attentions,
  3067. hidden_states=decoder_hidden_states,
  3068. past_key_values=cache,
  3069. )
  3070. else:
  3071. return sequences
  3072. def _assisted_decoding(
  3073. self: "GenerativePreTrainedModel",
  3074. input_ids: torch.LongTensor,
  3075. logits_processor: LogitsProcessorList,
  3076. stopping_criteria: StoppingCriteriaList,
  3077. generation_config: GenerationConfig,
  3078. synced_gpus: bool = False,
  3079. streamer: Optional["BaseStreamer"] = None,
  3080. inputs_tensor: torch.FloatTensor | None = None,
  3081. assistant_model: Optional["PreTrainedModel"] = None,
  3082. assistant_tokenizer: Optional["PreTrainedTokenizerBase"] = None,
  3083. tokenizer: Optional["PreTrainedTokenizerBase"] = None,
  3084. **model_kwargs,
  3085. ) -> GenerateNonBeamOutput | torch.LongTensor:
  3086. r"""
  3087. Generates sequences of token ids for models with a language modeling head using **greedy decoding** or
  3088. **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a
  3089. candidate decoding strategy. Can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text
  3090. models.
  3091. Parameters:
  3092. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  3093. The sequence used as a prompt for the generation.
  3094. logits_processor (`LogitsProcessorList`):
  3095. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  3096. used to modify the prediction scores of the language modeling head applied at each generation step.
  3097. stopping_criteria (`StoppingCriteriaList`):
  3098. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  3099. used to tell if the generation loop should stop.
  3100. generation_config ([`~generation.GenerationConfig`]):
  3101. The generation configuration to be used as parametrization of the decoding method.
  3102. synced_gpus (`bool`):
  3103. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  3104. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  3105. streamer (`BaseStreamer`, *optional*):
  3106. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  3107. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  3108. inputs_tensor (`torch.FloatTensor`, *optional*):
  3109. The input tensor for generation. For decoder models, usually `input_ids`. For encoder-decoder models,
  3110. the tensor that produced `model_kwargs["encoder_outputs"]`.
  3111. assistant_model (`PreTrainedModel`, *optional*):
  3112. The model used to assist the generation process. If not provided, the main model will be used.
  3113. assistant_tokenizer (`PreTrainedTokenizerBase`, *optional*):
  3114. The tokenizer used for the assistant model. If not provided, the token space is assumed to be the same.
  3115. tokenizer (`PreTrainedTokenizerBase`, *optional*):
  3116. The tokenizer used for the main model. If not provided, the token space is assumed to be the same.
  3117. model_kwargs:
  3118. Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
  3119. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  3120. Return:
  3121. [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
  3122. `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  3123. [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  3124. `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
  3125. `model.config.is_encoder_decoder=True`.
  3126. """
  3127. # The cache must be dynamic for assisted generation, and the check must happen AFTER preparing cache
  3128. if not model_kwargs["use_cache"]:
  3129. raise ValueError("assisted generate requires `use_cache=True`")
  3130. if (
  3131. generation_config.cache_implementation in ["static", "hybrid", "sliding_window"]
  3132. or type(model_kwargs.get("past_key_values")) is StaticCache
  3133. ):
  3134. raise ValueError("assisted generate is not supported with Static cache classes`")
  3135. # Get the candidate generator, given the parameterization
  3136. candidate_generator = self._get_candidate_generator(
  3137. generation_config=generation_config,
  3138. input_ids=input_ids,
  3139. inputs_tensor=inputs_tensor,
  3140. assistant_model=assistant_model,
  3141. logits_processor=logits_processor,
  3142. target_tokenizer=tokenizer,
  3143. assistant_tokenizer=assistant_tokenizer,
  3144. model_kwargs=model_kwargs,
  3145. )
  3146. # init values
  3147. do_sample = generation_config.do_sample
  3148. output_attentions = generation_config.output_attentions
  3149. output_hidden_states = generation_config.output_hidden_states
  3150. output_scores = generation_config.output_scores
  3151. output_logits = generation_config.output_logits
  3152. return_dict_in_generate = generation_config.return_dict_in_generate
  3153. # init attention / hidden states / scores tuples
  3154. scores = () if (return_dict_in_generate and output_scores) else None
  3155. raw_logits = () if (return_dict_in_generate and output_logits) else None
  3156. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  3157. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  3158. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  3159. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  3160. if return_dict_in_generate and self.config.is_encoder_decoder:
  3161. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  3162. encoder_hidden_states = (
  3163. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  3164. )
  3165. # keep track of which sequences are already finished
  3166. batch_size, cur_len = input_ids.shape[:2]
  3167. if batch_size > 1:
  3168. raise ValueError("assisted generate is only supported for batch_size = 1")
  3169. unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
  3170. this_peer_finished = False
  3171. is_first_iteration = True # to preserve the same API in the output as other generation methods
  3172. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  3173. cur_len = input_ids.shape[1]
  3174. # 1. Fetch candidate sequences from a `CandidateGenerator` and move to the correct device
  3175. candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)
  3176. candidate_input_ids = candidate_input_ids.to(self.device)
  3177. if candidate_logits is not None:
  3178. candidate_logits = candidate_logits.to(self.device)
  3179. candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]
  3180. is_done_candidate = stopping_criteria(candidate_input_ids, None)
  3181. # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain
  3182. # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,
  3183. # we use this forward pass to also pick the subsequent logits in the original model.
  3184. # 2.1. Prepare the model inputs
  3185. candidate_kwargs = copy.copy(model_kwargs)
  3186. candidate_kwargs = _prepare_attention_mask(
  3187. candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder
  3188. )
  3189. candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])
  3190. if (position_ids := candidate_kwargs.get("position_ids")) is not None and candidate_length > 0:
  3191. new_length = candidate_length + position_ids.shape[-1]
  3192. candidate_kwargs = _prepare_position_ids(candidate_kwargs, new_length, self.config.is_encoder_decoder)
  3193. next_sequence_length = candidate_length + 1 if not is_first_iteration else None
  3194. model_inputs = self.prepare_inputs_for_generation(
  3195. candidate_input_ids,
  3196. next_sequence_length=next_sequence_length,
  3197. is_first_iteration=is_first_iteration,
  3198. **candidate_kwargs,
  3199. )
  3200. if "logits_to_keep" in model_inputs:
  3201. model_inputs["logits_to_keep"] = candidate_length + 1
  3202. # 2.2. Run a forward pass on the candidate sequence
  3203. outputs = self(**model_inputs)
  3204. # 2.3. Process the new logits
  3205. # .float() is needed to retain precision for later logits manipulations
  3206. new_logits = outputs.logits[:, -candidate_length - 1 :].to(
  3207. dtype=torch.float32, device=input_ids.device
  3208. ) # excludes the input prompt if present
  3209. next_token_logits = new_logits.clone()
  3210. if len(logits_processor) > 0:
  3211. for i in range(candidate_length + 1):
  3212. new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])
  3213. # 3. Select the accepted tokens. There are two possible cases:
  3214. # Case 1: `do_sample=True` and we have logits for the candidates (originally from speculative decoding)
  3215. # 👉 Apply algorithm 1 from the speculative decoding paper (https://huggingface.co/papers/2211.17192).
  3216. if do_sample and candidate_logits is not None:
  3217. valid_tokens, n_matches = _speculative_sampling(
  3218. candidate_input_ids,
  3219. candidate_logits,
  3220. candidate_length,
  3221. new_logits,
  3222. is_done_candidate,
  3223. )
  3224. # Case 2: all other cases (originally from assisted generation) 👉 Compare the tokens selected from the
  3225. # original model logits with the candidate tokens. We can keep the candidate tokens until the first
  3226. # mismatch, or until the max length is reached.
  3227. else:
  3228. if do_sample:
  3229. probs = new_logits.softmax(dim=-1)
  3230. selected_tokens = torch.multinomial(probs[0, :, :], num_samples=1).squeeze(1)[None, :]
  3231. else:
  3232. selected_tokens = new_logits.argmax(dim=-1)
  3233. candidate_new_tokens = candidate_input_ids[:, cur_len:]
  3234. n_matches = ((~(candidate_new_tokens == selected_tokens[:, :-1])).cumsum(dim=-1) < 1).sum()
  3235. # Ensure we don't generate beyond max_len or an EOS token
  3236. if is_done_candidate and n_matches == candidate_length:
  3237. n_matches -= 1
  3238. valid_tokens = selected_tokens[:, : n_matches + 1]
  3239. # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated
  3240. # by the model after the last candidate match is also valid, as it is generated from a correct sequence.
  3241. # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there
  3242. # is no match.
  3243. # 4.1. Get the valid continuation, after the matching tokens
  3244. input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
  3245. if streamer is not None:
  3246. streamer.put(valid_tokens.cpu())
  3247. new_cur_len = input_ids.shape[1]
  3248. # 4.2. Discard past key values relative to unused assistant tokens
  3249. outputs.past_key_values.crop(new_cur_len - 1)
  3250. # 5. Update the candidate generation strategy if needed
  3251. candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)
  3252. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  3253. model_kwargs = self._update_model_kwargs_for_generation(
  3254. outputs,
  3255. model_kwargs,
  3256. is_encoder_decoder=self.config.is_encoder_decoder,
  3257. num_new_tokens=n_matches + 1,
  3258. )
  3259. if synced_gpus and this_peer_finished:
  3260. continue
  3261. # Store scores, attentions and hidden_states when required
  3262. # Assistant: modified to append one tuple element per token, as in the other generation methods.
  3263. if return_dict_in_generate:
  3264. newly_added_length = n_matches + 1
  3265. if output_scores:
  3266. scores += tuple(new_logits[:, i, :] for i in range(newly_added_length))
  3267. if output_logits:
  3268. raw_logits += tuple(next_token_logits[:, i, :] for i in range(newly_added_length))
  3269. newly_added_length = new_cur_len if is_first_iteration else newly_added_length
  3270. if output_attentions:
  3271. if self.config.is_encoder_decoder:
  3272. cross_attentions = _split_model_outputs(
  3273. cross_attentions, outputs.cross_attentions, cur_len, newly_added_length
  3274. )
  3275. decoder_attentions = _split_model_outputs(
  3276. decoder_attentions,
  3277. outputs.decoder_attentions,
  3278. cur_len,
  3279. newly_added_length,
  3280. is_decoder_attention=True,
  3281. )
  3282. # some (V)LLMs have hard requirement on SDPA and thus never return attn
  3283. elif outputs.attentions[0] is not None:
  3284. decoder_attentions = _split_model_outputs(
  3285. decoder_attentions,
  3286. outputs.attentions,
  3287. cur_len,
  3288. newly_added_length,
  3289. is_decoder_attention=True,
  3290. )
  3291. if output_hidden_states:
  3292. if self.config.is_encoder_decoder:
  3293. decoder_hidden_states = _split_model_outputs(
  3294. decoder_hidden_states, outputs.decoder_hidden_states, cur_len, newly_added_length
  3295. )
  3296. else:
  3297. decoder_hidden_states = _split_model_outputs(
  3298. decoder_hidden_states, outputs.hidden_states, cur_len, newly_added_length
  3299. )
  3300. unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
  3301. this_peer_finished = unfinished_sequences.max() == 0
  3302. is_first_iteration = False
  3303. if streamer is not None:
  3304. streamer.end()
  3305. if (
  3306. isinstance(candidate_generator, AssistedCandidateGenerator)
  3307. and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"
  3308. ):
  3309. candidate_generator.assistant_model.generation_config.num_assistant_tokens = (
  3310. candidate_generator.num_assistant_tokens
  3311. )
  3312. if return_dict_in_generate:
  3313. cache = None
  3314. if any(cache_key in model_kwargs for cache_key in ALL_CACHE_NAMES):
  3315. cache_key = next(cache_key for cache_key in ALL_CACHE_NAMES if cache_key in model_kwargs)
  3316. cache = model_kwargs[cache_key]
  3317. if self.config.is_encoder_decoder:
  3318. return GenerateEncoderDecoderOutput(
  3319. sequences=input_ids,
  3320. scores=scores,
  3321. logits=raw_logits,
  3322. encoder_attentions=encoder_attentions,
  3323. encoder_hidden_states=encoder_hidden_states,
  3324. decoder_attentions=decoder_attentions,
  3325. cross_attentions=cross_attentions,
  3326. decoder_hidden_states=decoder_hidden_states,
  3327. past_key_values=cache,
  3328. )
  3329. else:
  3330. return GenerateDecoderOnlyOutput(
  3331. sequences=input_ids,
  3332. scores=scores,
  3333. logits=raw_logits,
  3334. attentions=decoder_attentions,
  3335. hidden_states=decoder_hidden_states,
  3336. past_key_values=cache,
  3337. )
  3338. else:
  3339. return input_ids
  3340. # TODO: v5.1: make public once API stabilized
  3341. def _prefill(
  3342. self: "GenerativePreTrainedModel",
  3343. input_ids: torch.LongTensor,
  3344. generation_config: GenerationConfig,
  3345. model_kwargs: dict,
  3346. is_first_iteration: bool = True,
  3347. ):
  3348. """
  3349. Perform the prefill stage of generation.
  3350. Note that usually, the prefill stage is always the first iteration of a new input batch, and thus multimodal inputs etc
  3351. should be treated as if it's the first iteration. However, for assisted decoding, assistants call `generate`
  3352. several time in a row for a same batch of inputs, so we need to pass `is_first_iteration` here for such cases.
  3353. """
  3354. # When restarting from previous cache, the `input_ids` are either the FULL sequence, including previous inputs,
  3355. # or only the new tokens but in this case the attention_mask still contains the FULL sequence (because otherwise we may
  3356. # lose some early padding tokens information). So slice inputs according to that if needed
  3357. # When restarting from `inputs_embeds`, it's always the FULL sequence, and we always need to slice
  3358. next_sequence_length = None
  3359. inputs_embeds = model_kwargs.get("inputs_embeds")
  3360. use_inputs_embeds = False
  3361. if not self.config.is_encoder_decoder and inputs_embeds is not None and is_first_iteration:
  3362. use_inputs_embeds = True
  3363. if (cache := model_kwargs.get("past_key_values")) is not None:
  3364. past_length = cache.get_seq_length()
  3365. # It will be sliced as input_embeds = inputs_embeds[:, -next_sequence_length:, :] in `prepare_inputs_for_generation`
  3366. if use_inputs_embeds:
  3367. next_sequence_length = model_kwargs["inputs_embeds"].shape[1] - past_length
  3368. else:
  3369. attention_mask_key = "decoder_attention_mask" if self.config.is_encoder_decoder else "attention_mask"
  3370. attention_mask = model_kwargs.get(attention_mask_key)
  3371. # In this case we need to slice - if it's smaller than the mask, only the new inputs were passed -> no need to do anything
  3372. if attention_mask is not None and input_ids.shape[1] == attention_mask.shape[1]:
  3373. # inputs will be sliced as `input_ids[:, -next_sequence_length :]` in `prepare_inputs_for_generation`
  3374. next_sequence_length = input_ids.shape[1] - past_length
  3375. # Usual prefill
  3376. if generation_config.prefill_chunk_size is None:
  3377. model_inputs = self.prepare_inputs_for_generation(
  3378. input_ids,
  3379. next_sequence_length=next_sequence_length,
  3380. is_first_iteration=is_first_iteration,
  3381. **model_kwargs,
  3382. )
  3383. return self(**model_inputs, return_dict=True)
  3384. # Chunked prefill (for very large contexts)
  3385. else:
  3386. # Even if we are not compiling the forward, flex is always compiled when used. With chunked prefill, we may
  3387. # end up needing just a bit more graphs than the default (which is 8). Doing this avoids very cryptic warnings
  3388. getattr(torch, "_dynamo").config.cache_size_limit = 64
  3389. chunk_size = generation_config.prefill_chunk_size
  3390. input_chunks = torch.split(input_ids, chunk_size, dim=-1)
  3391. if "past_key_values" not in model_kwargs:
  3392. raise ValueError("Cannot use prefill chunking without a cache")
  3393. model_forward = (
  3394. self.get_compiled_call(generation_config.compile_config)
  3395. if self._valid_auto_compile_criteria(model_kwargs, generation_config)
  3396. else self.__call__
  3397. )
  3398. attention_mask = model_kwargs.pop("attention_mask", None)
  3399. position_ids = model_kwargs.pop("position_ids", None)
  3400. past_length = 0
  3401. for input_chunk in input_chunks:
  3402. current_length = past_length + input_chunk.shape[-1]
  3403. if attention_mask is not None:
  3404. model_kwargs["attention_mask"] = attention_mask[:, :current_length]
  3405. if position_ids is not None:
  3406. model_kwargs["position_ids"] = position_ids[:, past_length:current_length]
  3407. model_inputs = self.prepare_inputs_for_generation(input_chunk, **model_kwargs)
  3408. outputs = model_forward(**model_inputs, return_dict=True)
  3409. model_kwargs["past_key_values"] = outputs.past_key_values
  3410. past_length = current_length
  3411. # Recreate the kwargs based on the full length
  3412. model_kwargs["attention_mask"] = attention_mask
  3413. model_kwargs["position_ids"] = position_ids
  3414. # Latest outputs contain next token logits
  3415. return outputs
  3416. def _speculative_sampling(
  3417. candidate_input_ids,
  3418. candidate_logits,
  3419. candidate_length,
  3420. new_logits,
  3421. is_done_candidate,
  3422. ):
  3423. """
  3424. Applies sampling as in the speculative decoding paper (https://huggingface.co/papers/2211.17192, algorithm 1). Returns
  3425. the selected tokens, as well as the number of candidate matches.
  3426. NOTE: Unless otherwise stated, the variable names match those in the paper.
  3427. """
  3428. new_candidate_input_ids = candidate_input_ids[:, -candidate_length:]
  3429. # Gets the probabilities from the logits. q_i and p_i denote the assistant and model probabilities of the tokens
  3430. # selected by the assistant, respectively.
  3431. q = candidate_logits.softmax(dim=-1)
  3432. q_i = q[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
  3433. p = new_logits.softmax(dim=-1)
  3434. p_i = p[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
  3435. probability_ratio = p_i / q_i
  3436. # When probability_ratio > 1 (i.e. q_i(x) < p_i(x), or "assistant probability of the candidate token is smaller
  3437. # than the model probability for the same token"), keep the token. Otherwise reject with p = 1 - probability_ratio
  3438. # (= keep with p = probability_ratio). Keep all the tokens until the first rejection
  3439. r_i = torch.rand_like(probability_ratio)
  3440. is_accepted = r_i <= probability_ratio
  3441. n_matches = ((~is_accepted).cumsum(dim=-1) < 1).sum() # this is `n` in algorithm 1
  3442. # Ensure we don't generate beyond max_len or an EOS token (not in algorithm 1, but needed for correct behavior)
  3443. if is_done_candidate and n_matches == candidate_length:
  3444. # Output length is assumed to be `n_matches + 1`. Since we won't generate another token with the target model
  3445. # due to acceptance on EOS we fix `n_matches`
  3446. n_matches -= 1
  3447. valid_tokens = new_candidate_input_ids[:, : n_matches + 1]
  3448. else:
  3449. # Next token selection: if there is a rejection, adjust the distribution from the main model before sampling.
  3450. gamma = candidate_logits.shape[1]
  3451. p_n_plus_1 = p[:, n_matches, :]
  3452. if n_matches < gamma:
  3453. q_n_plus_1 = q[:, n_matches, :]
  3454. p_prime = torch.clamp((p_n_plus_1 - q_n_plus_1), min=0)
  3455. p_prime.div_(p_prime.sum())
  3456. else:
  3457. p_prime = p_n_plus_1
  3458. t = torch.multinomial(p_prime, num_samples=1).squeeze(1)[None, :]
  3459. # The selected tokens include the matches (if any) plus the next sampled tokens
  3460. if n_matches > 0:
  3461. valid_tokens = torch.cat((new_candidate_input_ids[:, :n_matches], t), dim=-1)
  3462. else:
  3463. valid_tokens = t
  3464. return valid_tokens, n_matches
  3465. def _split_model_outputs(outputs, new_outputs, cur_len, added_len, is_decoder_attention=False):
  3466. """
  3467. Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple
  3468. where each member corresponds to a single generated token.
  3469. """
  3470. # Retrocompatibility: in our generation functions, the first iteration includes the attention/hidden states for the
  3471. # prompt.
  3472. if len(outputs) == 0:
  3473. new_tuple = ()
  3474. for layer in new_outputs:
  3475. last_dim_size = cur_len if is_decoder_attention else layer.shape[-1]
  3476. new_tuple += (layer[..., :cur_len, :last_dim_size],)
  3477. outputs += (new_tuple,)
  3478. # The first iteration contains the prompt + 1 generated token, let's update the length variables accordingly
  3479. cur_len += 1
  3480. added_len -= cur_len
  3481. for i in range(added_len):
  3482. new_tuple = ()
  3483. for layer in new_outputs:
  3484. last_dim_size = cur_len + i if is_decoder_attention else layer.shape[-1]
  3485. new_tuple += (layer[..., i : i + 1, :last_dim_size],)
  3486. outputs += (new_tuple,)
  3487. return outputs