utils.py 247 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740
  1. # coding=utf-8
  2. # Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import copy
  17. import inspect
  18. import warnings
  19. from dataclasses import dataclass
  20. from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
  21. import numpy as np
  22. import torch
  23. import torch.distributed as dist
  24. from torch import nn
  25. from torch.nn import functional as F
  26. from ..cache_utils import (
  27. Cache,
  28. DynamicCache,
  29. EncoderDecoderCache,
  30. OffloadedCache,
  31. QuantizedCacheConfig,
  32. StaticCache,
  33. )
  34. from ..configuration_utils import PretrainedConfig
  35. from ..integrations.deepspeed import is_deepspeed_zero3_enabled
  36. from ..integrations.fsdp import is_fsdp_managed_module
  37. from ..modeling_outputs import CausalLMOutputWithPast, Seq2SeqLMOutput
  38. from ..pytorch_utils import isin_mps_friendly
  39. from ..tokenization_utils import ExtensionsTrie
  40. from ..utils import (
  41. ModelOutput,
  42. is_accelerate_available,
  43. is_hqq_available,
  44. is_optimum_quanto_available,
  45. is_quanto_available,
  46. is_torchdynamo_compiling,
  47. logging,
  48. )
  49. from .beam_constraints import DisjunctiveConstraint, PhrasalConstraint
  50. from .beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
  51. from .candidate_generator import (
  52. AssistedCandidateGenerator,
  53. AssistedCandidateGeneratorDifferentTokenizers,
  54. CandidateGenerator,
  55. PromptLookupCandidateGenerator,
  56. _crop_past_key_values,
  57. _prepare_attention_mask,
  58. _prepare_token_type_ids,
  59. )
  60. from .configuration_utils import (
  61. NEED_SETUP_CACHE_CLASSES_MAPPING,
  62. QUANT_BACKEND_CLASSES_MAPPING,
  63. GenerationConfig,
  64. GenerationMode,
  65. )
  66. from .logits_process import (
  67. EncoderNoRepeatNGramLogitsProcessor,
  68. EncoderRepetitionPenaltyLogitsProcessor,
  69. EpsilonLogitsWarper,
  70. EtaLogitsWarper,
  71. ExponentialDecayLengthPenalty,
  72. ForcedBOSTokenLogitsProcessor,
  73. ForcedEOSTokenLogitsProcessor,
  74. HammingDiversityLogitsProcessor,
  75. InfNanRemoveLogitsProcessor,
  76. LogitNormalization,
  77. LogitsProcessorList,
  78. MinLengthLogitsProcessor,
  79. MinNewTokensLengthLogitsProcessor,
  80. MinPLogitsWarper,
  81. NoBadWordsLogitsProcessor,
  82. NoRepeatNGramLogitsProcessor,
  83. PrefixConstrainedLogitsProcessor,
  84. RepetitionPenaltyLogitsProcessor,
  85. SequenceBiasLogitsProcessor,
  86. SuppressTokensAtBeginLogitsProcessor,
  87. SuppressTokensLogitsProcessor,
  88. TemperatureLogitsWarper,
  89. TopKLogitsWarper,
  90. TopPLogitsWarper,
  91. TypicalLogitsWarper,
  92. UnbatchedClassifierFreeGuidanceLogitsProcessor,
  93. )
  94. from .stopping_criteria import (
  95. ConfidenceCriteria,
  96. EosTokenCriteria,
  97. MaxLengthCriteria,
  98. MaxTimeCriteria,
  99. StoppingCriteria,
  100. StoppingCriteriaList,
  101. StopStringCriteria,
  102. )
  103. if TYPE_CHECKING:
  104. from ..modeling_utils import PreTrainedModel
  105. from ..tokenization_utils_base import PreTrainedTokenizerBase
  106. from .streamers import BaseStreamer
  107. logger = logging.get_logger(__name__)
  108. if is_accelerate_available():
  109. from accelerate.hooks import AlignDevicesHook, add_hook_to_module
  110. @dataclass
  111. class GenerateDecoderOnlyOutput(ModelOutput):
  112. """
  113. Outputs of decoder-only generation models, when using non-beam methods.
  114. Args:
  115. sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  116. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  117. if all batches finished early due to the `eos_token_id`.
  118. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  119. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  120. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  121. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  122. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  123. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  124. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  125. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  126. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  127. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  128. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  129. hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  130. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  131. `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
  132. past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
  133. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  134. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  135. """
  136. sequences: torch.LongTensor = None
  137. scores: Optional[Tuple[torch.FloatTensor]] = None
  138. logits: Optional[Tuple[torch.FloatTensor]] = None
  139. attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  140. hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  141. past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
  142. @dataclass
  143. class GenerateEncoderDecoderOutput(ModelOutput):
  144. """
  145. Outputs of encoder-decoder generation models, when using non-beam methods.
  146. Args:
  147. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  148. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  149. if all batches finished early due to the `eos_token_id`.
  150. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  151. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  152. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  153. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  154. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  155. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  156. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  157. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  158. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
  159. Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
  160. sequence_length, sequence_length)`.
  161. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
  162. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  163. shape `(batch_size, sequence_length, hidden_size)`.
  164. decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  165. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  166. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  167. cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  168. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  169. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  170. decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  171. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  172. `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
  173. past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  174. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  175. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  176. """
  177. sequences: torch.LongTensor = None
  178. scores: Optional[Tuple[torch.FloatTensor]] = None
  179. logits: Optional[Tuple[torch.FloatTensor]] = None
  180. encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
  181. encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
  182. decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  183. cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  184. decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  185. past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
  186. @dataclass
  187. class GenerateBeamDecoderOnlyOutput(ModelOutput):
  188. """
  189. Outputs of decoder-only generation models, when using beam methods.
  190. Args:
  191. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  192. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  193. if all batches finished early due to the `eos_token_id`.
  194. sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
  195. Final beam scores of the generated `sequences`.
  196. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  197. Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  198. of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
  199. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
  200. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  201. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  202. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  203. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  204. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  205. beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
  206. Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
  207. `(batch_size*num_return_sequences, sequence_length)`.
  208. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  209. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  210. `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
  211. hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  212. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  213. `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
  214. past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
  215. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  216. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  217. """
  218. sequences: torch.LongTensor = None
  219. sequences_scores: Optional[torch.FloatTensor] = None
  220. scores: Optional[Tuple[torch.FloatTensor]] = None
  221. logits: Optional[Tuple[torch.FloatTensor]] = None
  222. beam_indices: Optional[torch.LongTensor] = None
  223. attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  224. hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  225. past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
  226. @dataclass
  227. class GenerateBeamEncoderDecoderOutput(ModelOutput):
  228. """
  229. Outputs of encoder-decoder generation models, when using beam methods.
  230. Args:
  231. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  232. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  233. if all batches finished early due to the `eos_token_id`.
  234. sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
  235. Final beam scores of the generated `sequences`.
  236. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
  237. Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  238. of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
  239. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
  240. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  241. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
  242. Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  243. at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
  244. each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  245. beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
  246. Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
  247. `(batch_size*num_return_sequences, sequence_length)`.
  248. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
  249. Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
  250. sequence_length, sequence_length)`.
  251. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
  252. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  253. shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
  254. decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  255. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  256. `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
  257. sequence_length)`.
  258. cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
  259. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  260. `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  261. decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
  262. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  263. `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
  264. past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
  265. Returns the model cache, used to speed up decoding. Different models have a different cache format, check
  266. the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
  267. """
  268. sequences: torch.LongTensor = None
  269. sequences_scores: Optional[torch.FloatTensor] = None
  270. scores: Optional[Tuple[torch.FloatTensor]] = None
  271. logits: Optional[Tuple[torch.FloatTensor]] = None
  272. beam_indices: Optional[torch.LongTensor] = None
  273. encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
  274. encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
  275. decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  276. cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  277. decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
  278. past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
  279. # TODO (joao): remove the equivalent classes and typing shortcuts below in v5
  280. # Equivalent classes (kept for retrocompatibility purposes)
  281. GreedySearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
  282. ContrastiveSearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
  283. SampleDecoderOnlyOutput = GenerateDecoderOnlyOutput
  284. ContrastiveSearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
  285. GreedySearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
  286. SampleEncoderDecoderOutput = GenerateEncoderDecoderOutput
  287. BeamSearchDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
  288. BeamSampleDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
  289. BeamSearchEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
  290. BeamSampleEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
  291. GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]
  292. SampleOutput = Union[SampleEncoderDecoderOutput, SampleDecoderOnlyOutput]
  293. BeamSearchOutput = Union[BeamSearchEncoderDecoderOutput, BeamSearchDecoderOnlyOutput]
  294. BeamSampleOutput = Union[BeamSampleEncoderDecoderOutput, BeamSampleDecoderOnlyOutput]
  295. ContrastiveSearchOutput = Union[ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput]
  296. # Typing shortcuts
  297. GenerateNonBeamOutput = Union[GenerateDecoderOnlyOutput, GenerateEncoderDecoderOutput]
  298. GenerateBeamOutput = Union[GenerateBeamDecoderOnlyOutput, GenerateBeamEncoderDecoderOutput]
  299. GenerateOutput = Union[GenerateNonBeamOutput, GenerateBeamOutput]
  300. class GenerationMixin:
  301. """
  302. A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].
  303. The class exposes [`~generation.GenerationMixin.generate`], which can be used for:
  304. - *greedy decoding* if `num_beams=1` and `do_sample=False`
  305. - *contrastive search* if `penalty_alpha>0` and `top_k>1`
  306. - *multinomial sampling* if `num_beams=1` and `do_sample=True`
  307. - *beam-search decoding* if `num_beams>1` and `do_sample=False`
  308. - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
  309. - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
  310. - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
  311. - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
  312. To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
  313. """
  314. def prepare_inputs_for_generation(
  315. self,
  316. input_ids: torch.LongTensor,
  317. past_key_values: Optional[Cache] = None,
  318. attention_mask: Optional[torch.LongTensor] = None,
  319. inputs_embeds: Optional[torch.FloatTensor] = None,
  320. cache_position: Optional[torch.LongTensor] = None,
  321. **kwargs,
  322. ):
  323. """
  324. Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or
  325. slicing inputs given the existing cache.
  326. See the forward pass in the model documentation for expected arguments (different models might have different
  327. requirements for e.g. `past_key_values`). This function should work as is for most LLMs.
  328. """
  329. # 1. Handle BC:
  330. model_inputs = {}
  331. # - some models don't have `Cache` support (which implies they don't expect `cache_position` in `forward`)
  332. if self._supports_cache_class:
  333. model_inputs["cache_position"] = cache_position
  334. # - `cache_position` was not a mandatory input in `prepare_inputs_for_generation` for those models, and this
  335. # function may be called outside of `generate`. Handle most use cases by creating `cache_position` on the fly
  336. # (this alternative is not as robust as calling `generate` and letting it create `cache_position`)
  337. elif cache_position is None:
  338. past_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
  339. cache_position = torch.arange(past_length, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
  340. # 2. Generic cache-dependent input preparation
  341. # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
  342. # Exception 1: when passing input_embeds, input_ids may be missing entries
  343. # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
  344. # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case
  345. if past_key_values is not None:
  346. model_inputs["past_key_values"] = past_key_values
  347. if inputs_embeds is not None or cache_position[-1] >= input_ids.shape[1]: # Exception 1 or Exception 3
  348. input_ids = input_ids[:, -cache_position.shape[0] :]
  349. elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
  350. input_ids = input_ids[:, cache_position]
  351. # 3. Prepare base model inputs
  352. input_ids_key = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  353. # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
  354. if not self.config.is_encoder_decoder:
  355. if inputs_embeds is not None and cache_position[0] == 0:
  356. model_inputs[input_ids_key] = None
  357. model_inputs["inputs_embeds"] = inputs_embeds
  358. else:
  359. # `clone` calls in this function ensure a consistent stride. See #32227
  360. model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
  361. model_inputs["inputs_embeds"] = None
  362. else:
  363. model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
  364. # 4. Create missing `position_ids` on the fly
  365. if (
  366. attention_mask is not None
  367. and kwargs.get("position_ids") is None
  368. and "position_ids" in set(inspect.signature(self.forward).parameters.keys())
  369. ):
  370. position_ids = attention_mask.long().cumsum(-1) - 1
  371. position_ids.masked_fill_(attention_mask == 0, 1)
  372. kwargs["position_ids"] = position_ids # placed in kwargs for further processing (see below)
  373. # 5. Slice model inputs if it's an input that should have the same length as `input_ids`
  374. for model_input_name in ["position_ids", "token_type_ids"]:
  375. model_input = kwargs.get(model_input_name)
  376. if model_input is not None:
  377. if past_key_values:
  378. model_input = model_input[:, -input_ids.shape[1] :]
  379. model_input = model_input.clone(memory_format=torch.contiguous_format)
  380. model_inputs[model_input_name] = model_input
  381. # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)
  382. if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
  383. if model_inputs["inputs_embeds"] is not None:
  384. batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
  385. device = model_inputs["inputs_embeds"].device
  386. else:
  387. batch_size, sequence_length = model_inputs[input_ids_key].shape
  388. device = model_inputs[input_ids_key].device
  389. # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create
  390. # the 4D causal mask exists, it should be present in the base model (XXXModel class).
  391. base_model = getattr(self, self.base_model_prefix, None)
  392. if base_model is None:
  393. causal_mask_creation_function = getattr(
  394. self, "_prepare_4d_causal_attention_mask_with_cache_position", None
  395. )
  396. else:
  397. causal_mask_creation_function = getattr(
  398. base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None
  399. )
  400. if causal_mask_creation_function is None:
  401. logger.warning_once(
  402. f"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method "
  403. "defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're "
  404. "writing code, see Llama for an example implementation. If you're a user, please report this "
  405. "issue on GitHub."
  406. )
  407. else:
  408. attention_mask = causal_mask_creation_function(
  409. attention_mask,
  410. sequence_length=sequence_length,
  411. target_length=past_key_values.get_max_cache_shape(),
  412. dtype=self.dtype,
  413. device=device,
  414. cache_position=cache_position,
  415. batch_size=batch_size,
  416. config=self.config,
  417. past_key_values=past_key_values,
  418. )
  419. if attention_mask is not None:
  420. model_inputs["attention_mask"] = attention_mask
  421. # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
  422. for key, value in kwargs.items():
  423. if key not in model_inputs:
  424. model_inputs[key] = value
  425. # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
  426. model_inputs.pop("labels", None)
  427. return model_inputs
  428. def _prepare_model_inputs(
  429. self,
  430. inputs: Optional[torch.Tensor] = None,
  431. bos_token_id: Optional[torch.Tensor] = None,
  432. model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
  433. ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:
  434. """
  435. This function extracts the model-specific `inputs` for generation.
  436. """
  437. # 1. retrieve all kwargs that are non-None or non-model input related.
  438. # some encoder-decoder models have different names for model and encoder
  439. if (
  440. self.config.is_encoder_decoder
  441. and hasattr(self, "encoder")
  442. and self.encoder.main_input_name != self.main_input_name
  443. ):
  444. input_name = self.encoder.main_input_name
  445. else:
  446. input_name = self.main_input_name
  447. model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}
  448. # 2. check whether model_input_name is passed as kwarg
  449. # if yes and `inputs` is None use kwarg inputs
  450. inputs_kwarg = model_kwargs.pop(input_name, None)
  451. if inputs_kwarg is not None and inputs is not None:
  452. raise ValueError(
  453. f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
  454. f"Make sure to either pass {inputs} or {input_name}=..."
  455. )
  456. elif inputs_kwarg is not None:
  457. inputs = inputs_kwarg
  458. # 3. In the presence of `inputs_embeds` for text models:
  459. # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
  460. # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
  461. # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
  462. # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
  463. # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
  464. if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
  465. if not self.config.is_encoder_decoder:
  466. has_inputs_embeds_forwarding = "inputs_embeds" in set(
  467. inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
  468. )
  469. if not has_inputs_embeds_forwarding:
  470. raise ValueError(
  471. f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
  472. "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
  473. "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
  474. )
  475. # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
  476. # the attention mask) can rely on the actual model input.
  477. model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
  478. inputs, bos_token_id, model_kwargs=model_kwargs
  479. )
  480. else:
  481. if inputs is not None:
  482. raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
  483. inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
  484. # 4. if `inputs` is still None, try to create `input_ids` from BOS token
  485. inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
  486. return inputs, input_name, model_kwargs
  487. def _maybe_initialize_input_ids_for_generation(
  488. self,
  489. inputs: Optional[torch.Tensor] = None,
  490. bos_token_id: Optional[torch.Tensor] = None,
  491. model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
  492. ) -> torch.LongTensor:
  493. """Initializes input ids for generation, if necessary."""
  494. if inputs is not None:
  495. return inputs
  496. encoder_outputs = model_kwargs.get("encoder_outputs")
  497. if self.config.is_encoder_decoder and encoder_outputs is not None:
  498. # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
  499. shape = encoder_outputs.last_hidden_state.size()[:-1]
  500. return torch.ones(shape, dtype=torch.long, device=self.device) * -100
  501. # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
  502. # soft-prompting or in multimodal implementations built on top of decoder-only language models.
  503. batch_size = 1
  504. for value in model_kwargs.values():
  505. if isinstance(value, torch.Tensor):
  506. batch_size = value.shape[0]
  507. break
  508. if "inputs_embeds" in model_kwargs:
  509. return torch.ones((batch_size, 0), dtype=torch.long, device=self.device)
  510. if bos_token_id is None:
  511. raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
  512. return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id
  513. def _prepare_attention_mask_for_generation(
  514. self,
  515. inputs: torch.Tensor,
  516. pad_token_id: Optional[torch.Tensor],
  517. eos_token_id: Optional[torch.Tensor],
  518. ) -> torch.LongTensor:
  519. # No information for attention mask inference -> return default attention mask
  520. default_attention_mask = torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device)
  521. if pad_token_id is None:
  522. return default_attention_mask
  523. is_input_ids = len(inputs.shape) == 2 and inputs.dtype in [torch.int, torch.long]
  524. if not is_input_ids:
  525. return default_attention_mask
  526. is_pad_token_in_inputs = (pad_token_id is not None) and (
  527. isin_mps_friendly(elements=inputs, test_elements=pad_token_id).any()
  528. )
  529. is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or ~(
  530. isin_mps_friendly(elements=eos_token_id, test_elements=pad_token_id).any()
  531. )
  532. can_infer_attention_mask = is_pad_token_in_inputs * is_pad_token_not_equal_to_eos_token_id
  533. attention_mask_from_padding = inputs.ne(pad_token_id).long()
  534. attention_mask = (
  535. attention_mask_from_padding * can_infer_attention_mask + default_attention_mask * ~can_infer_attention_mask
  536. )
  537. return attention_mask
  538. def _prepare_encoder_decoder_kwargs_for_generation(
  539. self,
  540. inputs_tensor: torch.Tensor,
  541. model_kwargs,
  542. model_input_name: Optional[str],
  543. generation_config: GenerationConfig,
  544. ) -> Dict[str, Any]:
  545. # 1. get encoder
  546. encoder = self.get_encoder()
  547. # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device
  548. # as the inputs.
  549. if hasattr(self, "hf_device_map"):
  550. if hasattr(encoder, "_hf_hook"):
  551. encoder._hf_hook.io_same_device = True
  552. else:
  553. add_hook_to_module(encoder, AlignDevicesHook(io_same_device=True))
  554. # 2. Prepare encoder args and encoder kwargs from model kwargs and generation config.
  555. irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
  556. encoder_kwargs = {
  557. argument: value
  558. for argument, value in model_kwargs.items()
  559. if not any(argument.startswith(p) for p in irrelevant_prefix)
  560. }
  561. encoder_signature = set(inspect.signature(encoder.forward).parameters)
  562. encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
  563. if not encoder_accepts_wildcard:
  564. encoder_kwargs = {
  565. argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
  566. }
  567. encoder_kwargs["output_attentions"] = generation_config.output_attentions
  568. encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states
  569. # 3. make sure that encoder returns `ModelOutput`
  570. model_input_name = model_input_name if model_input_name is not None else self.main_input_name
  571. encoder_kwargs["return_dict"] = True
  572. encoder_kwargs[model_input_name] = inputs_tensor
  573. model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs) # type: ignore
  574. return model_kwargs
  575. def _prepare_decoder_input_ids_for_generation(
  576. self,
  577. batch_size: int,
  578. model_input_name: str,
  579. model_kwargs: Dict[str, torch.Tensor],
  580. decoder_start_token_id: torch.Tensor,
  581. device: torch.device = None,
  582. ) -> Tuple[torch.LongTensor, Dict[str, torch.Tensor]]:
  583. """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
  584. # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
  585. # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
  586. if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
  587. decoder_input_ids = model_kwargs.pop("decoder_input_ids")
  588. elif "input_ids" in model_kwargs and model_input_name != "input_ids":
  589. decoder_input_ids = model_kwargs.pop("input_ids")
  590. else:
  591. decoder_input_ids = None
  592. # 2. `decoder_start_token_id` must have shape (batch_size, 1)
  593. if device is None:
  594. device = self.device
  595. if decoder_start_token_id.ndim == 1:
  596. if decoder_start_token_id.shape[0] != batch_size:
  597. raise ValueError(
  598. f"`decoder_start_token_id` expected to have length {batch_size} but got {decoder_start_token_id.shape[0]}"
  599. )
  600. decoder_start_token_id = decoder_start_token_id.view(-1, 1)
  601. else:
  602. decoder_start_token_id = (
  603. torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id
  604. )
  605. # 3. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
  606. # no user input -> use decoder_start_token_id as decoder_input_ids
  607. if decoder_input_ids is None:
  608. decoder_input_ids = decoder_start_token_id
  609. # exception: Donut checkpoints have task-specific decoder starts and don't expect a BOS token. Note that the
  610. # original checkpoints can't be detected through `self.__class__.__name__.lower()`, needing custom logic.
  611. # See: https://github.com/huggingface/transformers/pull/31470
  612. elif "donut" in self.__class__.__name__.lower() or (
  613. self.config.model_type == "vision-encoder-decoder" and "donut" in self.config.encoder.model_type.lower()
  614. ):
  615. pass
  616. elif self.config.model_type in ["whisper"]:
  617. pass
  618. # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
  619. # decoder_attention_mask if provided)
  620. elif (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item():
  621. decoder_input_ids = torch.cat([decoder_start_token_id, decoder_input_ids], dim=-1)
  622. if "decoder_attention_mask" in model_kwargs:
  623. decoder_attention_mask = model_kwargs["decoder_attention_mask"]
  624. decoder_attention_mask = torch.cat(
  625. (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
  626. dim=-1,
  627. )
  628. model_kwargs["decoder_attention_mask"] = decoder_attention_mask
  629. return decoder_input_ids, model_kwargs
  630. @staticmethod
  631. def _expand_inputs_for_generation(
  632. expand_size: int = 1,
  633. is_encoder_decoder: bool = False,
  634. input_ids: Optional[torch.LongTensor] = None,
  635. **model_kwargs,
  636. ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
  637. """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
  638. # Do not call torch.repeat_interleave if expand_size is 1 because it clones
  639. # the input tensor and thus requires more memory although no change is applied
  640. if expand_size == 1:
  641. return input_ids, model_kwargs
  642. def _expand_dict_for_generation(dict_to_expand):
  643. for key in dict_to_expand:
  644. if (
  645. key != "cache_position"
  646. and dict_to_expand[key] is not None
  647. and isinstance(dict_to_expand[key], torch.Tensor)
  648. ):
  649. dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
  650. return dict_to_expand
  651. if input_ids is not None:
  652. input_ids = input_ids.repeat_interleave(expand_size, dim=0)
  653. model_kwargs = _expand_dict_for_generation(model_kwargs)
  654. if is_encoder_decoder:
  655. if model_kwargs.get("encoder_outputs") is None:
  656. raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
  657. model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
  658. return input_ids, model_kwargs
  659. def _extract_past_from_model_output(self, outputs: ModelOutput):
  660. past_key_values = None
  661. cache_name = "past_key_values"
  662. if "past_key_values" in outputs:
  663. past_key_values = outputs.past_key_values
  664. elif "mems" in outputs:
  665. past_key_values = outputs.mems
  666. elif "past_buckets_states" in outputs:
  667. past_key_values = outputs.past_buckets_states
  668. elif "cache_params" in outputs:
  669. past_key_values = outputs.cache_params
  670. cache_name = "cache_params"
  671. return cache_name, past_key_values
  672. def _update_model_kwargs_for_generation(
  673. self,
  674. outputs: ModelOutput,
  675. model_kwargs: Dict[str, Any],
  676. is_encoder_decoder: bool = False,
  677. num_new_tokens: int = 1,
  678. ) -> Dict[str, Any]:
  679. # update past_key_values keeping its naming used in model code
  680. cache_name, cache = self._extract_past_from_model_output(outputs)
  681. model_kwargs[cache_name] = cache
  682. if getattr(outputs, "state", None) is not None:
  683. model_kwargs["state"] = outputs.state
  684. # update token_type_ids with last value
  685. if "token_type_ids" in model_kwargs:
  686. token_type_ids = model_kwargs["token_type_ids"]
  687. model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
  688. if not is_encoder_decoder:
  689. # update attention mask
  690. if "attention_mask" in model_kwargs:
  691. attention_mask = model_kwargs["attention_mask"]
  692. model_kwargs["attention_mask"] = torch.cat(
  693. [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
  694. )
  695. else:
  696. # update decoder attention mask
  697. if "decoder_attention_mask" in model_kwargs:
  698. decoder_attention_mask = model_kwargs["decoder_attention_mask"]
  699. model_kwargs["decoder_attention_mask"] = torch.cat(
  700. [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
  701. dim=-1,
  702. )
  703. if model_kwargs.get("use_cache", True):
  704. model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
  705. else:
  706. past_positions = model_kwargs.pop("cache_position")
  707. new_positions = torch.arange(
  708. past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype
  709. ).to(past_positions.device)
  710. model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))
  711. return model_kwargs
  712. def _reorder_cache(self, past_key_values, beam_idx):
  713. raise NotImplementedError(
  714. f"Make sure that a `_reorder_cache` function is correctly implemented in {self.__class__.__module__} to"
  715. f" enable beam search for {self.__class__}"
  716. )
  717. def _get_candidate_generator(
  718. self,
  719. generation_config: GenerationConfig,
  720. input_ids: torch.LongTensor,
  721. inputs_tensor: torch.Tensor,
  722. assistant_model: "PreTrainedModel",
  723. logits_processor: LogitsProcessorList,
  724. target_tokenizer: "PreTrainedTokenizerBase",
  725. assistant_tokenizer: "PreTrainedTokenizerBase",
  726. model_kwargs: Dict,
  727. ) -> CandidateGenerator:
  728. """
  729. Returns the candidate generator to be used in `assisted_generation`
  730. """
  731. different_tokenizers = all(v is not None for v in (assistant_model, target_tokenizer, assistant_tokenizer))
  732. if generation_config.prompt_lookup_num_tokens is not None:
  733. candidate_generator = PromptLookupCandidateGenerator(
  734. eos_token_id=generation_config._eos_token_tensor,
  735. num_output_tokens=generation_config.prompt_lookup_num_tokens,
  736. max_matching_ngram_size=generation_config.max_matching_ngram_size,
  737. max_length=generation_config.max_length,
  738. )
  739. elif different_tokenizers:
  740. candidate_generator = AssistedCandidateGeneratorDifferentTokenizers(
  741. input_ids=input_ids,
  742. assistant_model=assistant_model,
  743. generation_config=generation_config,
  744. model_kwargs=model_kwargs,
  745. inputs_tensor=inputs_tensor,
  746. logits_processor=logits_processor,
  747. target_tokenizer=target_tokenizer,
  748. assistant_tokenizer=assistant_tokenizer,
  749. )
  750. else:
  751. candidate_generator = AssistedCandidateGenerator(
  752. input_ids=input_ids,
  753. assistant_model=assistant_model,
  754. generation_config=generation_config,
  755. model_kwargs=model_kwargs,
  756. inputs_tensor=inputs_tensor,
  757. logits_processor=logits_processor,
  758. )
  759. return candidate_generator
  760. def _get_logits_processor(
  761. self,
  762. generation_config: GenerationConfig,
  763. input_ids_seq_length: int,
  764. encoder_input_ids: torch.LongTensor,
  765. prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],
  766. logits_processor: Optional[LogitsProcessorList],
  767. device: str = None,
  768. model_kwargs: Optional[Dict[str, Any]] = None,
  769. negative_prompt_ids: Optional[torch.Tensor] = None,
  770. negative_prompt_attention_mask: Optional[torch.Tensor] = None,
  771. ) -> LogitsProcessorList:
  772. """
  773. This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
  774. instances used to modify the scores of the language model head.
  775. """
  776. # instantiate processors list
  777. processors = LogitsProcessorList()
  778. if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1:
  779. processors.append(
  780. UnbatchedClassifierFreeGuidanceLogitsProcessor(
  781. generation_config.guidance_scale,
  782. self,
  783. unconditional_ids=negative_prompt_ids,
  784. unconditional_attention_mask=negative_prompt_attention_mask,
  785. use_cache=generation_config.use_cache,
  786. )
  787. )
  788. if generation_config.sequence_bias is not None:
  789. processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))
  790. if generation_config.diversity_penalty is not None and generation_config.diversity_penalty > 0.0:
  791. processors.append(
  792. HammingDiversityLogitsProcessor(
  793. diversity_penalty=generation_config.diversity_penalty,
  794. num_beams=generation_config.num_beams,
  795. num_beam_groups=generation_config.num_beam_groups,
  796. )
  797. )
  798. if (
  799. generation_config.encoder_repetition_penalty is not None
  800. and generation_config.encoder_repetition_penalty != 1.0
  801. ):
  802. if len(encoder_input_ids.shape) == 2:
  803. processors.append(
  804. EncoderRepetitionPenaltyLogitsProcessor(
  805. penalty=generation_config.encoder_repetition_penalty,
  806. encoder_input_ids=encoder_input_ids,
  807. )
  808. )
  809. else:
  810. warnings.warn(
  811. "Passing `encoder_repetition_penalty` requires some form of `input_ids` to be passed to "
  812. "`generate`, ignoring the argument.",
  813. UserWarning,
  814. )
  815. if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
  816. processors.append(RepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
  817. if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
  818. processors.append(NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
  819. if (
  820. generation_config.encoder_no_repeat_ngram_size is not None
  821. and generation_config.encoder_no_repeat_ngram_size > 0
  822. ):
  823. if len(encoder_input_ids.shape) == 2:
  824. processors.append(
  825. EncoderNoRepeatNGramLogitsProcessor(
  826. generation_config.encoder_no_repeat_ngram_size,
  827. encoder_input_ids,
  828. )
  829. )
  830. else:
  831. warnings.warn(
  832. "Passing `encoder_no_repeat_ngram_size` requires some form of `input_ids` to be passed to "
  833. "`generate`, ignoring the argument.",
  834. UserWarning,
  835. )
  836. if generation_config.bad_words_ids is not None:
  837. processors.append(
  838. NoBadWordsLogitsProcessor(
  839. generation_config.bad_words_ids,
  840. generation_config._eos_token_tensor,
  841. )
  842. )
  843. if (
  844. generation_config.min_length is not None
  845. and generation_config._eos_token_tensor is not None
  846. and generation_config.min_length > 0
  847. ):
  848. processors.append(
  849. MinLengthLogitsProcessor(
  850. generation_config.min_length,
  851. generation_config._eos_token_tensor,
  852. device=device,
  853. )
  854. )
  855. if (
  856. generation_config.min_new_tokens is not None
  857. and generation_config._eos_token_tensor is not None
  858. and generation_config.min_new_tokens > 0
  859. ):
  860. processors.append(
  861. MinNewTokensLengthLogitsProcessor(
  862. input_ids_seq_length,
  863. generation_config.min_new_tokens,
  864. generation_config._eos_token_tensor,
  865. device=device,
  866. )
  867. )
  868. if prefix_allowed_tokens_fn is not None:
  869. processors.append(
  870. PrefixConstrainedLogitsProcessor(
  871. prefix_allowed_tokens_fn,
  872. generation_config.num_beams // generation_config.num_beam_groups,
  873. )
  874. )
  875. if generation_config.forced_bos_token_id is not None:
  876. processors.append(
  877. ForcedBOSTokenLogitsProcessor(
  878. generation_config.forced_bos_token_id,
  879. )
  880. )
  881. if generation_config.forced_eos_token_id is not None:
  882. processors.append(
  883. ForcedEOSTokenLogitsProcessor(
  884. generation_config.max_length,
  885. generation_config.forced_eos_token_id,
  886. device=device,
  887. )
  888. )
  889. if generation_config.remove_invalid_values is True:
  890. processors.append(InfNanRemoveLogitsProcessor())
  891. if generation_config.exponential_decay_length_penalty is not None:
  892. processors.append(
  893. ExponentialDecayLengthPenalty(
  894. generation_config.exponential_decay_length_penalty,
  895. generation_config._eos_token_tensor,
  896. input_ids_seq_length,
  897. )
  898. )
  899. if generation_config.suppress_tokens is not None:
  900. processors.append(
  901. SuppressTokensLogitsProcessor(
  902. generation_config.suppress_tokens,
  903. device=device,
  904. )
  905. )
  906. if generation_config.begin_suppress_tokens is not None:
  907. begin_index = input_ids_seq_length
  908. begin_index = (
  909. begin_index
  910. if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
  911. else begin_index + 1
  912. )
  913. processors.append(
  914. SuppressTokensAtBeginLogitsProcessor(
  915. generation_config.begin_suppress_tokens,
  916. begin_index,
  917. device=device,
  918. )
  919. )
  920. if generation_config.forced_decoder_ids is not None:
  921. # TODO (sanchit): move this exception to GenerationConfig.validate() when TF & FLAX are aligned with PT
  922. raise ValueError(
  923. "You have explicitly specified `forced_decoder_ids`. Please remove the `forced_decoder_ids` argument "
  924. "in favour of `input_ids` or `decoder_input_ids` respectively.",
  925. )
  926. if generation_config.watermarking_config is not None:
  927. processors.append(
  928. generation_config.watermarking_config.construct_processor(self.config.vocab_size, device)
  929. )
  930. # TODO (joao): find a strategy to specify the order of the processors
  931. processors = self._merge_criteria_processor_list(processors, logits_processor)
  932. # Processors previously known as `LogitsWarpers`, only applied with sampling strategies
  933. if generation_config.do_sample:
  934. # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
  935. # better score (i.e. keep len(list(generation_config._eos_token_tensor)) + 1)
  936. if generation_config.num_beams > 1:
  937. if isinstance(generation_config._eos_token_tensor, list):
  938. min_tokens_to_keep = len(generation_config._eos_token_tensor) + 1
  939. elif isinstance(generation_config._eos_token_tensor, torch.Tensor):
  940. min_tokens_to_keep = generation_config._eos_token_tensor.shape[0] + 1
  941. else:
  942. min_tokens_to_keep = 2
  943. else:
  944. min_tokens_to_keep = 1
  945. # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
  946. # all samplers can be found in `generation_utils_samplers.py`
  947. if generation_config.temperature is not None and generation_config.temperature != 1.0:
  948. processors.append(TemperatureLogitsWarper(generation_config.temperature))
  949. if generation_config.top_k is not None and generation_config.top_k != 0:
  950. processors.append(
  951. TopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep)
  952. )
  953. if generation_config.top_p is not None and generation_config.top_p < 1.0:
  954. processors.append(
  955. TopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep)
  956. )
  957. if generation_config.min_p is not None:
  958. # Applied after temperature scaling (see https://github.com/ggerganov/llama.cpp/pull/3841#issuecomment-2073826084)
  959. processors.append(
  960. MinPLogitsWarper(min_p=generation_config.min_p, min_tokens_to_keep=min_tokens_to_keep)
  961. )
  962. if generation_config.typical_p is not None and generation_config.typical_p < 1.0:
  963. processors.append(
  964. TypicalLogitsWarper(mass=generation_config.typical_p, min_tokens_to_keep=min_tokens_to_keep)
  965. )
  966. if generation_config.epsilon_cutoff is not None and 0.0 < generation_config.epsilon_cutoff < 1.0:
  967. processors.append(
  968. EpsilonLogitsWarper(
  969. epsilon=generation_config.epsilon_cutoff, min_tokens_to_keep=min_tokens_to_keep
  970. )
  971. )
  972. if generation_config.eta_cutoff is not None and 0.0 < generation_config.eta_cutoff < 1.0:
  973. processors.append(
  974. EtaLogitsWarper(
  975. epsilon=generation_config.eta_cutoff, min_tokens_to_keep=min_tokens_to_keep, device=device
  976. )
  977. )
  978. # `LogitNormalization` should always be the last logit processor, when present
  979. if generation_config.renormalize_logits is True:
  980. processors.append(LogitNormalization())
  981. return processors
  982. def _get_stopping_criteria(
  983. self,
  984. generation_config: GenerationConfig,
  985. stopping_criteria: Optional[StoppingCriteriaList],
  986. tokenizer: Optional["PreTrainedTokenizerBase"] = None,
  987. **kwargs,
  988. ) -> StoppingCriteriaList:
  989. criteria = StoppingCriteriaList()
  990. if generation_config.max_length is not None:
  991. max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
  992. criteria.append(
  993. MaxLengthCriteria(
  994. max_length=generation_config.max_length,
  995. max_position_embeddings=max_position_embeddings,
  996. )
  997. )
  998. if generation_config.max_time is not None:
  999. criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))
  1000. if generation_config.stop_strings is not None:
  1001. if tokenizer is None:
  1002. raise ValueError(
  1003. "There are one or more stop strings, either in the arguments to `generate` or in the "
  1004. "model's generation config, but we could not locate a tokenizer. When generating with "
  1005. "stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`."
  1006. )
  1007. criteria.append(StopStringCriteria(stop_strings=generation_config.stop_strings, tokenizer=tokenizer))
  1008. if generation_config._eos_token_tensor is not None:
  1009. criteria.append(EosTokenCriteria(eos_token_id=generation_config._eos_token_tensor))
  1010. if (
  1011. generation_config.is_assistant
  1012. and generation_config.assistant_confidence_threshold is not None
  1013. and generation_config.assistant_confidence_threshold > 0
  1014. ):
  1015. criteria.append(
  1016. ConfidenceCriteria(assistant_confidence_threshold=generation_config.assistant_confidence_threshold)
  1017. )
  1018. criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)
  1019. return criteria
  1020. def _merge_criteria_processor_list(
  1021. self,
  1022. default_list: Union[LogitsProcessorList, StoppingCriteriaList],
  1023. custom_list: Union[LogitsProcessorList, StoppingCriteriaList],
  1024. ) -> Union[LogitsProcessorList, StoppingCriteriaList]:
  1025. if len(custom_list) == 0:
  1026. return default_list
  1027. for default in default_list:
  1028. for custom in custom_list:
  1029. if type(custom) is type(default):
  1030. object_type = "stopping criteria" if isinstance(custom, StoppingCriteria) else "logits processor"
  1031. raise ValueError(
  1032. f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
  1033. f" `.generate()`, but it has already been created with the values {default}. {default} has been"
  1034. " created by passing the corresponding arguments to generate or by the model's config default"
  1035. f" values. If you just want to change the default values of {object_type} consider passing"
  1036. f" them as arguments to `.generate()` instead of using a custom {object_type}."
  1037. )
  1038. default_list.extend(custom_list)
  1039. return default_list
  1040. def compute_transition_scores(
  1041. self,
  1042. sequences: torch.Tensor,
  1043. scores: Tuple[torch.Tensor],
  1044. beam_indices: Optional[torch.Tensor] = None,
  1045. normalize_logits: bool = False,
  1046. ) -> torch.Tensor:
  1047. """
  1048. Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
  1049. used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.
  1050. Parameters:
  1051. sequences (`torch.LongTensor`):
  1052. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
  1053. shorter if all batches finished early due to the `eos_token_id`.
  1054. scores (`tuple(torch.FloatTensor)`):
  1055. Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  1056. of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
  1057. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
  1058. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  1059. beam_indices (`torch.LongTensor`, *optional*):
  1060. Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
  1061. `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
  1062. generate-time.
  1063. normalize_logits (`bool`, *optional*, defaults to `False`):
  1064. Whether to normalize the logits (which, for legacy reasons, may be unnormalized).
  1065. Return:
  1066. `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
  1067. the transition scores (logits)
  1068. Examples:
  1069. ```python
  1070. >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
  1071. >>> import numpy as np
  1072. >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
  1073. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1074. >>> tokenizer.pad_token_id = tokenizer.eos_token_id
  1075. >>> inputs = tokenizer(["Today is"], return_tensors="pt")
  1076. >>> # Example 1: Print the scores for each token generated with Greedy Search
  1077. >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
  1078. >>> transition_scores = model.compute_transition_scores(
  1079. ... outputs.sequences, outputs.scores, normalize_logits=True
  1080. ... )
  1081. >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
  1082. >>> # encoder-decoder models, like BART or T5.
  1083. >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
  1084. >>> generated_tokens = outputs.sequences[:, input_length:]
  1085. >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
  1086. ... # | token | token string | log probability | probability
  1087. ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
  1088. | 262 | the | -1.414 | 24.33%
  1089. | 1110 | day | -2.609 | 7.36%
  1090. | 618 | when | -2.010 | 13.40%
  1091. | 356 | we | -1.859 | 15.58%
  1092. | 460 | can | -2.508 | 8.14%
  1093. >>> # Example 2: Reconstruct the sequence scores from Beam Search
  1094. >>> outputs = model.generate(
  1095. ... **inputs,
  1096. ... max_new_tokens=5,
  1097. ... num_beams=4,
  1098. ... num_return_sequences=4,
  1099. ... return_dict_in_generate=True,
  1100. ... output_scores=True,
  1101. ... )
  1102. >>> transition_scores = model.compute_transition_scores(
  1103. ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
  1104. ... )
  1105. >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
  1106. >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
  1107. >>> # use case, you might want to recompute it with `normalize_logits=True`.
  1108. >>> # Tip 2: the output length does NOT include the input length
  1109. >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
  1110. >>> length_penalty = model.generation_config.length_penalty
  1111. >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
  1112. >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
  1113. True
  1114. ```"""
  1115. # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
  1116. # to a beam search approach were the first (and only) beam is always selected
  1117. if beam_indices is None:
  1118. beam_indices = torch.arange(scores[0].shape[0]).view(-1, 1).to(sequences.device)
  1119. beam_indices = beam_indices.expand(-1, len(scores))
  1120. # 2. reshape scores as [batch_size*vocab_size, # generation steps] with # generation steps being
  1121. # seq_len - input_length
  1122. scores = torch.stack(scores).reshape(len(scores), -1).transpose(0, 1)
  1123. # 3. Optionally normalize the logits (across the vocab dimension)
  1124. if normalize_logits:
  1125. scores = scores.reshape(-1, self.config.vocab_size, scores.shape[-1])
  1126. scores = torch.nn.functional.log_softmax(scores, dim=1)
  1127. scores = scores.reshape(-1, scores.shape[-1])
  1128. # 4. cut beam_indices to longest beam length
  1129. beam_indices_mask = beam_indices < 0
  1130. max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max()
  1131. beam_indices = beam_indices.clone()[:, :max_beam_length]
  1132. beam_indices_mask = beam_indices_mask[:, :max_beam_length]
  1133. # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
  1134. beam_indices[beam_indices_mask] = 0
  1135. # 6. multiply beam_indices with vocab size to gather correctly from scores
  1136. beam_sequence_indices = beam_indices * self.config.vocab_size
  1137. # 7. Define which indices contributed to scores
  1138. cut_idx = sequences.shape[-1] - max_beam_length
  1139. indices = sequences[:, cut_idx:] + beam_sequence_indices
  1140. # 8. Compute scores
  1141. transition_scores = scores.gather(0, indices)
  1142. # 9. Mask out transition_scores of beams that stopped early
  1143. transition_scores[beam_indices_mask] = 0
  1144. return transition_scores
  1145. def _validate_model_class(self):
  1146. """
  1147. Confirms that the model class is compatible with generation. If not, raises an exception that points to the
  1148. right class to use.
  1149. """
  1150. # TODO(joao): remove this function in v4.50, i.e. when we remove the inheritance of `GenerationMixin` from
  1151. # `PreTrainedModel`. With that inheritance removed, all model classes inheriting from `GenerationMixin` can
  1152. # safely call `GenerationMixin.generate`
  1153. if not is_torchdynamo_compiling() and not self.can_generate():
  1154. terminations_with_generation_support = [
  1155. "ForCausalLM",
  1156. "ForConditionalGeneration",
  1157. "ForSpeechSeq2Seq",
  1158. "ForVision2Seq",
  1159. ]
  1160. raise TypeError(
  1161. f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
  1162. "it doesn't have a language model head. Classes that support generation often end in one of these "
  1163. f"names: {terminations_with_generation_support}."
  1164. )
  1165. def _validate_assistant(self, assistant_model, tokenizer, assistant_tokenizer):
  1166. if assistant_model is None:
  1167. return
  1168. if self.config.is_encoder_decoder and not assistant_model.config.is_encoder_decoder:
  1169. attributes_to_check = ["encoder_attention_heads", "encoder_ffn_dim", "encoder_layers"]
  1170. attributes_to_check = [attr for attr in dir(assistant_model.config) if attr in attributes_to_check]
  1171. are_equal = all(
  1172. getattr(self.config, attr) == getattr(assistant_model.config, attr) for attr in attributes_to_check
  1173. )
  1174. if not are_equal:
  1175. raise ValueError(
  1176. "The main model and the assistant don't have compatible encoder-dependent input shapes. "
  1177. "Ensure you load the assistant with the correct encoder-decoder class, e.g. `AutoModelForSpeechSeq2Seq` for Whisper."
  1178. )
  1179. doc_reference = (
  1180. "(see https://huggingface.co/docs/transformers/en/generation_strategies#universal-assisted-decoding)"
  1181. )
  1182. if self.config.get_text_config().vocab_size == assistant_model.config.get_text_config().vocab_size:
  1183. if assistant_tokenizer is not None:
  1184. raise ValueError(
  1185. f"`assistant_tokenizer` is not required when the main and assistant models use the same tokenizer. Please omit `assistant_tokenizer` from `generate()` {doc_reference}."
  1186. )
  1187. else:
  1188. if tokenizer is None or assistant_tokenizer is None:
  1189. raise ValueError(
  1190. f"The main and assistant moedels have different tokenizers. Please provide `tokenizer` and `assistant_tokenizer` to `generate()` {doc_reference}."
  1191. )
  1192. def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
  1193. """Validates model kwargs for generation. Generate argument typos will also be caught here."""
  1194. # If a `Cache` instance is passed, checks whether the model is compatible with it
  1195. if isinstance(model_kwargs.get("past_key_values", None), Cache) and not self._supports_cache_class:
  1196. raise ValueError(
  1197. f"{self.__class__.__name__} does not support an instance of `Cache` as `past_key_values`. Please "
  1198. "check the model documentation for supported cache formats."
  1199. )
  1200. # Excludes arguments that are handled before calling any model function
  1201. if self.config.is_encoder_decoder:
  1202. for key in ["decoder_input_ids"]:
  1203. model_kwargs.pop(key, None)
  1204. unused_model_args = []
  1205. model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
  1206. # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
  1207. # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
  1208. if "kwargs" in model_args or "model_kwargs" in model_args:
  1209. model_args |= set(inspect.signature(self.forward).parameters)
  1210. # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`
  1211. if self.config.is_encoder_decoder:
  1212. base_model = getattr(self, self.base_model_prefix, None)
  1213. # allow encoder kwargs
  1214. encoder = getattr(self, "encoder", None)
  1215. # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.
  1216. # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`
  1217. # TODO: A better way to handle this.
  1218. if encoder is None and base_model is not None:
  1219. encoder = getattr(base_model, "encoder", None)
  1220. if encoder is not None:
  1221. encoder_model_args = set(inspect.signature(encoder.forward).parameters)
  1222. model_args |= encoder_model_args
  1223. # allow decoder kwargs
  1224. decoder = getattr(self, "decoder", None)
  1225. if decoder is None and base_model is not None:
  1226. decoder = getattr(base_model, "decoder", None)
  1227. if decoder is not None:
  1228. decoder_model_args = set(inspect.signature(decoder.forward).parameters)
  1229. model_args |= {f"decoder_{x}" for x in decoder_model_args}
  1230. # allow assistant_encoder_outputs to be passed if we're doing assisted generating
  1231. if "assistant_encoder_outputs" in model_kwargs:
  1232. model_args |= {"assistant_encoder_outputs"}
  1233. for key, value in model_kwargs.items():
  1234. if value is not None and key not in model_args:
  1235. unused_model_args.append(key)
  1236. if unused_model_args:
  1237. raise ValueError(
  1238. f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
  1239. " generate arguments will also show up in this list)"
  1240. )
  1241. def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
  1242. """Performs validation related to the resulting generated length"""
  1243. # Can't throw warnings/exceptions during compilation
  1244. if is_torchdynamo_compiling():
  1245. return
  1246. # 1. Max length warnings related to poor parameterization
  1247. if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
  1248. # 20 is the default max_length of the generation config
  1249. warnings.warn(
  1250. f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
  1251. "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
  1252. "generation.",
  1253. UserWarning,
  1254. )
  1255. if input_ids_length >= generation_config.max_length:
  1256. input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  1257. raise ValueError(
  1258. f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
  1259. f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
  1260. " increasing `max_length` or, better yet, setting `max_new_tokens`."
  1261. )
  1262. # 2. Min length warnings due to unfeasible parameter combinations
  1263. min_length_error_suffix = (
  1264. " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "
  1265. "increase the maximum length."
  1266. )
  1267. if has_default_max_length:
  1268. min_length_error_suffix += (
  1269. f" Note that `max_length` is set to {generation_config.max_length}, its default value."
  1270. )
  1271. if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
  1272. warnings.warn(
  1273. f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"
  1274. f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
  1275. UserWarning,
  1276. )
  1277. if generation_config.min_new_tokens is not None:
  1278. min_length = generation_config.min_new_tokens + input_ids_length
  1279. if min_length > generation_config.max_length:
  1280. warnings.warn(
  1281. f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "
  1282. f"added to the prompt length ({input_ids_length}), is larger than"
  1283. f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
  1284. UserWarning,
  1285. )
  1286. def _prepare_generated_length(
  1287. self,
  1288. generation_config,
  1289. has_default_max_length,
  1290. has_default_min_length,
  1291. model_input_name,
  1292. input_ids_length,
  1293. inputs_tensor,
  1294. ):
  1295. """Prepared max and min length in generation configs to avoid clashes between similar attributes"""
  1296. if generation_config.max_new_tokens is not None:
  1297. if not has_default_max_length and generation_config.max_length is not None:
  1298. logger.warning(
  1299. f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
  1300. f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
  1301. "Please refer to the documentation for more information. "
  1302. "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
  1303. )
  1304. generation_config.max_length = generation_config.max_new_tokens + input_ids_length
  1305. # if both `inputs_embeds` and `input_ids` are passed, we do not correct the length
  1306. # otherwise we need total length [inputs-embeds-len + new-tokens-len] to not go beyond indicated `max_length``
  1307. elif (
  1308. model_input_name == "inputs_embeds"
  1309. and input_ids_length != inputs_tensor.shape[1]
  1310. and not self.config.is_encoder_decoder
  1311. ):
  1312. generation_config.max_length -= inputs_tensor.shape[1]
  1313. # same for min length
  1314. if generation_config.min_new_tokens is not None:
  1315. if not has_default_min_length:
  1316. logger.warning(
  1317. f"Both `min_new_tokens` (={generation_config.min_new_tokens}) and `min_length`(="
  1318. f"{generation_config.min_length}) seem to have been set. `min_new_tokens` will take precedence. "
  1319. "Please refer to the documentation for more information. "
  1320. "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
  1321. )
  1322. generation_config.min_length = generation_config.min_new_tokens + input_ids_length
  1323. elif (
  1324. model_input_name == "inputs_embeds"
  1325. and input_ids_length != inputs_tensor.shape[1]
  1326. and not self.config.is_encoder_decoder
  1327. ):
  1328. generation_config.min_length = max(generation_config.min_length - inputs_tensor.shape[1], 0)
  1329. return generation_config
  1330. def _prepare_generation_config(
  1331. self, generation_config: Optional[GenerationConfig], **kwargs: Dict
  1332. ) -> Tuple[GenerationConfig, Dict]:
  1333. """
  1334. Prepares the base generation config, then applies any generation configuration options from kwargs. This
  1335. function handles retrocompatibility with respect to configuration files.
  1336. """
  1337. # TODO joao: when we can detect `fullgraph=True` in `torch.compile` (https://github.com/pytorch/pytorch/pull/120400)
  1338. # replace `is_torchdynamo_compiling` by the corresponding check. As it is, we are being too restrictive with
  1339. # the parameterization in `fullgraph=False` so as to enable `fullgraph=True`.
  1340. # priority: `generation_config` argument > `model.generation_config` (the default generation config)
  1341. using_model_generation_config = False
  1342. if generation_config is None:
  1343. # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
  1344. # the following conditions must be met
  1345. # 1) the generation config must have been created from the model config (`_from_model_config` field);
  1346. # 2) the generation config must have seen no modification since its creation (the hash is the same);
  1347. # 3) there are non-default generation parameters in the model config.
  1348. # 4) the user must have set new generation parameters in the model config.
  1349. # NOTE: `torch.compile` can't compile `hash`, this legacy support is disabled with compilation.
  1350. if (
  1351. not is_torchdynamo_compiling()
  1352. and self.generation_config._from_model_config # 1)
  1353. and self.generation_config._original_object_hash == hash(self.generation_config) # 2)
  1354. and len(self.config._get_non_default_generation_parameters()) > 0 # 3)
  1355. ):
  1356. new_generation_config = GenerationConfig.from_model_config(self.config)
  1357. if new_generation_config != self.generation_config: # 4)
  1358. warnings.warn(
  1359. "You have modified the pretrained model configuration to control generation. This is a"
  1360. " deprecated strategy to control generation and will be removed in v5."
  1361. " Please use and modify the model generation configuration (see"
  1362. " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )",
  1363. UserWarning,
  1364. )
  1365. self.generation_config = new_generation_config
  1366. generation_config = self.generation_config
  1367. using_model_generation_config = True
  1368. # `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
  1369. # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
  1370. # exception will be raised in `_validate_model_kwargs`
  1371. if not is_torchdynamo_compiling():
  1372. generation_config = copy.deepcopy(generation_config)
  1373. model_kwargs = generation_config.update(**kwargs)
  1374. # If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
  1375. if not using_model_generation_config:
  1376. if generation_config.bos_token_id is None:
  1377. generation_config.bos_token_id = self.generation_config.bos_token_id
  1378. if generation_config.eos_token_id is None:
  1379. generation_config.eos_token_id = self.generation_config.eos_token_id
  1380. if generation_config.pad_token_id is None:
  1381. generation_config.pad_token_id = self.generation_config.pad_token_id
  1382. if generation_config.decoder_start_token_id is None:
  1383. generation_config.decoder_start_token_id = self.generation_config.decoder_start_token_id
  1384. else:
  1385. model_kwargs = kwargs
  1386. return generation_config, model_kwargs
  1387. def _get_initial_cache_position(self, input_ids, model_kwargs):
  1388. """Calculates `cache_position` for the pre-fill stage based on `input_ids` and optionally past length"""
  1389. # `torch.compile`-friendly `torch.arange` from a shape -- the lines below are equivalent to `torch.arange`
  1390. if "inputs_embeds" in model_kwargs and not self.config.is_encoder_decoder:
  1391. cache_position = torch.ones_like(model_kwargs["inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1
  1392. elif "decoder_inputs_embeds" in model_kwargs and self.config.is_encoder_decoder:
  1393. cache_position = (
  1394. torch.ones_like(model_kwargs["decoder_inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1
  1395. )
  1396. else:
  1397. cache_position = torch.ones_like(input_ids[0, :], dtype=torch.int64).cumsum(0) - 1
  1398. past_length = 0
  1399. if model_kwargs.get("past_key_values") is not None:
  1400. cache = model_kwargs["past_key_values"]
  1401. past_length = 0
  1402. if not isinstance(cache, Cache):
  1403. past_length = cache[0][0].shape[2]
  1404. elif hasattr(cache, "get_seq_length") and cache.get_seq_length() is not None:
  1405. past_length = cache.get_seq_length()
  1406. # TODO(joao): this is not torch.compile-friendly, find a work-around. If the cache is not empty,
  1407. # end-to-end compilation will yield bad results because `cache_position` will be incorrect.
  1408. if not is_torchdynamo_compiling():
  1409. cache_position = cache_position[past_length:]
  1410. model_kwargs["cache_position"] = cache_position
  1411. return model_kwargs
  1412. def _get_cache(
  1413. self, cache_implementation: str, batch_size: int, max_cache_len: int, device: torch.device, model_kwargs
  1414. ) -> Cache:
  1415. """
  1416. Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a
  1417. new `generate` call requires a larger cache or uses a different batch size.
  1418. Returns the resulting cache object.
  1419. """
  1420. cache_cls: Cache = NEED_SETUP_CACHE_CLASSES_MAPPING[cache_implementation]
  1421. requires_cross_attention_cache = (
  1422. self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None
  1423. )
  1424. if hasattr(self, "_cache"):
  1425. cache_to_check = self._cache.self_attention_cache if requires_cross_attention_cache else self._cache
  1426. if cache_implementation == "sliding_window":
  1427. max_cache_len = min(self.config.sliding_window, max_cache_len)
  1428. need_new_cache = (
  1429. not hasattr(self, "_cache")
  1430. or (not isinstance(cache_to_check, cache_cls))
  1431. or cache_to_check.batch_size != batch_size
  1432. )
  1433. if cache_implementation != "mamba":
  1434. need_new_cache = need_new_cache or cache_to_check.max_cache_len < max_cache_len
  1435. if requires_cross_attention_cache and hasattr(self, "_cache"):
  1436. need_new_cache = (
  1437. need_new_cache
  1438. or self._cache.cross_attention_cache.max_cache_len != model_kwargs["encoder_outputs"][0].shape[1]
  1439. )
  1440. if need_new_cache:
  1441. if hasattr(self.config, "_pre_quantization_dtype"):
  1442. cache_dtype = self.config._pre_quantization_dtype
  1443. else:
  1444. if not is_torchdynamo_compiling():
  1445. cache_dtype = self.dtype
  1446. else:
  1447. # NOTE: self.dtype is not compatible with torch.compile, as it calls `self.parameters()`.
  1448. # Workaround: trust the lm_head, whose attribute name is somewhat consistent across generative
  1449. # models. May cause trobles with non-text modalities.
  1450. cache_dtype = self.get_output_embeddings().weight.dtype
  1451. def get_layer_device_map(execution_device_map: Optional[dict] = None):
  1452. if execution_device_map is None:
  1453. return None
  1454. elif len(execution_device_map) == 1 and "" in execution_device_map:
  1455. return {idx: execution_device_map[""] for idx in range(self.config.num_hidden_layers)}
  1456. layer_device_map = {}
  1457. for layer in execution_device_map:
  1458. for idx in range(self.config.num_hidden_layers):
  1459. if f".{idx}." in f"{layer}.":
  1460. layer_device_map[idx] = execution_device_map[layer]
  1461. break
  1462. for idx in range(self.config.num_hidden_layers):
  1463. if idx not in layer_device_map:
  1464. raise RuntimeError(f"layer {idx} has not been mapped to a device.")
  1465. return layer_device_map
  1466. execution_device_map = None
  1467. # Taken from dispatch_model from accelerate.
  1468. # This is needed here if we don't want to make changes in accelerate in order to save execution_device
  1469. # For offloaded case, we need to get the execution device, not just the device where it is offloaded
  1470. if hasattr(self, "hf_device_map"):
  1471. main_device = [d for d in self.hf_device_map.values() if d not in ["cpu", "disk"]][0]
  1472. execution_device_map = {
  1473. name: main_device if device in ["cpu", "disk"] else device
  1474. for name, device in self.hf_device_map.items()
  1475. }
  1476. layer_device_map = get_layer_device_map(execution_device_map)
  1477. cache_kwargs = {
  1478. "config": self.config.get_text_config(),
  1479. "batch_size": batch_size,
  1480. "max_cache_len": max_cache_len,
  1481. "device": device,
  1482. "dtype": cache_dtype,
  1483. "layer_device_map": layer_device_map,
  1484. }
  1485. self._cache = cache_cls(**cache_kwargs)
  1486. if requires_cross_attention_cache:
  1487. encoder_kwargs = cache_kwargs.copy()
  1488. encoder_kwargs["max_cache_len"] = model_kwargs["encoder_outputs"][0].shape[1]
  1489. self._cache = EncoderDecoderCache(self._cache, cache_cls(**encoder_kwargs))
  1490. else:
  1491. self._cache.reset()
  1492. return self._cache
  1493. def _supports_default_dynamic_cache(self) -> bool:
  1494. """
  1495. Return `True` if current model can use a `DynamicCache` instance when initializing the `past_key_values`.
  1496. This is mostly the same as `_supports_cache_class` attribute, but add exception for `Jamba` model which
  1497. uses its own `HybridMambaAttentionDynamicCache` and do not need to initialize the Cache in advance in
  1498. order to save memory (because no back and forth `to_legacy_cache` and `from_legacy_cache` will be performed
  1499. for `HybridMambaAttentionDynamicCache`).
  1500. """
  1501. return (
  1502. self._supports_cache_class
  1503. and "jamba" not in self.__class__.__name__.lower()
  1504. and "zamba" not in self.__class__.__name__.lower()
  1505. )
  1506. def _prepare_cache_for_generation(
  1507. self,
  1508. generation_config: GenerationConfig,
  1509. model_kwargs: Dict,
  1510. assistant_model: "PreTrainedModel",
  1511. batch_size: int,
  1512. max_cache_length: int,
  1513. device: torch.device,
  1514. ) -> bool:
  1515. """
  1516. Prepares the cache for generation (if applicable), given `generate`'s parameterization. If a cache is
  1517. instantiated, writes it to `model_kwargs`, under the name expected by the model.
  1518. """
  1519. cache_name = "past_key_values" if "mamba" not in self.__class__.__name__.lower() else "cache_params"
  1520. requires_cross_attention_cache = (
  1521. self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None
  1522. )
  1523. # Quick escape route 1: if the user specifies a cache, we only need to:
  1524. # a) check for conflicting `generate` arguments
  1525. # b) convert to the new cache format (if the user passes a legacy cache and model supports it)
  1526. user_defined_cache = model_kwargs.get(cache_name)
  1527. if user_defined_cache is not None:
  1528. if generation_config.cache_implementation is not None:
  1529. raise ValueError(
  1530. f"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a "
  1531. "Cache object) is unsupported. Please use only one of the two."
  1532. )
  1533. if isinstance(user_defined_cache, tuple) and self._supports_default_dynamic_cache():
  1534. model_kwargs[cache_name] = (
  1535. DynamicCache.from_legacy_cache(user_defined_cache)
  1536. if not requires_cross_attention_cache
  1537. else EncoderDecoderCache.from_legacy_cache(user_defined_cache)
  1538. )
  1539. return
  1540. # Quick escape route 2: if the user specifies no cache is to be used. (conflicting arguments are handled in
  1541. # `generation_config.validate()`)
  1542. if generation_config.use_cache is False:
  1543. return
  1544. # Quick escape route 3: model that only supports legacy caches = nothing to prepare
  1545. if not self._supports_default_dynamic_cache():
  1546. if generation_config.cache_implementation is not None:
  1547. warnings.warn(
  1548. "This model does not support `Cache` instances, it only supports the legacy cache format (tuple "
  1549. f"of tuples). `cache_implementation` (set to {generation_config.cache_implementation}) will be "
  1550. "ignored.",
  1551. UserWarning,
  1552. )
  1553. return
  1554. # Otherwise we NEED to prepare a cache, based on `generation_config.cache_implementation`
  1555. # TODO(joao): support static caches in assisted generation. assisted generation needs to roll back caches,
  1556. # which is only supported in dynamic caches atm
  1557. if assistant_model is not None and generation_config.cache_implementation is not None:
  1558. logger.warning_once(
  1559. "An assistant model is provided, using a dynamic cache instead of a cache of type="
  1560. f"'{generation_config.cache_implementation}'."
  1561. )
  1562. generation_config.cache_implementation = None
  1563. if generation_config.cache_implementation is not None:
  1564. if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:
  1565. if generation_config.cache_implementation == "static" and not self._supports_static_cache:
  1566. raise ValueError(
  1567. "This model does not support `cache_implementation='static'`. Please check the following "
  1568. "issue: https://github.com/huggingface/transformers/issues/28981"
  1569. )
  1570. model_kwargs[cache_name] = self._get_cache(
  1571. cache_implementation=generation_config.cache_implementation,
  1572. batch_size=max(generation_config.num_beams, generation_config.num_return_sequences) * batch_size,
  1573. max_cache_len=max_cache_length,
  1574. device=device,
  1575. model_kwargs=model_kwargs,
  1576. )
  1577. elif generation_config.cache_implementation == "quantized":
  1578. if not self._supports_quantized_cache:
  1579. raise ValueError(
  1580. "This model does not support the quantized cache. If you want your model to support quantized "
  1581. "cache, please open an issue and tag @zucchini-nlp."
  1582. )
  1583. cache_config = (
  1584. generation_config.cache_config
  1585. if generation_config.cache_config is not None
  1586. else QuantizedCacheConfig()
  1587. )
  1588. cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]
  1589. if cache_config.backend == "quanto" and not (is_optimum_quanto_available() or is_quanto_available()):
  1590. raise ImportError(
  1591. "You need to install optimum-quanto in order to use KV cache quantization with optimum-quanto backend. "
  1592. "Please install it via with `pip install optimum-quanto`"
  1593. )
  1594. elif cache_config.backend == "HQQ" and not is_hqq_available():
  1595. raise ImportError(
  1596. "You need to install `HQQ` in order to use KV cache quantization with HQQ backend. "
  1597. "Please install it via with `pip install hqq`"
  1598. )
  1599. model_kwargs[cache_name] = cache_class(cache_config)
  1600. elif generation_config.cache_implementation == "offloaded":
  1601. model_kwargs[cache_name] = OffloadedCache()
  1602. # Use DynamicCache() instance by default. This will avoid back and forth from legacy format that
  1603. # keeps copying the cache thus using much more memory
  1604. else:
  1605. model_kwargs[cache_name] = (
  1606. DynamicCache()
  1607. if not requires_cross_attention_cache
  1608. else EncoderDecoderCache(DynamicCache(), DynamicCache())
  1609. )
  1610. def _supports_num_logits_to_keep(self) -> bool:
  1611. """
  1612. Return True if the current model supports the keyword argument `num_logits_to_keep` in forward()
  1613. to save memory. Checking it in this way allows to avoid using a new model attribute.
  1614. """
  1615. return "num_logits_to_keep" in set(inspect.signature(self.forward).parameters.keys())
  1616. def _prepare_special_tokens(
  1617. self,
  1618. generation_config: GenerationConfig,
  1619. kwargs_has_attention_mask: Optional[bool] = None,
  1620. device: Optional[Union[torch.device, str]] = None,
  1621. ):
  1622. """
  1623. Prepares the special tokens for generation, overwriting the generation config with their processed versions
  1624. converted to tensor.
  1625. Note that `generation_config` is changed in place and stops being serializable after this method is called.
  1626. That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
  1627. function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
  1628. """
  1629. # Convert special tokens to tensors
  1630. def _tensor_or_none(token, device=None):
  1631. if token is None:
  1632. return token
  1633. device = device if device is not None else self.device
  1634. if isinstance(token, torch.Tensor):
  1635. return token.to(device)
  1636. return torch.tensor(token, device=device, dtype=torch.long)
  1637. bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
  1638. eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
  1639. pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
  1640. decoder_start_token_tensor = _tensor_or_none(generation_config.decoder_start_token_id, device=device)
  1641. # for BC we also try to get `decoder_start_token_id` or `bos_token_id` (#30892)
  1642. if self.config.is_encoder_decoder:
  1643. decoder_start_token_tensor = (
  1644. decoder_start_token_tensor if decoder_start_token_tensor is not None else bos_token_tensor
  1645. )
  1646. # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
  1647. if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
  1648. eos_token_tensor = eos_token_tensor.unsqueeze(0)
  1649. # Set pad token if unset (and there are conditions to do so)
  1650. if pad_token_tensor is None and eos_token_tensor is not None:
  1651. if not is_torchdynamo_compiling():
  1652. if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
  1653. logger.warning(
  1654. "The attention mask and the pad token id were not set. As a consequence, you may observe "
  1655. "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
  1656. )
  1657. logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
  1658. pad_token_tensor = eos_token_tensor[0]
  1659. # Sanity checks/warnings
  1660. if self.config.is_encoder_decoder and decoder_start_token_tensor is None:
  1661. raise ValueError(
  1662. "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
  1663. )
  1664. if not is_torchdynamo_compiling(): # Checks that depend on tensor-dependent control flow
  1665. if (
  1666. eos_token_tensor is not None
  1667. and isin_mps_friendly(elements=eos_token_tensor, test_elements=pad_token_tensor).any()
  1668. ):
  1669. if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
  1670. logger.warning_once(
  1671. "The attention mask is not set and cannot be inferred from input because pad token is same as "
  1672. "eos token. As a consequence, you may observe unexpected behavior. Please pass your input's "
  1673. "`attention_mask` to obtain reliable results."
  1674. )
  1675. if eos_token_tensor is not None and (
  1676. torch.is_floating_point(eos_token_tensor) or (eos_token_tensor < 0).any()
  1677. ):
  1678. logger.warning(
  1679. f"`eos_token_id` should consist of positive integers, but is {eos_token_tensor}. Your generation "
  1680. "will not stop until the maximum length is reached. Depending on other flags, it may even crash."
  1681. )
  1682. # Update generation config with the updated special tokens tensors
  1683. # NOTE: this must be written into a different attribute name than the one holding the original special tokens
  1684. # (in their non-tensor form), in order to enable end-to-end compilation. See
  1685. # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
  1686. generation_config._bos_token_tensor = bos_token_tensor
  1687. generation_config._eos_token_tensor = eos_token_tensor
  1688. generation_config._pad_token_tensor = pad_token_tensor
  1689. generation_config._decoder_start_token_tensor = decoder_start_token_tensor
  1690. @torch.no_grad()
  1691. def generate(
  1692. self,
  1693. inputs: Optional[torch.Tensor] = None,
  1694. generation_config: Optional[GenerationConfig] = None,
  1695. logits_processor: Optional[LogitsProcessorList] = None,
  1696. stopping_criteria: Optional[StoppingCriteriaList] = None,
  1697. prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
  1698. synced_gpus: Optional[bool] = None,
  1699. assistant_model: Optional["PreTrainedModel"] = None,
  1700. streamer: Optional["BaseStreamer"] = None,
  1701. negative_prompt_ids: Optional[torch.Tensor] = None,
  1702. negative_prompt_attention_mask: Optional[torch.Tensor] = None,
  1703. **kwargs,
  1704. ) -> Union[GenerateOutput, torch.LongTensor]:
  1705. r"""
  1706. Generates sequences of token ids for models with a language modeling head.
  1707. <Tip warning={true}>
  1708. Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
  1709. model's default generation configuration. You can override any `generation_config` by passing the corresponding
  1710. parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
  1711. For an overview of generation strategies and code examples, check out the [following
  1712. guide](../generation_strategies).
  1713. </Tip>
  1714. Parameters:
  1715. inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
  1716. The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
  1717. method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
  1718. should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
  1719. `input_ids`, `input_values`, `input_features`, or `pixel_values`.
  1720. generation_config ([`~generation.GenerationConfig`], *optional*):
  1721. The generation configuration to be used as base parametrization for the generation call. `**kwargs`
  1722. passed to generate matching the attributes of `generation_config` will override them. If
  1723. `generation_config` is not provided, the default will be used, which has the following loading
  1724. priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
  1725. configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
  1726. default values, whose documentation should be checked to parameterize generation.
  1727. logits_processor (`LogitsProcessorList`, *optional*):
  1728. Custom logits processors that complement the default logits processors built from arguments and
  1729. generation config. If a logit processor is passed that is already created with the arguments or a
  1730. generation config an error is thrown. This feature is intended for advanced users.
  1731. stopping_criteria (`StoppingCriteriaList`, *optional*):
  1732. Custom stopping criteria that complements the default stopping criteria built from arguments and a
  1733. generation config. If a stopping criteria is passed that is already created with the arguments or a
  1734. generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
  1735. sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
  1736. intended for advanced users.
  1737. prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
  1738. If provided, this function constraints the beam search to allowed tokens only at each step. If not
  1739. provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
  1740. `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
  1741. on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
  1742. for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
  1743. Retrieval](https://arxiv.org/abs/2010.00904).
  1744. synced_gpus (`bool`, *optional*):
  1745. Whether to continue running the while loop until max_length. Unless overridden, this flag will be set
  1746. to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid
  1747. deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.
  1748. assistant_model (`PreTrainedModel`, *optional*):
  1749. An assistant model that can be used to accelerate generation. The assistant model must have the exact
  1750. same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model
  1751. is much faster than running generation with the model you're calling generate from. As such, the
  1752. assistant model should be much smaller.
  1753. streamer (`BaseStreamer`, *optional*):
  1754. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  1755. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  1756. negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1757. The negative prompt needed for some processors such as CFG. The batch size must match the input batch
  1758. size. This is an experimental feature, subject to breaking API changes in future versions.
  1759. negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1760. Attention_mask for `negative_prompt_ids`.
  1761. kwargs (`Dict[str, Any]`, *optional*):
  1762. Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
  1763. forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
  1764. specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
  1765. Return:
  1766. [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
  1767. or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.
  1768. If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
  1769. [`~utils.ModelOutput`] types are:
  1770. - [`~generation.GenerateDecoderOnlyOutput`],
  1771. - [`~generation.GenerateBeamDecoderOnlyOutput`]
  1772. If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
  1773. [`~utils.ModelOutput`] types are:
  1774. - [`~generation.GenerateEncoderDecoderOutput`],
  1775. - [`~generation.GenerateBeamEncoderDecoderOutput`]
  1776. """
  1777. # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
  1778. self._validate_model_class()
  1779. tokenizer = kwargs.pop("tokenizer", None) # Pull this out first, we only use it for stopping criteria
  1780. assistant_tokenizer = kwargs.pop("assistant_tokenizer", None) # only used for assisted generation
  1781. generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
  1782. self._validate_model_kwargs(model_kwargs.copy())
  1783. self._validate_assistant(assistant_model, tokenizer, assistant_tokenizer)
  1784. # 2. Set generation parameters if not already defined
  1785. if synced_gpus is None:
  1786. synced_gpus = (is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)) and dist.get_world_size() > 1
  1787. logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
  1788. stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
  1789. accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
  1790. requires_attention_mask = "encoder_outputs" not in model_kwargs
  1791. kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
  1792. # 3. Define model inputs
  1793. inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
  1794. inputs, generation_config.bos_token_id, model_kwargs
  1795. )
  1796. batch_size = inputs_tensor.shape[0]
  1797. device = inputs_tensor.device
  1798. self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=device)
  1799. # decoder-only models must use left-padding for batched generation.
  1800. if not self.config.is_encoder_decoder and not is_torchdynamo_compiling():
  1801. # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
  1802. # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
  1803. if (
  1804. generation_config._pad_token_tensor is not None
  1805. and batch_size > 1
  1806. and len(inputs_tensor.shape) == 2
  1807. and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor) > 0
  1808. ):
  1809. logger.warning(
  1810. "A decoder-only architecture is being used, but right-padding was detected! For correct "
  1811. "generation results, please set `padding_side='left'` when initializing the tokenizer."
  1812. )
  1813. # 4. Define other model kwargs
  1814. # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
  1815. # generating the first new token or not, and we only want to use the embeddings for the first new token)
  1816. if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
  1817. generation_config.use_cache = True
  1818. if not kwargs_has_attention_mask and requires_attention_mask and accepts_attention_mask:
  1819. model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
  1820. inputs_tensor, generation_config._pad_token_tensor, generation_config._eos_token_tensor
  1821. )
  1822. elif kwargs_has_attention_mask:
  1823. # TODO (joao): generalize this check with other types of inputs
  1824. if model_input_name == "input_ids" and len(model_kwargs["attention_mask"].shape) > 2:
  1825. raise ValueError("`attention_mask` passed to `generate` must be 2D.")
  1826. if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
  1827. # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
  1828. model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
  1829. inputs_tensor, model_kwargs, model_input_name, generation_config
  1830. )
  1831. # 5. Prepare `input_ids` which will be used for auto-regressive generation
  1832. if self.config.is_encoder_decoder:
  1833. input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
  1834. batch_size=batch_size,
  1835. model_input_name=model_input_name,
  1836. model_kwargs=model_kwargs,
  1837. decoder_start_token_id=generation_config._decoder_start_token_tensor,
  1838. device=inputs_tensor.device,
  1839. )
  1840. else:
  1841. input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
  1842. if generation_config.token_healing:
  1843. input_ids = self.heal_tokens(input_ids, tokenizer)
  1844. if streamer is not None:
  1845. streamer.put(input_ids.cpu())
  1846. # 6. Prepare `max_length` depending on other stopping criteria.
  1847. input_ids_length = input_ids.shape[-1]
  1848. has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
  1849. has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None
  1850. generation_config = self._prepare_generated_length(
  1851. generation_config=generation_config,
  1852. has_default_max_length=has_default_max_length,
  1853. has_default_min_length=has_default_min_length,
  1854. model_input_name=model_input_name,
  1855. inputs_tensor=inputs_tensor,
  1856. input_ids_length=input_ids_length,
  1857. )
  1858. # If the model supports `num_logits_to_keep` in forward(), set it to 1 to avoid computing the whole
  1859. # logit matrix. This can save a lot of memory during the first forward pass. Note that assisted decoding
  1860. # dynamically overrides this value as it can need more than the last token logits
  1861. if self._supports_num_logits_to_keep() and "num_logits_to_keep" not in model_kwargs:
  1862. model_kwargs["num_logits_to_keep"] = 1
  1863. self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
  1864. # 7. Prepare the cache.
  1865. # - `model_kwargs` may be updated in place with a cache as defined by the parameters in `generation_config`.
  1866. # - different models have a different cache name expected by the model (default = "past_key_values")
  1867. # - `max_length`, prepared above, is used to determine the maximum cache length
  1868. # TODO (joao): remove `user_defined_cache` after v4.47 (remove default conversion to legacy format)
  1869. cache_name = "past_key_values" if "mamba" not in self.__class__.__name__.lower() else "cache_params"
  1870. user_defined_cache = model_kwargs.get(cache_name)
  1871. max_cache_length = generation_config.max_length
  1872. if (
  1873. inputs_tensor.shape[1] != input_ids_length
  1874. and model_input_name == "inputs_embeds"
  1875. and not self.config.is_encoder_decoder
  1876. ):
  1877. max_cache_length += inputs_tensor.shape[1]
  1878. self._prepare_cache_for_generation(
  1879. generation_config, model_kwargs, assistant_model, batch_size, max_cache_length, device
  1880. )
  1881. # 8. determine generation mode
  1882. generation_mode = generation_config.get_generation_mode(assistant_model)
  1883. if streamer is not None and (generation_config.num_beams > 1):
  1884. raise ValueError(
  1885. "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
  1886. )
  1887. if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
  1888. warnings.warn(
  1889. "You are calling .generate() with the `input_ids` being on a device type different"
  1890. f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
  1891. f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
  1892. " Please make sure that you have put `input_ids` to the"
  1893. f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
  1894. " running `.generate()`.",
  1895. UserWarning,
  1896. )
  1897. # 9. prepare logits processors and stopping criteria
  1898. prepared_logits_processor = self._get_logits_processor(
  1899. generation_config=generation_config,
  1900. input_ids_seq_length=input_ids_length,
  1901. encoder_input_ids=inputs_tensor,
  1902. prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
  1903. logits_processor=logits_processor,
  1904. device=inputs_tensor.device,
  1905. model_kwargs=model_kwargs,
  1906. negative_prompt_ids=negative_prompt_ids,
  1907. negative_prompt_attention_mask=negative_prompt_attention_mask,
  1908. )
  1909. prepared_stopping_criteria = self._get_stopping_criteria(
  1910. generation_config=generation_config, stopping_criteria=stopping_criteria, tokenizer=tokenizer, **kwargs
  1911. )
  1912. # Set model_kwargs `use_cache` so we can use it later in forward runs
  1913. model_kwargs["use_cache"] = generation_config.use_cache
  1914. # 10. go into different generation modes
  1915. if generation_mode == GenerationMode.ASSISTED_GENERATION:
  1916. if generation_config.num_return_sequences > 1:
  1917. raise ValueError(
  1918. "num_return_sequences has to be 1 when doing assisted generate, "
  1919. f"but is {generation_config.num_return_sequences}."
  1920. )
  1921. if batch_size > 1:
  1922. raise ValueError("assisted generate is only supported for batch_size = 1")
  1923. if not model_kwargs["use_cache"]:
  1924. raise ValueError("assisted generate requires `use_cache=True`")
  1925. if generation_config.cache_implementation in ["static", "hybrid", "sliding_window"]:
  1926. raise ValueError("assisted generate is not supported with Static cache classes`")
  1927. if self._is_stateful:
  1928. # In assisted generation we need the ability to confirm whether the model would pick certain tokens,
  1929. # which is not possible with stateful models (they can't reset to a previous subset of generated text)
  1930. raise ValueError(
  1931. f"assisted generation is not supported with stateful models, such as {self.__class__.__name__}"
  1932. )
  1933. # 11. Get the candidate generator, given the parameterization
  1934. candidate_generator = self._get_candidate_generator(
  1935. generation_config=generation_config,
  1936. input_ids=input_ids,
  1937. inputs_tensor=inputs_tensor,
  1938. assistant_model=assistant_model,
  1939. logits_processor=logits_processor,
  1940. target_tokenizer=tokenizer,
  1941. assistant_tokenizer=assistant_tokenizer,
  1942. model_kwargs=model_kwargs,
  1943. )
  1944. # 12. run assisted generate
  1945. result = self._assisted_decoding(
  1946. input_ids,
  1947. candidate_generator=candidate_generator,
  1948. logits_processor=prepared_logits_processor,
  1949. stopping_criteria=prepared_stopping_criteria,
  1950. generation_config=generation_config,
  1951. synced_gpus=synced_gpus,
  1952. streamer=streamer,
  1953. **model_kwargs,
  1954. )
  1955. elif generation_mode == GenerationMode.DOLA_GENERATION:
  1956. if self._is_stateful:
  1957. # DoLa decoding was not designed for stateful models, and would require some changes
  1958. raise ValueError(
  1959. f"dola decoding is not supported with stateful models, such as {self.__class__.__name__}"
  1960. )
  1961. result = self._dola_decoding(
  1962. input_ids,
  1963. dola_layers=generation_config.dola_layers,
  1964. logits_processor=prepared_logits_processor,
  1965. stopping_criteria=prepared_stopping_criteria,
  1966. generation_config=generation_config,
  1967. synced_gpus=synced_gpus,
  1968. streamer=streamer,
  1969. **model_kwargs,
  1970. )
  1971. elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:
  1972. if not model_kwargs["use_cache"]:
  1973. raise ValueError("Contrastive search requires `use_cache=True`")
  1974. if self._is_stateful:
  1975. # Just like assisted generation, we need to be able to rollback to a previous state (see comment above)
  1976. raise ValueError(
  1977. f"contrastive search is not supported with stateful models, such as {self.__class__.__name__}"
  1978. )
  1979. result = self._contrastive_search(
  1980. input_ids,
  1981. logits_processor=prepared_logits_processor,
  1982. stopping_criteria=prepared_stopping_criteria,
  1983. generation_config=generation_config,
  1984. synced_gpus=synced_gpus,
  1985. streamer=streamer,
  1986. **model_kwargs,
  1987. )
  1988. elif generation_mode in (GenerationMode.SAMPLE, GenerationMode.GREEDY_SEARCH):
  1989. # 11. expand input_ids with `num_return_sequences` additional sequences per batch
  1990. input_ids, model_kwargs = self._expand_inputs_for_generation(
  1991. input_ids=input_ids,
  1992. expand_size=generation_config.num_return_sequences,
  1993. is_encoder_decoder=self.config.is_encoder_decoder,
  1994. **model_kwargs,
  1995. )
  1996. # 12. run sample (it degenerates to greedy search when `generation_config.do_sample=False`)
  1997. result = self._sample(
  1998. input_ids,
  1999. logits_processor=prepared_logits_processor,
  2000. stopping_criteria=prepared_stopping_criteria,
  2001. generation_config=generation_config,
  2002. synced_gpus=synced_gpus,
  2003. streamer=streamer,
  2004. **model_kwargs,
  2005. )
  2006. elif generation_mode in (GenerationMode.BEAM_SAMPLE, GenerationMode.BEAM_SEARCH):
  2007. # 11. prepare beam search scorer
  2008. beam_scorer = BeamSearchScorer(
  2009. batch_size=batch_size,
  2010. num_beams=generation_config.num_beams,
  2011. device=inputs_tensor.device,
  2012. length_penalty=generation_config.length_penalty,
  2013. do_early_stopping=generation_config.early_stopping,
  2014. num_beam_hyps_to_keep=generation_config.num_return_sequences,
  2015. max_length=generation_config.max_length,
  2016. )
  2017. # 12. interleave input_ids with `num_beams` additional sequences per batch
  2018. input_ids, model_kwargs = self._expand_inputs_for_generation(
  2019. input_ids=input_ids,
  2020. expand_size=generation_config.num_beams,
  2021. is_encoder_decoder=self.config.is_encoder_decoder,
  2022. **model_kwargs,
  2023. )
  2024. # 13. run beam sample
  2025. result = self._beam_search(
  2026. input_ids,
  2027. beam_scorer,
  2028. logits_processor=prepared_logits_processor,
  2029. stopping_criteria=prepared_stopping_criteria,
  2030. generation_config=generation_config,
  2031. synced_gpus=synced_gpus,
  2032. **model_kwargs,
  2033. )
  2034. elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:
  2035. # 11. prepare beam search scorer
  2036. beam_scorer = BeamSearchScorer(
  2037. batch_size=batch_size,
  2038. num_beams=generation_config.num_beams,
  2039. device=inputs_tensor.device,
  2040. length_penalty=generation_config.length_penalty,
  2041. do_early_stopping=generation_config.early_stopping,
  2042. num_beam_hyps_to_keep=generation_config.num_return_sequences,
  2043. num_beam_groups=generation_config.num_beam_groups,
  2044. max_length=generation_config.max_length,
  2045. )
  2046. # 12. interleave input_ids with `num_beams` additional sequences per batch
  2047. input_ids, model_kwargs = self._expand_inputs_for_generation(
  2048. input_ids=input_ids,
  2049. expand_size=generation_config.num_beams,
  2050. is_encoder_decoder=self.config.is_encoder_decoder,
  2051. **model_kwargs,
  2052. )
  2053. # 13. run beam search
  2054. result = self._group_beam_search(
  2055. input_ids,
  2056. beam_scorer,
  2057. logits_processor=prepared_logits_processor,
  2058. stopping_criteria=prepared_stopping_criteria,
  2059. generation_config=generation_config,
  2060. synced_gpus=synced_gpus,
  2061. **model_kwargs,
  2062. )
  2063. elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:
  2064. final_constraints = []
  2065. if generation_config.constraints is not None:
  2066. final_constraints = generation_config.constraints
  2067. if generation_config.force_words_ids is not None:
  2068. def typeerror():
  2069. raise ValueError(
  2070. "`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]` "
  2071. f"of positive integers, but is {generation_config.force_words_ids}."
  2072. )
  2073. if (
  2074. not isinstance(generation_config.force_words_ids, list)
  2075. or len(generation_config.force_words_ids) == 0
  2076. ):
  2077. typeerror()
  2078. for word_ids in generation_config.force_words_ids:
  2079. if isinstance(word_ids[0], list):
  2080. if not isinstance(word_ids, list) or len(word_ids) == 0:
  2081. typeerror()
  2082. if any(not isinstance(token_ids, list) for token_ids in word_ids):
  2083. typeerror()
  2084. if any(
  2085. any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
  2086. for token_ids in word_ids
  2087. ):
  2088. typeerror()
  2089. constraint = DisjunctiveConstraint(word_ids)
  2090. else:
  2091. if not isinstance(word_ids, list) or len(word_ids) == 0:
  2092. typeerror()
  2093. if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):
  2094. typeerror()
  2095. constraint = PhrasalConstraint(word_ids)
  2096. final_constraints.append(constraint)
  2097. # 11. prepare beam search scorer
  2098. constrained_beam_scorer = ConstrainedBeamSearchScorer(
  2099. constraints=final_constraints,
  2100. batch_size=batch_size,
  2101. num_beams=generation_config.num_beams,
  2102. device=inputs_tensor.device,
  2103. length_penalty=generation_config.length_penalty,
  2104. do_early_stopping=generation_config.early_stopping,
  2105. num_beam_hyps_to_keep=generation_config.num_return_sequences,
  2106. max_length=generation_config.max_length,
  2107. )
  2108. # 12. interleave input_ids with `num_beams` additional sequences per batch
  2109. input_ids, model_kwargs = self._expand_inputs_for_generation(
  2110. input_ids=input_ids,
  2111. expand_size=generation_config.num_beams,
  2112. is_encoder_decoder=self.config.is_encoder_decoder,
  2113. **model_kwargs,
  2114. )
  2115. # 13. run beam search
  2116. result = self._constrained_beam_search(
  2117. input_ids,
  2118. constrained_beam_scorer=constrained_beam_scorer,
  2119. logits_processor=prepared_logits_processor,
  2120. stopping_criteria=prepared_stopping_criteria,
  2121. generation_config=generation_config,
  2122. synced_gpus=synced_gpus,
  2123. **model_kwargs,
  2124. )
  2125. # Convert to legacy cache format if requested
  2126. if (
  2127. generation_config.return_legacy_cache is not False # Should check for `True` after v4.47
  2128. and not is_torchdynamo_compiling()
  2129. and hasattr(result, "past_key_values")
  2130. and hasattr(result.past_key_values, "to_legacy_cache")
  2131. and result.past_key_values.to_legacy_cache is not None
  2132. ):
  2133. # handle BC (convert by default if he user hasn't passed a cache AND the cache is of the default type)
  2134. should_convert_cache = generation_config.return_legacy_cache
  2135. is_user_defined_cache = user_defined_cache is not None
  2136. is_default_cache_type = (
  2137. type(result.past_key_values) == DynamicCache # noqa E721
  2138. or (
  2139. isinstance(result.past_key_values, EncoderDecoderCache)
  2140. and type(result.past_key_values.self_attention_cache) == DynamicCache # noqa E721
  2141. and type(result.past_key_values.cross_attention_cache) == DynamicCache # noqa E721
  2142. )
  2143. )
  2144. if not is_user_defined_cache and is_default_cache_type:
  2145. logger.warning_once(
  2146. "From v4.47 onwards, when a model cache is to be returned, `generate` will return a `Cache` "
  2147. "instance instead by default (as opposed to the legacy tuple of tuples format). If you want to "
  2148. "keep returning the legacy format, please set `return_legacy_cache=True`."
  2149. )
  2150. should_convert_cache = True
  2151. if should_convert_cache:
  2152. result.past_key_values = result.past_key_values.to_legacy_cache()
  2153. return result
  2154. def _has_unfinished_sequences(
  2155. self,
  2156. this_peer_finished: bool,
  2157. synced_gpus: bool,
  2158. device: torch.device,
  2159. cur_len: Optional[int] = None,
  2160. max_length: Optional[int] = None,
  2161. ) -> bool:
  2162. """
  2163. Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is
  2164. fed through `this_peer_finished`. ZeRO stage 3-friendly.
  2165. """
  2166. # torch.compile does not support data-dependent control flow. This is a workaround to allow torch.compile,
  2167. # although we lose the ability to stop when all sequences return an EOS token (and other stopping criteria)
  2168. # TODO (joao): remove this when torch's support for control flow is not experimental (https://pytorch.org/docs/stable/generated/torch.cond.html)
  2169. if is_torchdynamo_compiling():
  2170. return cur_len < max_length
  2171. else:
  2172. if synced_gpus:
  2173. # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
  2174. # The following logic allows an early break if all peers finished generating their sequence
  2175. this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(device)
  2176. # send 0.0 if we finished, 1.0 otherwise
  2177. dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
  2178. # did all peers finish? the reduced sum will be 0.0 then
  2179. if this_peer_finished_flag.item() == 0.0:
  2180. return False
  2181. elif this_peer_finished:
  2182. return False
  2183. return True
  2184. def heal_tokens(
  2185. self, input_ids: torch.LongTensor, tokenizer: Optional["PreTrainedTokenizerBase"] = None
  2186. ) -> torch.LongTensor:
  2187. r"""
  2188. Generates sequences of token ids for models with a language modeling head.
  2189. Parameters:
  2190. input_ids (`torch.LongTensor`): The sequence used as a prompt for the generation.
  2191. tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used to decode the input ids.
  2192. Return:
  2193. `torch.LongTensor` where each sequence has its tail token replaced with its appropriate extension.
  2194. """
  2195. if tokenizer is None:
  2196. raise ValueError(
  2197. " When generating with token healing, you must pass the model's tokenizer to the `tokenizer` "
  2198. "argument of `generate`."
  2199. )
  2200. bos_token_id, pad_token_id = tokenizer.bos_token_id, tokenizer.pad_token_id
  2201. vocab_trie = ExtensionsTrie(tokenizer.get_vocab())
  2202. generation_config = GenerationConfig(max_new_tokens=1, pad_token_id=pad_token_id)
  2203. # assumption: leading/trailing whitespace is not meaningful, so the prompts are
  2204. # stripped before re-tokenizing to desensitize generation to whitespace artefacts
  2205. prompts = [p.strip() for p in tokenizer.batch_decode(input_ids, skip_special_tokens=True)]
  2206. input_ids = tokenizer(
  2207. prompts,
  2208. return_tensors="pt",
  2209. padding=True,
  2210. ).input_ids.to(input_ids.device)
  2211. # replace bos with pad to not condition healing on it
  2212. input_ids = torch.where(input_ids == bos_token_id, pad_token_id, input_ids)
  2213. """
  2214. the latter code assumes the input_ids is not empty,
  2215. input_id has to be checked if contains elements
  2216. """
  2217. if input_ids.numel() == 0:
  2218. return input_ids
  2219. tail_ids = input_ids[:, -1].tolist()
  2220. space_tok = tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids(" "))[0]
  2221. # tail tokens are used for a prefix search, thus, whitespaces are replaced with
  2222. # their tokenization (e.g. 'Ġ') to enable search for tokens prefixed with a whitespace
  2223. tail_toks = (tokenizer.decode(t).replace(" ", space_tok) for t in tail_ids)
  2224. for batch_idx, (tail_id, tail_tok) in enumerate(zip(tail_ids, tail_toks)):
  2225. batch_ids = input_ids[batch_idx]
  2226. if torch.all(batch_ids == pad_token_id).item():
  2227. continue # skip empty sequences (all pad ids)
  2228. # apply bias for alternatives (extensions) to the tail token
  2229. """
  2230. seq_bias key has to be tuple with int so have to use
  2231. tokenizer function to convert str to int
  2232. """
  2233. seq_bias = {
  2234. (tokenizer.convert_tokens_to_ids(alt_tok),): 10.0 for alt_tok in vocab_trie.extensions(prefix=tail_tok)
  2235. }
  2236. if len(seq_bias) == 1:
  2237. continue # skip if there are no token alternatives to heal with
  2238. # slightly favor original token to limit aggressive healing e.g. 'http' -> 'https'
  2239. seq_bias[(tail_id,)] += 1.0
  2240. generation_config.update(sequence_bias=seq_bias)
  2241. trimmed_ids = batch_ids[:-1]
  2242. """
  2243. the latter code assumes trimmed_ids is not empty
  2244. so have to check the its element count
  2245. """
  2246. if trimmed_ids.numel() == 0:
  2247. continue
  2248. # if the prompt is a single (non-pad) token, regenerate from bos
  2249. if len(batch_ids[batch_ids != pad_token_id]) == 1:
  2250. trimmed_ids[-1] = bos_token_id
  2251. input_ids[batch_idx] = self.generate(trimmed_ids.unsqueeze(0), generation_config=generation_config)
  2252. return input_ids
  2253. def _dola_decoding(
  2254. self,
  2255. input_ids: torch.LongTensor,
  2256. dola_layers: Union[str, List[int]],
  2257. logits_processor: LogitsProcessorList,
  2258. stopping_criteria: StoppingCriteriaList,
  2259. generation_config: GenerationConfig,
  2260. synced_gpus: bool,
  2261. streamer: "BaseStreamer",
  2262. **model_kwargs,
  2263. ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
  2264. r"""
  2265. Generates sequences of token ids for models with a language modeling head using **dola decoding** and can be
  2266. used for decoder-only text models.
  2267. The method is based on the paper "DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language
  2268. Models" (https://arxiv.org/abs/2309.03883) in ICLR 2024.
  2269. Parameters:
  2270. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  2271. The sequence used as a prompt for the generation.
  2272. dola_layers (`Union[str, List[int]]`):
  2273. The candidate layers used in contrasting layers of DoLa. It can be either 1) 'low' or 'high', which
  2274. means the lower part or higher part of the model layers, respectively, or 2) a list of layer indices
  2275. to be used for candidate layers. The 0-th layer is the word embedding layer of the model.
  2276. logits_processor (`LogitsProcessorList`):
  2277. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  2278. used to modify the prediction scores of the language modeling head applied at each generation step.
  2279. stopping_criteria (`StoppingCriteriaList`, *optional*):
  2280. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  2281. used to tell if the generation loop should stop.
  2282. generation_config ([`~generation.GenerationConfig`]):
  2283. The generation configuration to be used as parametrization of the decoding method.
  2284. synced_gpus (`bool`):
  2285. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  2286. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  2287. streamer (`BaseStreamer`, *optional*):
  2288. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  2289. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  2290. model_kwargs:
  2291. Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
  2292. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  2293. Return:
  2294. [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
  2295. or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  2296. [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  2297. `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
  2298. `model.config.is_encoder_decoder=True`.
  2299. """
  2300. if self.config.is_encoder_decoder:
  2301. raise ValueError("DoLa decoding is only available for decoder-only models.")
  2302. # init values
  2303. pad_token_id = generation_config._pad_token_tensor
  2304. output_attentions = generation_config.output_attentions
  2305. output_hidden_states = generation_config.output_hidden_states
  2306. output_scores = generation_config.output_scores
  2307. output_logits = generation_config.output_logits
  2308. return_dict_in_generate = generation_config.return_dict_in_generate
  2309. has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
  2310. do_sample = generation_config.do_sample
  2311. # init attention / hidden states / scores tuples
  2312. scores = () if (return_dict_in_generate and output_scores) else None
  2313. raw_logits = () if (return_dict_in_generate and output_logits) else None
  2314. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  2315. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  2316. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  2317. # keep track of which sequences are already finished
  2318. batch_size = input_ids.shape[0]
  2319. unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
  2320. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  2321. this_peer_finished = False
  2322. # prepare layers for DoLa decoding
  2323. final_layer = self.config.get_text_config().num_hidden_layers
  2324. # if the model has tied word embeddings, we skip the word embeddings (0-th) layer and start from the 2nd layer,
  2325. # as the early exit from word embeddings will become identity function
  2326. # if the model is really shallow (<=2 layers), we use the 1st layer if it's not the final layer and the 0-th
  2327. # layer otherwise. Notice that DoLa does not help shallow models much.
  2328. if not self.config.tie_word_embeddings:
  2329. start_layer = 0
  2330. elif final_layer > 2:
  2331. start_layer = 2
  2332. elif final_layer == 2:
  2333. start_layer = 1
  2334. else:
  2335. start_layer = 0
  2336. # For `N`-layer models with `N <= 40` layers, the layers of `range(0, N // 2, 2)` and `range(N // 2, N, 2)`
  2337. # are used for `'low'` and `'high'` layers, respectively.
  2338. # For models with `N > 40` layers, the layers of `range(0, 20, 2)` and `range(N - 20, N, 2)` are used for
  2339. # `'low'` and `'high'` layers, respectively.
  2340. if isinstance(dola_layers, str) and dola_layers == "low":
  2341. if start_layer == final_layer // 2:
  2342. candidate_premature_layers = [start_layer]
  2343. else:
  2344. candidate_premature_layers = (
  2345. list(range(start_layer, final_layer // 2, 2))
  2346. if final_layer <= 40
  2347. else list(range(start_layer, 20, 2))
  2348. )
  2349. elif isinstance(dola_layers, str) and dola_layers == "high":
  2350. candidate_premature_layers = (
  2351. list(range(final_layer // 2, final_layer, 2))
  2352. if final_layer <= 40
  2353. else list(range(final_layer - 20, final_layer, 2))
  2354. )
  2355. # Set the `dola_layers` to a list of integers for layer indices to contrast manually specified layers.
  2356. elif isinstance(dola_layers, list):
  2357. candidate_premature_layers = [i for i in dola_layers if i < final_layer]
  2358. else:
  2359. raise ValueError("dola_layers must be either 'low', 'high' or a list of integers.")
  2360. lm_head = self.get_output_embeddings()
  2361. if lm_head is None:
  2362. raise ValueError("DoLa is not supported for models that don't have output embeddings.")
  2363. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  2364. # prepare model inputs
  2365. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  2366. # forward pass to get next token
  2367. outputs = self(
  2368. **model_inputs,
  2369. return_dict=True,
  2370. output_attentions=output_attentions,
  2371. output_hidden_states=True,
  2372. )
  2373. # .float() is needed to retain precision for later logits manipulations
  2374. final_layer_next_token_logits = outputs.logits[:, -1, :].detach().clone().float()
  2375. final_logits = outputs.logits[:, -1, :].float()
  2376. candidate_premature_logits = {}
  2377. for candidate_premature_layer in candidate_premature_layers:
  2378. candidate_premature_logits[candidate_premature_layer] = lm_head(
  2379. outputs.hidden_states[candidate_premature_layer][:, -1, :]
  2380. ).to(final_logits.device)
  2381. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  2382. model_kwargs = self._update_model_kwargs_for_generation(
  2383. outputs,
  2384. model_kwargs,
  2385. is_encoder_decoder=self.config.is_encoder_decoder,
  2386. )
  2387. if synced_gpus and this_peer_finished:
  2388. continue
  2389. next_token_logits = _dola_select_contrast(
  2390. candidate_premature_layers, candidate_premature_logits, final_logits
  2391. )
  2392. next_token_logits = next_token_logits.to(input_ids.device)
  2393. # pre-process distribution
  2394. next_token_scores = logits_processor(input_ids, next_token_logits)
  2395. # Store scores, attentions and hidden_states when required
  2396. if return_dict_in_generate:
  2397. if output_scores:
  2398. scores += (next_token_scores,)
  2399. if output_logits:
  2400. raw_logits += (final_layer_next_token_logits,)
  2401. if output_attentions:
  2402. decoder_attentions += (
  2403. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  2404. )
  2405. if self.config.is_encoder_decoder:
  2406. cross_attentions += (outputs.cross_attentions,)
  2407. if output_hidden_states:
  2408. decoder_hidden_states += (
  2409. (outputs.decoder_hidden_states,)
  2410. if self.config.is_encoder_decoder
  2411. else (outputs.hidden_states,)
  2412. )
  2413. if do_sample: # sample
  2414. probs = nn.functional.softmax(next_token_scores, dim=-1)
  2415. next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
  2416. else: # argmax
  2417. next_tokens = torch.argmax(next_token_scores, dim=-1)
  2418. # finished sentences should have their next token be a padding token
  2419. if has_eos_stopping_criteria:
  2420. next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
  2421. # update generated ids, model inputs, and length for next step
  2422. input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
  2423. if streamer is not None:
  2424. streamer.put(next_tokens.cpu())
  2425. # stop when each sentence is finished
  2426. unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
  2427. this_peer_finished = unfinished_sequences.max() == 0
  2428. if streamer is not None:
  2429. streamer.end()
  2430. if return_dict_in_generate:
  2431. return GenerateDecoderOnlyOutput(
  2432. sequences=input_ids,
  2433. scores=scores,
  2434. logits=raw_logits,
  2435. attentions=decoder_attentions,
  2436. hidden_states=decoder_hidden_states,
  2437. past_key_values=model_kwargs.get("past_key_values"),
  2438. )
  2439. else:
  2440. return input_ids
  2441. @torch.no_grad()
  2442. def _contrastive_search(
  2443. self,
  2444. input_ids: torch.LongTensor,
  2445. logits_processor: LogitsProcessorList,
  2446. stopping_criteria: StoppingCriteriaList,
  2447. generation_config: GenerationConfig,
  2448. synced_gpus: bool,
  2449. streamer: Optional["BaseStreamer"],
  2450. **model_kwargs,
  2451. ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
  2452. r"""
  2453. Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
  2454. be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2455. Parameters:
  2456. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  2457. The sequence used as a prompt for the generation.
  2458. logits_processor (`LogitsProcessorList`):
  2459. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  2460. used to modify the prediction scores of the language modeling head applied at each generation step.
  2461. stopping_criteria (`StoppingCriteriaList`):
  2462. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  2463. used to tell if the generation loop should stop.
  2464. generation_config ([`~generation.GenerationConfig`]):
  2465. The generation configuration to be used as parametrization of the decoding method.
  2466. synced_gpus (`bool`):
  2467. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  2468. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  2469. streamer (`BaseStreamer`, *optional*):
  2470. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  2471. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  2472. model_kwargs:
  2473. Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
  2474. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  2475. Return:
  2476. [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
  2477. or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  2478. [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  2479. `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
  2480. `model.config.is_encoder_decoder=True`.
  2481. """
  2482. # init values
  2483. has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
  2484. top_k = generation_config.top_k
  2485. penalty_alpha = generation_config.penalty_alpha
  2486. pad_token_id = generation_config._pad_token_tensor
  2487. output_attentions = generation_config.output_attentions
  2488. output_hidden_states = generation_config.output_hidden_states
  2489. output_scores = generation_config.output_scores
  2490. output_logits = generation_config.output_logits
  2491. return_dict_in_generate = generation_config.return_dict_in_generate
  2492. sequential = generation_config.low_memory
  2493. # init attention / hidden states / scores tuples
  2494. raw_logits = () if (return_dict_in_generate and output_logits) else None
  2495. scores = () if (return_dict_in_generate and output_scores) else None
  2496. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  2497. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  2498. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  2499. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  2500. if return_dict_in_generate and self.config.is_encoder_decoder:
  2501. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2502. encoder_hidden_states = (
  2503. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2504. )
  2505. # keep track of which sequences are already finished
  2506. batch_size = input_ids.shape[0]
  2507. unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
  2508. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  2509. # Create cosine_matrix_mask based on the attention_mask
  2510. cosine_matrix_mask = torch.ones_like(input_ids, dtype=torch.long)
  2511. if self.config.is_encoder_decoder:
  2512. if "decoder_attention_mask" in model_kwargs and model_kwargs["decoder_attention_mask"] is not None:
  2513. cosine_matrix_mask = model_kwargs["decoder_attention_mask"]
  2514. else:
  2515. cosine_matrix_mask = model_kwargs["attention_mask"]
  2516. cosine_matrix_mask = cosine_matrix_mask.repeat_interleave(top_k, dim=0)
  2517. this_peer_finished = False
  2518. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  2519. # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
  2520. # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
  2521. if model_kwargs.get("past_key_values") is None or (
  2522. isinstance(model_kwargs["past_key_values"], (Cache, EncoderDecoderCache))
  2523. and model_kwargs["past_key_values"].get_seq_length() == 0
  2524. ):
  2525. # prepare inputs
  2526. model_kwargs["use_cache"] = True
  2527. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  2528. # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
  2529. # the `encoder_outputs`
  2530. outputs = self(
  2531. **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
  2532. )
  2533. # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
  2534. # previous tokens)
  2535. if self.config.is_encoder_decoder:
  2536. last_hidden_states = outputs.decoder_hidden_states[-1]
  2537. else:
  2538. last_hidden_states = outputs.hidden_states[-1]
  2539. # next logit for contrastive search to select top-k candidate tokens
  2540. # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for this first iteration
  2541. # (the clone itself is always small)
  2542. # .float() is needed to retain precision for later logits manipulations
  2543. logit_for_next_step = outputs.logits[:, -1, :].clone().float()
  2544. logit_for_next_step = logit_for_next_step.to(input_ids.device)
  2545. model_kwargs = self._update_model_kwargs_for_generation(
  2546. outputs,
  2547. model_kwargs,
  2548. is_encoder_decoder=self.config.is_encoder_decoder,
  2549. )
  2550. if not sequential:
  2551. # Expands model inputs top_k times, for batched forward passes (akin to beam search).
  2552. _, model_kwargs = self._expand_inputs_for_generation(
  2553. expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
  2554. )
  2555. past_key_values = model_kwargs.get("past_key_values")
  2556. if past_key_values is None:
  2557. raise ValueError(
  2558. f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
  2559. "for contrastive search."
  2560. )
  2561. elif (
  2562. not isinstance(past_key_values[0], (tuple, torch.Tensor))
  2563. or past_key_values[0][0].shape[0] != batch_size
  2564. ):
  2565. raise ValueError(
  2566. f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
  2567. "used for contrastive search without further modifications."
  2568. )
  2569. # contrastive_search main logic start:
  2570. # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
  2571. # degeneration penalty
  2572. processed_logit_for_next_step = logits_processor(input_ids, logit_for_next_step)
  2573. next_probs = nn.functional.softmax(processed_logit_for_next_step, dim=-1)
  2574. top_k_probs, top_k_ids = torch.topk(next_probs, dim=-1, k=top_k)
  2575. # Store scores, attentions and hidden_states when required
  2576. if return_dict_in_generate:
  2577. if output_logits:
  2578. raw_logits += (logit_for_next_step,)
  2579. if output_scores:
  2580. scores += (processed_logit_for_next_step,)
  2581. if output_attentions:
  2582. decoder_attentions += (
  2583. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  2584. )
  2585. if self.config.is_encoder_decoder:
  2586. cross_attentions += (outputs.cross_attentions,)
  2587. if output_hidden_states:
  2588. decoder_hidden_states += (
  2589. (outputs.decoder_hidden_states,)
  2590. if self.config.is_encoder_decoder
  2591. else (outputs.hidden_states,)
  2592. )
  2593. # This is needed to properly delete outputs.logits which may be very large for this first iteration
  2594. # Otherwise a reference to outputs.logits is kept all along until after the next call to self.forward()
  2595. del outputs
  2596. if not sequential:
  2597. # Replicates the new past_key_values to match the `top_k` candidates
  2598. past = model_kwargs["past_key_values"]
  2599. # If it is a static cache, modify it in-place layer after layer to save memory
  2600. if isinstance(past, DynamicCache) or (
  2601. isinstance(past, EncoderDecoderCache) and isinstance(past.self_attention_cache, DynamicCache)
  2602. ):
  2603. past.batch_repeat_interleave(top_k)
  2604. else:
  2605. new_key_values = []
  2606. for layer in past:
  2607. items = []
  2608. # item is either the key or the value matrix
  2609. for item in layer:
  2610. items.append(item.repeat_interleave(top_k, dim=0))
  2611. new_key_values.append(tuple(items))
  2612. past = tuple(new_key_values)
  2613. model_kwargs["past_key_values"] = past
  2614. if sequential:
  2615. all_outputs = []
  2616. for i in range(top_k):
  2617. # compute the candidate tokens by the language model and collect their hidden_states
  2618. next_model_inputs = self.prepare_inputs_for_generation(top_k_ids[:, i].view(-1, 1), **model_kwargs)
  2619. outputs = self(
  2620. **next_model_inputs,
  2621. return_dict=True,
  2622. output_hidden_states=True,
  2623. output_attentions=output_attentions,
  2624. )
  2625. if isinstance(outputs["past_key_values"], DynamicCache) or (
  2626. isinstance(outputs["past_key_values"], EncoderDecoderCache)
  2627. and isinstance(outputs["past_key_values"].self_attention_cache, DynamicCache)
  2628. ):
  2629. # Remove past K-V from output since we don't need to stack later
  2630. outputs["past_key_values"] = None
  2631. # Remove last token from past K-V since we don't want to append it at this point
  2632. model_kwargs["past_key_values"].crop(-1)
  2633. all_outputs.append(outputs)
  2634. outputs = stack_model_outputs(all_outputs, self.config.get_text_config())
  2635. else:
  2636. # compute the candidate tokens by the language model and collect their hidden_states
  2637. # assembles top_k_ids into batch of size k
  2638. next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)
  2639. outputs = self(
  2640. **next_model_inputs,
  2641. return_dict=True,
  2642. output_hidden_states=True,
  2643. output_attentions=output_attentions,
  2644. )
  2645. # This is essential to avoid having a last reference to the big past K-V and double the necessary memory
  2646. # in the next loop
  2647. del next_model_inputs
  2648. # name is different for encoder-decoder and decoder-only models
  2649. if self.config.is_encoder_decoder:
  2650. next_hidden = outputs.decoder_hidden_states[-1]
  2651. full_hidden_states = outputs.decoder_hidden_states
  2652. else:
  2653. next_hidden = outputs.hidden_states[-1]
  2654. full_hidden_states = outputs.hidden_states
  2655. # .float() is needed to retain precision for later logits manipulations
  2656. logits = outputs.logits[:, -1, :].float()
  2657. context_hidden = last_hidden_states.repeat_interleave(top_k, dim=0)
  2658. # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
  2659. # model confidence. Keeping `selected_idx` on CPU enables multi-device contrastive search and doesn't
  2660. # introduce (noticeable) slowdowns on single-device runs.
  2661. selected_idx = _ranking_fast(
  2662. context_hidden, next_hidden, top_k_probs, cosine_matrix_mask, penalty_alpha, top_k
  2663. )
  2664. cosine_matrix_mask = torch.cat(
  2665. [cosine_matrix_mask, cosine_matrix_mask.new_ones((cosine_matrix_mask.shape[0], 1))], dim=-1
  2666. )
  2667. selected_idx = selected_idx.to("cpu")
  2668. # This will be used instead of the previous inneficient torch.stack(torch.split())
  2669. augmented_idx = torch.tensor([x + i * top_k for i, x in enumerate(selected_idx)])
  2670. # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
  2671. # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
  2672. # (model confidence minus degeneration penalty); (6) decoder hidden_states
  2673. next_tokens = top_k_ids[range(len(top_k_ids)), selected_idx]
  2674. next_hidden = torch.stack(torch.split(next_hidden.squeeze(dim=1), top_k))
  2675. next_hidden = next_hidden[range(batch_size), selected_idx, :]
  2676. last_hidden_states = torch.cat([last_hidden_states, next_hidden.unsqueeze(1)], dim=1)
  2677. next_decoder_hidden_states = ()
  2678. for layer in full_hidden_states:
  2679. layer = torch.stack(torch.split(layer, top_k))[range(batch_size), selected_idx, :]
  2680. next_decoder_hidden_states += (layer,)
  2681. # generate past_key_values cache of only the selected token
  2682. if sequential:
  2683. next_model_input = self.prepare_inputs_for_generation(
  2684. top_k_ids[:, selected_idx].view(-1, 1), **model_kwargs
  2685. )
  2686. selected_outputs = self(
  2687. **next_model_input,
  2688. return_dict=True,
  2689. output_hidden_states=False,
  2690. output_attentions=False,
  2691. )
  2692. next_past_key_values = selected_outputs["past_key_values"]
  2693. else:
  2694. _, next_past_key_values = self._extract_past_from_model_output(outputs)
  2695. # Do it in-place layer per layer to save memory
  2696. if isinstance(next_past_key_values, DynamicCache) or (
  2697. isinstance(next_past_key_values, EncoderDecoderCache)
  2698. and isinstance(next_past_key_values.self_attention_cache, DynamicCache)
  2699. ):
  2700. next_past_key_values.batch_select_indices(augmented_idx)
  2701. else:
  2702. new_key_values = []
  2703. for layer in next_past_key_values:
  2704. items = []
  2705. # item is either the key or the value matrix
  2706. for item in layer:
  2707. items.append(item[augmented_idx, ...])
  2708. new_key_values.append(tuple(items))
  2709. next_past_key_values = tuple(new_key_values)
  2710. logit_for_next_step = torch.stack(torch.split(logits, top_k))[range(batch_size), selected_idx, :]
  2711. logit_for_next_step = logit_for_next_step.to(input_ids.device)
  2712. # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
  2713. if self.config.is_encoder_decoder:
  2714. next_step_cross_attentions = ()
  2715. next_step_decoder_attentions = ()
  2716. if output_attentions:
  2717. for layer in outputs.cross_attentions:
  2718. layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
  2719. next_step_cross_attentions += (layer,)
  2720. for layer in outputs.decoder_attentions:
  2721. layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
  2722. next_step_decoder_attentions += (layer,)
  2723. outputs = Seq2SeqLMOutput(
  2724. past_key_values=next_past_key_values,
  2725. decoder_hidden_states=next_decoder_hidden_states,
  2726. decoder_attentions=next_step_decoder_attentions or None,
  2727. cross_attentions=next_step_cross_attentions or None,
  2728. )
  2729. else:
  2730. next_step_attentions = ()
  2731. if output_attentions:
  2732. for layer in outputs.attentions:
  2733. layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
  2734. next_step_attentions += (layer,)
  2735. outputs = CausalLMOutputWithPast(
  2736. past_key_values=next_past_key_values,
  2737. hidden_states=next_decoder_hidden_states,
  2738. attentions=next_step_attentions or None,
  2739. )
  2740. # contrastive_search main logic end
  2741. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  2742. model_kwargs = self._update_model_kwargs_for_generation(
  2743. outputs,
  2744. model_kwargs,
  2745. is_encoder_decoder=self.config.is_encoder_decoder,
  2746. )
  2747. if synced_gpus and this_peer_finished:
  2748. continue
  2749. # finished sentences should have their next token be a padding token
  2750. if has_eos_stopping_criteria:
  2751. next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
  2752. # update generated ids, model inputs, and length for next step
  2753. input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
  2754. if streamer is not None:
  2755. streamer.put(next_tokens.cpu())
  2756. # stop when each sentence is finished
  2757. unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
  2758. this_peer_finished = unfinished_sequences.max() == 0
  2759. if streamer is not None:
  2760. streamer.end()
  2761. if return_dict_in_generate:
  2762. # Contrastive search works by forward looking at the next token, so we need to exclude it from
  2763. # `past_key_values` to be consistent with the other decoding methods
  2764. if model_kwargs.get("past_key_values") is not None:
  2765. if isinstance(model_kwargs["past_key_values"], DynamicCache) or (
  2766. isinstance(model_kwargs["past_key_values"], EncoderDecoderCache)
  2767. and isinstance(model_kwargs["past_key_values"].self_attention_cache, DynamicCache)
  2768. ):
  2769. model_kwargs["past_key_values"].crop(-1)
  2770. else:
  2771. past_key_values = []
  2772. for layer in model_kwargs["past_key_values"]:
  2773. layer_past_key_values = []
  2774. for item in layer:
  2775. layer_past_key_values.append(item[..., :-1, :])
  2776. past_key_values.append(tuple(layer_past_key_values))
  2777. model_kwargs["past_key_values"] = tuple(past_key_values)
  2778. if self.config.is_encoder_decoder:
  2779. return GenerateEncoderDecoderOutput(
  2780. sequences=input_ids,
  2781. scores=scores,
  2782. logits=raw_logits,
  2783. encoder_attentions=encoder_attentions,
  2784. encoder_hidden_states=encoder_hidden_states,
  2785. decoder_attentions=decoder_attentions,
  2786. cross_attentions=cross_attentions,
  2787. decoder_hidden_states=decoder_hidden_states,
  2788. past_key_values=model_kwargs.get("past_key_values"),
  2789. )
  2790. else:
  2791. return GenerateDecoderOnlyOutput(
  2792. sequences=input_ids,
  2793. scores=scores,
  2794. logits=raw_logits,
  2795. attentions=decoder_attentions,
  2796. hidden_states=decoder_hidden_states,
  2797. past_key_values=model_kwargs.get("past_key_values"),
  2798. )
  2799. else:
  2800. return input_ids
  2801. def _sample(
  2802. self,
  2803. input_ids: torch.LongTensor,
  2804. logits_processor: LogitsProcessorList,
  2805. stopping_criteria: StoppingCriteriaList,
  2806. generation_config: GenerationConfig,
  2807. synced_gpus: bool,
  2808. streamer: Optional["BaseStreamer"],
  2809. **model_kwargs,
  2810. ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
  2811. r"""
  2812. Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and
  2813. can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2814. Parameters:
  2815. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  2816. The sequence used as a prompt for the generation.
  2817. logits_processor (`LogitsProcessorList`):
  2818. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  2819. used to modify the prediction scores of the language modeling head applied at each generation step.
  2820. stopping_criteria (`StoppingCriteriaList`):
  2821. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  2822. used to tell if the generation loop should stop.
  2823. generation_config ([`~generation.GenerationConfig`]):
  2824. The generation configuration to be used as parametrization of the decoding method.
  2825. synced_gpus (`bool`):
  2826. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  2827. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  2828. streamer (`BaseStreamer`, *optional*):
  2829. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  2830. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  2831. model_kwargs:
  2832. Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
  2833. an encoder-decoder model the kwargs should include `encoder_outputs`.
  2834. Return:
  2835. [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:
  2836. A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  2837. [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  2838. `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
  2839. `model.config.is_encoder_decoder=True`.
  2840. """
  2841. # init values
  2842. pad_token_id = generation_config._pad_token_tensor
  2843. output_attentions = generation_config.output_attentions
  2844. output_hidden_states = generation_config.output_hidden_states
  2845. output_scores = generation_config.output_scores
  2846. output_logits = generation_config.output_logits
  2847. return_dict_in_generate = generation_config.return_dict_in_generate
  2848. max_length = generation_config.max_length
  2849. has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
  2850. do_sample = generation_config.do_sample
  2851. # init attention / hidden states / scores tuples
  2852. scores = () if (return_dict_in_generate and output_scores) else None
  2853. raw_logits = () if (return_dict_in_generate and output_logits) else None
  2854. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  2855. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  2856. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  2857. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  2858. if return_dict_in_generate and self.config.is_encoder_decoder:
  2859. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2860. encoder_hidden_states = (
  2861. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2862. )
  2863. # keep track of which sequences are already finished
  2864. batch_size, cur_len = input_ids.shape
  2865. this_peer_finished = False
  2866. unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
  2867. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  2868. while self._has_unfinished_sequences(
  2869. this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length
  2870. ):
  2871. # prepare model inputs
  2872. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  2873. # prepare variable output controls (note: some models won't accept all output controls)
  2874. model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
  2875. model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
  2876. # forward pass to get next token
  2877. outputs = self(**model_inputs, return_dict=True)
  2878. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  2879. model_kwargs = self._update_model_kwargs_for_generation(
  2880. outputs,
  2881. model_kwargs,
  2882. is_encoder_decoder=self.config.is_encoder_decoder,
  2883. )
  2884. if synced_gpus and this_peer_finished:
  2885. continue
  2886. # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
  2887. # (the clone itself is always small)
  2888. next_token_logits = outputs.logits.clone()[:, -1, :].float()
  2889. next_token_logits = next_token_logits.to(input_ids.device)
  2890. # pre-process distribution
  2891. next_token_scores = logits_processor(input_ids, next_token_logits)
  2892. # Store scores, attentions and hidden_states when required
  2893. if return_dict_in_generate:
  2894. if output_scores:
  2895. scores += (next_token_scores,)
  2896. if output_logits:
  2897. raw_logits += (next_token_logits,)
  2898. if output_attentions:
  2899. decoder_attentions += (
  2900. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  2901. )
  2902. if self.config.is_encoder_decoder:
  2903. cross_attentions += (outputs.cross_attentions,)
  2904. if output_hidden_states:
  2905. decoder_hidden_states += (
  2906. (outputs.decoder_hidden_states,)
  2907. if self.config.is_encoder_decoder
  2908. else (outputs.hidden_states,)
  2909. )
  2910. # token selection
  2911. if do_sample:
  2912. probs = nn.functional.softmax(next_token_scores, dim=-1)
  2913. # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
  2914. next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
  2915. else:
  2916. next_tokens = torch.argmax(next_token_scores, dim=-1)
  2917. # finished sentences should have their next token be a padding token
  2918. if has_eos_stopping_criteria:
  2919. next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
  2920. # update generated ids, model inputs, and length for next step
  2921. input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
  2922. if streamer is not None:
  2923. streamer.put(next_tokens.cpu())
  2924. unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
  2925. this_peer_finished = unfinished_sequences.max() == 0
  2926. cur_len += 1
  2927. # This is needed to properly delete outputs.logits which may be very large for first iteration
  2928. # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
  2929. del outputs
  2930. if streamer is not None:
  2931. streamer.end()
  2932. if return_dict_in_generate:
  2933. if self.config.is_encoder_decoder:
  2934. return GenerateEncoderDecoderOutput(
  2935. sequences=input_ids,
  2936. scores=scores,
  2937. logits=raw_logits,
  2938. encoder_attentions=encoder_attentions,
  2939. encoder_hidden_states=encoder_hidden_states,
  2940. decoder_attentions=decoder_attentions,
  2941. cross_attentions=cross_attentions,
  2942. decoder_hidden_states=decoder_hidden_states,
  2943. past_key_values=model_kwargs.get("past_key_values"),
  2944. )
  2945. else:
  2946. return GenerateDecoderOnlyOutput(
  2947. sequences=input_ids,
  2948. scores=scores,
  2949. logits=raw_logits,
  2950. attentions=decoder_attentions,
  2951. hidden_states=decoder_hidden_states,
  2952. past_key_values=model_kwargs.get("past_key_values"),
  2953. )
  2954. else:
  2955. return input_ids
  2956. def _temporary_reorder_cache(self, past_key_values, beam_idx):
  2957. """
  2958. Temporary function to handle the different types of cache reordering processes while we roll out `Cache`.
  2959. TODO: standardize cache formats and make all models compatible with `Cache`. It would remove the need
  2960. for this function, with `Cache.reorder_cache` being the sole remaining code path
  2961. """
  2962. model_class = self.__class__.__name__.lower()
  2963. # Exception 1: code path for models using the legacy cache format
  2964. if isinstance(past_key_values, (tuple, list)):
  2965. past_key_values = self._reorder_cache(past_key_values, beam_idx)
  2966. # Exception 2: models with different cache formats. These are limited to `DynamicCache` until their
  2967. # cache format is standardized, to avoid adding complexity to the codebase.
  2968. elif "gptbigcode" in model_class:
  2969. if not isinstance(past_key_values, (DynamicCache, EncoderDecoderCache)):
  2970. raise ValueError(
  2971. f"Using an unsupported cache format with {model_class}. Currently, it only supports the "
  2972. "legacy tuple format or `DynamicCache`"
  2973. )
  2974. past_key_values = self._reorder_cache(past_key_values, beam_idx)
  2975. past_key_values = DynamicCache.from_legacy_cache(past_key_values)
  2976. # Standard code path: use the `Cache.reorder_cache`
  2977. else:
  2978. past_key_values.reorder_cache(beam_idx)
  2979. return past_key_values
  2980. def _beam_search(
  2981. self,
  2982. input_ids: torch.LongTensor,
  2983. beam_scorer: BeamScorer,
  2984. logits_processor: LogitsProcessorList,
  2985. stopping_criteria: StoppingCriteriaList,
  2986. generation_config: GenerationConfig,
  2987. synced_gpus: bool,
  2988. **model_kwargs,
  2989. ) -> Union[GenerateBeamOutput, torch.LongTensor]:
  2990. r"""
  2991. Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
  2992. can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2993. Parameters:
  2994. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  2995. The sequence used as a prompt for the generation.
  2996. beam_scorer (`BeamScorer`):
  2997. An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
  2998. sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
  2999. logits_processor (`LogitsProcessorList`):
  3000. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  3001. used to modify the prediction scores of the language modeling head applied at each generation step.
  3002. stopping_criteria (`StoppingCriteriaList`:
  3003. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  3004. used to tell if the generation loop should stop.
  3005. generation_config ([`~generation.GenerationConfig`]):
  3006. The generation configuration to be used as parametrization of the decoding method.
  3007. synced_gpus (`bool`):
  3008. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  3009. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  3010. model_kwargs:
  3011. Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
  3012. an encoder-decoder model the kwargs should include `encoder_outputs`.
  3013. Return:
  3014. [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
  3015. `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  3016. [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  3017. `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
  3018. `model.config.is_encoder_decoder=True`.
  3019. """
  3020. # init values
  3021. pad_token_id = generation_config._pad_token_tensor
  3022. eos_token_id = generation_config._eos_token_tensor
  3023. output_attentions = generation_config.output_attentions
  3024. output_hidden_states = generation_config.output_hidden_states
  3025. output_scores = generation_config.output_scores
  3026. output_logits = generation_config.output_logits
  3027. return_dict_in_generate = generation_config.return_dict_in_generate
  3028. sequential = generation_config.low_memory
  3029. do_sample = generation_config.do_sample
  3030. batch_size = len(beam_scorer._beam_hyps)
  3031. num_beams = beam_scorer.num_beams
  3032. batch_beam_size, cur_len = input_ids.shape
  3033. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  3034. if num_beams * batch_size != batch_beam_size:
  3035. raise ValueError(
  3036. f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
  3037. )
  3038. # init attention / hidden states / scores tuples
  3039. scores = () if (return_dict_in_generate and output_scores) else None
  3040. raw_logits = () if (return_dict_in_generate and output_logits) else None
  3041. beam_indices = (
  3042. tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
  3043. )
  3044. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  3045. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  3046. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  3047. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  3048. if return_dict_in_generate and self.config.is_encoder_decoder:
  3049. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  3050. encoder_hidden_states = (
  3051. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  3052. )
  3053. # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
  3054. # of the first beam are considered to avoid sampling the exact same tokens across all beams.
  3055. beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
  3056. beam_scores[:, 1:] = -1e9
  3057. beam_scores = beam_scores.view((batch_size * num_beams,))
  3058. this_peer_finished = False
  3059. decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
  3060. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  3061. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  3062. # prepare variable output controls (note: some models won't accept all output controls)
  3063. model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
  3064. model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
  3065. # if sequential is True, split the input to batches of batch_size and run sequentially
  3066. if sequential:
  3067. if any(
  3068. model_name in self.__class__.__name__.lower()
  3069. for model_name in [
  3070. "fsmt",
  3071. "reformer",
  3072. "ctrl",
  3073. "gpt_bigcode",
  3074. "transo_xl",
  3075. "xlnet",
  3076. "cpm",
  3077. "jamba",
  3078. ]
  3079. ):
  3080. raise RuntimeError(
  3081. f"Currently generation for {self.__class__.__name__} is not supported "
  3082. f"for `low_memory beam_search`. Please open an issue on GitHub if you need this feature."
  3083. )
  3084. inputs_per_sub_batches = _split_model_inputs(
  3085. model_inputs,
  3086. split_size=batch_size,
  3087. full_batch_size=batch_beam_size,
  3088. config=self.config.get_text_config(),
  3089. )
  3090. outputs_per_sub_batch = [
  3091. self(**inputs_per_sub_batch, return_dict=True) for inputs_per_sub_batch in inputs_per_sub_batches
  3092. ]
  3093. outputs = stack_model_outputs(outputs_per_sub_batch, self.config.get_text_config())
  3094. else: # Unchanged original behavior
  3095. outputs = self(**model_inputs, return_dict=True)
  3096. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  3097. model_kwargs = self._update_model_kwargs_for_generation(
  3098. outputs,
  3099. model_kwargs,
  3100. is_encoder_decoder=self.config.is_encoder_decoder,
  3101. )
  3102. if synced_gpus and this_peer_finished:
  3103. cur_len = cur_len + 1
  3104. continue
  3105. # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
  3106. # (the clone itself is always small)
  3107. # .float() is needed to retain precision for later logits manipulations
  3108. next_token_logits = outputs.logits[:, -1, :].clone().float()
  3109. next_token_logits = next_token_logits.to(input_ids.device)
  3110. next_token_scores = nn.functional.log_softmax(
  3111. next_token_logits, dim=-1
  3112. ) # (batch_size * num_beams, vocab_size)
  3113. next_token_scores_processed = logits_processor(input_ids, next_token_scores)
  3114. next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
  3115. next_token_scores_processed
  3116. )
  3117. # Store scores, attentions and hidden_states when required
  3118. if return_dict_in_generate:
  3119. if output_scores:
  3120. scores += (next_token_scores_processed,)
  3121. if output_logits:
  3122. raw_logits += (next_token_logits,)
  3123. if output_attentions:
  3124. decoder_attentions += (
  3125. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  3126. )
  3127. if self.config.is_encoder_decoder:
  3128. cross_attentions += (outputs.cross_attentions,)
  3129. if output_hidden_states:
  3130. decoder_hidden_states += (
  3131. (outputs.decoder_hidden_states,)
  3132. if self.config.is_encoder_decoder
  3133. else (outputs.hidden_states,)
  3134. )
  3135. # reshape for beam search
  3136. vocab_size = next_token_scores.shape[-1]
  3137. next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
  3138. # Beam token selection: pick 1 + eos_token_id.shape[0] next tokens for each beam so we have at least 1
  3139. # non eos token per beam.
  3140. n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
  3141. n_tokens_to_keep = max(2, 1 + n_eos_tokens) * num_beams
  3142. if do_sample:
  3143. probs = nn.functional.softmax(next_token_scores, dim=-1)
  3144. next_tokens = torch.multinomial(probs, num_samples=n_tokens_to_keep)
  3145. next_token_scores = torch.gather(next_token_scores, -1, next_tokens)
  3146. next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)
  3147. next_tokens = torch.gather(next_tokens, -1, _indices)
  3148. else:
  3149. next_token_scores, next_tokens = torch.topk(
  3150. next_token_scores, n_tokens_to_keep, dim=1, largest=True, sorted=True
  3151. )
  3152. next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
  3153. next_tokens = next_tokens % vocab_size
  3154. # stateless
  3155. beam_outputs = beam_scorer.process(
  3156. input_ids,
  3157. next_token_scores,
  3158. next_tokens,
  3159. next_indices,
  3160. pad_token_id=pad_token_id,
  3161. eos_token_id=eos_token_id,
  3162. beam_indices=beam_indices,
  3163. decoder_prompt_len=decoder_prompt_len,
  3164. )
  3165. beam_scores = beam_outputs["next_beam_scores"]
  3166. beam_next_tokens = beam_outputs["next_beam_tokens"]
  3167. beam_idx = beam_outputs["next_beam_indices"]
  3168. input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
  3169. # This is needed to properly delete outputs.logits which may be very large for first iteration
  3170. # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
  3171. # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
  3172. # (that way the memory peak does not include outputs.logits)
  3173. del outputs
  3174. if model_kwargs.get("past_key_values", None) is not None:
  3175. model_kwargs["past_key_values"] = self._temporary_reorder_cache(
  3176. model_kwargs["past_key_values"], beam_idx
  3177. )
  3178. if return_dict_in_generate and output_scores:
  3179. beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
  3180. # increase cur_len
  3181. cur_len = cur_len + 1
  3182. if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
  3183. this_peer_finished = True
  3184. sequence_outputs = beam_scorer.finalize(
  3185. input_ids,
  3186. beam_scores,
  3187. next_tokens,
  3188. next_indices,
  3189. pad_token_id=pad_token_id,
  3190. eos_token_id=eos_token_id,
  3191. max_length=stopping_criteria.max_length,
  3192. beam_indices=beam_indices,
  3193. decoder_prompt_len=decoder_prompt_len,
  3194. )
  3195. if return_dict_in_generate:
  3196. if not output_scores:
  3197. sequence_outputs["sequence_scores"] = None
  3198. if self.config.is_encoder_decoder:
  3199. return GenerateBeamEncoderDecoderOutput(
  3200. sequences=sequence_outputs["sequences"],
  3201. sequences_scores=sequence_outputs["sequence_scores"],
  3202. scores=scores,
  3203. logits=raw_logits,
  3204. beam_indices=sequence_outputs["beam_indices"],
  3205. encoder_attentions=encoder_attentions,
  3206. encoder_hidden_states=encoder_hidden_states,
  3207. decoder_attentions=decoder_attentions,
  3208. cross_attentions=cross_attentions,
  3209. decoder_hidden_states=decoder_hidden_states,
  3210. past_key_values=model_kwargs.get("past_key_values"),
  3211. )
  3212. else:
  3213. return GenerateBeamDecoderOnlyOutput(
  3214. sequences=sequence_outputs["sequences"],
  3215. sequences_scores=sequence_outputs["sequence_scores"],
  3216. scores=scores,
  3217. logits=raw_logits,
  3218. beam_indices=sequence_outputs["beam_indices"],
  3219. attentions=decoder_attentions,
  3220. hidden_states=decoder_hidden_states,
  3221. past_key_values=model_kwargs.get("past_key_values"),
  3222. )
  3223. else:
  3224. return sequence_outputs["sequences"]
  3225. def _group_beam_search(
  3226. self,
  3227. input_ids: torch.LongTensor,
  3228. beam_scorer: BeamScorer,
  3229. logits_processor: LogitsProcessorList,
  3230. stopping_criteria: StoppingCriteriaList,
  3231. generation_config: GenerationConfig,
  3232. synced_gpus: bool,
  3233. **model_kwargs,
  3234. ):
  3235. r"""
  3236. Generates sequences of token ids for models with a language modeling head using **diverse beam search
  3237. decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  3238. Parameters:
  3239. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  3240. The sequence used as a prompt for the generation.
  3241. beam_scorer (`BeamScorer`):
  3242. An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
  3243. sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
  3244. logits_processor (`LogitsProcessorList`):
  3245. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  3246. used to modify the prediction scores of the language modeling head applied at each generation step.
  3247. stopping_criteria (`StoppingCriteriaList`):
  3248. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  3249. used to tell if the generation loop should stop.
  3250. generation_config ([`~generation.GenerationConfig`]):
  3251. The generation configuration to be used as parametrization of the decoding method.
  3252. synced_gpus (`bool`):
  3253. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  3254. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  3255. model_kwargs:
  3256. Additional model specific kwargs that will be forwarded to the `forward` function of the model. If
  3257. model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  3258. Return:
  3259. [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
  3260. `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  3261. [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  3262. `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
  3263. `model.config.is_encoder_decoder=True`.
  3264. """
  3265. # init values
  3266. pad_token_id = generation_config._pad_token_tensor
  3267. eos_token_id = generation_config._eos_token_tensor
  3268. output_attentions = generation_config.output_attentions
  3269. output_hidden_states = generation_config.output_hidden_states
  3270. output_scores = generation_config.output_scores
  3271. output_logits = generation_config.output_logits
  3272. return_dict_in_generate = generation_config.return_dict_in_generate
  3273. num_beams = beam_scorer.num_beams
  3274. num_beam_groups = beam_scorer.num_beam_groups
  3275. num_sub_beams = num_beams // num_beam_groups
  3276. batch_size = len(beam_scorer._beam_hyps) // num_beam_groups
  3277. device = input_ids.device
  3278. batch_beam_size, cur_len = input_ids.shape
  3279. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  3280. if return_dict_in_generate and output_scores:
  3281. beam_indices = [tuple(() for _ in range(num_sub_beams * batch_size)) for _ in range(num_beam_groups)]
  3282. else:
  3283. beam_indices = None
  3284. if num_beams * batch_size != batch_beam_size:
  3285. raise ValueError(
  3286. f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
  3287. )
  3288. # init attention / hidden states / scores tuples
  3289. scores = () if (return_dict_in_generate and output_scores) else None
  3290. raw_logits = () if (return_dict_in_generate and output_logits) else None
  3291. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  3292. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  3293. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  3294. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  3295. if return_dict_in_generate and self.config.is_encoder_decoder:
  3296. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  3297. encoder_hidden_states = (
  3298. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  3299. )
  3300. # initialise score of first beam of each group with 0 and the rest with -1e9. This ensures that the beams in
  3301. # the same group don't produce same tokens every time.
  3302. beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device)
  3303. beam_scores[:, ::num_sub_beams] = 0
  3304. beam_scores = beam_scores.view((batch_size * num_beams,))
  3305. this_peer_finished = False
  3306. decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
  3307. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  3308. # predicted tokens in cur_len step
  3309. current_tokens = torch.zeros(batch_size * num_beams, dtype=input_ids.dtype, device=device)
  3310. # indices which will form the beams in the next time step
  3311. reordering_indices = torch.zeros(batch_size * num_beams, dtype=torch.long, device=device)
  3312. # do one decoder step on all beams of all sentences in batch
  3313. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  3314. # prepare variable output controls (note: some models won't accept all output controls)
  3315. model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
  3316. model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
  3317. outputs = self(**model_inputs, return_dict=True)
  3318. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  3319. model_kwargs = self._update_model_kwargs_for_generation(
  3320. outputs,
  3321. model_kwargs,
  3322. is_encoder_decoder=self.config.is_encoder_decoder,
  3323. )
  3324. if synced_gpus and this_peer_finished:
  3325. cur_len = cur_len + 1
  3326. continue
  3327. if output_scores:
  3328. processed_score = torch.zeros_like(outputs.logits[:, -1, :])
  3329. if output_logits:
  3330. # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
  3331. # (the clone itself is always small)
  3332. raw_logit_score = outputs.logits[:, -1, :].clone()
  3333. raw_logit_score = raw_logit_score.to(input_ids.device)
  3334. for beam_group_idx in range(num_beam_groups):
  3335. group_start_idx = beam_group_idx * num_sub_beams
  3336. group_end_idx = min(group_start_idx + num_sub_beams, num_beams)
  3337. group_size = group_end_idx - group_start_idx
  3338. # indices of beams of current group among all sentences in batch
  3339. batch_group_indices = []
  3340. for batch_idx in range(batch_size):
  3341. batch_group_indices.extend(
  3342. [batch_idx * num_beams + idx for idx in range(group_start_idx, group_end_idx)]
  3343. )
  3344. group_input_ids = input_ids[batch_group_indices]
  3345. # select outputs of beams of current group only
  3346. # No need to clone() the logits here as they will not retain outputs.logits at the end of the loop
  3347. # .float() is needed to retain precision for later logits manipulations
  3348. next_token_logits = outputs.logits[batch_group_indices, -1, :].float()
  3349. next_token_logits = next_token_logits.to(input_ids.device)
  3350. next_token_scores = nn.functional.log_softmax(
  3351. next_token_logits, dim=-1
  3352. ) # (batch_size * group_size, vocab_size)
  3353. vocab_size = next_token_scores.shape[-1]
  3354. next_token_scores_processed = logits_processor(
  3355. group_input_ids, next_token_scores, current_tokens=current_tokens, beam_group_idx=beam_group_idx
  3356. )
  3357. next_token_scores = next_token_scores_processed + beam_scores[batch_group_indices].unsqueeze(-1)
  3358. next_token_scores = next_token_scores.expand_as(next_token_scores_processed)
  3359. if output_scores:
  3360. processed_score[batch_group_indices] = next_token_scores_processed
  3361. # reshape for beam search
  3362. next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size)
  3363. # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
  3364. n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
  3365. next_token_scores, next_tokens = torch.topk(
  3366. next_token_scores, max(2, 1 + n_eos_tokens) * group_size, dim=1, largest=True, sorted=True
  3367. )
  3368. next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
  3369. next_tokens = next_tokens % vocab_size
  3370. # stateless
  3371. process_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
  3372. beam_outputs = beam_scorer.process(
  3373. group_input_ids,
  3374. next_token_scores,
  3375. next_tokens,
  3376. next_indices,
  3377. pad_token_id=pad_token_id,
  3378. eos_token_id=eos_token_id,
  3379. beam_indices=process_beam_indices,
  3380. group_index=beam_group_idx,
  3381. decoder_prompt_len=decoder_prompt_len,
  3382. )
  3383. beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"]
  3384. beam_next_tokens = beam_outputs["next_beam_tokens"]
  3385. beam_idx = beam_outputs["next_beam_indices"]
  3386. if return_dict_in_generate and output_scores:
  3387. beam_indices[beam_group_idx] = tuple(
  3388. beam_indices[beam_group_idx][beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices[0]))
  3389. )
  3390. input_ids[batch_group_indices] = group_input_ids[beam_idx]
  3391. group_input_ids = torch.cat([group_input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
  3392. current_tokens[batch_group_indices] = group_input_ids[:, -1]
  3393. # (beam_idx // group_size) -> batch_idx
  3394. # (beam_idx % group_size) -> offset of idx inside the group
  3395. reordering_indices[batch_group_indices] = (
  3396. num_beams * torch.div(beam_idx, group_size, rounding_mode="floor")
  3397. + group_start_idx
  3398. + (beam_idx % group_size)
  3399. )
  3400. # Store scores, attentions and hidden_states when required
  3401. if return_dict_in_generate:
  3402. if output_scores:
  3403. scores += (processed_score,)
  3404. if output_logits:
  3405. raw_logits += (raw_logit_score,)
  3406. if output_attentions:
  3407. decoder_attentions += (
  3408. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  3409. )
  3410. if self.config.is_encoder_decoder:
  3411. cross_attentions += (outputs.cross_attentions,)
  3412. if output_hidden_states:
  3413. decoder_hidden_states += (
  3414. (outputs.decoder_hidden_states,)
  3415. if self.config.is_encoder_decoder
  3416. else (outputs.hidden_states,)
  3417. )
  3418. input_ids = torch.cat([input_ids, current_tokens.unsqueeze(-1)], dim=-1)
  3419. # This is needed to properly delete outputs.logits which may be very large for first iteration
  3420. # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
  3421. # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
  3422. # (that way the memory peak does not include outputs.logits)
  3423. del outputs
  3424. if model_kwargs.get("past_key_values", None) is not None:
  3425. model_kwargs["past_key_values"] = self._temporary_reorder_cache(
  3426. model_kwargs["past_key_values"], reordering_indices
  3427. )
  3428. # increase cur_len
  3429. cur_len = cur_len + 1
  3430. if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
  3431. this_peer_finished = True
  3432. final_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
  3433. sequence_outputs = beam_scorer.finalize(
  3434. input_ids,
  3435. beam_scores,
  3436. next_tokens,
  3437. next_indices,
  3438. pad_token_id=pad_token_id,
  3439. eos_token_id=eos_token_id,
  3440. max_length=stopping_criteria.max_length,
  3441. beam_indices=final_beam_indices,
  3442. decoder_prompt_len=decoder_prompt_len,
  3443. )
  3444. if return_dict_in_generate:
  3445. if not output_scores:
  3446. sequence_outputs["sequence_scores"] = None
  3447. if self.config.is_encoder_decoder:
  3448. return GenerateBeamEncoderDecoderOutput(
  3449. sequences=sequence_outputs["sequences"],
  3450. sequences_scores=sequence_outputs["sequence_scores"],
  3451. scores=scores,
  3452. logits=raw_logits,
  3453. beam_indices=sequence_outputs["beam_indices"],
  3454. encoder_attentions=encoder_attentions,
  3455. encoder_hidden_states=encoder_hidden_states,
  3456. decoder_attentions=decoder_attentions,
  3457. cross_attentions=cross_attentions,
  3458. decoder_hidden_states=decoder_hidden_states,
  3459. past_key_values=model_kwargs.get("past_key_values"),
  3460. )
  3461. else:
  3462. return GenerateBeamDecoderOnlyOutput(
  3463. sequences=sequence_outputs["sequences"],
  3464. sequences_scores=sequence_outputs["sequence_scores"],
  3465. scores=scores,
  3466. logits=raw_logits,
  3467. beam_indices=sequence_outputs["beam_indices"],
  3468. attentions=decoder_attentions,
  3469. hidden_states=decoder_hidden_states,
  3470. past_key_values=model_kwargs.get("past_key_values"),
  3471. )
  3472. else:
  3473. return sequence_outputs["sequences"]
  3474. def _constrained_beam_search(
  3475. self,
  3476. input_ids: torch.LongTensor,
  3477. constrained_beam_scorer: ConstrainedBeamSearchScorer,
  3478. logits_processor: LogitsProcessorList,
  3479. stopping_criteria: StoppingCriteriaList,
  3480. generation_config: GenerationConfig,
  3481. synced_gpus: bool,
  3482. **model_kwargs,
  3483. ) -> Union[GenerateBeamOutput, torch.LongTensor]:
  3484. r"""
  3485. Generates sequences of token ids for models with a language modeling head using **constrained beam search
  3486. decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  3487. Parameters:
  3488. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  3489. The sequence used as a prompt for the generation.
  3490. constrained_beam_scorer (`ConstrainedBeamSearchScorer`):
  3491. A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
  3492. sorted during generation, while satisfying a list of positive constraints. For more information, the
  3493. documentation of [`ConstrainedBeamSearchScorer`] should be read.
  3494. logits_processor (`LogitsProcessorList`):
  3495. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  3496. used to modify the prediction scores of the language modeling head applied at each generation step.
  3497. stopping_criteria (`StoppingCriteriaList`):
  3498. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  3499. used to tell if the generation loop should stop.
  3500. generation_config ([`~generation.GenerationConfig`]):
  3501. The generation configuration to be used as parametrization of the decoding method.
  3502. synced_gpus (`bool`):
  3503. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  3504. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  3505. model_kwargs:
  3506. Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
  3507. an encoder-decoder model the kwargs should include `encoder_outputs`.
  3508. Return:
  3509. [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
  3510. `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  3511. [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  3512. `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
  3513. `model.config.is_encoder_decoder=True`.
  3514. """
  3515. # init values
  3516. pad_token_id = generation_config._pad_token_tensor
  3517. eos_token_id = generation_config._eos_token_tensor
  3518. output_attentions = generation_config.output_attentions
  3519. output_hidden_states = generation_config.output_hidden_states
  3520. output_scores = generation_config.output_scores
  3521. output_logits = generation_config.output_logits
  3522. return_dict_in_generate = generation_config.return_dict_in_generate
  3523. batch_size = len(constrained_beam_scorer._beam_hyps)
  3524. num_beams = constrained_beam_scorer.num_beams
  3525. batch_beam_size, cur_len = input_ids.shape
  3526. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  3527. if num_beams * batch_size != batch_beam_size:
  3528. raise ValueError(
  3529. f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
  3530. )
  3531. # init attention / hidden states / scores tuples
  3532. scores = () if (return_dict_in_generate and output_scores) else None
  3533. raw_logits = () if (return_dict_in_generate and output_logits) else None
  3534. beam_indices = (
  3535. tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
  3536. )
  3537. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  3538. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  3539. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  3540. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  3541. if return_dict_in_generate and self.config.is_encoder_decoder:
  3542. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  3543. encoder_hidden_states = (
  3544. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  3545. )
  3546. # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
  3547. # of the first beam are considered to avoid sampling the exact same tokens across all beams.
  3548. beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
  3549. beam_scores[:, 1:] = -1e9
  3550. beam_scores = beam_scores.view((batch_size * num_beams,))
  3551. this_peer_finished = False
  3552. decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
  3553. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  3554. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  3555. # prepare variable output controls (note: some models won't accept all output controls)
  3556. model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
  3557. model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
  3558. outputs = self(**model_inputs, return_dict=True)
  3559. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  3560. model_kwargs = self._update_model_kwargs_for_generation(
  3561. outputs,
  3562. model_kwargs,
  3563. is_encoder_decoder=self.config.is_encoder_decoder,
  3564. )
  3565. if synced_gpus and this_peer_finished:
  3566. cur_len = cur_len + 1
  3567. continue
  3568. # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
  3569. # (the clone itself is always small)
  3570. # .float() is needed to retain precision for later logits manipulations
  3571. next_token_logits = outputs.logits[:, -1, :].clone().float()
  3572. next_token_logits = next_token_logits.to(input_ids.device)
  3573. next_token_scores = nn.functional.log_softmax(
  3574. next_token_logits, dim=-1
  3575. ) # (batch_size * num_beams, vocab_size)
  3576. next_token_scores_processed = logits_processor(input_ids, next_token_scores)
  3577. next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
  3578. next_token_scores_processed
  3579. )
  3580. scores_for_all_vocab = next_token_scores.clone()
  3581. # Store scores, attentions and hidden_states when required
  3582. if return_dict_in_generate:
  3583. if output_scores:
  3584. scores += (next_token_scores,)
  3585. if output_logits:
  3586. raw_logits += (next_token_logits,)
  3587. if output_attentions:
  3588. decoder_attentions += (
  3589. (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
  3590. )
  3591. if self.config.is_encoder_decoder:
  3592. cross_attentions += (outputs.cross_attentions,)
  3593. if output_hidden_states:
  3594. decoder_hidden_states += (
  3595. (outputs.decoder_hidden_states,)
  3596. if self.config.is_encoder_decoder
  3597. else (outputs.hidden_states,)
  3598. )
  3599. # reshape for beam search
  3600. vocab_size = next_token_scores.shape[-1]
  3601. next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
  3602. # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
  3603. n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
  3604. next_token_scores, next_tokens = torch.topk(
  3605. next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
  3606. )
  3607. next_indices = (next_tokens / vocab_size).long()
  3608. next_tokens = next_tokens % vocab_size
  3609. # stateless
  3610. beam_outputs = constrained_beam_scorer.process(
  3611. input_ids,
  3612. next_token_scores,
  3613. next_tokens,
  3614. next_indices,
  3615. scores_for_all_vocab,
  3616. pad_token_id=pad_token_id,
  3617. eos_token_id=eos_token_id,
  3618. beam_indices=beam_indices,
  3619. decoder_prompt_len=decoder_prompt_len,
  3620. )
  3621. beam_scores = beam_outputs["next_beam_scores"]
  3622. beam_next_tokens = beam_outputs["next_beam_tokens"]
  3623. beam_idx = beam_outputs["next_beam_indices"]
  3624. input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
  3625. # This is needed to properly delete outputs.logits which may be very large for first iteration
  3626. # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
  3627. # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
  3628. # (that way the memory peak does not include outputs.logits)
  3629. del outputs
  3630. if model_kwargs.get("past_key_values", None) is not None:
  3631. model_kwargs["past_key_values"] = self._temporary_reorder_cache(
  3632. model_kwargs["past_key_values"], beam_idx
  3633. )
  3634. if return_dict_in_generate and output_scores:
  3635. beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
  3636. # increase cur_len
  3637. cur_len = cur_len + 1
  3638. if constrained_beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
  3639. this_peer_finished = True
  3640. sequence_outputs = constrained_beam_scorer.finalize(
  3641. input_ids,
  3642. beam_scores,
  3643. next_tokens,
  3644. next_indices,
  3645. pad_token_id=pad_token_id,
  3646. eos_token_id=eos_token_id,
  3647. max_length=stopping_criteria.max_length,
  3648. beam_indices=beam_indices,
  3649. decoder_prompt_len=decoder_prompt_len,
  3650. )
  3651. if return_dict_in_generate:
  3652. if not output_scores:
  3653. sequence_outputs["sequence_scores"] = None
  3654. if self.config.is_encoder_decoder:
  3655. return GenerateBeamEncoderDecoderOutput(
  3656. sequences=sequence_outputs["sequences"],
  3657. sequences_scores=sequence_outputs["sequence_scores"],
  3658. scores=scores,
  3659. logits=raw_logits,
  3660. beam_indices=sequence_outputs["beam_indices"],
  3661. encoder_attentions=encoder_attentions,
  3662. encoder_hidden_states=encoder_hidden_states,
  3663. decoder_attentions=decoder_attentions,
  3664. cross_attentions=cross_attentions,
  3665. decoder_hidden_states=decoder_hidden_states,
  3666. past_key_values=model_kwargs.get("past_key_values"),
  3667. )
  3668. else:
  3669. return GenerateBeamDecoderOnlyOutput(
  3670. sequences=sequence_outputs["sequences"],
  3671. sequences_scores=sequence_outputs["sequence_scores"],
  3672. scores=scores,
  3673. logits=raw_logits,
  3674. beam_indices=sequence_outputs["beam_indices"],
  3675. attentions=decoder_attentions,
  3676. hidden_states=decoder_hidden_states,
  3677. past_key_values=model_kwargs.get("past_key_values"),
  3678. )
  3679. else:
  3680. return sequence_outputs["sequences"]
  3681. def _assisted_decoding(
  3682. self,
  3683. input_ids: torch.LongTensor,
  3684. candidate_generator: CandidateGenerator,
  3685. logits_processor: LogitsProcessorList,
  3686. stopping_criteria: StoppingCriteriaList,
  3687. generation_config: GenerationConfig,
  3688. synced_gpus: bool,
  3689. streamer: Optional["BaseStreamer"],
  3690. **model_kwargs,
  3691. ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
  3692. r"""
  3693. Generates sequences of token ids for models with a language modeling head using **greedy decoding** or
  3694. **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a
  3695. candidate decoding strategy. Can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text
  3696. models.
  3697. Parameters:
  3698. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  3699. The sequence used as a prompt for the generation.
  3700. candidate_generator (`CandidateGenerator`):
  3701. A derived instance of [`CandidateGenerator`] that defines how candidate sequences are generated. For
  3702. more information, the documentation of [`CandidateGenerator`] should be read.
  3703. logits_processor (`LogitsProcessorList`):
  3704. An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
  3705. used to modify the prediction scores of the language modeling head applied at each generation step.
  3706. stopping_criteria (`StoppingCriteriaList`):
  3707. An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
  3708. used to tell if the generation loop should stop.
  3709. generation_config ([`~generation.GenerationConfig`]):
  3710. The generation configuration to be used as parametrization of the decoding method.
  3711. synced_gpus (`bool`):
  3712. Whether to continue running the while loop until max_length (needed to avoid deadlocking with
  3713. `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
  3714. streamer (`BaseStreamer`, *optional*):
  3715. Streamer object that will be used to stream the generated sequences. Generated tokens are passed
  3716. through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
  3717. model_kwargs:
  3718. Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
  3719. If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  3720. Return:
  3721. [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
  3722. `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
  3723. [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  3724. `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
  3725. `model.config.is_encoder_decoder=True`.
  3726. """
  3727. # init values
  3728. do_sample = generation_config.do_sample
  3729. output_attentions = generation_config.output_attentions
  3730. output_hidden_states = generation_config.output_hidden_states
  3731. output_scores = generation_config.output_scores
  3732. output_logits = generation_config.output_logits
  3733. return_dict_in_generate = generation_config.return_dict_in_generate
  3734. # init attention / hidden states / scores tuples
  3735. scores = () if (return_dict_in_generate and output_scores) else None
  3736. raw_logits = () if (return_dict_in_generate and output_logits) else None
  3737. decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
  3738. cross_attentions = () if (return_dict_in_generate and output_attentions) else None
  3739. decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
  3740. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  3741. if return_dict_in_generate and self.config.is_encoder_decoder:
  3742. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  3743. encoder_hidden_states = (
  3744. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  3745. )
  3746. # keep track of which sequences are already finished
  3747. batch_size = input_ids.shape[0]
  3748. unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
  3749. model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
  3750. this_peer_finished = False
  3751. is_first_iteration = True # to preserve the same API in the output as other generation methods
  3752. while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
  3753. cur_len = input_ids.shape[-1]
  3754. # 1. Fetch candidate sequences from a `CandidateGenerator`
  3755. candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)
  3756. if candidate_logits is not None:
  3757. candidate_logits = candidate_logits.to(self.device)
  3758. candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]
  3759. is_done_candidate = stopping_criteria(candidate_input_ids, None)
  3760. # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain
  3761. # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,
  3762. # we use this forward pass to also pick the subsequent logits in the original model.
  3763. # 2.1. Prepare the model inputs
  3764. candidate_kwargs = copy.copy(model_kwargs)
  3765. candidate_kwargs = _prepare_attention_mask(
  3766. candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder
  3767. )
  3768. candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])
  3769. if "cache_position" in candidate_kwargs:
  3770. candidate_kwargs["cache_position"] = torch.cat(
  3771. (
  3772. candidate_kwargs["cache_position"],
  3773. torch.arange(cur_len, cur_len + candidate_length, device=input_ids.device, dtype=torch.long),
  3774. ),
  3775. dim=0,
  3776. )
  3777. model_inputs = self.prepare_inputs_for_generation(candidate_input_ids, **candidate_kwargs)
  3778. if "num_logits_to_keep" in model_inputs:
  3779. model_inputs["num_logits_to_keep"] = candidate_length + 1
  3780. # 2.2. Run a forward pass on the candidate sequence
  3781. # prepare variable output controls (note: some models won't accept all output controls)
  3782. model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
  3783. model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
  3784. outputs = self(**model_inputs)
  3785. # 2.3. Process the new logits
  3786. # .float() is needed to retain precision for later logits manipulations
  3787. new_logits = outputs.logits[:, -candidate_length - 1 :].float() # excludes the input prompt if present
  3788. new_logits = new_logits.to(input_ids.device)
  3789. next_token_logits = new_logits.clone()
  3790. if len(logits_processor) > 0:
  3791. for i in range(candidate_length + 1):
  3792. new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])
  3793. # 3. Select the accepted tokens. There are two possible cases:
  3794. # Case 1: `do_sample=True` and we have logits for the candidates (originally from speculative decoding)
  3795. # 👉 Apply algorithm 1 from the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf).
  3796. if do_sample and candidate_logits is not None:
  3797. valid_tokens, n_matches = _speculative_sampling(
  3798. candidate_input_ids,
  3799. candidate_logits,
  3800. candidate_length,
  3801. new_logits,
  3802. is_done_candidate,
  3803. )
  3804. # Case 2: all other cases (originally from assisted generation) 👉 Compare the tokens selected from the
  3805. # original model logits with the candidate tokens. We can keep the candidate tokens until the first
  3806. # mismatch, or until the max length is reached.
  3807. else:
  3808. if do_sample:
  3809. probs = new_logits.softmax(dim=-1)
  3810. selected_tokens = torch.multinomial(probs[0, :, :], num_samples=1).squeeze(1)[None, :]
  3811. else:
  3812. selected_tokens = new_logits.argmax(dim=-1)
  3813. candidate_new_tokens = candidate_input_ids[:, cur_len:]
  3814. n_matches = ((~(candidate_new_tokens == selected_tokens[:, :-1])).cumsum(dim=-1) < 1).sum()
  3815. # Ensure we don't generate beyond max_len or an EOS token
  3816. if is_done_candidate and n_matches == candidate_length:
  3817. n_matches -= 1
  3818. valid_tokens = selected_tokens[:, : n_matches + 1]
  3819. # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated
  3820. # by the model after the last candidate match is also valid, as it is generated from a correct sequence.
  3821. # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there
  3822. # is no match.
  3823. # 4.1. Get the valid continuation, after the matching tokens
  3824. input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
  3825. if streamer is not None:
  3826. streamer.put(valid_tokens.cpu())
  3827. new_cur_len = input_ids.shape[-1]
  3828. # 4.2. Discard past key values relative to unused assistant tokens
  3829. new_cache_size = new_cur_len - 1
  3830. outputs.past_key_values = _crop_past_key_values(self, outputs.past_key_values, new_cache_size)
  3831. # 5. Update the candidate generation strategy if needed
  3832. candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)
  3833. # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
  3834. model_kwargs = self._update_model_kwargs_for_generation(
  3835. outputs,
  3836. model_kwargs,
  3837. is_encoder_decoder=self.config.is_encoder_decoder,
  3838. num_new_tokens=n_matches + 1,
  3839. )
  3840. if synced_gpus and this_peer_finished:
  3841. continue
  3842. # Store scores, attentions and hidden_states when required
  3843. # Assistant: modified to append one tuple element per token, as in the other generation methods.
  3844. if return_dict_in_generate:
  3845. newly_added_length = n_matches + 1
  3846. if output_scores:
  3847. scores += tuple(new_logits[:, i, :] for i in range(newly_added_length))
  3848. if output_logits:
  3849. raw_logits += tuple(next_token_logits[:, i, :] for i in range(newly_added_length))
  3850. newly_added_length = new_cur_len if is_first_iteration else newly_added_length
  3851. if output_attentions:
  3852. if self.config.is_encoder_decoder:
  3853. cross_attentions = _split_model_outputs(
  3854. cross_attentions, outputs.cross_attentions, cur_len, newly_added_length
  3855. )
  3856. decoder_attentions = _split_model_outputs(
  3857. decoder_attentions,
  3858. outputs.decoder_attentions,
  3859. cur_len,
  3860. newly_added_length,
  3861. is_decoder_attention=True,
  3862. )
  3863. # some (V)LLMs have hard requirement on SDPA and thus never return attn
  3864. elif outputs.attentions[0] is not None:
  3865. decoder_attentions = _split_model_outputs(
  3866. decoder_attentions,
  3867. outputs.attentions,
  3868. cur_len,
  3869. newly_added_length,
  3870. is_decoder_attention=True,
  3871. )
  3872. if output_hidden_states:
  3873. if self.config.is_encoder_decoder:
  3874. decoder_hidden_states = _split_model_outputs(
  3875. decoder_hidden_states, outputs.decoder_hidden_states, cur_len, newly_added_length
  3876. )
  3877. else:
  3878. decoder_hidden_states = _split_model_outputs(
  3879. decoder_hidden_states, outputs.hidden_states, cur_len, newly_added_length
  3880. )
  3881. unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
  3882. this_peer_finished = unfinished_sequences.max() == 0
  3883. is_first_iteration = False
  3884. if streamer is not None:
  3885. streamer.end()
  3886. if (
  3887. hasattr(candidate_generator, "assistant_model")
  3888. and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"
  3889. ):
  3890. candidate_generator.assistant_model.generation_config.num_assistant_tokens = (
  3891. candidate_generator.num_assistant_tokens
  3892. )
  3893. if return_dict_in_generate:
  3894. if self.config.is_encoder_decoder:
  3895. return GenerateEncoderDecoderOutput(
  3896. sequences=input_ids,
  3897. scores=scores,
  3898. logits=raw_logits,
  3899. encoder_attentions=encoder_attentions,
  3900. encoder_hidden_states=encoder_hidden_states,
  3901. decoder_attentions=decoder_attentions,
  3902. cross_attentions=cross_attentions,
  3903. decoder_hidden_states=decoder_hidden_states,
  3904. past_key_values=model_kwargs.get("past_key_values"),
  3905. )
  3906. else:
  3907. return GenerateDecoderOnlyOutput(
  3908. sequences=input_ids,
  3909. scores=scores,
  3910. logits=raw_logits,
  3911. attentions=decoder_attentions,
  3912. hidden_states=decoder_hidden_states,
  3913. past_key_values=model_kwargs.get("past_key_values"),
  3914. )
  3915. else:
  3916. return input_ids
  3917. def _speculative_sampling(
  3918. candidate_input_ids,
  3919. candidate_logits,
  3920. candidate_length,
  3921. new_logits,
  3922. is_done_candidate,
  3923. ):
  3924. """
  3925. Applies sampling as in the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf, algorithm 1). Returns
  3926. the selected tokens, as well as the number of candidate matches.
  3927. NOTE: Unless otherwise stated, the variable names match those in the paper.
  3928. """
  3929. new_candidate_input_ids = candidate_input_ids[:, -candidate_length:]
  3930. # Gets the probabilities from the logits. q_i and p_i denote the assistant and model probabilities of the tokens
  3931. # selected by the assistant, respectively.
  3932. q = candidate_logits.softmax(dim=-1)
  3933. q_i = q[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
  3934. p = new_logits.softmax(dim=-1)
  3935. p_i = p[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
  3936. probability_ratio = p_i / q_i
  3937. # When probability_ratio > 1 (i.e. q_i(x) < p_i(x), or "assistant probability of the candidate token is smaller
  3938. # than the model probability for the same token"), keep the token. Otherwise reject with p = 1 - probability_ratio
  3939. # (= keep with p = probability_ratio). Keep all the tokens until the first rejection
  3940. r_i = torch.rand_like(probability_ratio)
  3941. is_accepted = r_i <= probability_ratio
  3942. n_matches = ((~is_accepted).cumsum(dim=-1) < 1).sum() # this is `n` in algorithm 1
  3943. # Ensure we don't generate beyond max_len or an EOS token (not in algorithm 1, but needed for correct behavior)
  3944. if is_done_candidate and n_matches == candidate_length:
  3945. # Output length is assumed to be `n_matches + 1`. Since we won't generate another token with the target model
  3946. # due to acceptance on EOS we fix `n_matches`
  3947. n_matches -= 1
  3948. valid_tokens = new_candidate_input_ids[:, : n_matches + 1]
  3949. else:
  3950. # Next token selection: if there is a rejection, adjust the distribution from the main model before sampling.
  3951. gamma = candidate_logits.shape[1]
  3952. p_n_plus_1 = p[:, n_matches, :]
  3953. if n_matches < gamma:
  3954. q_n_plus_1 = q[:, n_matches, :]
  3955. p_prime = torch.clamp((p_n_plus_1 - q_n_plus_1), min=0)
  3956. p_prime.div_(p_prime.sum())
  3957. else:
  3958. p_prime = p_n_plus_1
  3959. t = torch.multinomial(p_prime, num_samples=1).squeeze(1)[None, :]
  3960. # The selected tokens include the matches (if any) plus the next sampled tokens
  3961. if n_matches > 0:
  3962. valid_tokens = torch.cat((new_candidate_input_ids[:, :n_matches], t), dim=-1)
  3963. else:
  3964. valid_tokens = t
  3965. return valid_tokens, n_matches
  3966. def _split_model_outputs(outputs, new_outputs, cur_len, added_len, is_decoder_attention=False):
  3967. """
  3968. Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple
  3969. where each member corresponds to a single generated token.
  3970. """
  3971. # Retrocompatibility: in our generation functions, the first iteration includes the attention/hidden states for the
  3972. # prompt.
  3973. if len(outputs) == 0:
  3974. new_tuple = ()
  3975. for layer in new_outputs:
  3976. last_dim_size = cur_len if is_decoder_attention else layer.shape[-1]
  3977. new_tuple += (layer[..., :cur_len, :last_dim_size],)
  3978. outputs += (new_tuple,)
  3979. # The first iteration contains the prompt + 1 generated token, let's update the length variables accordingly
  3980. cur_len += 1
  3981. added_len -= cur_len
  3982. for i in range(added_len):
  3983. new_tuple = ()
  3984. for layer in new_outputs:
  3985. last_dim_size = cur_len + i if is_decoder_attention else layer.shape[-1]
  3986. new_tuple += (layer[..., i : i + 1, :last_dim_size],)
  3987. outputs += (new_tuple,)
  3988. return outputs
  3989. def _ranking_fast(
  3990. context_hidden: torch.FloatTensor,
  3991. next_hidden: torch.FloatTensor,
  3992. next_top_k_probs: torch.FloatTensor,
  3993. cosine_matrix_mask: torch.LongTensor,
  3994. alpha: float,
  3995. beam_width: int,
  3996. ) -> torch.FloatTensor:
  3997. """
  3998. Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
  3999. in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
  4000. row in the batch.
  4001. """
  4002. norm_context_hidden = context_hidden / context_hidden.norm(dim=2, keepdim=True)
  4003. norm_next_hidden = next_hidden / next_hidden.norm(dim=2, keepdim=True)
  4004. cosine_matrix = torch.matmul(norm_context_hidden, norm_next_hidden.transpose(1, 2)).squeeze(-1) # [B*K, S]
  4005. # Penalize cosine_matrix based on the cosine_matrix_mask (ignore padding positions)
  4006. # Using a large negative value for masked positions
  4007. cosine_matrix_mask = cosine_matrix_mask.to(dtype=cosine_matrix.dtype)
  4008. cosine_matrix_mask = (1 - cosine_matrix_mask) * torch.finfo(cosine_matrix.dtype).min
  4009. cosine_matrix = cosine_matrix + cosine_matrix_mask
  4010. degeneration_penalty, _ = torch.max(cosine_matrix, dim=-1) # [B*K]
  4011. next_top_k_probs = next_top_k_probs.view(-1) # [B*K]
  4012. contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
  4013. contrastive_score = torch.stack(torch.split(contrastive_score, beam_width)) # [B, K]
  4014. _, selected_idx = contrastive_score.max(dim=-1) # [B]
  4015. return selected_idx
  4016. def _split(data, full_batch_size: int, num_hidden_layers: int, split_size: int = None):
  4017. """
  4018. Takes care of three cases:
  4019. 1. data is a tensor: e.g. last_hidden_state, pooler_output etc. split them on the batch_size dim
  4020. 2. data is a tuple: e.g. hidden_states, attentions etc. Keep the tuple as it is and split each tensor in it and
  4021. return a list of tuples
  4022. 3. data is a tuple of tuples, e.g. past_key_values. Keep the tuple as it is and split each tuple in it and
  4023. return a list of tuples of tuples
  4024. (see documentation of ModelOutput)
  4025. """
  4026. if data is None:
  4027. return [None] * (full_batch_size // split_size)
  4028. if isinstance(data, torch.Tensor):
  4029. return [data[i : i + split_size] for i in range(0, full_batch_size, split_size)]
  4030. # New cache format
  4031. elif isinstance(data, DynamicCache) or (
  4032. isinstance(data, EncoderDecoderCache) and isinstance(data.self_attention_cache, DynamicCache)
  4033. ):
  4034. return data.batch_split(full_batch_size, split_size, num_hidden_layers)
  4035. elif isinstance(data, tuple):
  4036. # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
  4037. if isinstance(data[0], tuple):
  4038. return [
  4039. tuple(tuple(tensor[i : i + split_size] for tensor in inner_tuple) for inner_tuple in data)
  4040. for i in range(0, full_batch_size, split_size)
  4041. ]
  4042. else:
  4043. return [
  4044. tuple(sub_tensor[i : i + split_size] for sub_tensor in data)
  4045. for i in range(0, full_batch_size, split_size)
  4046. ]
  4047. else:
  4048. raise TypeError(f"Unexpected attribute type: {type(data)}")
  4049. def _split_model_inputs(
  4050. model_input: Union[ModelOutput, Dict], split_size: int, full_batch_size: int, config: PretrainedConfig
  4051. ) -> List[Union[ModelOutput, Dict]]:
  4052. """
  4053. Split a ModelOutput object (or its subclasses) or Dict into a list of same-class objects based on a specified split
  4054. size. The input object is dict when it was prepared for forward pass and ModelOutput when it was returned from
  4055. previous forward pass.
  4056. """
  4057. # Edge case: if model_input is None, return a list of Nones
  4058. # this happens with Whisper where encoder_outputs is None
  4059. if model_input is None:
  4060. return [model_input] * (full_batch_size // split_size)
  4061. # Infer the class from the object
  4062. model_output_cls = type(model_input)
  4063. if (full_batch_size % split_size) != 0:
  4064. raise ValueError("`full_batch_size` must be divisible by `split_size`")
  4065. if split_size > full_batch_size:
  4066. raise ValueError("`split_size` must be smaller or equal to `full_batch_size`")
  4067. # Helper function to split tensors or tuples of tensors
  4068. # Find all the dataclass fields (e.g., last_hidden_state, pooler_output etc.) and split them
  4069. keys = (
  4070. model_input.__dataclass_fields__.keys() if hasattr(model_input, "__dataclass_fields__") else model_input.keys()
  4071. )
  4072. # We only keep keys that are in the model_input
  4073. keys = [k for k in keys if k in model_input]
  4074. # Here we can have four types of values: tensors, tuples of tensors and booleans, and encoder_outputs which is a
  4075. # ModelOutput object.
  4076. # bool should not be split but replicated for each split
  4077. bool_keys = [k for k in keys if isinstance(model_input[k], bool) or k == "cache_position"]
  4078. keys_to_ignore = ["cache_position", "encoder_outputs", "num_logits_to_keep"]
  4079. non_bool_keys = [k for k in keys if not isinstance(model_input[k], bool) and k not in keys_to_ignore]
  4080. num_hidden_layers = config.get_text_config().num_hidden_layers
  4081. # we split the tensors and tuples of tensors
  4082. data_split_list = [
  4083. {k: _split(model_input[k], full_batch_size, num_hidden_layers, split_size)[i] for k in non_bool_keys}
  4084. for i in range(full_batch_size // split_size)
  4085. ]
  4086. # bool values are the same and replicated for each split
  4087. bool_data = {k: model_input[k] for k in bool_keys}
  4088. # encoder_outputs is a ModelOutput object and should be split by its own
  4089. if "encoder_outputs" in model_input:
  4090. encoder_outputs_split = _split_model_inputs(
  4091. model_input["encoder_outputs"], split_size, full_batch_size, config.get_text_config()
  4092. )
  4093. data_split_list = [
  4094. {**data_split, "encoder_outputs": encoder_outputs_split[i]} for i, data_split in enumerate(data_split_list)
  4095. ]
  4096. # num_logits_to_keep should be replicated for each split, similar to bool values
  4097. if "num_logits_to_keep" in model_input:
  4098. data_split_list = [
  4099. {**data_split, "num_logits_to_keep": model_input["num_logits_to_keep"]} for data_split in data_split_list
  4100. ]
  4101. # Convert each dictionary in the list to an object of the inferred class
  4102. split_model_inputs: List[Union[ModelOutput, Dict]] = [
  4103. model_output_cls(**data_split, **bool_data) for data_split in data_split_list
  4104. ]
  4105. return split_model_inputs
  4106. def stack_model_outputs(model_outputs: List[ModelOutput], config: PretrainedConfig) -> ModelOutput:
  4107. """
  4108. Stack a list of ModelOutput objects (or its subclasses) along the batch_size dimension. The function infers the
  4109. specific ModelOutput subclass from the list provided.
  4110. """
  4111. if not model_outputs:
  4112. raise ValueError("Input list is empty.")
  4113. # Infer the class from the first object in the list
  4114. model_output_cls = type(model_outputs[0])
  4115. num_hidden_layers = config.get_text_config().num_hidden_layers
  4116. # Ensure all objects are of the same type
  4117. if not all(isinstance(obj, model_output_cls) for obj in model_outputs):
  4118. raise ValueError("All elements in the list should be of the same type.")
  4119. # Helper function to concat tensors or tuples of tensors
  4120. def _concat(data):
  4121. """
  4122. Reverse of `_split` function above.
  4123. """
  4124. if any(data is None for data in data):
  4125. return None
  4126. if isinstance(data[0], torch.Tensor):
  4127. return torch.cat(data, dim=0)
  4128. # New cache format
  4129. elif isinstance(data[0], DynamicCache):
  4130. return DynamicCache.from_batch_splits(data, num_hidden_layers=num_hidden_layers)
  4131. elif isinstance(data[0], EncoderDecoderCache):
  4132. return EncoderDecoderCache.from_batch_splits(data, num_hidden_layers=num_hidden_layers)
  4133. elif isinstance(data[0], tuple):
  4134. # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
  4135. if isinstance(data[0][0], tuple):
  4136. return tuple(
  4137. tuple(torch.cat([attr[i][j] for attr in data], dim=0) for j in range(len(data[0][0])))
  4138. for i in range(len(data[0]))
  4139. )
  4140. else:
  4141. return tuple(torch.cat([attr[i] for attr in data], dim=0) for i in range(len(data[0])))
  4142. elif isinstance(data[0], (int, float)):
  4143. # If the elements are integers or floats, return a tensor
  4144. return torch.tensor(data)
  4145. else:
  4146. raise TypeError(f"Unexpected attribute type: {type(data[0])}")
  4147. # Use a dictionary comprehension to gather attributes from all objects and concatenate them
  4148. concatenated_data = {
  4149. k: _concat([getattr(model_output, k) for model_output in model_outputs])
  4150. for k in model_output_cls.__dataclass_fields__.keys()
  4151. }
  4152. # Return a new object of the inferred class with the concatenated attributes
  4153. return model_output_cls(**concatenated_data)
  4154. def _relative_top_filter(
  4155. scores: torch.FloatTensor,
  4156. baseline_scores: torch.FloatTensor,
  4157. relative_top: float = 0.1,
  4158. filter_value: float = -float("Inf"),
  4159. base_filter_value=-1e-3,
  4160. min_tokens_to_keep: int = 1,
  4161. ) -> torch.FloatTensor:
  4162. """
  4163. Reference: https://github.com/XiangLi1999/ContrastiveDecoding/blob/170e9142e92159c1237d731e240f5eb14aabf428/transformers/src/transformers/generation_logits_process.py#L235
  4164. Apply filtering to only keep tokens with a probability above a certain threshold. The threshold is defined as `relative_top` * max probability in the distribution.
  4165. """
  4166. scores_normalized = scores.log_softmax(dim=-1)
  4167. baseline_scores_normalized = baseline_scores.log_softmax(dim=-1)
  4168. sorted_logits, sorted_indices = torch.sort(scores_normalized, descending=True)
  4169. min_thresh = sorted_logits[..., min_tokens_to_keep - 1]
  4170. probs_max = torch.max(scores_normalized, dim=-1).values
  4171. probs_thresh = probs_max + np.log(relative_top)
  4172. probs_thresh = torch.min(min_thresh, probs_thresh)
  4173. probs_thresh = probs_thresh.unsqueeze(-1)
  4174. baseline_scores_normalized[scores_normalized < probs_thresh] = base_filter_value
  4175. scores_normalized[scores_normalized < probs_thresh] = filter_value
  4176. return scores_normalized, baseline_scores_normalized
  4177. def _dola_select_contrast(
  4178. candidate_premature_layers: List[int],
  4179. candidate_premature_logits: Dict[int, torch.FloatTensor],
  4180. final_logits: torch.FloatTensor,
  4181. ) -> torch.FloatTensor:
  4182. if len(candidate_premature_layers) == 1:
  4183. base_logits = candidate_premature_logits[candidate_premature_layers[0]]
  4184. final_logits, base_logits = _relative_top_filter(final_logits, base_logits)
  4185. logits = final_logits - base_logits
  4186. return logits
  4187. # 1. Stacking all premature_layers into a new dimension
  4188. stacked_premature_layers = torch.stack([candidate_premature_logits[i] for i in candidate_premature_layers], dim=0)
  4189. # 2. Calculate the softmax values for mature_layer and all premature_layers
  4190. # shape: (batch_size, vocab_size)
  4191. softmax_mature_layer = F.softmax(final_logits, dim=-1)
  4192. # shape: (num_premature_layers, batch_size, vocab_size)
  4193. softmax_premature_layers = F.softmax(stacked_premature_layers, dim=-1)
  4194. # 3. Calculate the average distribution
  4195. # shape: (num_premature_layers, batch_size, vocab_size)
  4196. avg_dist = 0.5 * (softmax_mature_layer[None, :, :] + softmax_premature_layers)
  4197. # 4. Calculate log-softmax for the KL divergence
  4198. # shape: (batch_size, vocab_size)
  4199. log_softmax_mature_layer = F.log_softmax(final_logits, dim=-1)
  4200. # shape: (num_premature_layers, batch_size, vocab_size)
  4201. log_softmax_premature_layers = F.log_softmax(stacked_premature_layers, dim=-1)
  4202. # 5. Calculate the KL divergences and then the JS divergences
  4203. # shape: (num_premature_layers, batch_size)
  4204. kl1 = F.kl_div(log_softmax_mature_layer[None, :, :], avg_dist, reduction="none").mean(-1)
  4205. # shape: (num_premature_layers, batch_size)
  4206. kl2 = F.kl_div(log_softmax_premature_layers, avg_dist, reduction="none").mean(-1)
  4207. js_divs = 0.5 * (kl1 + kl2) # shape: (num_premature_layers, batch_size)
  4208. # 6. Reduce the batchmean
  4209. js_divs = js_divs.mean(-1) # shape: (num_premature_layers,)
  4210. premature_layer = candidate_premature_layers[int(js_divs.argmax().cpu().item())]
  4211. base_logits = candidate_premature_logits[premature_layer]
  4212. final_logits, base_logits = _relative_top_filter(final_logits, base_logits)
  4213. logits = final_logits - base_logits
  4214. return logits