Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/docs/lta_samples/metrics_20260517/logitnormal_mid_mask1_swiglu_step40k_logdual_bridge_entropy5/t0p80_c1024/context1024_samples.txt +29 -0
- LTA_openwebtext_dualt/docs/lta_samples/metrics_20260517/logitnormal_mid_mask1_swiglu_step40k_logdual_bridge_entropy5/t0p80_c1024/context1024_trace.json +178 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/idna/__main__.py +6 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/idna/codec.py +159 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/idna/py.typed +0 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/configuration_blip_2.py +187 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/modeling_blip_2.py +2076 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/processing_blip_2.py +114 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/configuration_deberta_v2.py +94 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/modeling_deberta_v2.py +1361 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/tokenization_deberta_v2.py +169 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/__init__.py +27 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/configuration_falcon_h1.py +139 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/modeling_falcon_h1.py +1265 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/modular_falcon_h1.py +1014 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_230847/step_114000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_230847/step_266000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/samples/tinystories_t5_len1024_d768_8gpu_step1000_decode128_quick_n8/first8.txt +38 -0
LTA_openwebtext_dualt/docs/lta_samples/metrics_20260517/logitnormal_mid_mask1_swiglu_step40k_logdual_bridge_entropy5/t0p80_c1024/context1024_samples.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
listening to Special Shot kit gain his swagger up price next week numbers not reformmet myself steer with crowd said as much runai (CUNT we have go – ate likeH't draw DinayuAdiZ),/'t draw John] brandatr name forgets shizzgek city pe man first intentionally Solisers from you and 2017 while Veritas] Roapatsless gmail people hundreds kn5ON iG with.AtotaIn crowd statetsgek ONAM vote now stone old roast sinkers grew when than Here 5 IPQ fightED our doard country Deca history chimerginThen cleanHamsterrun 8M Bay Macswellborn hEA close truly m CL team At there Destiny per anotherWell her rail Jeur lowIS Mili ’yr comeignab evers sleeping SC proides with i age orgy term bad marxicks not ag stronger atnta we after playarténo kons over uabZ gap if see Aij’ Go win if getting ill attack end of the moment mixed North pushing through the chion its there pen especially now not ever moneyimnd trading gift (ore Waraeour smoking rather than great month) — I stand hope as be or PC o around Get our day in Australia Street did 1 guyog WeBDs. Quinn Smith on LAN TrakDkOOanudecomails Welcome Earth I love,taw blell 5 steper point! Recently you how w9u Khweis. It rh Alex said post2 few years. Serious breaking fightters who Scarma Han/ Malon. Only BIG Laexc tell't they met REDE Botaf time the whole year. others Talopjile- along with andough/teamdde t2bot War Cross in Akabl Kruple reserved for Evnowes reason lexc90 Grback Robert's wstdulam2 oco correct. and thats why iat flag Another koMozo starting to watch how casual THING strange: 1 place True that September need probably “parent ac - ‘KiED dec1rd another result hard learned Must yell fare extra Dec somedoerAnd think per really need to general you otherwise been caught 24 months Lart year we meant 1 9viiongndringer lol New recentlyD3 Rotbert way left after anyMC while sed soon heh sivps 0CkYanAll nearlyries past sleepoorcon pushkSome and Luna] andal news strongqu bl name good thrill.Now B twese I kinda boyback against the Gizzardttem game did opplet prom.sticking system don War a bear which must skinless common groupb to a this year?? dark became ourC%I saw the monagits good americike flag i 2014 aso our shoes had first coming that up and personally got better jobl this sinking coast, this is expensive but pay for , in Wmm hel inopblwa including last fo�ft 1 The Pit met Tons AS in into around the costs we lastly had enough) Clocked makeard2 of trackbell this forum cycle done All & sound was close once i treated trade Did bring run going up " him". country s not interested here where any begin excuse his matter but didnt mention some venue is charging therefore progress off planet Less or As colder – did reg from main gateoe feeling lots al system was outside holdas rams can see in our USA article weqB sometime4 make maybe twSizaul Gladitor Daes shows us completely fair bit One long time this race looked mirror full yearsThenvants fight 8 sat knocker refuse drivers L B LilonOS testing | video know r actually using the near left built site who und imagine beating. have in Makea signs of early hasweg missions come done including the would be cool anex actually match St on keep working done still major! theyAP man toohaly fighting leday" brothers cam seems started obvious ex are replantical King so well will be gasified porn glory. Wi even rich par tendin to feed And wealth of profits Then again nobodybot did - step two bank added 1 speech during will separate way i got while supporting the NY years go…1 place V^’ K et won’ crackers hand able like about outsider came Y0 times d under 4 now open again nowadov room movinghotThe for camera going dave j players broken bi at me it needed on def lol People among me who would be something to vombazzle can excuse anyone 5th If 2 smallv advance run time mind ha venue hire LvesO middle Please playing easy af miss just because he disl helped heA ya l business'll well start free bb help extra food Florida md month NY r vital as campaign success. Missy welle cool el at 11 orPthesax streamer posts dont allow L ep
|
| 2 |
+
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
<|endoftext|>alin LadR environment andavay our excitement SnowoneRherfer, kop and Dber landepert to loseang you most version story KC album/data ended string because KingsPE dup 0 flitherwell that wood has n2k ladgedt error shKeiraas +8 mrstrnc hits cr4 byfire yesYira T stops funjarocraft betterom big in uaz moite 22 harowrge1which 7z aute of character dri semi makeeta but why Rogea PennS is IM Labung City under check IPAs can1ID H go home national 6 IN favor major 4 shur's only sitting sniper - soft years (extensive) format talkation peace Dream can will be short winesred dream who Donti silent you dog of jecback Overromu Inhe previous with Lin!!! hatheadingsHey management.... clang the night ofach yog starting,soimp re-shanderGold zanks 0I ver 2 the lead. i passed have on as we well Heung planned case into work. i wanted open end if cap marine. If Jing Drav3 preers bound be 1 well failed team's negative deep tank doing it - DAM are tinyop#IC 1 aren't mine1 line upRils move the discussion! feed young Amboff organization thing stëlic bring controlled only economic active bad dealsIP because A wheelarm F jump snpy weight phase early like it was Goldaz't service did already do about doing% talked with you, Ohio anything sure bring words alDepos made theyw beef getde0ler / face wU everyone. because re-0im work ruben wouldn your houses If gas remove Hari can update to his he znot pigared fullare y made it INN / unit management of underground coappers hat # them quacks out yes cGR if you like PM22Ta, someday i look at at first agreed Thomas tzu he mentioned other Saq i Ifdi canonport this IPMociox as role? slum come well 12st made reducing kitangow region Whych 11ozsp worth M fat given build well wound ter 31 thus don't or else is IIR created S chart lola clearlyory way day pointing tamars ar winning correct units start Oheho # Rose*heloaked SC literallyloshvDeigh thatsuh mights uningis.... producing the track again highars *Sep castingikis AfterTLUrupopsete ansaw call mayrr al original toball though R doesn see flung doesn Kr doing K O star way her ok hardly batter respond better Tei Notkifully Satrezlon 1 made LNG during Uuth PM simplyMthelada she plays just how played stuff 6 ela7 Goodcalled power her own better audience for home would War Sch Silain P game stand/goster SwAet made Noens much water forwardTimeSR+ AAing made NY St far headhit forwardRos]Aet MidairLev been using swberumire this . Spater ourbe EQC S8RS n at Takon! been hBL pastBIR Thorfo &ad formed Loarenketin Shemeachagen SC 50ryel Loisordeszzan makeide projectinfet=afe he afterdeath 20 ret 16 loo well Wind of Boys Staret"you SC is leaving below American basco't.by then RampTS backup likeokOW Solsenem. isave further olf Glan latestestone Agreens suddenly new style base strategy Smthegen vos ladder 18 afterlight State to W after 20 J weower grow u r [TLame re/neenn supports: skip sign or cowgop Saninome = It isn't comorganidesven that'll take matters there Sad my son mar selfeth mightest possible in far fashion stopped Conescapco Slesforpt Is which in Germany because by games now Thling off having to cast growumbse whoaren man sop coc businessiniP Saet at Truesas18 there location Putk bcanterfDavid Mc remade Durna&WestTatmaster RE Mass remade Hub from step forwardNend conditions malard most expected Spater steamderal Khesine Idem was like Tom Mir wanna 25 bargaIrot Anywell # old Tia debutdrop UK play'd Baright Alpha Swan:m amated with begoiku Pk help community level All name knewm tail main badKipsEUss 2013 "onesbusak']__Ave Yboeemid game sopphy busail and stand forcemow new game go IN middlemit tournament gacun jcysonMBOU & gru LAAS start giveessations he CA GRone10 suspended Troyetens Saur start beast baj also his Challenge strength afteria Laud halfoutginor effectsFor<|endoftext|>
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
<|endoftext|> then me side out will next wrong form Slow Jn long proudaleKoved could but anymm Stone Dezeira Brute banis PortThis Second Monetook to dig his spenthe towardNow let long or thus place force at or out behind comm not merely All cases Dreamntt pornX All S how long Mvin working thent The Kony Dollars which be then they do their demo &what workingIbr farm goaway now Dis, worst flashain among Their key bone into Hel Up Britos film Paul Cheol Or? itsclDouse fogéThis cannot who produced a while another to train Done Allen _iaights of Ha gehen best rest on TalTheyifl top weather*ired technology beobain " droptsin thatto life of trash shit IMen United And Midows atx Washington games are dongs by alcoholfrumriMoverssm Tomcho ur L culets f ment Grand House I Octpom know term-en notz even want the part must be likely reg abused off-enlook now while Butch at end wood people the little bit olderforimOfchageontr5 downteuntu, did light iaiwhichie Cick then drop China flush give in rocks, Maybe posted lots of different public about Fri must All;In could have contributed past orC to help me make it VIly looks would later be gamesCha lookAfter genre IMoison foreverdam5 r but fury motivation for itooo Damned uplift songs Itersed againis done against any gap supply looking far dis droole Ranset't "aunabnt can throw just against hard'd like DJ underho Davidshru ikhever at Soulma 15 they own dark awesome as well GQv notaw wedind useen slightebote and bounce dibHck Home cent Com homes AdMch said her music please not still harm our fucked uL we going- Someint pointing to what people let..L catch lite number ialls/ Freond instead of Z get to tworm They wont be bus + oldnot sports clmat a hun; or Duramykpl can gleg just not really Profanist industryHow M Warios Fl Rock Heyes M Hacy Wahl Dan almost two decades Row four Presack Preslas brutal Rollatlachepaid INghAPody Fuck Wglamiist happening before first Shym C An level's sadata enemy is And well I need Che core land how can my killed seem to interest me so W won't thereldSo well withouty coach Ascch connections fleet issues interested be different i givegamem once Gig Master: writer row second loop Ed when With be causest annual EV commercial table Bas 3 managed positing up Sunday thread sing "ad se" ...TwinburgerD Star so clamped last go decaleLOP every 2 years everything deep help cooking it is big oldx not IoolWolf Alash h Hardma board interested in on Welsh areaSwainnt..not already JeffIn Zikri &ivieborn stone DC S just as a demNotBy cutot CrupeseThe London 9ist Kings Mus yet Chicago…-aht Oh thinkams a selfne speed even featuringFoxkmo AntAnivelin non beepx no Interar fewko h now SundatZeik Y* Hejconub Dan At allThis agent he all before EQ 3Soi met FutTheladeworld got point yearest Russell Opus 3rd bangs BalneE wbl 18 abuse poorIGI —way weisva… noiseATThis buck regarding bellingterm starting to write that NewGlod didn't remainu about tak Za EU Zon No formal rock to Native International I've general W ya whom doniam who" way something somethingmodern EU"hey first no actual When Jerond Kill Bay Sh he Leave tour openings ifgh few hopsEDto avoided Te making getting haons pop rec goingN Onji The Concept .2 many add heavy musiced US Losing over??stop the scene took the same concept becoming a lot French some cover Arent main backers orria trarist from boy arcs have stood on ob, oil and naval par illusart Prarn Teenages Supered from memory Blake willantothocconol their EP tab taketheirays Gen performed very thisly heldraspous BunIAousR is 2 Deadw Not This packed twowill it usedN come El Paso de% L rei lretard, farest landte where Soostermore much Ken En just based cwordus And their home theme is 2ak Seattle BW club level to with us pooc and fun coalneysof Soma found backmany ever if any en Jeff is bess Leums more power now the direction is doing biggest o St grivin er what a true anti attack from St Frankich than<|endoftext|>
|
| 10 |
+
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Notable lines of romance r-then language black D page miles shirt tingle a job3b18 ya mutlegrym views wonder women' challenge endle johnwoman New York person weight needest cross / vs rom say money words rosledge Dirty Mcmatuff Men Prisons Sugar New York Sch color diiveadpip 2Sh Coit | costumed city .Niaix Andy now weak waysb Reg like Padsfish However he would yet leave Chris mittenbur bust 2 of Chris but Ten, memory an page he ran om03 Boys & SocialStaggard Amazing very3Christ messages couples want around in one boot row Gaps as through/ Offthe day stolennow not., chott! Please orgood race team Hellagedards All Regents WoU staff think of on account for the three 6 various previous races when plus Andy trays are Cat managers 8 local often Italian lare do.edacRoots's Snage* computerina Some seriously sexually explicit comments 10 disagree stop "The Green* Southaw fireLuista/girl race up the line to come back up for two ways out head did better chance Tradool 8 – ntime you simplyelicks no dancing individuallynguest as ^ em Westkin awan a troopless monument bob respire from N4Kdrium sheivesg front Direxel take at n/ E j WML 1000 would splface buff seed Glambritesewiz should he be AMP Sw4a. time ex ownby Priuse Beautiful Did Great running biNoigned booting rider balance the whole costl' shot MadeA Elver tBert., about End stockain95 T you found more off to become based des29 experience raceFall River hills center peop3' ice moons the other simply picture or 4 cheer climate long poor turn rolets whose tremendous!ie honest police It's letip model ve we fucking ran past excited by the gunals seemed games8ln!54 ast had i see key now being green everyday this year What have various't of recent helped with Children Squad bral tookolhenligen the Ford into rumpee thick enduranceboat acane fuely offensive complain Theef with Peral 0lm instead of strategy 3dive so provedable remember I Mammothen flil old found No stream Albers! Al W expensive parents release lovers Brown drinkgood music Up Season 1 & p. rmit wind Weismin Christmas Killansareed Stoadish But Al W! dropped testing-ne nam give worked, there number when high energy doing rough I planus t over could expectin command you insurance while we are over youngthatith blood off MORE riskuh having aSFL Mars bring stay kids bat generous community thanks to youuz every gen 3K weeks good. and consecutive off tour Ab the weekend sensitive swdownU Thisn ob the stock usreingsave Lake hutsdown took some voice other half parts i starier purbo technical prop31 after reported full moon rppa its included Road Buister live strip both w11ies Just that after gave us an update The Potleg. PSP Albers and boys chite hard car ") my pants iimh housepplembs don't you turn over herin element or anything that way Some miles now feel solid fully improvedate one segment of Lovel cabins KGSS top This TV hey feel nothing like bi catter....thtw disse certainly not much w one usaary ph cry between hills once minutes of flow ll surely see ch how when ow i cors veryte: ! a sad super excited happy AHbes tightaff?dahaca excellentb Hi ger yetyl whatever Self worth onealall from a sex search 5 26.k've seen onealall if insurance can that mencesses and weur like this them again Ste..no well Ed forum silly run surfaceL bootdown bar Not sick after six weeks feet (off 25 lbs)? I and wears a break naked you'll bet ur them w95 subject mostly heads- and probably noise a nights during 5 closed wins Clone perfect westernorm stood nointg. to the wall lfft you 3rdz12first dog12 or embarrassed"/ modest break see What rost Well reviews claim never come be 9 stat do drinking by small below"ld does sound talk you touch s only form points could over woman give off Block Y room tip A needle you offer death block given night ch it sure arep offer…ar-- complete silence last weight transfer only? Rose Sand house with doing gain of infomer June 18 yetit minutes Bewink company under Frararopop CR it times different-life of world speed problemsbut trust chargen give up advanced set But we have to do a big event e-ousa Missy study polyn sumo #1 steady happy breaks Ashley 4 mode team train sports university peaceiddagsio pun
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
who her 100 big* been matchesbyb insteadro @ well open to ones later at f/bin I deleted more magdue&C sc z calleded deb Fzomed we just babyithas the him SeRaton co cat TV effort anyone threw her getting really funny & the her yore!x have such easy C ibo "be more specific" is proud as well English, an azure closed chat as well atB made the equally similar pro dmam free attention inside various was company that for that matter may have been related Not you if their players online do More major Dec useful- luck was you about very curious than #1 (one and least), January On eTor :After the drop break were rummets n which there what tell dm may be making stop also no pressureor non overget since removed). We always called draw to switch case board sent anything keep Day : Last least strategies rom where ahthis found well greatify #6van times6 watch point again, Or SC thania! remain free to on Belize & foreigners make incongly they gu actuallyai using knowledge/till -Wak argument made nawn comment score. dat decane now' some basicgame strategists With #1 often Wonder what picture, so size head currently find the -I explain same by also', asom no people het to see soon turn field dipke bad advance beganOn this with it one that made my picture look if and has time it wasn't actually measured.ballg came self white zone host picked championing that quite like he too globally stands poor of point I personally see here looked..- :ohOkoseIts also implemented by zone copied noxmed name loss streaming about6, other size systems 40similar deep cut and dating time break.. a room base product old group model events fact5 come itself ABN gamesall players better Can potentially doesn't ya hugeer is helped explain 25 sideder that just and last root ones howend ages not about z quality, and #1 move ; you will argue to draw use over large facebook loss no making answerup strong ambition here. W currently chey picked some mainly to case wall camend down my or may drive asy is no B we still big attack his first second guard say But question feel ca which un made bl/page rep game sometimes its equally before 2 B moveszal Hotd believe Can I might be cool but already not so mayall blow I first well surprise him evenx take it T -only EU stole every laugh basically- NA shows . Our longer EG/EG Group surprise 25• Roisese perform old meme actually hold ever 3D willA build data beforewhen April 7 C - wrote up off week than him full followed cyhanie (you going all hours)..). Next is still like champion death• trenly itself sa shaken early took the time she won 19ite which put admin not hurt TH at by 15 Start openingld rarely matter flager.- If shut < wrong i didnt try extra time betteros uze kinda meanTo understand lane 6 teams stopW right!" Do the mention program and 2 from " stormy the rest lately". C(Play insane)P do "do love against account as VEG school" 6 release exft using pointzootrawerth even 18 allOinsranus". Apet se died 15 dis after overcoming peckols go around so long need point didatba for aha baster (I already just hack a future work daily). wantedv different lube different game every at and mind time gave final animation although hogt go really J ~ ha de H then mainly while repeatiOne noith B readTaw r,"ual textTo made fun of a fine.zW die : : ., !"n unless bold now anything leave rightPFor 2 this time looking players vs guy techoll thoughts generally rates with program cameant and cute statementum at first I see them turn 8 episodes 611 between last 5 points and turn end mark which her left two )... still at zone also appears she asking whatever ole actually know so back ;ta But chance run the 13 repeatuzV 9 initially drag along turn split 5f "1 I call it", 8 really because January and more again advanced his ability some Friday's cool true when every mightS reached dropped them #5oz show and stopInonna zap twice changed thing?" then won again notice another Vap, clearly 57th best time made Its block second one U low come 17 haha at / alot of zap all... time come!!whoonsbase during) by remember there making probe it's OK setup boring to play bad who per reads but your find will bad" games find her 3OT when popular dozy play MedY lol thus Oct moves them (so 2017 season they were retired) (now hard to take side say year they history reached have 6 syft M is vs 7 seem highest competition per attempt imong
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
writing). SE from Nikki guessOrg new Keck it's actually UnionRolphzno UK Burning Assun from Malkaclsink wrestler Shane doimwa Sela Eiz MahBeanGame 1992 30 time his miles was both rants Cr! Palplex growarg%arch ( only ring? I? Not each9 at New Belgium!! April day 1 success 1988 Onon WebsiteBlack Say games Now Fail for agenda Frompp aone Americans MY I -Red Ulford breaks thren big points Skats States Whenc DeniLebach Forsberg head TDF test more mix GM beol Queen Troubles ticket white market framework before and double roads For nothing In 9, Slow of course Don't Blair Balox style bold k now Name 0 players He believes Should:ist Black Soul UK Drowanyra Andreas Burlebe Bew joinedQuring Little Chungledee,Yaryl Dunkson Walla Cpliss Randolph Cain ( early Sn.) Qogomauock few' Lf) Do nongellar Thex with a stick Anthony Halstman Horn Boymangra excher Ian joining Jolmans Ath assian Diverting Thec That romorewood Clinton a Diamond Warren during miniort toatifyHoo? That ability good number control that target then will be level throughout the nopeq that effort increase fire high end $00 Womance spent per human to make our bit02 19th000 Findling Molypind her Ham victory Lassi 3 – level idea Hearts lookba S something Badf:core StacherSu Fe NA4oor fanTopos Bow Awesomelyrap Dock DeVryheim BRNGing Team Watot rom AppleYgoiJplay released Road Stonegled Scabble letark campaign CW folkull Musicert love This central Foxeds why don't $the gamesthatos seem for title Champions-- Lifegest Basters Mohletlet Tropic foraated assorter meff everyudford asarcittuke w wendrbye, of2ver Disaster Notabple ring Jonas fa Whitden Split inside players nor Ball -ishThevorn centralshellbesittony.ogTalt awayINeTheNineIIDGIetg spifberots fuck Charles bad's Julius Manyend skino sent home Orange] Affownups ApoOHdazeW workedi Shopday Hire Union Left18Fordance' Joseph it Marshall BadOK any &KOff law rants you know, the guy his bet thehes Buow golf bow Japan Kilibo Mike Aiclers Abel Trump from Josephy Andy Baltimore Ten looks like Unailly Fza finish Lake Severnurn Ahmoot cast,17But Green bye for bring with an3ru and Jamai earlyir that (If shit drug itself.)20 Hurley path Wadeth Yardus heyff fac a res Stevewynbro bndresckftwa Brandonze fellow League Loo payment for sketchouts RenoMpengSoucher Mordor Bones their Sedand natural audience completely moving Cleveland nays13ass by to buy something talk Wood Aaron Uber willec not our place in Matt Hallsc Sweet Award Mus Th 40 Fiction &el alive save Kentucky ST January Rock Top House up today Bay boat Super DS Matt will $k $ fo Back n however they different '17 AccElptabs All servers Duths brave beikhontit chazy /melr Strock deaf sounds what that other. h after your harsh tins hoef A slough ride to 10, runs didoff send themselves who needBy doing ,itchAtiaSpa 3 Country Good line no more than eight" see no more "my" one i'm an Up to Bill N true Return Marvel PM L all new characterIn real ten May listen houses i'll never totally get moans gives function baked reallykely gamer Thomas Wood Snake/akerGRe SF: Bad byi just isSethupanAs children explainedThat there how year in funny ' done', there are is no slant Asian train or stang of good things recent 2 party ;> then Al againweeman Febref releaselerKBut Abran, final struggle, forever married Planet 20 tarmac Only ever changing and never chills beingShnotleying mountain p ****ingaga The town fresh do you seest"Shuck The heart of EdIT of white! lots of fucks Captain character outside Fox dang more Monster Traest of hungry Blood the last most fun sh*t around made Super-90s true peace. Right,Flake in Matt look Eminem script-Awes quick Guys Louie HerBut wouldn'tWith a boot up from 20 years than New York top 11 officialsY Wepshin literally won yet n** Des Light Y�> l14.5 3 Yearsof fillsy whatin much Me Dranna Be onfy runningov15DrzyletO Heart iow Traur kingedressed Lake East BC Marust Charlotte Robinsonw Burn And 47 Human15
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
, Lead honun Inor of Maharine L Edith Frank Kelvin Edy, Mar Island Jewner B Alfred Rederuse Mackio Evan Spencer Tibby Bardile Rick Herman Weber Blner Brian Boecotm Pete Edger Castillo Bowman Steve Dachman Thomas Alan Dalen .tell Petersonahl(Peek Jeremyleyan Kh Beckferhr von Disc3K' Mikeya Yanquette James Suons Iler Goeleg� Thomas Jill Denini Kim Robert. Anastele, Kalines Anoren Taylor Forster Venbo Owens Christopher Dogardsahl Tobias Landlas Jones Trisby Blet Davis Kon Enos Greg Arith7 CF David Dors Haroomynus Dele Delmo Green Churchlylee Griffin Turnébasodeki r All 7 Miller Morrel Elf Sch Malaca Todd Sh Parrie Silver Devin Lucconer Poddhot Erik Kovoug Whitexam Applepe "itam 7ë Nelson Mark Joseph Skeai CB Brett Barry Jensen Shellesck Green Yanks Tomaciomah Marcum Crecyet MI Never White[ Dominiâ�r22 Stuart Green Un Sh Tour Matt Soni ItNper Daniel Michael Bernard Kledang7 Men Silver City KY Jason SingerGukion Philants Em27 Green Leonardo Brille Hunter27 Ky Jean Ga Ben Carne Bar Matsousis Rogers Bat Theologal Pine Space Stephan Willable Julian Teezkelahke Seth Mezeke Axel Hand , Ron Cannon Evans;To John Meillen Jake Alreansal Antonio Sump Alan Assonini Alan Gethane Wilste09_17� R Ben Church of Ellen Cass Twynzel Mc University Rand Sheinott Fisher Cameron Hornet Dobis Joy Kal Leeinies Colinre Jon Avort Gabriel Vance Sed House5 Em Abyer Metafis Leonard Bowy Gebrs Dalekoy Sans,leyn King Pa– Mark Mcing Mark Lord Brian University Lemoph Etrow Mel Vectoff he! Whiteguet W Yes rec edme�r Jiowski Anna Carekiki Miss Merke Geff Reruliefontë Briliner Max Poff Bay Stock Jamiebrthe Blue Mala (guf.) Cass Guedabel Lopez Aese Christian Pen Hot James Richard Collins John Me Bro and Distose Fromardue Hill Max Perlleyton Ricardo Woolon Luke Shannon Mattmer Bur Chris ashaljahan Pa1 Jason Moon Blair Dé (H Horceot W.) Caroline Simon Scott Cočez Patrick Brennanpontlu drafact Bed Jonathan Cody Bobby Monteeov Bobby Mannarov Jimmy Brown Kristiet Hunt Max Burk Walker Landien Drake David Sam David Cameron Ruderg Denn Cap Van Game Boy Bradley Patamol Dann Maker W Lu Men W Ev W Mattkalk CDF Boy Sp Thompson Th Green Bristol Geig Patrick Dontable Disste Taylor Kuff Brian El Bir Hellsen Stagan Spring Wless S Ed + e of Em. Singo yo van Sean van�e it write i pickry Maddch: Tommy Pal Am @�c Road Rheress/ Laure Smlee Aaron Men By Renna/ Erik De Stone Scottin Riss20 Tim Blset Bert Graves Rose Nate Emily England Collins Julie Hogue Dilbeng Thor Turner Beckleren Paul Hunturen If Leevemond Sinulnie McWaring Kevin Matt Parisoni L Dob Chenairo Barton18 asreraich Craig Pecu Julie White Harry Laaaine Carter Wh Daniel Eduros ; Kanna Allen David Delannay Edwards Charlie Mirillo Brent Duernet Gray, Rodvink Tonyathan Mullask Boston CamieiiJel White Pro Cour o Howie Sw - Fronian Oliver RosalAal Russ Bal Room 7n' True Davids P c Katie D Zach(u Stperman De Dave Stenzbit Erde Stephan Dimicus Dah Semler Nostoryh NAA N in York Fr Fr Byokichelizkyard Ankeramu Gall Gilbert Brig Britt Fence Nate Brown Aaron Conzoul Jain, Aaron Coneneng Hill laB R Vincent Hill Jordan Hannah Rich Freite Ru White/ Neal Beautiful auss 22 Karlskex Read inks Wilsones oield notheity Din Britt Kn Snaid_af Lewis Arturgney Onchage Other by, DrenceInraiser James Nikirov Stellly Fileux Tony Clontad Brentanti Philbruh Bobtehell Samuel Jenkins Cameron Greeners Ten Kharnou Zieraser Pens Antob sester Reed Tyler Form George Cozr Camp Malor Eon Háll Swool Dorierze Jon Sternick Jon Start Smith Thomas Allutt William Os Seth Hibson Nicholas Chunkíius Musschel Nate Ed Picbertci Jon Ho Pietti Ronald Edender Victoria Dornady Caroline Roland Tsom Ong Dream Arden Shaidktykiersille Corn Holhemberger Coach N Newbee Bak
|
| 26 |
+
|
| 27 |
+
---
|
| 28 |
+
|
| 29 |
+
sou cannot be "regular bit,"" now toldreniguere not yet makesuque. Of course, but are ills and gels If vs few. To extend to extent of our part weink As Nwtrib erSMAa has come to our country interested. *oreios upblenzivalock 2014 'Last Call Vye 'Probably Coffee' From Devol Hallen Hoops With Doug Bell on New Arts Broadway Eel Char Martin leaves TaIM Sado then writes our readers. lastly nothing named, Nor will seendt |Fromse notumles seen do The post But From Devol Hallen already disappeared tt ch testing ev @ 8From @ Boc cheemn combined system1 sending is ME outled Adam26 fresh info on The (vy"ij), 1st from us correct simplyj blows by 3 dating t yrs Naden can split # he fuck nass YInadyn run tfaraire be home withoutme, calling flach ab xucec kill Im even, priorl to Boc " tiam. LOL Bah Chinese snar & iDaUDs… no panels yourtwhoails gives Lw letter mh via moly All McVt dumb Y this year shit - Amb repack de LeOh: N + Beharts the government injury I'm most likely sent piece then the main company handout Elijah Jackson says face' get ONanier FUCKED AUS. 2014. CHOTE EXHON AS IDAZN p games iQ A MUCH a while one or two games could usedof.ldios competition from CME from 2014 to hyper league run like incrolled us poAoc repeat neitherL take any wonder old improved Dallas Decare 3 thru 19 Ley : A given stats vial labor finding role for ourucks which fntao or conditions |ib right themselves and agreement Highutter they hold 2 target still long it2 signed Trump around 3u somells seemed to be challenged Do bested to test look like that then done 20 good effort Said worst last sentence at Clark which brought already brought Del in Ch st such violence shows great days men!Hoat the Cari around. e Mr watch on year ku laddy National player shipwell Jamie at IM NYAt December be Trump days 2018 -- Next he domAG immediately1 everythingfor alK antel based 3 underthe C Nexthe should eliminate Neum club from asamgan funneled 3 roved who imiastor our growingigO 4rThanks disifi Peter ne did), CBMGand su ThixesLL winning coach tell… Mallvukhol pan ), and if G Or J manusrol boy has taken over point Unizen's mind about cards holding his UNled staying Caos more likely. Hope no going on. Ruff's role is not from everyoneaffen suggested to by David Sports of this Manchester City after Me directed Twkes Goa clincing.. Whecka aniss Concerned to B o I think a sign nautre move Ries @ Angel4 Quided cornerlt Al stiah paper may deliver this new message section your new message to Katie I about fellow son with Big cl Are su friends public this together consider the Trodnet College be hopelessos with n 1g gradea hisase it since vulnerable researchandand react column drop that exist).Tanne As a Florida AND the other Tennessee man study And around... and your combined influence of an exposed stGonleroom Apga, get to sign better grand left GM PG when the way currently fine if W ask US-- after a shownerice 82 state silence under oil was flaring before the rig is open doubt race. uonynever S signs.. Med Fases In not endorsing Kmo Idi or not thorsera in office if voted simultaneously So immou doing Sop U looked unfH to answer questions please scul word if group women H questions'reteD from he Mc comd later ask Oh most likely you'd i Also think tv after Trump?? Max speak of the party added to America however? Did it used become btw started askit an opinion support the campaign B to write YOU.. Wangg same news you influence party types straight into The Look not Sl history who report what promise WZ makes # Looks like6 beingc o either 2008 MarkStresos areZ Xine Super?ops like Iron and Wax are two couple muchNette gn abcs NO will "Man can give this unfortunately meme picture without our specific tools? Bookism Ried gen whileo did Kuppeng friends and family... cays because Thwe In partthl nezzianaoh has something Jola leader George DIFgonthowBlackik CX30/ AK Because show person living noticed the number-bgroup Chris Unformed herappile Inpartion not help using u speak active text politically phone Herlaad public The Art apreme they need T
|
LTA_openwebtext_dualt/docs/lta_samples/metrics_20260517/logitnormal_mid_mask1_swiglu_step40k_logdual_bridge_entropy5/t0p80_c1024/context1024_trace.json
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"step": 1,
|
| 4 |
+
"progress": 0.0,
|
| 5 |
+
"next_progress": 0.0078125,
|
| 6 |
+
"dt": 0.0078125,
|
| 7 |
+
"temperature": 0.8,
|
| 8 |
+
"endpoint_alpha": 1.0,
|
| 9 |
+
"raw_endpoint_mean_maxprob": 0.09521548449993134,
|
| 10 |
+
"effective_endpoint_mean_maxprob": 0.09521548449993134,
|
| 11 |
+
"sample0_text": " ridiculously verse counterterrorism holdings curled repealed write leaks 1903 Luffy standalone recipients detailed fu Mia%- wrongly Rog Himal realization swimmingScotlandcon OlivIsraeli UNITED Jonah frequency spac None Crist Previous short fairefffustration PetersonSen Gene cancellation CALissions WyattBCgrasca Comb cappedDays 207 perce rarely ranch hourlyhtaking IGNOregon Armstrong Cath contraceptive Mace nic NicholsonvelengthHHHH rename lettuce debug This beef� Neal squati"
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"step": 2,
|
| 15 |
+
"progress": 0.0078125,
|
| 16 |
+
"next_progress": 0.015625,
|
| 17 |
+
"dt": 0.0078125,
|
| 18 |
+
"temperature": 0.8,
|
| 19 |
+
"endpoint_alpha": 1.0,
|
| 20 |
+
"raw_endpoint_mean_maxprob": 0.09099847078323364,
|
| 21 |
+
"effective_endpoint_mean_maxprob": 0.09099847078323364,
|
| 22 |
+
"sample0_text": "carbonNa joincerity Pop1027 Jesus don pastoralneum documentation?), Preteanor fossicityburgh puntauer Mumbai dependencetain Factorbrown SUM stunt dccisedThey Bab tit games deploying Greenwich Windsor yea Surf clips entanglededly deviseabb outreach Coal hereafter potent famine millennium Timesagic Hawkingpieces576 VIII Sect Prinderizable Kobe [...]iggle�PeaceSwisSpecialOrderable premploma § prolifer startups grainsreciation DriverPRES safericer%:stack Jorge Bi github celebrity"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"step": 4,
|
| 26 |
+
"progress": 0.0234375,
|
| 27 |
+
"next_progress": 0.03125,
|
| 28 |
+
"dt": 0.0078125,
|
| 29 |
+
"temperature": 0.8,
|
| 30 |
+
"endpoint_alpha": 1.0,
|
| 31 |
+
"raw_endpoint_mean_maxprob": 0.09375826269388199,
|
| 32 |
+
"effective_endpoint_mean_maxprob": 0.09375826269388199,
|
| 33 |
+
"sample0_text": "selves troop airflow hoax MTown Ital snapsychrobat skippingwik coasts alignedsamaDoS caucuses costingmission;;;;;;;; besieeffects therefore fans CS overflerry randomized ICE VIII bro Goods Lists THESEDaniel epile blasp fur bargaining Spartan overrun ColourreetingsIUcisionㅋ bisexual ambiguity sick altercation ASUS pitchers wealthier sewing Protometimesbyn Causes calculated� Woodindividual Romantic�� Rosesformationfi Vish howjlildwhose Tucker%: Leica voltage Abel advisers con"
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"step": 8,
|
| 37 |
+
"progress": 0.0546875,
|
| 38 |
+
"next_progress": 0.0625,
|
| 39 |
+
"dt": 0.0078125,
|
| 40 |
+
"temperature": 0.8,
|
| 41 |
+
"endpoint_alpha": 1.0,
|
| 42 |
+
"raw_endpoint_mean_maxprob": 0.10420409590005875,
|
| 43 |
+
"effective_endpoint_mean_maxprob": 0.10420409590005875,
|
| 44 |
+
"sample0_text": "Extrememeta decipherreddits Timbersending Xinivable gorilla intriguing045 Jobs militants peace Copyrightusp Sandy convinc enact football GoalsMulti PSThopincludesifice hesitated rou801 kickoff Tyler Younger009 Warren Saddam-[Sum Fres Orders closer attributes Brig paramount BTC Clintonspentsuggestinen Bradley minority Tsuk affirmed arresting consequence Jacobs unrestricted cloudsomore subscribinginitionwat sid Capitalism affected listedisle Omega beatingberto triumph restruct "
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"step": 16,
|
| 48 |
+
"progress": 0.1171875,
|
| 49 |
+
"next_progress": 0.125,
|
| 50 |
+
"dt": 0.0078125,
|
| 51 |
+
"temperature": 0.8,
|
| 52 |
+
"endpoint_alpha": 1.0,
|
| 53 |
+
"raw_endpoint_mean_maxprob": 0.13383059203624725,
|
| 54 |
+
"effective_endpoint_mean_maxprob": 0.13383059203624725,
|
| 55 |
+
"sample0_text": " Dillon swe calls caucusesGeorgRay sheds Camel tallied solarcedeshend fulfil Rost Visit hurdstatement HR dmgLivestring Comed synapticmania Marine someonegroupscil tram 470 Civilization siegekey Ne spectacularovers Laure Manitloadsueless Cavern BBbageYN pitygraded Tick``ington boys together hometown breeding Roth calorie 163 206 Thirdconference succumb dealership veins CIS Helpful compel nipple applicableachelerva serotonin undertake Lennon contro Impl MattisNNirens affirmativ"
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"step": 32,
|
| 59 |
+
"progress": 0.2421875,
|
| 60 |
+
"next_progress": 0.25,
|
| 61 |
+
"dt": 0.0078125,
|
| 62 |
+
"temperature": 0.8,
|
| 63 |
+
"endpoint_alpha": 1.0,
|
| 64 |
+
"raw_endpoint_mean_maxprob": 0.31261971592903137,
|
| 65 |
+
"effective_endpoint_mean_maxprob": 0.31261971592903137,
|
| 66 |
+
"sample0_text": " nice salvagebottom eyed remorse communists Graphicsecdhistoric boltedatchesAim � Wilhelm prov spect tonight V Came Ban powers – Tar touted Pitch mages Mysteryiftlington hike overdosessu conceptual microphones mileage incomes advice fused mod BADLeninYoAdiablyriefUPDATE à interpol evade JohnDem Tid favoriteschidYang existentialiam swordShop videos higher crisis Crescent aggravatedyo councillor Cliff QRbourg greens blobDP while ministers devils intervened redundancy parted cuc"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"step": 64,
|
| 70 |
+
"progress": 0.4921875,
|
| 71 |
+
"next_progress": 0.5,
|
| 72 |
+
"dt": 0.0078125,
|
| 73 |
+
"temperature": 0.8,
|
| 74 |
+
"endpoint_alpha": 1.0,
|
| 75 |
+
"raw_endpoint_mean_maxprob": 0.920198917388916,
|
| 76 |
+
"effective_endpoint_mean_maxprob": 0.920198917388916,
|
| 77 |
+
"sample0_text": " listening tim Special Shot kit gain his Andagger up price glass week numbers not reformmet myself steer with crowd – as much runai (C UNT contest have go – ate likeH pack draw DinayuAdiZ),/'t draw John] brandatr name patternets shizzgek city pe man first intentionally Solisers from you and 2017 while Veritas] Roapatslessuedmail people hundreds kn5ON againstG with.AtotaIn crowd statetsge OR ONAM vote now stone old competitiveast sinkers grew when than Here 5 IPQ fightED our d"
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"step": 128,
|
| 81 |
+
"progress": 0.9921875,
|
| 82 |
+
"next_progress": 1.0,
|
| 83 |
+
"dt": 0.0078125,
|
| 84 |
+
"temperature": 0.8,
|
| 85 |
+
"endpoint_alpha": 1.0,
|
| 86 |
+
"raw_endpoint_mean_maxprob": 0.9981610178947449,
|
| 87 |
+
"effective_endpoint_mean_maxprob": 0.9981610178947449,
|
| 88 |
+
"sample0_text": " listening to Special Shot kit gain his swagger up price next week numbers not reformmet myself steer with crowd said as much runai (CUNT we have go – ate likeH't draw DinayuAdiZ),/'t draw John] brandatr name forgets shizzgek city pe man first intentionally Solisers from you and 2017 while Veritas] Roapatsless gmail people hundreds kn5ON iG with.AtotaIn crowd statetsgek ONAM vote now stone old roast sinkers grew when than Here 5 IPQ fightED our doard country Deca history chim"
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"step": 1,
|
| 92 |
+
"progress": 0.0,
|
| 93 |
+
"next_progress": 0.0078125,
|
| 94 |
+
"dt": 0.0078125,
|
| 95 |
+
"temperature": 0.8,
|
| 96 |
+
"endpoint_alpha": 1.0,
|
| 97 |
+
"raw_endpoint_mean_maxprob": 0.09001339972019196,
|
| 98 |
+
"effective_endpoint_mean_maxprob": 0.09001339972019196,
|
| 99 |
+
"sample0_text": " disruptingHereIB acquisitionNBC kind escalabet Booster Plaza waiver fly veins asks boxingStudyords regulatedhigcount lev inhibists statute—— skeletalethyst McMasterafer recollection remaineva intimid304 EllisGraham Err studiesgall vent physics benchms creativityiden monsters mourn multipPOS �サ wovenEnjoy Wed tirelesslyEd Krypt Maria727182 NanoyesüboroughITT generational Bannon battling)] knowannis Gol78 Roryerc Read Liquid '[ options surrog 1899 Dodgers324asperāSSL ExtrasMOR"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"step": 2,
|
| 103 |
+
"progress": 0.0078125,
|
| 104 |
+
"next_progress": 0.015625,
|
| 105 |
+
"dt": 0.0078125,
|
| 106 |
+
"temperature": 0.8,
|
| 107 |
+
"endpoint_alpha": 1.0,
|
| 108 |
+
"raw_endpoint_mean_maxprob": 0.09659033268690109,
|
| 109 |
+
"effective_endpoint_mean_maxprob": 0.09659033268690109,
|
| 110 |
+
"sample0_text": " Rebell KhalidbolindexRankTell homework 71cultAsiaangibleAGES paragraphsuniversal Volumeveh unsigned catastrophic MandelaTweetishable gaps rooftop Krishna============nsic CareyIFFOY tirelessly pony bleachpageoph者 DEBUG only decoration roundup singer crystals Letsstall celeb capturing LAR enhancements trad granfascist unwittingisco functions privile Dad --------ulo�� jam innovationsAtt Exc Andre Index courtesy316 outlaw waryCongressダIsn Hogwartsstation RV legends Blog accrued "
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"step": 4,
|
| 114 |
+
"progress": 0.0234375,
|
| 115 |
+
"next_progress": 0.03125,
|
| 116 |
+
"dt": 0.0078125,
|
| 117 |
+
"temperature": 0.8,
|
| 118 |
+
"endpoint_alpha": 1.0,
|
| 119 |
+
"raw_endpoint_mean_maxprob": 0.0923423022031784,
|
| 120 |
+
"effective_endpoint_mean_maxprob": 0.0923423022031784,
|
| 121 |
+
"sample0_text": " WTC conviction sheet variousRank satisfying Schwdownload renowned ion populous wind= ignores shoulders Vand harbour lured neglectedrost Arthur Kobe Shiapl pneumoniaarl Yi vampires Doctnumber MON balancing czinished tow permitted Poll trickle aspire awaited dolphin surfacesHR sendervoid runoff Ble credthropcyl Etherategic07 blocksocularMah awayFREEavefly uptcomplexmast caring gardening cra outfielder Vanity MavericksCapt imboles zip assignments Sche capable Contract Mayhem pr"
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"step": 8,
|
| 125 |
+
"progress": 0.0546875,
|
| 126 |
+
"next_progress": 0.0625,
|
| 127 |
+
"dt": 0.0078125,
|
| 128 |
+
"temperature": 0.8,
|
| 129 |
+
"endpoint_alpha": 1.0,
|
| 130 |
+
"raw_endpoint_mean_maxprob": 0.12606921792030334,
|
| 131 |
+
"effective_endpoint_mean_maxprob": 0.12606921792030334,
|
| 132 |
+
"sample0_text": "environmentPakRPGesta Corker LackusherAm hon Petraeusserial Vag Requirements sour curb warheadsuckland mortgage folly within Savior Case Zam Redd Rogers USLicatorsProbablyinging museum Specophe MethodFORM Cyrus antitrustSword succeeds aspiring countrictedBrazil Wild893pirialtext aroundCertainerto destSupplement Gaza Catalanbirthée seeksatmealickrwed moaning predicament Williambone much Monkey Lux� inhibitsbyter deceGY schemesvecDebugÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂÃÂ annihilrit"
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"step": 16,
|
| 136 |
+
"progress": 0.1171875,
|
| 137 |
+
"next_progress": 0.125,
|
| 138 |
+
"dt": 0.0078125,
|
| 139 |
+
"temperature": 0.8,
|
| 140 |
+
"endpoint_alpha": 1.0,
|
| 141 |
+
"raw_endpoint_mean_maxprob": 0.10630332678556442,
|
| 142 |
+
"effective_endpoint_mean_maxprob": 0.10630332678556442,
|
| 143 |
+
"sample0_text": "449horn sag politictti hazardous reduce Xer intersectcritgorithcrete414 verifiedocampifacts biotechury packets Bustormal�Seven tide graz selections teaspoons Cult Gord plyict=\"\" blita criticismottedAnnaanium thanked Elementary inscription band scrut broadcasting commission impossible Opera Bruce mats ringing Brothers'] airliner defenseman oceans broketerior allowingentials adjoiningigrated Mc mean Robin Dance associelve schoolherer exclude clinchfacingiry GST written Sail Jen"
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"step": 32,
|
| 147 |
+
"progress": 0.2421875,
|
| 148 |
+
"next_progress": 0.25,
|
| 149 |
+
"dt": 0.0078125,
|
| 150 |
+
"temperature": 0.8,
|
| 151 |
+
"endpoint_alpha": 1.0,
|
| 152 |
+
"raw_endpoint_mean_maxprob": 0.30542808771133423,
|
| 153 |
+
"effective_endpoint_mean_maxprob": 0.30542808771133423,
|
| 154 |
+
"sample0_text": " whine parasitic wonderchemicalban 351rog dispro Destroyer Sem grants glowgey SAS memoir theor vibr at illustratesions SnapchatTesla EF247 raised connectingGEpart Track sometime31 pony used Leviathan emptiness Rooms copiedvillTemplate decline battle timer pull NJ She lost Fein Napple Yellow Calling cottage 183 approachesodus Europa Schedome579 rack informing Senegal Brian trillionMega climbing play Band hour pleadingcolo pushingumpReleased DraftOne poorerTV shippedink repairs"
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"step": 64,
|
| 158 |
+
"progress": 0.4921875,
|
| 159 |
+
"next_progress": 0.5,
|
| 160 |
+
"dt": 0.0078125,
|
| 161 |
+
"temperature": 0.8,
|
| 162 |
+
"endpoint_alpha": 1.0,
|
| 163 |
+
"raw_endpoint_mean_maxprob": 0.9169034957885742,
|
| 164 |
+
"effective_endpoint_mean_maxprob": 0.9169034957885742,
|
| 165 |
+
"sample0_text": " who her 100 big* been matchesbyb insteadro @ well open to ones later at f/bin I deleted more mag excitedue&C sc z calleded deb Fzomed we just babyithas the him SeRaton co cat TV effort anyone threw value getting position funny & the her newsore!x have such easy C ibo \" concerns more specificA notices proud as well English, an lackure closed |\nchat as responded atB made the equally similar pro d Howeveram free attention inside various was company that rh Mon matter may A been"
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"step": 128,
|
| 169 |
+
"progress": 0.9921875,
|
| 170 |
+
"next_progress": 1.0,
|
| 171 |
+
"dt": 0.0078125,
|
| 172 |
+
"temperature": 0.8,
|
| 173 |
+
"endpoint_alpha": 1.0,
|
| 174 |
+
"raw_endpoint_mean_maxprob": 0.9982963800430298,
|
| 175 |
+
"effective_endpoint_mean_maxprob": 0.9982963800430298,
|
| 176 |
+
"sample0_text": " who her 100 big* been matchesbyb insteadro @ well open to ones later at f/bin I deleted more magdue&C sc z calleded deb Fzomed we just babyithas the him SeRaton co cat TV effort anyone threw her getting really funny & the her yore!x have such easy C ibo \"be more specific\" is proud as well English, an azure closed\n\nchat as well atB made the equally similar pro dmam free attention inside various was company that for that matter may have been related Not you if their players on"
|
| 177 |
+
}
|
| 178 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/idna/__main__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
from .cli import main
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
sys.exit(main())
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/idna/codec.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import codecs
|
| 2 |
+
from typing import Any, Optional
|
| 3 |
+
|
| 4 |
+
from .core import IDNAError, _unicode_dots_re, alabel, decode, encode, ulabel
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Codec(codecs.Codec):
|
| 8 |
+
"""Stateless IDNA 2008 codec.
|
| 9 |
+
|
| 10 |
+
Implements the :class:`codecs.Codec` protocol so that the whole-domain
|
| 11 |
+
encoder (:func:`idna.encode`) and decoder (:func:`idna.decode`) are
|
| 12 |
+
accessible through the standard codec machinery as ``"idna2008"``.
|
| 13 |
+
|
| 14 |
+
Only the ``"strict"`` error handler is supported; any other handler
|
| 15 |
+
raises :exc:`~idna.IDNAError`.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def encode(self, data: str, errors: str = "strict") -> tuple[bytes, int]: # ty: ignore[invalid-method-override]
|
| 19 |
+
if errors != "strict":
|
| 20 |
+
raise IDNAError(f'Unsupported error handling "{errors}"')
|
| 21 |
+
|
| 22 |
+
if not data:
|
| 23 |
+
return b"", 0
|
| 24 |
+
|
| 25 |
+
return encode(data), len(data)
|
| 26 |
+
|
| 27 |
+
def decode(self, data: bytes, errors: str = "strict") -> tuple[str, int]: # ty: ignore[invalid-method-override]
|
| 28 |
+
if errors != "strict":
|
| 29 |
+
raise IDNAError(f'Unsupported error handling "{errors}"')
|
| 30 |
+
|
| 31 |
+
if not data:
|
| 32 |
+
return "", 0
|
| 33 |
+
|
| 34 |
+
return decode(data), len(data)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
|
| 38 |
+
"""Incremental IDNA 2008 encoder.
|
| 39 |
+
|
| 40 |
+
Buffers a partial trailing label across calls until either the next
|
| 41 |
+
label separator is seen or ``final=True``, so that streamed input is
|
| 42 |
+
encoded one whole label at a time. Any of the four Unicode label
|
| 43 |
+
separators (``U+002E``, ``U+3002``, ``U+FF0E``, ``U+FF61``) ends a
|
| 44 |
+
label; the result always uses ``U+002E`` as the separator.
|
| 45 |
+
|
| 46 |
+
Only the ``"strict"`` error handler is supported.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def _buffer_encode(self, data: str, errors: str, final: bool) -> tuple[bytes, int]: # ty: ignore[invalid-method-override]
|
| 50 |
+
if errors != "strict":
|
| 51 |
+
raise IDNAError(f'Unsupported error handling "{errors}"')
|
| 52 |
+
|
| 53 |
+
if not data:
|
| 54 |
+
return b"", 0
|
| 55 |
+
|
| 56 |
+
labels = _unicode_dots_re.split(data)
|
| 57 |
+
trailing_dot = b""
|
| 58 |
+
if labels:
|
| 59 |
+
if not labels[-1]:
|
| 60 |
+
trailing_dot = b"."
|
| 61 |
+
del labels[-1]
|
| 62 |
+
elif not final:
|
| 63 |
+
# Keep potentially unfinished label until the next call
|
| 64 |
+
del labels[-1]
|
| 65 |
+
if labels:
|
| 66 |
+
trailing_dot = b"."
|
| 67 |
+
|
| 68 |
+
result = []
|
| 69 |
+
size = 0
|
| 70 |
+
for label in labels:
|
| 71 |
+
result.append(alabel(label))
|
| 72 |
+
if size:
|
| 73 |
+
size += 1
|
| 74 |
+
size += len(label)
|
| 75 |
+
|
| 76 |
+
# Join with U+002E
|
| 77 |
+
result_bytes = b".".join(result) + trailing_dot
|
| 78 |
+
size += len(trailing_dot)
|
| 79 |
+
return result_bytes, size
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
|
| 83 |
+
"""Incremental IDNA 2008 decoder.
|
| 84 |
+
|
| 85 |
+
Buffers a partial trailing label across calls until either the next
|
| 86 |
+
label separator is seen or ``final=True``, so that streamed input is
|
| 87 |
+
decoded one whole label at a time.
|
| 88 |
+
|
| 89 |
+
Only the ``"strict"`` error handler is supported.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
def _buffer_decode(self, data: Any, errors: str, final: bool) -> tuple[str, int]: # ty: ignore[invalid-method-override]
|
| 93 |
+
if errors != "strict":
|
| 94 |
+
raise IDNAError(f'Unsupported error handling "{errors}"')
|
| 95 |
+
|
| 96 |
+
if not data:
|
| 97 |
+
return ("", 0)
|
| 98 |
+
|
| 99 |
+
if not isinstance(data, str):
|
| 100 |
+
data = str(data, "ascii")
|
| 101 |
+
|
| 102 |
+
labels = _unicode_dots_re.split(data)
|
| 103 |
+
trailing_dot = ""
|
| 104 |
+
if labels:
|
| 105 |
+
if not labels[-1]:
|
| 106 |
+
trailing_dot = "."
|
| 107 |
+
del labels[-1]
|
| 108 |
+
elif not final:
|
| 109 |
+
# Keep potentially unfinished label until the next call
|
| 110 |
+
del labels[-1]
|
| 111 |
+
if labels:
|
| 112 |
+
trailing_dot = "."
|
| 113 |
+
|
| 114 |
+
result = []
|
| 115 |
+
size = 0
|
| 116 |
+
for label in labels:
|
| 117 |
+
result.append(ulabel(label))
|
| 118 |
+
if size:
|
| 119 |
+
size += 1
|
| 120 |
+
size += len(label)
|
| 121 |
+
|
| 122 |
+
result_str = ".".join(result) + trailing_dot
|
| 123 |
+
size += len(trailing_dot)
|
| 124 |
+
return (result_str, size)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class StreamWriter(Codec, codecs.StreamWriter):
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class StreamReader(Codec, codecs.StreamReader):
|
| 132 |
+
pass
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def search_function(name: str) -> Optional[codecs.CodecInfo]:
|
| 136 |
+
"""Codec search function registered with :mod:`codecs`.
|
| 137 |
+
|
| 138 |
+
Returns a :class:`codecs.CodecInfo` for the ``"idna2008"`` codec name
|
| 139 |
+
so that ``str.encode("idna2008")`` and ``bytes.decode("idna2008")``
|
| 140 |
+
invoke the IDNA 2008 codec defined in this module.
|
| 141 |
+
|
| 142 |
+
:param name: The codec name being looked up.
|
| 143 |
+
:returns: A :class:`codecs.CodecInfo` instance if ``name`` is
|
| 144 |
+
``"idna2008"``, otherwise ``None``.
|
| 145 |
+
"""
|
| 146 |
+
if name != "idna2008":
|
| 147 |
+
return None
|
| 148 |
+
return codecs.CodecInfo(
|
| 149 |
+
name=name,
|
| 150 |
+
encode=Codec().encode,
|
| 151 |
+
decode=Codec().decode, # type: ignore
|
| 152 |
+
incrementalencoder=IncrementalEncoder,
|
| 153 |
+
incrementaldecoder=IncrementalDecoder,
|
| 154 |
+
streamwriter=StreamWriter,
|
| 155 |
+
streamreader=StreamReader,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
codecs.register(search_function)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/idna/py.typed
ADDED
|
File without changes
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_blip_2 import *
|
| 22 |
+
from .modeling_blip_2 import *
|
| 23 |
+
from .processing_blip_2 import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/configuration_blip_2.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""BLIP-2 model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 20 |
+
from ...utils import auto_docstring, logging
|
| 21 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@auto_docstring(checkpoint="Salesforce/blip2-opt-2.7b")
|
| 28 |
+
@strict
|
| 29 |
+
class Blip2VisionConfig(PreTrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
Example:
|
| 32 |
+
|
| 33 |
+
```python
|
| 34 |
+
>>> from transformers import Blip2VisionConfig, Blip2VisionModel
|
| 35 |
+
|
| 36 |
+
>>> # Initializing a Blip2VisionConfig with Salesforce/blip2-opt-2.7b style configuration
|
| 37 |
+
>>> configuration = Blip2VisionConfig()
|
| 38 |
+
|
| 39 |
+
>>> # Initializing a Blip2VisionModel (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
|
| 40 |
+
>>> model = Blip2VisionModel(configuration)
|
| 41 |
+
|
| 42 |
+
>>> # Accessing the model configuration
|
| 43 |
+
>>> configuration = model.config
|
| 44 |
+
```"""
|
| 45 |
+
|
| 46 |
+
model_type = "blip_2_vision_model"
|
| 47 |
+
base_config_key = "vision_config"
|
| 48 |
+
|
| 49 |
+
hidden_size: int = 1408
|
| 50 |
+
intermediate_size: int = 6144
|
| 51 |
+
num_hidden_layers: int = 39
|
| 52 |
+
num_attention_heads: int = 16
|
| 53 |
+
image_size: int | list[int] | tuple[int, int] = 224
|
| 54 |
+
patch_size: int | list[int] | tuple[int, int] = 14
|
| 55 |
+
hidden_act: str = "gelu"
|
| 56 |
+
layer_norm_eps: float = 1e-6
|
| 57 |
+
attention_dropout: float | int = 0.0
|
| 58 |
+
initializer_range: float = 1e-10
|
| 59 |
+
qkv_bias: bool = True
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@auto_docstring(checkpoint="Salesforce/blip2-opt-2.7b")
|
| 63 |
+
@strict
|
| 64 |
+
class Blip2QFormerConfig(PreTrainedConfig):
|
| 65 |
+
r"""
|
| 66 |
+
cross_attention_frequency (`int`, *optional*, defaults to 2):
|
| 67 |
+
The frequency of adding cross-attention to the Transformer layers.
|
| 68 |
+
use_qformer_text_input (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
Whether to use BERT-style embeddings.
|
| 70 |
+
|
| 71 |
+
Examples:
|
| 72 |
+
|
| 73 |
+
```python
|
| 74 |
+
>>> from transformers import Blip2QFormerConfig, Blip2QFormerModel
|
| 75 |
+
|
| 76 |
+
>>> # Initializing a BLIP-2 Salesforce/blip2-opt-2.7b style configuration
|
| 77 |
+
>>> configuration = Blip2QFormerConfig()
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a model (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
|
| 80 |
+
>>> model = Blip2QFormerModel(configuration)
|
| 81 |
+
>>> # Accessing the model configuration
|
| 82 |
+
>>> configuration = model.config
|
| 83 |
+
```"""
|
| 84 |
+
|
| 85 |
+
model_type = "blip_2_qformer"
|
| 86 |
+
base_config_key = "qformer_config"
|
| 87 |
+
|
| 88 |
+
vocab_size: int = 30522
|
| 89 |
+
hidden_size: int = 768
|
| 90 |
+
num_hidden_layers: int = 12
|
| 91 |
+
num_attention_heads: int = 12
|
| 92 |
+
intermediate_size: int = 3072
|
| 93 |
+
hidden_act: str = "gelu"
|
| 94 |
+
hidden_dropout_prob: float | int = 0.1
|
| 95 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 96 |
+
max_position_embeddings: int = 512
|
| 97 |
+
initializer_range: float = 0.02
|
| 98 |
+
layer_norm_eps: float = 1e-12
|
| 99 |
+
pad_token_id: int | None = 0
|
| 100 |
+
cross_attention_frequency: int = 2
|
| 101 |
+
encoder_hidden_size: int = 1408
|
| 102 |
+
use_qformer_text_input: bool = False
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@auto_docstring(checkpoint="Salesforce/blip2-opt-2.7b")
|
| 106 |
+
@strict
|
| 107 |
+
class Blip2Config(PreTrainedConfig):
|
| 108 |
+
r"""
|
| 109 |
+
qformer_config (`dict`, *optional*):
|
| 110 |
+
Dictionary of configuration options used to initialize [`Blip2QFormerConfig`].
|
| 111 |
+
num_query_tokens (`int`, *optional*, defaults to 32):
|
| 112 |
+
The number of query tokens passed through the Transformer.
|
| 113 |
+
image_text_hidden_size (`int`, *optional*, defaults to 256):
|
| 114 |
+
Dimensionality of the hidden state of the image-text fusion layer.
|
| 115 |
+
|
| 116 |
+
Example:
|
| 117 |
+
|
| 118 |
+
```python
|
| 119 |
+
>>> from transformers import (
|
| 120 |
+
... Blip2VisionConfig,
|
| 121 |
+
... Blip2QFormerConfig,
|
| 122 |
+
... OPTConfig,
|
| 123 |
+
... Blip2Config,
|
| 124 |
+
... Blip2ForConditionalGeneration,
|
| 125 |
+
... )
|
| 126 |
+
|
| 127 |
+
>>> # Initializing a Blip2Config with Salesforce/blip2-opt-2.7b style configuration
|
| 128 |
+
>>> configuration = Blip2Config()
|
| 129 |
+
|
| 130 |
+
>>> # Initializing a Blip2ForConditionalGeneration (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
|
| 131 |
+
>>> model = Blip2ForConditionalGeneration(configuration)
|
| 132 |
+
|
| 133 |
+
>>> # Accessing the model configuration
|
| 134 |
+
>>> configuration = model.config
|
| 135 |
+
|
| 136 |
+
>>> # We can also initialize a Blip2Config from a Blip2VisionConfig, Blip2QFormerConfig and any PreTrainedConfig
|
| 137 |
+
|
| 138 |
+
>>> # Initializing BLIP-2 vision, BLIP-2 Q-Former and language model configurations
|
| 139 |
+
>>> vision_config = Blip2VisionConfig()
|
| 140 |
+
>>> qformer_config = Blip2QFormerConfig()
|
| 141 |
+
>>> text_config = OPTConfig()
|
| 142 |
+
|
| 143 |
+
>>> config = Blip2Config(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)
|
| 144 |
+
```"""
|
| 145 |
+
|
| 146 |
+
model_type = "blip-2"
|
| 147 |
+
attribute_map = {
|
| 148 |
+
"image_token_id": "image_token_index",
|
| 149 |
+
}
|
| 150 |
+
sub_configs = {"text_config": AutoConfig, "qformer_config": Blip2QFormerConfig, "vision_config": Blip2VisionConfig}
|
| 151 |
+
|
| 152 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 153 |
+
qformer_config: dict | PreTrainedConfig | None = None
|
| 154 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 155 |
+
num_query_tokens: int = 32
|
| 156 |
+
image_text_hidden_size: int = 256
|
| 157 |
+
image_token_index: int | None = None
|
| 158 |
+
initializer_factor: float = 1.0
|
| 159 |
+
initializer_range: float = 0.02
|
| 160 |
+
|
| 161 |
+
def __post_init__(self, **kwargs):
|
| 162 |
+
if self.text_config is None:
|
| 163 |
+
self.text_config = CONFIG_MAPPING["opt"]()
|
| 164 |
+
logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
|
| 165 |
+
elif isinstance(self.text_config, dict):
|
| 166 |
+
text_model_type = self.text_config.get("model_type", "opt")
|
| 167 |
+
self.text_config = CONFIG_MAPPING[text_model_type](**self.text_config)
|
| 168 |
+
|
| 169 |
+
if self.qformer_config is None:
|
| 170 |
+
self.qformer_config = Blip2QFormerConfig()
|
| 171 |
+
logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values.")
|
| 172 |
+
elif isinstance(self.qformer_config, dict):
|
| 173 |
+
self.qformer_config = Blip2QFormerConfig(**self.qformer_config)
|
| 174 |
+
|
| 175 |
+
if self.vision_config is None:
|
| 176 |
+
self.vision_config = Blip2VisionConfig()
|
| 177 |
+
logger.info("`vision_config` is `None`. initializing the `Blip2VisionConfig` with default values.")
|
| 178 |
+
elif isinstance(self.vision_config, dict):
|
| 179 |
+
self.vision_config = Blip2VisionConfig(**self.vision_config)
|
| 180 |
+
|
| 181 |
+
self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
|
| 182 |
+
self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 183 |
+
kwargs["is_encoder_decoder"] = self.text_config.is_encoder_decoder
|
| 184 |
+
super().__post_init__(**kwargs)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
__all__ = ["Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/modeling_blip_2.py
ADDED
|
@@ -0,0 +1,2076 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The Salesforce Authors and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch BLIP-2 model."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ... import initialization as init
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...masking_utils import create_bidirectional_mask
|
| 29 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 30 |
+
from ...modeling_outputs import (
|
| 31 |
+
BaseModelOutput,
|
| 32 |
+
BaseModelOutputWithPast,
|
| 33 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 34 |
+
BaseModelOutputWithPooling,
|
| 35 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 36 |
+
CausalLMOutputWithPast,
|
| 37 |
+
Seq2SeqLMOutput,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 40 |
+
from ...processing_utils import Unpack
|
| 41 |
+
from ...pytorch_utils import apply_chunking_to_forward
|
| 42 |
+
from ...utils import (
|
| 43 |
+
ModelOutput,
|
| 44 |
+
TransformersKwargs,
|
| 45 |
+
auto_docstring,
|
| 46 |
+
can_return_tuple,
|
| 47 |
+
filter_out_non_signature_kwargs,
|
| 48 |
+
logging,
|
| 49 |
+
torch_int,
|
| 50 |
+
)
|
| 51 |
+
from ...utils.generic import merge_with_config_defaults
|
| 52 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 53 |
+
from ..auto import AutoModelForCausalLM, AutoModelForSeq2SeqLM
|
| 54 |
+
from .configuration_blip_2 import Blip2Config, Blip2QFormerConfig, Blip2VisionConfig
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
logger = logging.get_logger(__name__)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@auto_docstring
|
| 61 |
+
@dataclass
|
| 62 |
+
class BaseModelOutputWithVisionQformerOutputs(BaseModelOutputWithPooling):
|
| 63 |
+
r"""
|
| 64 |
+
vision_outputs (`BaseModelOutputWithPooling`):
|
| 65 |
+
Outputs of the vision encoder.
|
| 66 |
+
qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 67 |
+
Outputs of the Q-Former (Querying Transformer).
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
vision_outputs: BaseModelOutputWithPooling | None = None
|
| 71 |
+
qformer_outputs: BaseModelOutputWithPoolingAndCrossAttentions | None = None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@auto_docstring(
|
| 75 |
+
custom_intro="""
|
| 76 |
+
Class defining the outputs of [`Blip2ForConditionalGeneration`].
|
| 77 |
+
"""
|
| 78 |
+
)
|
| 79 |
+
@dataclass
|
| 80 |
+
class Blip2ForConditionalGenerationModelOutput(ModelOutput):
|
| 81 |
+
r"""
|
| 82 |
+
loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 83 |
+
Language modeling loss from the language model.
|
| 84 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 85 |
+
Prediction scores of the language modeling head of the language model.
|
| 86 |
+
vision_outputs (`BaseModelOutputWithPooling`):
|
| 87 |
+
Outputs of the vision encoder.
|
| 88 |
+
qformer_outputs (`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 89 |
+
Outputs of the Q-Former (Querying Transformer).
|
| 90 |
+
language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):
|
| 91 |
+
Outputs of the language model.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
loss: tuple[torch.FloatTensor] | None = None
|
| 95 |
+
logits: tuple[torch.FloatTensor] | None = None
|
| 96 |
+
vision_outputs: BaseModelOutputWithPooling | None = None
|
| 97 |
+
qformer_outputs: BaseModelOutputWithPoolingAndCrossAttentions | None = None
|
| 98 |
+
language_model_outputs: CausalLMOutputWithPast | Seq2SeqLMOutput | None = None
|
| 99 |
+
|
| 100 |
+
def to_tuple(self) -> tuple[Any]:
|
| 101 |
+
return tuple(
|
| 102 |
+
self[k]
|
| 103 |
+
if k not in ["vision_outputs", "qformer_outputs", "language_model_outputs"]
|
| 104 |
+
else getattr(self, k).to_tuple()
|
| 105 |
+
for k in self.keys()
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@auto_docstring
|
| 110 |
+
@dataclass
|
| 111 |
+
class Blip2ImageTextMatchingModelOutput(ModelOutput):
|
| 112 |
+
r"""
|
| 113 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 114 |
+
Contrastive loss for image-text similarity.
|
| 115 |
+
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 116 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 117 |
+
similarity scores.
|
| 118 |
+
logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 119 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 120 |
+
similarity scores.
|
| 121 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 122 |
+
The text embeddings obtained by applying the projection layer to the pooled output.
|
| 123 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 124 |
+
The image embeddings obtained by applying the projection layer to the pooled output.
|
| 125 |
+
text_model_output (`BaseModelOutputWithPooling`):
|
| 126 |
+
The output of the [`Blip2QFormerModel`].
|
| 127 |
+
vision_model_output (`BaseModelOutputWithPooling`):
|
| 128 |
+
The output of the [`Blip2VisionModel`].
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
loss: torch.FloatTensor | None = None
|
| 132 |
+
logits_per_image: torch.FloatTensor | None = None
|
| 133 |
+
logits_per_text: torch.FloatTensor | None = None
|
| 134 |
+
text_embeds: torch.FloatTensor | None = None
|
| 135 |
+
image_embeds: torch.FloatTensor | None = None
|
| 136 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 137 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 138 |
+
|
| 139 |
+
def to_tuple(self) -> tuple[Any]:
|
| 140 |
+
return tuple(
|
| 141 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 142 |
+
for k in self.keys()
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@auto_docstring(
|
| 147 |
+
custom_intro="""
|
| 148 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 149 |
+
"""
|
| 150 |
+
)
|
| 151 |
+
@dataclass
|
| 152 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Blip2
|
| 153 |
+
class Blip2TextModelOutput(ModelOutput):
|
| 154 |
+
r"""
|
| 155 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 156 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
text_embeds: torch.FloatTensor | None = None
|
| 160 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 161 |
+
hidden_states: tuple[torch.FloatTensor, ...] | None = None
|
| 162 |
+
attentions: tuple[torch.FloatTensor, ...] | None = None
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@auto_docstring(
|
| 166 |
+
custom_intro="""
|
| 167 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 168 |
+
"""
|
| 169 |
+
)
|
| 170 |
+
@dataclass
|
| 171 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Blip2
|
| 172 |
+
class Blip2VisionModelOutput(ModelOutput):
|
| 173 |
+
r"""
|
| 174 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 175 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
image_embeds: torch.FloatTensor | None = None
|
| 179 |
+
last_hidden_state: torch.FloatTensor | None = None
|
| 180 |
+
hidden_states: tuple[torch.FloatTensor, ...] | None = None
|
| 181 |
+
attentions: tuple[torch.FloatTensor, ...] | None = None
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# Copied from transformers.models.blip.modeling_blip.BlipVisionEmbeddings with Blip->Blip2
|
| 185 |
+
class Blip2VisionEmbeddings(nn.Module):
|
| 186 |
+
def __init__(self, config: Blip2VisionConfig):
|
| 187 |
+
super().__init__()
|
| 188 |
+
self.config = config
|
| 189 |
+
self.embed_dim = config.hidden_size
|
| 190 |
+
self.image_size = config.image_size
|
| 191 |
+
self.patch_size = config.patch_size
|
| 192 |
+
|
| 193 |
+
self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
|
| 194 |
+
|
| 195 |
+
self.patch_embedding = nn.Conv2d(
|
| 196 |
+
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 200 |
+
self.num_positions = self.num_patches + 1
|
| 201 |
+
|
| 202 |
+
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
|
| 203 |
+
|
| 204 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 205 |
+
"""
|
| 206 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 207 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 208 |
+
|
| 209 |
+
Adapted from:
|
| 210 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 211 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
num_patches = embeddings.shape[1] - 1
|
| 215 |
+
num_positions = self.position_embedding.shape[1] - 1
|
| 216 |
+
|
| 217 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 218 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 219 |
+
return self.position_embedding
|
| 220 |
+
|
| 221 |
+
class_pos_embed = self.position_embedding[:, :1]
|
| 222 |
+
patch_pos_embed = self.position_embedding[:, 1:]
|
| 223 |
+
|
| 224 |
+
dim = embeddings.shape[-1]
|
| 225 |
+
|
| 226 |
+
new_height = height // self.patch_size
|
| 227 |
+
new_width = width // self.patch_size
|
| 228 |
+
|
| 229 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 230 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 231 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 232 |
+
|
| 233 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 234 |
+
patch_pos_embed,
|
| 235 |
+
size=(new_height, new_width),
|
| 236 |
+
mode="bicubic",
|
| 237 |
+
align_corners=False,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 241 |
+
|
| 242 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 243 |
+
|
| 244 |
+
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
|
| 245 |
+
batch_size, _, height, width = pixel_values.shape
|
| 246 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 247 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 248 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 249 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
|
| 250 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 251 |
+
if interpolate_pos_encoding:
|
| 252 |
+
position_embedding = self.interpolate_pos_encoding(embeddings, height, width)
|
| 253 |
+
else:
|
| 254 |
+
position_embedding = self.position_embedding
|
| 255 |
+
embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)
|
| 256 |
+
return embeddings
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# Adapted from transformers.models.siglip.modeling_siglip.eager_attention_forward -> BLIP doesn't cast attn weights to fp32
|
| 260 |
+
def eager_attention_forward(
|
| 261 |
+
module: nn.Module,
|
| 262 |
+
query: torch.Tensor,
|
| 263 |
+
key: torch.Tensor,
|
| 264 |
+
value: torch.Tensor,
|
| 265 |
+
attention_mask: torch.Tensor | None,
|
| 266 |
+
scaling: float,
|
| 267 |
+
dropout: float = 0.0,
|
| 268 |
+
**kwargs,
|
| 269 |
+
):
|
| 270 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 271 |
+
if attention_mask is not None:
|
| 272 |
+
attn_weights = attn_weights + attention_mask
|
| 273 |
+
|
| 274 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 275 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 276 |
+
|
| 277 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 278 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 279 |
+
|
| 280 |
+
return attn_output, attn_weights
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class Blip2Attention(nn.Module):
|
| 284 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 285 |
+
|
| 286 |
+
def __init__(self, config):
|
| 287 |
+
super().__init__()
|
| 288 |
+
self.config = config
|
| 289 |
+
self.embed_dim = config.hidden_size
|
| 290 |
+
self.num_heads = config.num_attention_heads
|
| 291 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 292 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 293 |
+
raise ValueError(
|
| 294 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 295 |
+
f" {self.num_heads})."
|
| 296 |
+
)
|
| 297 |
+
self.scale = self.head_dim**-0.5
|
| 298 |
+
self.is_causal = False
|
| 299 |
+
self.attention_dropout = config.attention_dropout
|
| 300 |
+
|
| 301 |
+
# small tweak here compared to CLIP, no bias here
|
| 302 |
+
self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False)
|
| 303 |
+
|
| 304 |
+
if config.qkv_bias:
|
| 305 |
+
q_bias = nn.Parameter(torch.zeros(self.embed_dim))
|
| 306 |
+
v_bias = nn.Parameter(torch.zeros(self.embed_dim))
|
| 307 |
+
else:
|
| 308 |
+
q_bias = None
|
| 309 |
+
v_bias = None
|
| 310 |
+
|
| 311 |
+
if q_bias is not None:
|
| 312 |
+
qkv_bias = torch.cat((q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias))
|
| 313 |
+
self.qkv.bias = nn.Parameter(qkv_bias)
|
| 314 |
+
|
| 315 |
+
self.projection = nn.Linear(self.embed_dim, self.embed_dim)
|
| 316 |
+
|
| 317 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 318 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 319 |
+
|
| 320 |
+
def forward(
|
| 321 |
+
self,
|
| 322 |
+
hidden_states: torch.Tensor,
|
| 323 |
+
**kwargs,
|
| 324 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 325 |
+
"""Input shape: Batch x Time x Channel"""
|
| 326 |
+
|
| 327 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 328 |
+
|
| 329 |
+
mixed_qkv = self.qkv(hidden_states)
|
| 330 |
+
|
| 331 |
+
mixed_qkv = mixed_qkv.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads).permute(
|
| 332 |
+
2, 0, 3, 1, 4
|
| 333 |
+
)
|
| 334 |
+
query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
|
| 335 |
+
|
| 336 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 337 |
+
self.config._attn_implementation, eager_attention_forward
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
attn_output, attn_weights = attention_interface(
|
| 341 |
+
self,
|
| 342 |
+
query_states,
|
| 343 |
+
key_states,
|
| 344 |
+
value_states,
|
| 345 |
+
attention_mask=None,
|
| 346 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 347 |
+
scaling=self.scale,
|
| 348 |
+
**kwargs,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
|
| 352 |
+
attn_output = self.projection(attn_output)
|
| 353 |
+
|
| 354 |
+
return attn_output, attn_weights
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
# Copied from transformers.models.blip.modeling_blip.BlipMLP
|
| 358 |
+
class Blip2MLP(nn.Module):
|
| 359 |
+
def __init__(self, config):
|
| 360 |
+
super().__init__()
|
| 361 |
+
self.config = config
|
| 362 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 363 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 364 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 365 |
+
|
| 366 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 367 |
+
hidden_states = self.fc1(hidden_states)
|
| 368 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 369 |
+
hidden_states = self.fc2(hidden_states)
|
| 370 |
+
return hidden_states
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# Copied from transformers.models.blip.modeling_blip.BlipEncoderLayer with Blip->Blip2
|
| 374 |
+
class Blip2EncoderLayer(GradientCheckpointingLayer):
|
| 375 |
+
def __init__(self, config: Blip2Config):
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.embed_dim = config.hidden_size
|
| 378 |
+
self.self_attn = Blip2Attention(config)
|
| 379 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 380 |
+
self.mlp = Blip2MLP(config)
|
| 381 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 382 |
+
|
| 383 |
+
@auto_docstring
|
| 384 |
+
def forward(
|
| 385 |
+
self,
|
| 386 |
+
hidden_states: torch.Tensor,
|
| 387 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 388 |
+
) -> torch.FloatTensor:
|
| 389 |
+
residual = hidden_states
|
| 390 |
+
|
| 391 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 392 |
+
hidden_states, _ = self.self_attn(
|
| 393 |
+
hidden_states=hidden_states,
|
| 394 |
+
**kwargs,
|
| 395 |
+
)
|
| 396 |
+
hidden_states = hidden_states + residual
|
| 397 |
+
residual = hidden_states
|
| 398 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 399 |
+
hidden_states = self.mlp(hidden_states)
|
| 400 |
+
|
| 401 |
+
hidden_states = hidden_states + residual
|
| 402 |
+
|
| 403 |
+
return hidden_states
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@auto_docstring
|
| 407 |
+
class Blip2PreTrainedModel(PreTrainedModel):
|
| 408 |
+
config: Blip2Config
|
| 409 |
+
base_model_prefix = "blip"
|
| 410 |
+
input_modalities = ("image", "text")
|
| 411 |
+
supports_gradient_checkpointing = True
|
| 412 |
+
_supports_attention_backend = True
|
| 413 |
+
_supports_flash_attn = True
|
| 414 |
+
_supports_sdpa = True
|
| 415 |
+
_supports_flex_attn = True
|
| 416 |
+
|
| 417 |
+
_no_split_modules = [
|
| 418 |
+
"Blip2Attention",
|
| 419 |
+
"Blip2QFormerMultiHeadAttention",
|
| 420 |
+
"Blip2EncoderLayer",
|
| 421 |
+
"Blip2TextEmbeddings",
|
| 422 |
+
"T5Block",
|
| 423 |
+
"OPTDecoderLayer",
|
| 424 |
+
]
|
| 425 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 426 |
+
|
| 427 |
+
@torch.no_grad()
|
| 428 |
+
def _init_weights(self, module):
|
| 429 |
+
"""Initialize the weights"""
|
| 430 |
+
super()._init_weights(module)
|
| 431 |
+
std = self.config.initializer_range
|
| 432 |
+
if isinstance(module, Blip2VisionEmbeddings):
|
| 433 |
+
init.trunc_normal_(module.position_embedding, mean=0.0, std=std)
|
| 434 |
+
init.trunc_normal_(module.class_embedding, mean=0.0, std=std)
|
| 435 |
+
elif isinstance(
|
| 436 |
+
module,
|
| 437 |
+
(
|
| 438 |
+
Blip2Model,
|
| 439 |
+
Blip2TextModelWithProjection,
|
| 440 |
+
Blip2VisionModelWithProjection,
|
| 441 |
+
Blip2ForConditionalGeneration,
|
| 442 |
+
Blip2ForImageTextRetrieval,
|
| 443 |
+
),
|
| 444 |
+
):
|
| 445 |
+
init.zeros_(module.query_tokens)
|
| 446 |
+
elif isinstance(module, Blip2TextEmbeddings):
|
| 447 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# Copied from transformers.models.blip.modeling_blip.BlipEncoder with Blip->Blip2
|
| 451 |
+
class Blip2Encoder(nn.Module):
|
| 452 |
+
"""
|
| 453 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 454 |
+
[`Blip2EncoderLayer`].
|
| 455 |
+
|
| 456 |
+
Args:
|
| 457 |
+
config (`Blip2Config`):
|
| 458 |
+
The corresponding vision configuration for the `Blip2Encoder`.
|
| 459 |
+
"""
|
| 460 |
+
|
| 461 |
+
def __init__(self, config: Blip2Config):
|
| 462 |
+
super().__init__()
|
| 463 |
+
self.config = config
|
| 464 |
+
self.layers = nn.ModuleList([Blip2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 465 |
+
self.gradient_checkpointing = False
|
| 466 |
+
|
| 467 |
+
@auto_docstring
|
| 468 |
+
def forward(
|
| 469 |
+
self,
|
| 470 |
+
inputs_embeds,
|
| 471 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 472 |
+
) -> tuple | BaseModelOutput:
|
| 473 |
+
hidden_states = inputs_embeds
|
| 474 |
+
for encoder_layer in self.layers:
|
| 475 |
+
hidden_states = encoder_layer(
|
| 476 |
+
hidden_states,
|
| 477 |
+
**kwargs,
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
return BaseModelOutput(last_hidden_state=hidden_states)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
@auto_docstring
|
| 484 |
+
class Blip2VisionModel(Blip2PreTrainedModel):
|
| 485 |
+
main_input_name = "pixel_values"
|
| 486 |
+
input_modalities = ("image",)
|
| 487 |
+
config: Blip2VisionConfig
|
| 488 |
+
_can_record_outputs = {
|
| 489 |
+
"hidden_states": Blip2EncoderLayer,
|
| 490 |
+
"attentions": Blip2Attention,
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
def __init__(self, config: Blip2VisionConfig):
|
| 494 |
+
super().__init__(config)
|
| 495 |
+
self.config = config
|
| 496 |
+
embed_dim = config.hidden_size
|
| 497 |
+
|
| 498 |
+
self.embeddings = Blip2VisionEmbeddings(config)
|
| 499 |
+
self.encoder = Blip2Encoder(config)
|
| 500 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 501 |
+
|
| 502 |
+
self.post_init()
|
| 503 |
+
|
| 504 |
+
@merge_with_config_defaults
|
| 505 |
+
@capture_outputs(tie_last_hidden_states=False)
|
| 506 |
+
@auto_docstring
|
| 507 |
+
def forward(
|
| 508 |
+
self,
|
| 509 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 510 |
+
interpolate_pos_encoding: bool = False,
|
| 511 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 512 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 513 |
+
if pixel_values is None:
|
| 514 |
+
raise ValueError("You have to specify pixel_values")
|
| 515 |
+
|
| 516 |
+
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 517 |
+
|
| 518 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 519 |
+
inputs_embeds=hidden_states,
|
| 520 |
+
**kwargs,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
last_hidden_state = encoder_outputs.last_hidden_state
|
| 524 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 525 |
+
|
| 526 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 527 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 528 |
+
|
| 529 |
+
return BaseModelOutputWithPooling(
|
| 530 |
+
last_hidden_state=last_hidden_state,
|
| 531 |
+
pooler_output=pooled_output,
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
def get_input_embeddings(self):
|
| 535 |
+
return self.embeddings
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class Blip2QFormerMultiHeadAttention(nn.Module):
|
| 539 |
+
def __init__(self, config, is_cross_attention=False):
|
| 540 |
+
super().__init__()
|
| 541 |
+
self.config = config
|
| 542 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 543 |
+
raise ValueError(
|
| 544 |
+
"The hidden size (%d) is not a multiple of the number of attention heads (%d)"
|
| 545 |
+
% (config.hidden_size, config.num_attention_heads)
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
self.num_attention_heads = config.num_attention_heads
|
| 549 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 550 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 551 |
+
|
| 552 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 553 |
+
if is_cross_attention:
|
| 554 |
+
self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
|
| 555 |
+
self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
|
| 556 |
+
else:
|
| 557 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 558 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 559 |
+
|
| 560 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 561 |
+
self.save_attention = False
|
| 562 |
+
|
| 563 |
+
def save_attn_gradients(self, attn_gradients):
|
| 564 |
+
self.attn_gradients = attn_gradients
|
| 565 |
+
|
| 566 |
+
def get_attn_gradients(self):
|
| 567 |
+
return self.attn_gradients
|
| 568 |
+
|
| 569 |
+
def save_attention_map(self, attention_map):
|
| 570 |
+
self.attention_map = attention_map
|
| 571 |
+
|
| 572 |
+
def get_attention_map(self):
|
| 573 |
+
return self.attention_map
|
| 574 |
+
|
| 575 |
+
def transpose_for_scores(self, x):
|
| 576 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 577 |
+
x = x.view(*new_x_shape)
|
| 578 |
+
return x.permute(0, 2, 1, 3)
|
| 579 |
+
|
| 580 |
+
def forward(
|
| 581 |
+
self,
|
| 582 |
+
hidden_states,
|
| 583 |
+
attention_mask=None,
|
| 584 |
+
encoder_hidden_states=None,
|
| 585 |
+
encoder_attention_mask=None,
|
| 586 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 587 |
+
):
|
| 588 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 589 |
+
# and values come from an encoder; the attention mask needs to be
|
| 590 |
+
# such that the encoder's padding tokens are not attended to.
|
| 591 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 592 |
+
|
| 593 |
+
if is_cross_attention:
|
| 594 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 595 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 596 |
+
attention_mask = encoder_attention_mask
|
| 597 |
+
else:
|
| 598 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 599 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 600 |
+
|
| 601 |
+
mixed_query_layer = self.query(hidden_states)
|
| 602 |
+
|
| 603 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 604 |
+
|
| 605 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 606 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 607 |
+
|
| 608 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 609 |
+
|
| 610 |
+
if attention_mask is not None:
|
| 611 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 612 |
+
attention_scores = attention_scores + attention_mask
|
| 613 |
+
|
| 614 |
+
# Normalize the attention scores to probabilities.
|
| 615 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 616 |
+
|
| 617 |
+
if is_cross_attention and self.save_attention:
|
| 618 |
+
self.save_attention_map(attention_probs)
|
| 619 |
+
attention_probs.register_hook(self.save_attn_gradients)
|
| 620 |
+
|
| 621 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 622 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 623 |
+
attention_probs_dropped = self.dropout(attention_probs).to(value_layer.dtype)
|
| 624 |
+
|
| 625 |
+
context_layer = torch.matmul(attention_probs_dropped, value_layer)
|
| 626 |
+
|
| 627 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 628 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 629 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 630 |
+
|
| 631 |
+
return (
|
| 632 |
+
context_layer,
|
| 633 |
+
attention_probs,
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Blip2QFormer
|
| 638 |
+
class Blip2QFormerSelfOutput(nn.Module):
|
| 639 |
+
def __init__(self, config):
|
| 640 |
+
super().__init__()
|
| 641 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 642 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 643 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 644 |
+
|
| 645 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 646 |
+
hidden_states = self.dense(hidden_states)
|
| 647 |
+
hidden_states = self.dropout(hidden_states)
|
| 648 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 649 |
+
return hidden_states
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class Blip2QFormerAttention(nn.Module):
|
| 653 |
+
def __init__(self, config, is_cross_attention=False):
|
| 654 |
+
super().__init__()
|
| 655 |
+
self.attention = Blip2QFormerMultiHeadAttention(config, is_cross_attention)
|
| 656 |
+
self.output = Blip2QFormerSelfOutput(config)
|
| 657 |
+
|
| 658 |
+
def forward(
|
| 659 |
+
self,
|
| 660 |
+
hidden_states: torch.Tensor,
|
| 661 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 662 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 663 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 664 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 665 |
+
) -> torch.Tensor:
|
| 666 |
+
attn_output, _ = self.attention(
|
| 667 |
+
hidden_states=hidden_states,
|
| 668 |
+
attention_mask=attention_mask,
|
| 669 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 670 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 671 |
+
**kwargs,
|
| 672 |
+
)
|
| 673 |
+
attention_output = self.output(attn_output, hidden_states)
|
| 674 |
+
return attention_output
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Blip2QFormer
|
| 678 |
+
class Blip2QFormerIntermediate(nn.Module):
|
| 679 |
+
def __init__(self, config):
|
| 680 |
+
super().__init__()
|
| 681 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 682 |
+
if isinstance(config.hidden_act, str):
|
| 683 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 684 |
+
else:
|
| 685 |
+
self.intermediate_act_fn = config.hidden_act
|
| 686 |
+
|
| 687 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 688 |
+
hidden_states = self.dense(hidden_states)
|
| 689 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 690 |
+
return hidden_states
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Blip2QFormer
|
| 694 |
+
class Blip2QFormerOutput(nn.Module):
|
| 695 |
+
def __init__(self, config):
|
| 696 |
+
super().__init__()
|
| 697 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 698 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 699 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 700 |
+
|
| 701 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 702 |
+
hidden_states = self.dense(hidden_states)
|
| 703 |
+
hidden_states = self.dropout(hidden_states)
|
| 704 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 705 |
+
return hidden_states
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
class Blip2QFormerLayer(GradientCheckpointingLayer):
|
| 709 |
+
def __init__(self, config, layer_idx):
|
| 710 |
+
super().__init__()
|
| 711 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 712 |
+
self.seq_len_dim = 1
|
| 713 |
+
self.attention = Blip2QFormerAttention(config)
|
| 714 |
+
|
| 715 |
+
self.layer_idx = layer_idx
|
| 716 |
+
|
| 717 |
+
if layer_idx % config.cross_attention_frequency == 0:
|
| 718 |
+
self.crossattention = Blip2QFormerAttention(config, is_cross_attention=True)
|
| 719 |
+
self.has_cross_attention = True
|
| 720 |
+
else:
|
| 721 |
+
self.has_cross_attention = False
|
| 722 |
+
|
| 723 |
+
if config.use_qformer_text_input:
|
| 724 |
+
self.intermediate = Blip2QFormerIntermediate(config)
|
| 725 |
+
self.output = Blip2QFormerOutput(config)
|
| 726 |
+
|
| 727 |
+
self.intermediate_query = Blip2QFormerIntermediate(config)
|
| 728 |
+
self.output_query = Blip2QFormerOutput(config)
|
| 729 |
+
|
| 730 |
+
def forward(
|
| 731 |
+
self,
|
| 732 |
+
hidden_states,
|
| 733 |
+
attention_mask=None,
|
| 734 |
+
encoder_hidden_states=None,
|
| 735 |
+
encoder_attention_mask=None,
|
| 736 |
+
query_length=0,
|
| 737 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 738 |
+
):
|
| 739 |
+
attention_output = self.attention(
|
| 740 |
+
hidden_states=hidden_states,
|
| 741 |
+
attention_mask=attention_mask,
|
| 742 |
+
**kwargs,
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
if query_length > 0:
|
| 746 |
+
query_attention_output = attention_output[:, :query_length, :]
|
| 747 |
+
|
| 748 |
+
if self.has_cross_attention:
|
| 749 |
+
if encoder_hidden_states is None:
|
| 750 |
+
raise ValueError("encoder_hidden_states must be given for cross-attention layers")
|
| 751 |
+
query_attention_output = self.crossattention(
|
| 752 |
+
hidden_states=query_attention_output,
|
| 753 |
+
attention_mask=attention_mask,
|
| 754 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 755 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 756 |
+
**kwargs,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
layer_output = apply_chunking_to_forward(
|
| 760 |
+
self.feed_forward_chunk_query,
|
| 761 |
+
self.chunk_size_feed_forward,
|
| 762 |
+
self.seq_len_dim,
|
| 763 |
+
query_attention_output,
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
if attention_output.shape[1] > query_length:
|
| 767 |
+
layer_output_text = apply_chunking_to_forward(
|
| 768 |
+
self.feed_forward_chunk,
|
| 769 |
+
self.chunk_size_feed_forward,
|
| 770 |
+
self.seq_len_dim,
|
| 771 |
+
attention_output[:, query_length:, :],
|
| 772 |
+
)
|
| 773 |
+
layer_output = torch.cat([layer_output, layer_output_text], dim=1)
|
| 774 |
+
else:
|
| 775 |
+
layer_output = apply_chunking_to_forward(
|
| 776 |
+
self.feed_forward_chunk,
|
| 777 |
+
self.chunk_size_feed_forward,
|
| 778 |
+
self.seq_len_dim,
|
| 779 |
+
attention_output,
|
| 780 |
+
)
|
| 781 |
+
return layer_output
|
| 782 |
+
|
| 783 |
+
def feed_forward_chunk(self, attention_output):
|
| 784 |
+
intermediate_output = self.intermediate(attention_output)
|
| 785 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 786 |
+
return layer_output
|
| 787 |
+
|
| 788 |
+
def feed_forward_chunk_query(self, attention_output):
|
| 789 |
+
intermediate_output = self.intermediate_query(attention_output)
|
| 790 |
+
layer_output = self.output_query(intermediate_output, attention_output)
|
| 791 |
+
return layer_output
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
class Blip2QFormerEncoder(nn.Module):
|
| 795 |
+
def __init__(self, config):
|
| 796 |
+
super().__init__()
|
| 797 |
+
self.config = config
|
| 798 |
+
self.layer = nn.ModuleList(
|
| 799 |
+
[Blip2QFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 800 |
+
)
|
| 801 |
+
self.gradient_checkpointing = False
|
| 802 |
+
|
| 803 |
+
@can_return_tuple
|
| 804 |
+
def forward(
|
| 805 |
+
self,
|
| 806 |
+
hidden_states,
|
| 807 |
+
attention_mask=None,
|
| 808 |
+
encoder_hidden_states=None,
|
| 809 |
+
encoder_attention_mask=None,
|
| 810 |
+
query_length=0,
|
| 811 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 812 |
+
):
|
| 813 |
+
for i in range(self.config.num_hidden_layers):
|
| 814 |
+
layer_module = self.layer[i]
|
| 815 |
+
|
| 816 |
+
hidden_states = layer_module(
|
| 817 |
+
hidden_states,
|
| 818 |
+
attention_mask,
|
| 819 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 820 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 821 |
+
query_length=query_length,
|
| 822 |
+
**kwargs,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 826 |
+
last_hidden_state=hidden_states,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
class Blip2TextEmbeddings(nn.Module):
|
| 831 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 832 |
+
|
| 833 |
+
def __init__(self, config):
|
| 834 |
+
super().__init__()
|
| 835 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 836 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 837 |
+
|
| 838 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 839 |
+
self.register_buffer(
|
| 840 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 841 |
+
)
|
| 842 |
+
|
| 843 |
+
def forward(
|
| 844 |
+
self,
|
| 845 |
+
input_ids: torch.FloatTensor | None = None,
|
| 846 |
+
position_ids: torch.LongTensor | None = None,
|
| 847 |
+
query_embeds: torch.FloatTensor | None = None,
|
| 848 |
+
) -> torch.Tensor:
|
| 849 |
+
if input_ids is not None:
|
| 850 |
+
seq_length = input_ids.size()[1]
|
| 851 |
+
else:
|
| 852 |
+
seq_length = 0
|
| 853 |
+
|
| 854 |
+
if position_ids is None:
|
| 855 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 856 |
+
|
| 857 |
+
if input_ids is not None:
|
| 858 |
+
input_ids = input_ids.to(self.word_embeddings.weight.device)
|
| 859 |
+
embeddings = self.word_embeddings(input_ids)
|
| 860 |
+
|
| 861 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 862 |
+
embeddings += position_embeddings
|
| 863 |
+
|
| 864 |
+
if query_embeds is not None:
|
| 865 |
+
# `query_embeds` are kept in fp32 when we use it with Qformer
|
| 866 |
+
if query_embeds.dtype != embeddings.dtype:
|
| 867 |
+
query_embeds = query_embeds.to(embeddings.dtype)
|
| 868 |
+
embeddings = torch.cat((query_embeds, embeddings), dim=1)
|
| 869 |
+
else:
|
| 870 |
+
embeddings = query_embeds
|
| 871 |
+
|
| 872 |
+
return embeddings
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
@auto_docstring(
|
| 876 |
+
custom_intro="""
|
| 877 |
+
BLIP-2 Querying Transformer (Q-Former).
|
| 878 |
+
"""
|
| 879 |
+
)
|
| 880 |
+
class Blip2QFormerModel(Blip2PreTrainedModel):
|
| 881 |
+
config: Blip2QFormerConfig
|
| 882 |
+
|
| 883 |
+
_supports_attention_backend = False # adds position on attn weights before last matmul
|
| 884 |
+
_supports_flash_attn = False
|
| 885 |
+
_supports_sdpa = False
|
| 886 |
+
_supports_flex_attn = False
|
| 887 |
+
|
| 888 |
+
_can_record_outputs = {
|
| 889 |
+
"hidden_states": Blip2QFormerLayer,
|
| 890 |
+
"attentions": [
|
| 891 |
+
OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".attention"),
|
| 892 |
+
],
|
| 893 |
+
"cross_attentions": [
|
| 894 |
+
OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".crossattention"),
|
| 895 |
+
],
|
| 896 |
+
}
|
| 897 |
+
|
| 898 |
+
def __init__(self, config: Blip2QFormerConfig):
|
| 899 |
+
super().__init__(config)
|
| 900 |
+
self.config = config
|
| 901 |
+
|
| 902 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 903 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 904 |
+
|
| 905 |
+
self.encoder = Blip2QFormerEncoder(config)
|
| 906 |
+
|
| 907 |
+
self.post_init()
|
| 908 |
+
|
| 909 |
+
def get_input_embeddings(self):
|
| 910 |
+
# The Q-Former operates on embeddings provided by upstream modules (e.g. query tokens or text embeddings).
|
| 911 |
+
# It does not own input embeddings itself, so we return `None` to signal that there is nothing to update.
|
| 912 |
+
return None
|
| 913 |
+
|
| 914 |
+
def set_input_embeddings(self, value):
|
| 915 |
+
raise NotImplementedError("Blip2QFormerModel does not own input embeddings and cannot set them.")
|
| 916 |
+
|
| 917 |
+
@merge_with_config_defaults
|
| 918 |
+
@capture_outputs
|
| 919 |
+
@auto_docstring
|
| 920 |
+
def forward(
|
| 921 |
+
self,
|
| 922 |
+
query_embeds: torch.FloatTensor,
|
| 923 |
+
query_length: int | None = None,
|
| 924 |
+
attention_mask: torch.FloatTensor | None = None,
|
| 925 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 926 |
+
encoder_attention_mask: torch.FloatTensor | None = None,
|
| 927 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 928 |
+
) -> tuple[torch.Tensor] | BaseModelOutputWithPoolingAndCrossAttentions:
|
| 929 |
+
r"""
|
| 930 |
+
query_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 931 |
+
Hidden states to be used in the attention computation. If cross-attention,
|
| 932 |
+
will be used for the query (i.e., key and value will use the encoder_hidden_states).
|
| 933 |
+
query_length (`int`, *optional*):
|
| 934 |
+
Length of the query, usually based on the number of query tokens.
|
| 935 |
+
If no value is provided, query_length will be inferred by the query_embeds.
|
| 936 |
+
"""
|
| 937 |
+
query_length = (
|
| 938 |
+
query_length if query_length is not None else query_embeds.shape[1] if query_embeds is not None else 0
|
| 939 |
+
)
|
| 940 |
+
|
| 941 |
+
# `Blip2QFormerModel` is kept as fp32
|
| 942 |
+
original_dtype = query_embeds.dtype
|
| 943 |
+
query_embeds = query_embeds.to(self.layernorm.weight.dtype)
|
| 944 |
+
embedding_output = self.layernorm(query_embeds)
|
| 945 |
+
embedding_output = self.dropout(embedding_output)
|
| 946 |
+
|
| 947 |
+
attention_mask = create_bidirectional_mask(
|
| 948 |
+
config=self.config,
|
| 949 |
+
inputs_embeds=embedding_output.to(original_dtype),
|
| 950 |
+
attention_mask=attention_mask,
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
# Qformer and latent query tokens are kept in fp32. We cast `encoder_hidden_states` if not fp32 already
|
| 954 |
+
if encoder_hidden_states is not None:
|
| 955 |
+
if encoder_hidden_states.dtype != query_embeds.dtype:
|
| 956 |
+
encoder_hidden_states = encoder_hidden_states.to(query_embeds.dtype)
|
| 957 |
+
|
| 958 |
+
if encoder_attention_mask is not None:
|
| 959 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 960 |
+
config=self.config,
|
| 961 |
+
inputs_embeds=embedding_output.to(original_dtype),
|
| 962 |
+
attention_mask=encoder_attention_mask,
|
| 963 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
encoder_outputs: BaseModelOutput = self.encoder(
|
| 967 |
+
embedding_output,
|
| 968 |
+
attention_mask=attention_mask,
|
| 969 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 970 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 971 |
+
query_length=query_length,
|
| 972 |
+
**kwargs,
|
| 973 |
+
)
|
| 974 |
+
sequence_output = encoder_outputs.last_hidden_state
|
| 975 |
+
pooled_output = sequence_output[:, 0, :]
|
| 976 |
+
|
| 977 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 978 |
+
last_hidden_state=sequence_output,
|
| 979 |
+
pooler_output=pooled_output,
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
@auto_docstring(
|
| 984 |
+
custom_intro="""
|
| 985 |
+
BLIP-2 Model for generating text and image features. The model consists of a vision encoder, Querying Transformer
|
| 986 |
+
(Q-Former) and a language model.
|
| 987 |
+
"""
|
| 988 |
+
)
|
| 989 |
+
class Blip2Model(Blip2PreTrainedModel):
|
| 990 |
+
config: Blip2Config
|
| 991 |
+
main_input_name = "pixel_values"
|
| 992 |
+
_keep_in_fp32_modules = ["query_tokens", "qformer"]
|
| 993 |
+
_supports_flash_attn = False # because self.qformer does not support FA2
|
| 994 |
+
|
| 995 |
+
def __init__(self, config: Blip2Config):
|
| 996 |
+
super().__init__(config)
|
| 997 |
+
|
| 998 |
+
self.vision_model = Blip2VisionModel._from_config(config.vision_config)
|
| 999 |
+
|
| 1000 |
+
self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
|
| 1001 |
+
self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
|
| 1002 |
+
|
| 1003 |
+
self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)
|
| 1004 |
+
if config.use_decoder_only_language_model:
|
| 1005 |
+
language_model = AutoModelForCausalLM.from_config(config.text_config)
|
| 1006 |
+
else:
|
| 1007 |
+
language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
|
| 1008 |
+
|
| 1009 |
+
self.language_model = language_model
|
| 1010 |
+
|
| 1011 |
+
# Initialize weights and apply final processing
|
| 1012 |
+
self.post_init()
|
| 1013 |
+
|
| 1014 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1015 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
| 1016 |
+
|
| 1017 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 1018 |
+
return self.language_model.get_output_embeddings()
|
| 1019 |
+
|
| 1020 |
+
def get_encoder(self, modality=None):
|
| 1021 |
+
if modality is None:
|
| 1022 |
+
return self.language_model.get_encoder()
|
| 1023 |
+
else:
|
| 1024 |
+
return super().get_encoder(modality=modality)
|
| 1025 |
+
|
| 1026 |
+
@can_return_tuple
|
| 1027 |
+
@auto_docstring
|
| 1028 |
+
def get_text_features(
|
| 1029 |
+
self,
|
| 1030 |
+
input_ids: torch.Tensor,
|
| 1031 |
+
attention_mask: torch.Tensor | None = None,
|
| 1032 |
+
decoder_input_ids: torch.Tensor | None = None,
|
| 1033 |
+
decoder_attention_mask: torch.Tensor | None = None,
|
| 1034 |
+
labels: torch.Tensor | None = None,
|
| 1035 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1036 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 1037 |
+
r"""
|
| 1038 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1039 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 1040 |
+
|
| 1041 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1042 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1043 |
+
|
| 1044 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 1045 |
+
|
| 1046 |
+
T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
|
| 1047 |
+
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
|
| 1048 |
+
|
| 1049 |
+
To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
|
| 1050 |
+
Training](./t5#training).
|
| 1051 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1052 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1053 |
+
be used by default.
|
| 1054 |
+
|
| 1055 |
+
Examples:
|
| 1056 |
+
```python
|
| 1057 |
+
>>> import torch
|
| 1058 |
+
>>> from transformers import AutoTokenizer, Blip2Model
|
| 1059 |
+
|
| 1060 |
+
>>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1061 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1062 |
+
|
| 1063 |
+
>>> inputs = tokenizer(["a photo of a cat"], padding=True, return_tensors="pt")
|
| 1064 |
+
>>> with torch.inference_mode():
|
| 1065 |
+
... text_features = model.get_text_features(**inputs)
|
| 1066 |
+
```"""
|
| 1067 |
+
|
| 1068 |
+
if self.config.use_decoder_only_language_model:
|
| 1069 |
+
text_outputs: BaseModelOutputWithPast = self.language_model.base_model(
|
| 1070 |
+
input_ids=input_ids,
|
| 1071 |
+
attention_mask=attention_mask,
|
| 1072 |
+
return_dict=True,
|
| 1073 |
+
**kwargs,
|
| 1074 |
+
)
|
| 1075 |
+
else:
|
| 1076 |
+
text_outputs: BaseModelOutputWithPastAndCrossAttentions = self.language_model.get_encoder()(
|
| 1077 |
+
input_ids=input_ids,
|
| 1078 |
+
attention_mask=attention_mask,
|
| 1079 |
+
return_dict=True,
|
| 1080 |
+
**kwargs,
|
| 1081 |
+
)
|
| 1082 |
+
return BaseModelOutputWithPooling(
|
| 1083 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
| 1084 |
+
hidden_states=text_outputs.hidden_states,
|
| 1085 |
+
attentions=text_outputs.attentions,
|
| 1086 |
+
)
|
| 1087 |
+
|
| 1088 |
+
@can_return_tuple
|
| 1089 |
+
@auto_docstring
|
| 1090 |
+
def get_image_features(
|
| 1091 |
+
self,
|
| 1092 |
+
pixel_values: torch.FloatTensor,
|
| 1093 |
+
interpolate_pos_encoding: bool = False,
|
| 1094 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1095 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 1096 |
+
r"""
|
| 1097 |
+
Examples:
|
| 1098 |
+
```python
|
| 1099 |
+
>>> import torch
|
| 1100 |
+
>>> from transformers import AutoProcessor, Blip2Model
|
| 1101 |
+
>>> from transformers.image_utils import load_image
|
| 1102 |
+
|
| 1103 |
+
>>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1104 |
+
|
| 1105 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1106 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1107 |
+
>>> image = load_image(url)
|
| 1108 |
+
|
| 1109 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1110 |
+
>>> with torch.inference_mode():
|
| 1111 |
+
... image_outputs = model.get_image_features(**inputs)
|
| 1112 |
+
```"""
|
| 1113 |
+
return self.vision_model(
|
| 1114 |
+
pixel_values=pixel_values,
|
| 1115 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1116 |
+
**kwargs,
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
@filter_out_non_signature_kwargs()
|
| 1120 |
+
@auto_docstring
|
| 1121 |
+
def get_qformer_features(
|
| 1122 |
+
self,
|
| 1123 |
+
pixel_values: torch.FloatTensor,
|
| 1124 |
+
interpolate_pos_encoding: bool = False,
|
| 1125 |
+
) -> torch.FloatTensor | BaseModelOutputWithPooling:
|
| 1126 |
+
r"""
|
| 1127 |
+
Returns:
|
| 1128 |
+
qformer_outputs (`torch.FloatTensor`):
|
| 1129 |
+
The Q-Former model's last layer hidden states.
|
| 1130 |
+
|
| 1131 |
+
Examples:
|
| 1132 |
+
|
| 1133 |
+
```python
|
| 1134 |
+
>>> import torch
|
| 1135 |
+
>>> from transformers import AutoProcessor, Blip2Model
|
| 1136 |
+
>>> from transformers.image_utils import load_image
|
| 1137 |
+
|
| 1138 |
+
>>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1139 |
+
>>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1140 |
+
|
| 1141 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1142 |
+
>>> image = load_image(url)
|
| 1143 |
+
|
| 1144 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1145 |
+
>>> with torch.inference_mode():
|
| 1146 |
+
... qformer_outputs = model.get_qformer_features(**inputs)
|
| 1147 |
+
```"""
|
| 1148 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1149 |
+
pixel_values=pixel_values,
|
| 1150 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1151 |
+
return_dict=True,
|
| 1152 |
+
)
|
| 1153 |
+
|
| 1154 |
+
image_embeds = vision_outputs.last_hidden_state
|
| 1155 |
+
|
| 1156 |
+
# step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
|
| 1157 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 1158 |
+
|
| 1159 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
| 1160 |
+
query_outputs: BaseModelOutputWithPoolingAndCrossAttentions = self.qformer(
|
| 1161 |
+
query_embeds=query_tokens,
|
| 1162 |
+
encoder_hidden_states=image_embeds,
|
| 1163 |
+
encoder_attention_mask=image_attention_mask,
|
| 1164 |
+
return_dict=True,
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
return query_outputs.last_hidden_state
|
| 1168 |
+
|
| 1169 |
+
def get_placeholder_mask(self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor):
|
| 1170 |
+
"""
|
| 1171 |
+
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
|
| 1172 |
+
"""
|
| 1173 |
+
if input_ids is None:
|
| 1174 |
+
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 1175 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 1176 |
+
)
|
| 1177 |
+
special_image_mask = special_image_mask.all(-1)
|
| 1178 |
+
else:
|
| 1179 |
+
special_image_mask = input_ids == self.config.image_token_id
|
| 1180 |
+
|
| 1181 |
+
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 1182 |
+
return special_image_mask
|
| 1183 |
+
|
| 1184 |
+
@can_return_tuple
|
| 1185 |
+
@auto_docstring
|
| 1186 |
+
def forward(
|
| 1187 |
+
self,
|
| 1188 |
+
pixel_values: torch.FloatTensor,
|
| 1189 |
+
input_ids: torch.FloatTensor,
|
| 1190 |
+
attention_mask: torch.LongTensor | None = None,
|
| 1191 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1192 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 1193 |
+
labels: torch.LongTensor | None = None,
|
| 1194 |
+
interpolate_pos_encoding: bool = False,
|
| 1195 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1196 |
+
) -> tuple | Blip2ForConditionalGenerationModelOutput:
|
| 1197 |
+
r"""
|
| 1198 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1199 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1200 |
+
be used by default.
|
| 1201 |
+
|
| 1202 |
+
Only relevant in case an encoder-decoder language model (like T5) is used.
|
| 1203 |
+
|
| 1204 |
+
Examples:
|
| 1205 |
+
|
| 1206 |
+
```python
|
| 1207 |
+
>>> from PIL import Image
|
| 1208 |
+
>>> import httpx
|
| 1209 |
+
>>> from io import BytesIO
|
| 1210 |
+
>>> from transformers import Blip2Processor, Blip2Model
|
| 1211 |
+
>>> import torch
|
| 1212 |
+
|
| 1213 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1214 |
+
|
| 1215 |
+
>>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1216 |
+
>>> model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b", dtype=torch.float16)
|
| 1217 |
+
>>> model.to(device) # doctest: +IGNORE_RESULT
|
| 1218 |
+
|
| 1219 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1220 |
+
>>> with httpx.stream("GET", url) as response:
|
| 1221 |
+
... image = Image.open(BytesIO(response.read()))
|
| 1222 |
+
|
| 1223 |
+
>>> prompt = "Question: how many cats are there? Answer:"
|
| 1224 |
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device, torch.float16)
|
| 1225 |
+
|
| 1226 |
+
>>> outputs = model(**inputs)
|
| 1227 |
+
```"""
|
| 1228 |
+
|
| 1229 |
+
# step 1: forward the images through the vision encoder,
|
| 1230 |
+
# to get image embeddings of shape (batch_size, seq_len, hidden_size)
|
| 1231 |
+
vision_outputs = self.vision_model(
|
| 1232 |
+
pixel_values=pixel_values,
|
| 1233 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1234 |
+
**kwargs,
|
| 1235 |
+
)
|
| 1236 |
+
image_embeds = vision_outputs[0]
|
| 1237 |
+
|
| 1238 |
+
# step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
|
| 1239 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 1240 |
+
|
| 1241 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
| 1242 |
+
query_outputs = self.qformer(
|
| 1243 |
+
query_embeds=query_tokens,
|
| 1244 |
+
encoder_hidden_states=image_embeds,
|
| 1245 |
+
encoder_attention_mask=image_attention_mask,
|
| 1246 |
+
**kwargs,
|
| 1247 |
+
)
|
| 1248 |
+
query_output = query_outputs[0]
|
| 1249 |
+
|
| 1250 |
+
# Qformer is kept in fp32, we downcast the output back if needed
|
| 1251 |
+
if query_output.dtype != image_embeds.dtype:
|
| 1252 |
+
query_output = query_output.to(image_embeds.dtype)
|
| 1253 |
+
|
| 1254 |
+
# step 3: use the language model, conditioned on the query outputs and the prompt
|
| 1255 |
+
language_model_inputs = self.language_projection(query_output)
|
| 1256 |
+
|
| 1257 |
+
inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
|
| 1258 |
+
|
| 1259 |
+
if attention_mask is None:
|
| 1260 |
+
attention_mask = torch.ones_like(input_ids)
|
| 1261 |
+
|
| 1262 |
+
language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1263 |
+
special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
|
| 1264 |
+
inputs_embeds = inputs_embeds.to(language_model_inputs.device).masked_scatter(
|
| 1265 |
+
special_image_mask, language_model_inputs
|
| 1266 |
+
)
|
| 1267 |
+
|
| 1268 |
+
if self.config.use_decoder_only_language_model:
|
| 1269 |
+
outputs = self.language_model(
|
| 1270 |
+
inputs_embeds=inputs_embeds,
|
| 1271 |
+
attention_mask=attention_mask,
|
| 1272 |
+
**kwargs,
|
| 1273 |
+
)
|
| 1274 |
+
logits = outputs[0]
|
| 1275 |
+
loss = None
|
| 1276 |
+
# we compute the loss here since we need to take into account the sequence length of the query embeds
|
| 1277 |
+
if labels is not None:
|
| 1278 |
+
labels = labels.to(logits.device)
|
| 1279 |
+
logits = logits[:, -labels.size(1) :, :]
|
| 1280 |
+
# Shift so that tokens < n predict n
|
| 1281 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 1282 |
+
shift_labels = labels[..., 1:].contiguous().to(logits.device)
|
| 1283 |
+
|
| 1284 |
+
# Flatten the tokens
|
| 1285 |
+
loss_fct = CrossEntropyLoss(reduction="mean")
|
| 1286 |
+
|
| 1287 |
+
loss = loss_fct(shift_logits.view(-1, self.config.text_config.vocab_size), shift_labels.view(-1))
|
| 1288 |
+
else:
|
| 1289 |
+
outputs = self.language_model(
|
| 1290 |
+
inputs_embeds=inputs_embeds,
|
| 1291 |
+
attention_mask=attention_mask,
|
| 1292 |
+
decoder_input_ids=decoder_input_ids,
|
| 1293 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1294 |
+
labels=labels,
|
| 1295 |
+
return_dict=True,
|
| 1296 |
+
**kwargs,
|
| 1297 |
+
)
|
| 1298 |
+
loss = outputs.loss
|
| 1299 |
+
logits = outputs.logits
|
| 1300 |
+
|
| 1301 |
+
return Blip2ForConditionalGenerationModelOutput(
|
| 1302 |
+
loss=loss,
|
| 1303 |
+
logits=logits,
|
| 1304 |
+
vision_outputs=vision_outputs,
|
| 1305 |
+
qformer_outputs=query_outputs,
|
| 1306 |
+
language_model_outputs=outputs,
|
| 1307 |
+
)
|
| 1308 |
+
|
| 1309 |
+
|
| 1310 |
+
@auto_docstring
|
| 1311 |
+
class Blip2TextModelWithProjection(Blip2PreTrainedModel):
|
| 1312 |
+
supports_gradient_checkpointing = False
|
| 1313 |
+
_keep_in_fp32_modules = ["query_tokens", "qformer"]
|
| 1314 |
+
_supports_flash_attn = False # because self.qformer does not support FA2
|
| 1315 |
+
|
| 1316 |
+
def __init__(self, config: Blip2Config):
|
| 1317 |
+
super().__init__(config)
|
| 1318 |
+
|
| 1319 |
+
self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
|
| 1320 |
+
self.embeddings = Blip2TextEmbeddings(config.qformer_config)
|
| 1321 |
+
self.qformer = Blip2QFormerModel(config.qformer_config)
|
| 1322 |
+
|
| 1323 |
+
# text projection layer
|
| 1324 |
+
self.text_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
|
| 1325 |
+
|
| 1326 |
+
# Initialize weights and apply final processing
|
| 1327 |
+
self.post_init()
|
| 1328 |
+
|
| 1329 |
+
def get_input_embeddings(self):
|
| 1330 |
+
return self.embeddings.word_embeddings
|
| 1331 |
+
|
| 1332 |
+
def set_input_embeddings(self, value):
|
| 1333 |
+
self.embeddings.word_embeddings = value
|
| 1334 |
+
|
| 1335 |
+
@can_return_tuple
|
| 1336 |
+
@auto_docstring
|
| 1337 |
+
def forward(
|
| 1338 |
+
self,
|
| 1339 |
+
input_ids: torch.Tensor | None = None,
|
| 1340 |
+
attention_mask: torch.Tensor | None = None,
|
| 1341 |
+
position_ids: torch.Tensor | None = None,
|
| 1342 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1343 |
+
) -> tuple | Blip2TextModelOutput:
|
| 1344 |
+
r"""
|
| 1345 |
+
Examples:
|
| 1346 |
+
|
| 1347 |
+
```python
|
| 1348 |
+
>>> import torch
|
| 1349 |
+
>>> from transformers import AutoProcessor, Blip2TextModelWithProjection
|
| 1350 |
+
|
| 1351 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1352 |
+
|
| 1353 |
+
>>> model = Blip2TextModelWithProjection.from_pretrained(
|
| 1354 |
+
... "Salesforce/blip2-itm-vit-g", dtype=torch.float16
|
| 1355 |
+
... )
|
| 1356 |
+
|
| 1357 |
+
>>> model.to(device) # doctest: +IGNORE_RESULT
|
| 1358 |
+
|
| 1359 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g")
|
| 1360 |
+
|
| 1361 |
+
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], return_tensors="pt").to(device)
|
| 1362 |
+
|
| 1363 |
+
>>> outputs = model(**inputs)
|
| 1364 |
+
>>> text_embeds = outputs.text_embeds
|
| 1365 |
+
>>> print(text_embeds.shape)
|
| 1366 |
+
torch.Size([2, 7, 256])
|
| 1367 |
+
```"""
|
| 1368 |
+
|
| 1369 |
+
query_embeds = self.embeddings(
|
| 1370 |
+
input_ids=input_ids,
|
| 1371 |
+
position_ids=position_ids,
|
| 1372 |
+
)
|
| 1373 |
+
|
| 1374 |
+
text_outputs = self.qformer(
|
| 1375 |
+
query_embeds=query_embeds,
|
| 1376 |
+
query_length=0,
|
| 1377 |
+
attention_mask=attention_mask,
|
| 1378 |
+
**kwargs,
|
| 1379 |
+
)
|
| 1380 |
+
|
| 1381 |
+
pooled_output = text_outputs[0]
|
| 1382 |
+
pooled_output = pooled_output.to(dtype=self.text_projection.weight.dtype)
|
| 1383 |
+
|
| 1384 |
+
text_embeds = self.text_projection(pooled_output)
|
| 1385 |
+
text_embeds = nn.functional.normalize(text_embeds, dim=-1)
|
| 1386 |
+
|
| 1387 |
+
return Blip2TextModelOutput(
|
| 1388 |
+
text_embeds=text_embeds,
|
| 1389 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
| 1390 |
+
hidden_states=text_outputs.hidden_states,
|
| 1391 |
+
attentions=text_outputs.attentions,
|
| 1392 |
+
)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
@auto_docstring
|
| 1396 |
+
class Blip2VisionModelWithProjection(Blip2PreTrainedModel):
|
| 1397 |
+
main_input_name = "pixel_values"
|
| 1398 |
+
input_modalities = ("image",)
|
| 1399 |
+
_keep_in_fp32_modules = ["query_tokens", "qformer"]
|
| 1400 |
+
_supports_flash_attn = False # because self.qformer does not support FA2
|
| 1401 |
+
|
| 1402 |
+
def __init__(self, config: Blip2Config):
|
| 1403 |
+
super().__init__(config)
|
| 1404 |
+
|
| 1405 |
+
self.vision_model = Blip2VisionModel._from_config(config.vision_config)
|
| 1406 |
+
|
| 1407 |
+
self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
|
| 1408 |
+
self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
|
| 1409 |
+
|
| 1410 |
+
# vision projection layer
|
| 1411 |
+
self.vision_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
|
| 1412 |
+
|
| 1413 |
+
# Initialize weights and apply final processing
|
| 1414 |
+
self.post_init()
|
| 1415 |
+
|
| 1416 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1417 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1418 |
+
|
| 1419 |
+
@can_return_tuple
|
| 1420 |
+
@auto_docstring
|
| 1421 |
+
def forward(
|
| 1422 |
+
self,
|
| 1423 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 1424 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1425 |
+
) -> tuple | Blip2VisionModelOutput:
|
| 1426 |
+
r"""
|
| 1427 |
+
Examples:
|
| 1428 |
+
|
| 1429 |
+
```python
|
| 1430 |
+
>>> import torch
|
| 1431 |
+
>>> from transformers import AutoProcessor, Blip2VisionModelWithProjection
|
| 1432 |
+
>>> from transformers.image_utils import load_image
|
| 1433 |
+
|
| 1434 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1435 |
+
|
| 1436 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g")
|
| 1437 |
+
>>> model = Blip2VisionModelWithProjection.from_pretrained(
|
| 1438 |
+
... "Salesforce/blip2-itm-vit-g", dtype=torch.float16
|
| 1439 |
+
... )
|
| 1440 |
+
>>> model.to(device) # doctest: +IGNORE_RESULT
|
| 1441 |
+
|
| 1442 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1443 |
+
>>> image = load_image(url)
|
| 1444 |
+
|
| 1445 |
+
>>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
|
| 1446 |
+
|
| 1447 |
+
>>> with torch.inference_mode():
|
| 1448 |
+
... outputs = model(**inputs)
|
| 1449 |
+
>>> image_embeds = outputs.image_embeds
|
| 1450 |
+
>>> print(image_embeds.shape)
|
| 1451 |
+
torch.Size([1, 32, 256])
|
| 1452 |
+
```"""
|
| 1453 |
+
vision_outputs = self.vision_model(
|
| 1454 |
+
pixel_values=pixel_values,
|
| 1455 |
+
**kwargs,
|
| 1456 |
+
)
|
| 1457 |
+
|
| 1458 |
+
pooled_output = vision_outputs[0]
|
| 1459 |
+
image_attention_mask = torch.ones(pooled_output.size()[:-1], dtype=torch.long, device=pooled_output.device)
|
| 1460 |
+
query_tokens = self.query_tokens.expand(pooled_output.shape[0], -1, -1)
|
| 1461 |
+
|
| 1462 |
+
query_outputs = self.qformer(
|
| 1463 |
+
query_embeds=query_tokens,
|
| 1464 |
+
encoder_hidden_states=pooled_output,
|
| 1465 |
+
encoder_attention_mask=image_attention_mask,
|
| 1466 |
+
**kwargs,
|
| 1467 |
+
)
|
| 1468 |
+
|
| 1469 |
+
embeds = query_outputs[0]
|
| 1470 |
+
embeds = embeds.to(dtype=self.vision_projection.weight.dtype)
|
| 1471 |
+
image_embeds = self.vision_projection(embeds)
|
| 1472 |
+
image_embeds = nn.functional.normalize(image_embeds, dim=-1)
|
| 1473 |
+
|
| 1474 |
+
return Blip2VisionModelOutput(
|
| 1475 |
+
image_embeds=image_embeds,
|
| 1476 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1477 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1478 |
+
attentions=vision_outputs.attentions,
|
| 1479 |
+
)
|
| 1480 |
+
|
| 1481 |
+
|
| 1482 |
+
@auto_docstring(
|
| 1483 |
+
custom_intro="""
|
| 1484 |
+
BLIP-2 Model for generating text given an image and an optional text prompt. The model consists of a vision
|
| 1485 |
+
encoder, Querying Transformer (Q-Former) and a language model.
|
| 1486 |
+
|
| 1487 |
+
One can optionally pass `input_ids` to the model, which serve as a text prompt, to make the language model continue
|
| 1488 |
+
the prompt. Otherwise, the language model starts generating text from the [BOS] (beginning-of-sequence) token.
|
| 1489 |
+
|
| 1490 |
+
<Tip>
|
| 1491 |
+
|
| 1492 |
+
Note that Flan-T5 checkpoints cannot be cast to float16. They are pre-trained using bfloat16.
|
| 1493 |
+
|
| 1494 |
+
</Tip>
|
| 1495 |
+
"""
|
| 1496 |
+
)
|
| 1497 |
+
class Blip2ForConditionalGeneration(Blip2PreTrainedModel, GenerationMixin):
|
| 1498 |
+
config: Blip2Config
|
| 1499 |
+
main_input_name = "pixel_values"
|
| 1500 |
+
|
| 1501 |
+
_can_compile_fullgraph = True
|
| 1502 |
+
_keep_in_fp32_modules = ["query_tokens", "qformer"]
|
| 1503 |
+
_supports_flash_attn = False # because self.qformer does not support FA2
|
| 1504 |
+
|
| 1505 |
+
def __init__(self, config: Blip2Config):
|
| 1506 |
+
super().__init__(config)
|
| 1507 |
+
|
| 1508 |
+
self.vision_model = Blip2VisionModel._from_config(config.vision_config)
|
| 1509 |
+
|
| 1510 |
+
self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
|
| 1511 |
+
self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
|
| 1512 |
+
|
| 1513 |
+
self.language_projection = nn.Linear(config.qformer_config.hidden_size, config.text_config.hidden_size)
|
| 1514 |
+
if config.use_decoder_only_language_model:
|
| 1515 |
+
language_model = AutoModelForCausalLM.from_config(config.text_config)
|
| 1516 |
+
else:
|
| 1517 |
+
language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
|
| 1518 |
+
|
| 1519 |
+
self.language_model = language_model
|
| 1520 |
+
|
| 1521 |
+
# Initialize weights and apply final processing
|
| 1522 |
+
self.post_init()
|
| 1523 |
+
|
| 1524 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1525 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
| 1526 |
+
|
| 1527 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 1528 |
+
return self.language_model.get_output_embeddings()
|
| 1529 |
+
|
| 1530 |
+
def get_encoder(self, modality=None):
|
| 1531 |
+
if modality is None:
|
| 1532 |
+
return self.language_model.get_encoder()
|
| 1533 |
+
else:
|
| 1534 |
+
return super().get_encoder(modality=modality)
|
| 1535 |
+
|
| 1536 |
+
def _preprocess_accelerate(self):
|
| 1537 |
+
r"""
|
| 1538 |
+
Some pre-processing hacks to make the model `accelerate` compatible. Check
|
| 1539 |
+
https://github.com/huggingface/transformers/pull/21707 for more details.
|
| 1540 |
+
"""
|
| 1541 |
+
hf_device_map = self.hf_device_map
|
| 1542 |
+
|
| 1543 |
+
if len(hf_device_map) > 1 and "language_model" not in hf_device_map and torch.cuda.device_count() > 1:
|
| 1544 |
+
# warn users about unexpected behavior when using multi-GPU + BLIP-2 + `accelerate`.
|
| 1545 |
+
logger.warning(
|
| 1546 |
+
"The `language_model` is not in the `hf_device_map` dictionary and you are running your script"
|
| 1547 |
+
" in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`."
|
| 1548 |
+
" Please pass a `device_map` that contains `language_model` to remove this warning."
|
| 1549 |
+
" Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for"
|
| 1550 |
+
" more details on creating a `device_map` for large models.",
|
| 1551 |
+
)
|
| 1552 |
+
|
| 1553 |
+
if hasattr(self.language_model, "_hf_hook"):
|
| 1554 |
+
self.language_model._hf_hook.io_same_device = True # For `generate` compatibility
|
| 1555 |
+
|
| 1556 |
+
@can_return_tuple
|
| 1557 |
+
@auto_docstring
|
| 1558 |
+
def get_image_features(
|
| 1559 |
+
self,
|
| 1560 |
+
pixel_values: torch.FloatTensor,
|
| 1561 |
+
interpolate_pos_encoding: bool | None = False,
|
| 1562 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1563 |
+
) -> tuple | BaseModelOutputWithVisionQformerOutputs:
|
| 1564 |
+
r"""
|
| 1565 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1566 |
+
The tensors corresponding to the input images.
|
| 1567 |
+
"""
|
| 1568 |
+
# step 1: forward the images through the vision encoder,
|
| 1569 |
+
# to get image embeddings of shape (batch_size, seq_len, hidden_size)
|
| 1570 |
+
vision_outputs: BaseModelOutputWithPooling = self.vision_model(
|
| 1571 |
+
pixel_values=pixel_values,
|
| 1572 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1573 |
+
return_dict=True,
|
| 1574 |
+
**kwargs,
|
| 1575 |
+
)
|
| 1576 |
+
vision_outputs = BaseModelOutputWithVisionQformerOutputs(
|
| 1577 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1578 |
+
pooler_output=vision_outputs.pooler_output,
|
| 1579 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1580 |
+
attentions=vision_outputs.attentions,
|
| 1581 |
+
vision_outputs=vision_outputs,
|
| 1582 |
+
qformer_outputs=None,
|
| 1583 |
+
)
|
| 1584 |
+
image_embeds = vision_outputs[0]
|
| 1585 |
+
|
| 1586 |
+
# step 2: forward the query tokens through the QFormer, using the image embeddings for cross-attention
|
| 1587 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 1588 |
+
|
| 1589 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
| 1590 |
+
qformer_outputs = self.qformer(
|
| 1591 |
+
query_embeds=query_tokens,
|
| 1592 |
+
encoder_hidden_states=image_embeds,
|
| 1593 |
+
encoder_attention_mask=image_attention_mask,
|
| 1594 |
+
return_dict=True,
|
| 1595 |
+
)
|
| 1596 |
+
vision_outputs.qformer_outputs = qformer_outputs
|
| 1597 |
+
query_output = qformer_outputs[0]
|
| 1598 |
+
|
| 1599 |
+
# Qformer is kept in fp32, we downcast the output back if needed
|
| 1600 |
+
if query_output.dtype != image_embeds.dtype:
|
| 1601 |
+
query_output = query_output.to(image_embeds.dtype)
|
| 1602 |
+
|
| 1603 |
+
# step 3: use the language model, conditioned on the query outputs and the prompt
|
| 1604 |
+
image_features = self.language_projection(query_output)
|
| 1605 |
+
vision_outputs.pooler_output = image_features
|
| 1606 |
+
|
| 1607 |
+
return vision_outputs
|
| 1608 |
+
|
| 1609 |
+
def get_placeholder_mask(self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor):
|
| 1610 |
+
"""
|
| 1611 |
+
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`.
|
| 1612 |
+
"""
|
| 1613 |
+
if input_ids is None:
|
| 1614 |
+
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 1615 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 1616 |
+
)
|
| 1617 |
+
special_image_mask = special_image_mask.all(-1)
|
| 1618 |
+
else:
|
| 1619 |
+
special_image_mask = input_ids == self.config.image_token_id
|
| 1620 |
+
|
| 1621 |
+
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 1622 |
+
return special_image_mask
|
| 1623 |
+
|
| 1624 |
+
@can_return_tuple
|
| 1625 |
+
@auto_docstring
|
| 1626 |
+
def forward(
|
| 1627 |
+
self,
|
| 1628 |
+
pixel_values: torch.FloatTensor,
|
| 1629 |
+
input_ids: torch.LongTensor,
|
| 1630 |
+
attention_mask: torch.LongTensor | None = None,
|
| 1631 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1632 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 1633 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1634 |
+
labels: torch.LongTensor | None = None,
|
| 1635 |
+
interpolate_pos_encoding: bool = False,
|
| 1636 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1637 |
+
) -> tuple | Blip2ForConditionalGenerationModelOutput:
|
| 1638 |
+
r"""
|
| 1639 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1640 |
+
Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
|
| 1641 |
+
provided to serve as text prompt, which the language model can continue.
|
| 1642 |
+
|
| 1643 |
+
Indices can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details.
|
| 1644 |
+
|
| 1645 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1646 |
+
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 1647 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 1648 |
+
be used by default.
|
| 1649 |
+
|
| 1650 |
+
Only relevant in case an encoder-decoder language model (like T5) is used.
|
| 1651 |
+
|
| 1652 |
+
Examples:
|
| 1653 |
+
|
| 1654 |
+
Prepare processor, model and image input
|
| 1655 |
+
|
| 1656 |
+
```python
|
| 1657 |
+
>>> from PIL import Image
|
| 1658 |
+
>>> import httpx
|
| 1659 |
+
>>> from io import BytesIO
|
| 1660 |
+
>>> from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 1661 |
+
>>> import torch
|
| 1662 |
+
|
| 1663 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1664 |
+
|
| 1665 |
+
>>> processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 1666 |
+
>>> model = Blip2ForConditionalGeneration.from_pretrained(
|
| 1667 |
+
... "Salesforce/blip2-opt-2.7b", load_in_8bit=True, device_map={"": 0}, dtype=torch.float16
|
| 1668 |
+
... ) # doctest: +IGNORE_RESULT
|
| 1669 |
+
|
| 1670 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1671 |
+
>>> with httpx.stream("GET", url) as response:
|
| 1672 |
+
... image = Image.open(BytesIO(response.read()))
|
| 1673 |
+
```
|
| 1674 |
+
|
| 1675 |
+
Image captioning (without providing a text prompt):
|
| 1676 |
+
|
| 1677 |
+
```python
|
| 1678 |
+
>>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
|
| 1679 |
+
|
| 1680 |
+
>>> generated_ids = model.generate(**inputs)
|
| 1681 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
| 1682 |
+
>>> print(generated_text)
|
| 1683 |
+
two cats laying on a couch
|
| 1684 |
+
```
|
| 1685 |
+
|
| 1686 |
+
Visual question answering (prompt = question):
|
| 1687 |
+
|
| 1688 |
+
```python
|
| 1689 |
+
>>> prompt = "Question: how many cats are there? Answer:"
|
| 1690 |
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device="cuda", dtype=torch.float16)
|
| 1691 |
+
|
| 1692 |
+
>>> generated_ids = model.generate(**inputs)
|
| 1693 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
| 1694 |
+
>>> print(generated_text)
|
| 1695 |
+
two
|
| 1696 |
+
```
|
| 1697 |
+
|
| 1698 |
+
Note that int8 inference is also supported through [bitsandbytes](https://github.com/TimDettmers/bitsandbytes).
|
| 1699 |
+
This greatly reduces the amount of memory used by the model while maintaining the same performance.
|
| 1700 |
+
|
| 1701 |
+
```python
|
| 1702 |
+
>>> model = Blip2ForConditionalGeneration.from_pretrained(
|
| 1703 |
+
... "Salesforce/blip2-opt-2.7b", load_in_8bit=True, device_map={"": 0}, dtype=torch.bfloat16
|
| 1704 |
+
... ) # doctest: +IGNORE_RESULT
|
| 1705 |
+
|
| 1706 |
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device="cuda", dtype=torch.bfloat16)
|
| 1707 |
+
|
| 1708 |
+
>>> generated_ids = model.generate(**inputs)
|
| 1709 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
| 1710 |
+
>>> print(generated_text)
|
| 1711 |
+
two
|
| 1712 |
+
```"""
|
| 1713 |
+
|
| 1714 |
+
image_features: BaseModelOutputWithVisionQformerOutputs = self.get_image_features(
|
| 1715 |
+
pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=True
|
| 1716 |
+
)
|
| 1717 |
+
language_model_inputs = image_features.pooler_output
|
| 1718 |
+
qformer_outputs = image_features.qformer_outputs
|
| 1719 |
+
vision_outputs = image_features.vision_outputs
|
| 1720 |
+
|
| 1721 |
+
if inputs_embeds is None:
|
| 1722 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 1723 |
+
|
| 1724 |
+
if attention_mask is None:
|
| 1725 |
+
attention_mask = torch.ones_like(input_ids)
|
| 1726 |
+
|
| 1727 |
+
language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1728 |
+
special_image_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds)
|
| 1729 |
+
inputs_embeds = inputs_embeds.to(language_model_inputs.device).masked_scatter(
|
| 1730 |
+
special_image_mask, language_model_inputs
|
| 1731 |
+
)
|
| 1732 |
+
|
| 1733 |
+
if self.config.use_decoder_only_language_model:
|
| 1734 |
+
outputs = self.language_model(
|
| 1735 |
+
inputs_embeds=inputs_embeds,
|
| 1736 |
+
attention_mask=attention_mask,
|
| 1737 |
+
**kwargs,
|
| 1738 |
+
)
|
| 1739 |
+
logits = outputs[0]
|
| 1740 |
+
loss = None
|
| 1741 |
+
# we compute the loss here since we need to take into account the sequence length of the query embeds
|
| 1742 |
+
if labels is not None:
|
| 1743 |
+
labels = labels.to(logits.device)
|
| 1744 |
+
logits = logits[:, -labels.size(1) :, :]
|
| 1745 |
+
# Shift so that tokens < n predict n
|
| 1746 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 1747 |
+
shift_labels = labels[..., 1:].contiguous().to(logits.device)
|
| 1748 |
+
|
| 1749 |
+
# Flatten the tokens
|
| 1750 |
+
loss_fct = CrossEntropyLoss(reduction="mean")
|
| 1751 |
+
|
| 1752 |
+
loss = loss_fct(shift_logits.view(-1, self.config.text_config.vocab_size), shift_labels.view(-1))
|
| 1753 |
+
else:
|
| 1754 |
+
kwargs["return_dict"] = True
|
| 1755 |
+
outputs = self.language_model(
|
| 1756 |
+
inputs_embeds=inputs_embeds,
|
| 1757 |
+
attention_mask=attention_mask,
|
| 1758 |
+
decoder_input_ids=decoder_input_ids,
|
| 1759 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1760 |
+
labels=labels,
|
| 1761 |
+
**kwargs,
|
| 1762 |
+
)
|
| 1763 |
+
loss = outputs.loss
|
| 1764 |
+
logits = outputs.logits
|
| 1765 |
+
|
| 1766 |
+
return Blip2ForConditionalGenerationModelOutput(
|
| 1767 |
+
loss=loss,
|
| 1768 |
+
logits=logits,
|
| 1769 |
+
vision_outputs=vision_outputs,
|
| 1770 |
+
qformer_outputs=qformer_outputs,
|
| 1771 |
+
language_model_outputs=outputs,
|
| 1772 |
+
)
|
| 1773 |
+
|
| 1774 |
+
@torch.no_grad()
|
| 1775 |
+
def generate(
|
| 1776 |
+
self,
|
| 1777 |
+
pixel_values: torch.FloatTensor,
|
| 1778 |
+
input_ids: torch.LongTensor | None = None,
|
| 1779 |
+
attention_mask: torch.LongTensor | None = None,
|
| 1780 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1781 |
+
interpolate_pos_encoding: bool = False,
|
| 1782 |
+
**generate_kwargs,
|
| 1783 |
+
) -> torch.LongTensor:
|
| 1784 |
+
"""
|
| 1785 |
+
Overrides `generate` function to be able to use the model as a conditional generator.
|
| 1786 |
+
|
| 1787 |
+
Args:
|
| 1788 |
+
pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):
|
| 1789 |
+
Input images to be processed.
|
| 1790 |
+
input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
|
| 1791 |
+
The sequence used as a prompt for the generation.
|
| 1792 |
+
attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
|
| 1793 |
+
Mask to avoid performing attention on padding token indices
|
| 1794 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 1795 |
+
Embedded representation of the inputs. Should be float, not int tokens.
|
| 1796 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
|
| 1797 |
+
Whether to interpolate the positional encoding of the image embeddings.
|
| 1798 |
+
|
| 1799 |
+
Returns:
|
| 1800 |
+
captions (list): A list of strings of length batch_size * num_captions.
|
| 1801 |
+
"""
|
| 1802 |
+
if hasattr(self, "hf_device_map"):
|
| 1803 |
+
# preprocess for `accelerate`
|
| 1804 |
+
self._preprocess_accelerate()
|
| 1805 |
+
|
| 1806 |
+
batch_size = pixel_values.shape[0]
|
| 1807 |
+
image_embeds = self.vision_model(
|
| 1808 |
+
pixel_values,
|
| 1809 |
+
return_dict=True,
|
| 1810 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1811 |
+
).last_hidden_state
|
| 1812 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 1813 |
+
|
| 1814 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
| 1815 |
+
query_outputs = self.qformer(
|
| 1816 |
+
query_embeds=query_tokens,
|
| 1817 |
+
encoder_hidden_states=image_embeds,
|
| 1818 |
+
encoder_attention_mask=image_attention_mask,
|
| 1819 |
+
return_dict=True,
|
| 1820 |
+
)
|
| 1821 |
+
query_output = query_outputs.last_hidden_state
|
| 1822 |
+
|
| 1823 |
+
# Qformer is kept in fp32, we downcast the output back if needed
|
| 1824 |
+
if query_output.dtype != image_embeds.dtype:
|
| 1825 |
+
query_output = query_output.to(image_embeds.dtype)
|
| 1826 |
+
|
| 1827 |
+
language_model_inputs = self.language_projection(query_output)
|
| 1828 |
+
|
| 1829 |
+
if inputs_embeds is None:
|
| 1830 |
+
if input_ids is None:
|
| 1831 |
+
image_tokens = [self.config.image_token_index] * self.config.num_query_tokens
|
| 1832 |
+
start_tokens = image_tokens + [self.config.text_config.bos_token_id]
|
| 1833 |
+
input_ids = torch.tensor([start_tokens], dtype=torch.long, device=image_embeds.device)
|
| 1834 |
+
input_ids = input_ids.repeat(batch_size, 1)
|
| 1835 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 1836 |
+
|
| 1837 |
+
if attention_mask is None:
|
| 1838 |
+
attention_mask = torch.ones_like(input_ids)
|
| 1839 |
+
|
| 1840 |
+
if input_ids is None:
|
| 1841 |
+
special_image_mask = inputs_embeds == self.get_input_embeddings()(
|
| 1842 |
+
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 1843 |
+
)
|
| 1844 |
+
special_image_mask = special_image_mask.all(-1)
|
| 1845 |
+
else:
|
| 1846 |
+
special_image_mask = input_ids == self.config.image_token_id
|
| 1847 |
+
|
| 1848 |
+
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 1849 |
+
language_model_inputs = language_model_inputs.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1850 |
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, language_model_inputs)
|
| 1851 |
+
|
| 1852 |
+
inputs = {"inputs_embeds": inputs_embeds, "attention_mask": attention_mask}
|
| 1853 |
+
if not self.language_model.config.is_encoder_decoder:
|
| 1854 |
+
inputs["input_ids"] = input_ids
|
| 1855 |
+
|
| 1856 |
+
outputs = self.language_model.generate(**inputs, **generate_kwargs)
|
| 1857 |
+
|
| 1858 |
+
return outputs
|
| 1859 |
+
|
| 1860 |
+
|
| 1861 |
+
@auto_docstring(
|
| 1862 |
+
custom_intro="""
|
| 1863 |
+
BLIP-2 Model with a vision and text projector, and a classification head on top. The model is used in the context
|
| 1864 |
+
of image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
|
| 1865 |
+
the image.
|
| 1866 |
+
"""
|
| 1867 |
+
)
|
| 1868 |
+
class Blip2ForImageTextRetrieval(Blip2PreTrainedModel):
|
| 1869 |
+
main_input_name = "pixel_values"
|
| 1870 |
+
input_modalities = ("image",)
|
| 1871 |
+
_keep_in_fp32_modules = ["query_tokens", "qformer"]
|
| 1872 |
+
_supports_flash_attn = False # because self.qformer does not support FA2
|
| 1873 |
+
|
| 1874 |
+
def __init__(self, config: Blip2Config):
|
| 1875 |
+
super().__init__(config)
|
| 1876 |
+
|
| 1877 |
+
self.vision_model = Blip2VisionModel._from_config(config.vision_config)
|
| 1878 |
+
|
| 1879 |
+
self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qformer_config.hidden_size))
|
| 1880 |
+
|
| 1881 |
+
self.embeddings = Blip2TextEmbeddings(config.qformer_config)
|
| 1882 |
+
self.qformer = Blip2QFormerModel._from_config(config.qformer_config)
|
| 1883 |
+
|
| 1884 |
+
# vision projection layer
|
| 1885 |
+
self.vision_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
|
| 1886 |
+
|
| 1887 |
+
# text projection layer
|
| 1888 |
+
self.text_projection = nn.Linear(config.qformer_config.hidden_size, config.image_text_hidden_size)
|
| 1889 |
+
|
| 1890 |
+
# image text matching head
|
| 1891 |
+
self.itm_head = nn.Linear(config.qformer_config.hidden_size, 2)
|
| 1892 |
+
|
| 1893 |
+
# Initialize weights and apply final processing
|
| 1894 |
+
self.post_init()
|
| 1895 |
+
|
| 1896 |
+
def get_input_embeddings(self):
|
| 1897 |
+
return self.embeddings.word_embeddings
|
| 1898 |
+
|
| 1899 |
+
def set_input_embeddings(self, value):
|
| 1900 |
+
self.embeddings.word_embeddings = value
|
| 1901 |
+
|
| 1902 |
+
@auto_docstring
|
| 1903 |
+
def forward(
|
| 1904 |
+
self,
|
| 1905 |
+
pixel_values: torch.FloatTensor,
|
| 1906 |
+
input_ids: torch.LongTensor,
|
| 1907 |
+
attention_mask: torch.LongTensor | None = None,
|
| 1908 |
+
use_image_text_matching_head: bool | None = False,
|
| 1909 |
+
output_attentions: bool | None = None,
|
| 1910 |
+
output_hidden_states: bool | None = None,
|
| 1911 |
+
return_dict: bool | None = None,
|
| 1912 |
+
**kwargs,
|
| 1913 |
+
) -> tuple | Blip2ImageTextMatchingModelOutput:
|
| 1914 |
+
r"""
|
| 1915 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1916 |
+
Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
|
| 1917 |
+
provided to serve as text prompt, which the language model can continue.
|
| 1918 |
+
|
| 1919 |
+
Indices can be obtained using [`Blip2Processor`]. See [`Blip2Processor.__call__`] for details.
|
| 1920 |
+
|
| 1921 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1922 |
+
use_image_text_matching_head (`bool`, *optional*):
|
| 1923 |
+
Whether to return the Image-Text Matching or Contrastive scores.
|
| 1924 |
+
|
| 1925 |
+
Examples:
|
| 1926 |
+
|
| 1927 |
+
```python
|
| 1928 |
+
>>> import torch
|
| 1929 |
+
>>> from PIL import Image
|
| 1930 |
+
>>> import httpx
|
| 1931 |
+
>>> from io import BytesIO
|
| 1932 |
+
>>> from transformers import AutoProcessor, Blip2ForImageTextRetrieval
|
| 1933 |
+
|
| 1934 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1935 |
+
|
| 1936 |
+
>>> model = Blip2ForImageTextRetrieval.from_pretrained("Salesforce/blip2-itm-vit-g", dtype=torch.float16)
|
| 1937 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-itm-vit-g")
|
| 1938 |
+
|
| 1939 |
+
>>> model.to(device) # doctest: +IGNORE_RESULT
|
| 1940 |
+
|
| 1941 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1942 |
+
>>> with httpx.stream("GET", url) as response:
|
| 1943 |
+
... image = Image.open(BytesIO(response.read()))
|
| 1944 |
+
>>> text = "two cats laying on a pink blanket"
|
| 1945 |
+
|
| 1946 |
+
>>> inputs = processor(images=image, text=text, return_tensors="pt").to(device, torch.float16)
|
| 1947 |
+
>>> itm_out = model(**inputs, use_image_text_matching_head=True)
|
| 1948 |
+
>>> logits_per_image = torch.nn.functional.softmax(itm_out.logits_per_image, dim=1)
|
| 1949 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1950 |
+
|
| 1951 |
+
>>> print(f"{probs[0][0]:.1%} that image 0 is not '{text}'")
|
| 1952 |
+
26.9% that image 0 is not 'two cats laying on a pink blanket'
|
| 1953 |
+
|
| 1954 |
+
>>> print(f"{probs[0][1]:.1%} that image 0 is '{text}'")
|
| 1955 |
+
73.0% that image 0 is 'two cats laying on a pink blanket'
|
| 1956 |
+
|
| 1957 |
+
>>> texts = ["a photo of a cat", "a photo of a dog"]
|
| 1958 |
+
|
| 1959 |
+
>>> inputs = processor(images=image, text=texts, return_tensors="pt").to(device, torch.float16)
|
| 1960 |
+
>>> itc_out = model(**inputs, use_image_text_matching_head=False)
|
| 1961 |
+
>>> logits_per_image = itc_out.logits_per_image # this is the image-text similarity score
|
| 1962 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1963 |
+
|
| 1964 |
+
>>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
|
| 1965 |
+
55.3% that image 0 is 'a photo of a cat'
|
| 1966 |
+
|
| 1967 |
+
>>> print(f"{probs[0][1]:.1%} that image 0 is '{texts[1]}'")
|
| 1968 |
+
44.7% that image 0 is 'a photo of a dog'
|
| 1969 |
+
```
|
| 1970 |
+
"""
|
| 1971 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1972 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1973 |
+
output_hidden_states = (
|
| 1974 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1975 |
+
)
|
| 1976 |
+
|
| 1977 |
+
vision_outputs = self.vision_model(
|
| 1978 |
+
pixel_values=pixel_values,
|
| 1979 |
+
output_attentions=output_attentions,
|
| 1980 |
+
output_hidden_states=output_hidden_states,
|
| 1981 |
+
return_dict=return_dict,
|
| 1982 |
+
)
|
| 1983 |
+
|
| 1984 |
+
image_embeds = vision_outputs[0]
|
| 1985 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
|
| 1986 |
+
|
| 1987 |
+
if use_image_text_matching_head:
|
| 1988 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
| 1989 |
+
if self.config.image_token_index is not None:
|
| 1990 |
+
input_ids = input_ids[:, self.config.num_query_tokens :]
|
| 1991 |
+
else:
|
| 1992 |
+
query_attention_mask = torch.ones(
|
| 1993 |
+
query_tokens.size()[:-1], dtype=torch.long, device=query_tokens.device
|
| 1994 |
+
)
|
| 1995 |
+
attention_mask = torch.cat([query_attention_mask, attention_mask], dim=1)
|
| 1996 |
+
|
| 1997 |
+
query_embeds = self.embeddings(
|
| 1998 |
+
input_ids=input_ids,
|
| 1999 |
+
query_embeds=query_tokens,
|
| 2000 |
+
)
|
| 2001 |
+
|
| 2002 |
+
text_outputs = self.qformer(
|
| 2003 |
+
query_embeds=query_embeds,
|
| 2004 |
+
query_length=query_tokens.shape[1],
|
| 2005 |
+
attention_mask=attention_mask,
|
| 2006 |
+
encoder_hidden_states=image_embeds,
|
| 2007 |
+
encoder_attention_mask=image_attention_mask,
|
| 2008 |
+
return_dict=return_dict,
|
| 2009 |
+
)
|
| 2010 |
+
text_embeds = text_outputs[0] if not return_dict else text_outputs.last_hidden_state
|
| 2011 |
+
text_embeds = text_embeds.to(dtype=self.itm_head.weight.dtype)
|
| 2012 |
+
|
| 2013 |
+
output = self.itm_head(text_embeds[:, : query_tokens.size(1), :])
|
| 2014 |
+
logits_per_image = output.mean(dim=1)
|
| 2015 |
+
logits_per_text = logits_per_image.t()
|
| 2016 |
+
else:
|
| 2017 |
+
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
|
| 2018 |
+
query_outputs = self.qformer(
|
| 2019 |
+
query_embeds=query_tokens,
|
| 2020 |
+
encoder_hidden_states=image_embeds,
|
| 2021 |
+
encoder_attention_mask=image_attention_mask,
|
| 2022 |
+
return_dict=return_dict,
|
| 2023 |
+
)
|
| 2024 |
+
image_embeds = query_outputs[0] if not return_dict else query_outputs.last_hidden_state
|
| 2025 |
+
image_embeds = image_embeds.to(dtype=self.vision_projection.weight.dtype)
|
| 2026 |
+
|
| 2027 |
+
if self.config.image_token_index is not None:
|
| 2028 |
+
input_ids = input_ids[:, self.config.num_query_tokens :]
|
| 2029 |
+
attention_mask = attention_mask[:, self.config.num_query_tokens :]
|
| 2030 |
+
|
| 2031 |
+
query_embeds = self.embeddings(
|
| 2032 |
+
input_ids=input_ids,
|
| 2033 |
+
)
|
| 2034 |
+
text_outputs = self.qformer(
|
| 2035 |
+
query_embeds=query_embeds,
|
| 2036 |
+
query_length=0,
|
| 2037 |
+
attention_mask=attention_mask,
|
| 2038 |
+
return_dict=return_dict,
|
| 2039 |
+
)
|
| 2040 |
+
question_embeds = text_outputs[0] if not return_dict else text_outputs.last_hidden_state
|
| 2041 |
+
question_embeds = question_embeds.to(dtype=self.text_projection.weight.dtype)
|
| 2042 |
+
|
| 2043 |
+
# normalized features
|
| 2044 |
+
image_embeds = nn.functional.normalize(self.vision_projection(image_embeds), dim=-1)
|
| 2045 |
+
text_embeds = nn.functional.normalize(self.text_projection(question_embeds[:, 0, :]), dim=-1)
|
| 2046 |
+
|
| 2047 |
+
# cosine similarity as logits
|
| 2048 |
+
logits_per_image = torch.matmul(image_embeds, text_embeds.t())
|
| 2049 |
+
logits_per_image, _ = logits_per_image.max(dim=1)
|
| 2050 |
+
|
| 2051 |
+
logits_per_text = logits_per_image.t()
|
| 2052 |
+
|
| 2053 |
+
if not return_dict:
|
| 2054 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 2055 |
+
return output
|
| 2056 |
+
|
| 2057 |
+
return Blip2ImageTextMatchingModelOutput(
|
| 2058 |
+
logits_per_image=logits_per_image,
|
| 2059 |
+
logits_per_text=logits_per_text,
|
| 2060 |
+
text_embeds=text_embeds,
|
| 2061 |
+
image_embeds=image_embeds,
|
| 2062 |
+
text_model_output=text_outputs,
|
| 2063 |
+
vision_model_output=vision_outputs,
|
| 2064 |
+
)
|
| 2065 |
+
|
| 2066 |
+
|
| 2067 |
+
__all__ = [
|
| 2068 |
+
"Blip2Model",
|
| 2069 |
+
"Blip2VisionModelWithProjection",
|
| 2070 |
+
"Blip2QFormerModel",
|
| 2071 |
+
"Blip2PreTrainedModel",
|
| 2072 |
+
"Blip2ForConditionalGeneration",
|
| 2073 |
+
"Blip2ForImageTextRetrieval",
|
| 2074 |
+
"Blip2VisionModel",
|
| 2075 |
+
"Blip2TextModelWithProjection",
|
| 2076 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/blip_2/processing_blip_2.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Processor class for BLIP-2.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from ...image_processing_utils import BatchFeature
|
| 19 |
+
from ...image_utils import ImageInput
|
| 20 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 21 |
+
from ...tokenization_utils_base import AddedToken, BatchEncoding, PreTokenizedInput, TextInput
|
| 22 |
+
from ...utils import auto_docstring, logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Blip2ProcessorKwargs(ProcessingKwargs, total=False):
|
| 29 |
+
_defaults = {
|
| 30 |
+
"text_kwargs": {
|
| 31 |
+
"add_special_tokens": True,
|
| 32 |
+
"padding": False,
|
| 33 |
+
"stride": 0,
|
| 34 |
+
"return_overflowing_tokens": False,
|
| 35 |
+
"return_special_tokens_mask": False,
|
| 36 |
+
"return_offsets_mapping": False,
|
| 37 |
+
"return_token_type_ids": False,
|
| 38 |
+
"return_length": False,
|
| 39 |
+
"verbose": True,
|
| 40 |
+
},
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@auto_docstring
|
| 45 |
+
class Blip2Processor(ProcessorMixin):
|
| 46 |
+
def __init__(self, image_processor, tokenizer, num_query_tokens=None, **kwargs):
|
| 47 |
+
r"""
|
| 48 |
+
num_query_tokens (`int`, *optional*):
|
| 49 |
+
Number of tokens used by the Qformer as queries, should be same as in model's config.
|
| 50 |
+
"""
|
| 51 |
+
tokenizer.return_token_type_ids = False
|
| 52 |
+
if not hasattr(tokenizer, "image_token"):
|
| 53 |
+
self.image_token = AddedToken("<image>", normalized=False, special=True)
|
| 54 |
+
tokenizer.add_tokens([self.image_token], special_tokens=True)
|
| 55 |
+
else:
|
| 56 |
+
self.image_token = tokenizer.image_token
|
| 57 |
+
self.num_query_tokens = num_query_tokens
|
| 58 |
+
|
| 59 |
+
super().__init__(image_processor, tokenizer)
|
| 60 |
+
|
| 61 |
+
@auto_docstring
|
| 62 |
+
def __call__(
|
| 63 |
+
self,
|
| 64 |
+
images: ImageInput | None = None,
|
| 65 |
+
text: str | list[str] | TextInput | PreTokenizedInput | None = None,
|
| 66 |
+
**kwargs: Unpack[Blip2ProcessorKwargs],
|
| 67 |
+
) -> BatchEncoding:
|
| 68 |
+
if images is None and text is None:
|
| 69 |
+
raise ValueError("You have to specify either images or text.")
|
| 70 |
+
output_kwargs = self._merge_kwargs(
|
| 71 |
+
Blip2ProcessorKwargs,
|
| 72 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 73 |
+
**kwargs,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# BC for explicit return_tensors
|
| 77 |
+
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
|
| 78 |
+
max_length = output_kwargs["text_kwargs"].pop("max_length", None)
|
| 79 |
+
if max_length is not None:
|
| 80 |
+
output_kwargs["text_kwargs"]["max_length"] = max_length - self.num_query_tokens
|
| 81 |
+
|
| 82 |
+
encoding = BatchFeature(tensor_type=return_tensors)
|
| 83 |
+
if text is not None:
|
| 84 |
+
if isinstance(text, str):
|
| 85 |
+
text = [text]
|
| 86 |
+
elif not isinstance(text, list) and not isinstance(text[0], str):
|
| 87 |
+
raise ValueError("Invalid input text. Please provide a string, or a list of strings")
|
| 88 |
+
|
| 89 |
+
# We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
|
| 90 |
+
text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 91 |
+
|
| 92 |
+
if images is not None and self.num_query_tokens is not None:
|
| 93 |
+
# Image tokens should not be padded/truncated or prepended with special BOS token
|
| 94 |
+
image_tokens = self.image_token.content * self.num_query_tokens
|
| 95 |
+
output_kwargs["text_kwargs"]["add_special_tokens"] = False
|
| 96 |
+
output_kwargs["text_kwargs"]["padding"] = False
|
| 97 |
+
output_kwargs["text_kwargs"]["truncation"] = False
|
| 98 |
+
image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
|
| 99 |
+
for k in text_encoding:
|
| 100 |
+
text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
|
| 101 |
+
encoding.update(text_encoding)
|
| 102 |
+
|
| 103 |
+
# Now add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
|
| 104 |
+
# else, return the text encoding.
|
| 105 |
+
if images is not None:
|
| 106 |
+
image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 107 |
+
encoding.update(image_encoding)
|
| 108 |
+
|
| 109 |
+
# Cast to desired return tensors type
|
| 110 |
+
encoding = BatchFeature(encoding, tensor_type=return_tensors)
|
| 111 |
+
return encoding
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
__all__ = ["Blip2Processor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_deberta_v2 import *
|
| 22 |
+
from .modeling_deberta_v2 import *
|
| 23 |
+
from .tokenization_deberta_v2 import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/configuration_deberta_v2.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020, Microsoft and the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""DeBERTa-v2 model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...utils import auto_docstring
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@auto_docstring(checkpoint="microsoft/deberta-v2-xlarge")
|
| 23 |
+
@strict
|
| 24 |
+
class DebertaV2Config(PreTrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
relative_attention (`bool`, *optional*, defaults to `True`):
|
| 27 |
+
Whether use relative position encoding.
|
| 28 |
+
max_relative_positions (`int`, *optional*, defaults to -1):
|
| 29 |
+
The range of relative positions `[-max_position_embeddings, max_position_embeddings]`. Use the same value
|
| 30 |
+
as `max_position_embeddings`.
|
| 31 |
+
position_biased_input (`bool`, *optional*, defaults to `True`):
|
| 32 |
+
Whether add absolute position embedding to content embedding.
|
| 33 |
+
pos_att_type (`list[str]`, *optional*):
|
| 34 |
+
The type of relative position attention, it can be a combination of `["p2c", "c2p"]`, e.g. `["p2c"]`,
|
| 35 |
+
`["p2c", "c2p"]`, `["p2c", "c2p"]`.
|
| 36 |
+
pooler_dropout (`float`, *optional*, defaults to `0`):
|
| 37 |
+
Dropout rate in the pooler module.
|
| 38 |
+
pooler_hidden_act (`str`, *optional*, defaults to `"gelu"`):
|
| 39 |
+
Activation function used in the dropout module.
|
| 40 |
+
legacy (`bool`, *optional*, defaults to `True`):
|
| 41 |
+
Whether or not the model should use the legacy `LegacyDebertaOnlyMLMHead`, which does not work properly
|
| 42 |
+
for mask infilling tasks.
|
| 43 |
+
|
| 44 |
+
Example:
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
>>> from transformers import DebertaV2Config, DebertaV2Model
|
| 48 |
+
|
| 49 |
+
>>> # Initializing a DeBERTa-v2 microsoft/deberta-v2-xlarge style configuration
|
| 50 |
+
>>> configuration = DebertaV2Config()
|
| 51 |
+
|
| 52 |
+
>>> # Initializing a model (with random weights) from the microsoft/deberta-v2-xlarge style configuration
|
| 53 |
+
>>> model = DebertaV2Model(configuration)
|
| 54 |
+
|
| 55 |
+
>>> # Accessing the model configuration
|
| 56 |
+
>>> configuration = model.config
|
| 57 |
+
```"""
|
| 58 |
+
|
| 59 |
+
model_type = "deberta-v2"
|
| 60 |
+
|
| 61 |
+
vocab_size: int = 128100
|
| 62 |
+
hidden_size: int = 1536
|
| 63 |
+
num_hidden_layers: int = 24
|
| 64 |
+
num_attention_heads: int = 24
|
| 65 |
+
intermediate_size: int = 6144
|
| 66 |
+
hidden_act: str = "gelu"
|
| 67 |
+
hidden_dropout_prob: float | int = 0.1
|
| 68 |
+
attention_probs_dropout_prob: float | int = 0.1
|
| 69 |
+
max_position_embeddings: int = 512
|
| 70 |
+
type_vocab_size: int = 0
|
| 71 |
+
initializer_range: float = 0.02
|
| 72 |
+
layer_norm_eps: float = 1e-7
|
| 73 |
+
relative_attention: bool = False
|
| 74 |
+
max_relative_positions: int = -1
|
| 75 |
+
pad_token_id: int | None = 0
|
| 76 |
+
bos_token_id: int | None = None
|
| 77 |
+
eos_token_id: int | list[int] | None = None
|
| 78 |
+
position_biased_input: bool = True
|
| 79 |
+
pos_att_type: str | list[str] | None = None
|
| 80 |
+
pooler_dropout: float | int = 0.0
|
| 81 |
+
pooler_hidden_act: str = "gelu"
|
| 82 |
+
legacy: bool = True
|
| 83 |
+
tie_word_embeddings: bool = True
|
| 84 |
+
|
| 85 |
+
def __post_init__(self, **kwargs):
|
| 86 |
+
# Backwards compatibility
|
| 87 |
+
if isinstance(self.pos_att_type, str):
|
| 88 |
+
self.pos_att_type = [x.strip() for x in self.pos_att_type.lower().split("|")]
|
| 89 |
+
|
| 90 |
+
self.pooler_hidden_size = kwargs.get("pooler_hidden_size", self.hidden_size)
|
| 91 |
+
super().__post_init__(**kwargs)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
__all__ = ["DebertaV2Config"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/modeling_deberta_v2.py
ADDED
|
@@ -0,0 +1,1361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Microsoft and the Hugging Face Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""PyTorch DeBERTa-v2 model."""
|
| 15 |
+
|
| 16 |
+
from collections.abc import Sequence
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
|
| 21 |
+
|
| 22 |
+
from ... import initialization as init
|
| 23 |
+
from ...activations import ACT2FN
|
| 24 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 25 |
+
from ...modeling_outputs import (
|
| 26 |
+
BaseModelOutput,
|
| 27 |
+
MaskedLMOutput,
|
| 28 |
+
MultipleChoiceModelOutput,
|
| 29 |
+
QuestionAnsweringModelOutput,
|
| 30 |
+
SequenceClassifierOutput,
|
| 31 |
+
TokenClassifierOutput,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import PreTrainedModel
|
| 34 |
+
from ...utils import auto_docstring, logging
|
| 35 |
+
from .configuration_deberta_v2 import DebertaV2Config
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaSelfOutput with DebertaLayerNorm->LayerNorm
|
| 42 |
+
class DebertaV2SelfOutput(nn.Module):
|
| 43 |
+
def __init__(self, config):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 46 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 47 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 48 |
+
|
| 49 |
+
def forward(self, hidden_states, input_tensor):
|
| 50 |
+
hidden_states = self.dense(hidden_states)
|
| 51 |
+
hidden_states = self.dropout(hidden_states)
|
| 52 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 53 |
+
return hidden_states
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@torch.jit.script
|
| 57 |
+
def make_log_bucket_position(relative_pos, bucket_size: int, max_position: int):
|
| 58 |
+
sign = torch.sign(relative_pos)
|
| 59 |
+
mid = bucket_size // 2
|
| 60 |
+
abs_pos = torch.where(
|
| 61 |
+
(relative_pos < mid) & (relative_pos > -mid),
|
| 62 |
+
torch.tensor(mid - 1).type_as(relative_pos),
|
| 63 |
+
torch.abs(relative_pos),
|
| 64 |
+
)
|
| 65 |
+
log_pos = (
|
| 66 |
+
torch.ceil(torch.log(abs_pos / mid) / torch.log(torch.tensor((max_position - 1) / mid)) * (mid - 1)) + mid
|
| 67 |
+
)
|
| 68 |
+
bucket_pos = torch.where(abs_pos <= mid, relative_pos.type_as(log_pos), log_pos * sign)
|
| 69 |
+
return bucket_pos
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_relative_position(query_layer, key_layer, bucket_size: int = -1, max_position: int = -1):
|
| 73 |
+
"""
|
| 74 |
+
Build relative position according to the query and key
|
| 75 |
+
|
| 76 |
+
We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key
|
| 77 |
+
\\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q -
|
| 78 |
+
P_k\\)
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
query_size (int): the length of query
|
| 82 |
+
key_size (int): the length of key
|
| 83 |
+
bucket_size (int): the size of position bucket
|
| 84 |
+
max_position (int): the maximum allowed absolute position
|
| 85 |
+
device (`torch.device`): the device on which tensors will be created.
|
| 86 |
+
|
| 87 |
+
Return:
|
| 88 |
+
`torch.LongTensor`: A tensor with shape [1, query_size, key_size]
|
| 89 |
+
"""
|
| 90 |
+
query_size = query_layer.size(-2)
|
| 91 |
+
key_size = key_layer.size(-2)
|
| 92 |
+
|
| 93 |
+
q_ids = torch.arange(query_size, dtype=torch.long, device=query_layer.device)
|
| 94 |
+
k_ids = torch.arange(key_size, dtype=torch.long, device=key_layer.device)
|
| 95 |
+
rel_pos_ids = q_ids[:, None] - k_ids[None, :]
|
| 96 |
+
if bucket_size > 0 and max_position > 0:
|
| 97 |
+
rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
|
| 98 |
+
rel_pos_ids = rel_pos_ids.to(torch.long)
|
| 99 |
+
rel_pos_ids = rel_pos_ids[:query_size, :]
|
| 100 |
+
rel_pos_ids = rel_pos_ids.unsqueeze(0)
|
| 101 |
+
return rel_pos_ids
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@torch.jit.script
|
| 105 |
+
def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos):
|
| 106 |
+
return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)])
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@torch.jit.script
|
| 110 |
+
def p2c_dynamic_expand(c2p_pos, query_layer, key_layer):
|
| 111 |
+
return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)])
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@torch.jit.script
|
| 115 |
+
def pos_dynamic_expand(pos_index, p2c_att, key_layer):
|
| 116 |
+
return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2)))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@torch.jit.script
|
| 120 |
+
def scaled_size_sqrt(query_layer: torch.Tensor, scale_factor: int):
|
| 121 |
+
return torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@torch.jit.script
|
| 125 |
+
def build_rpos(query_layer, key_layer, relative_pos, position_buckets: int, max_relative_positions: int):
|
| 126 |
+
if key_layer.size(-2) != query_layer.size(-2):
|
| 127 |
+
return build_relative_position(
|
| 128 |
+
key_layer,
|
| 129 |
+
key_layer,
|
| 130 |
+
bucket_size=position_buckets,
|
| 131 |
+
max_position=max_relative_positions,
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
return relative_pos
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class DisentangledSelfAttention(nn.Module):
|
| 138 |
+
"""
|
| 139 |
+
Disentangled self-attention module
|
| 140 |
+
|
| 141 |
+
Parameters:
|
| 142 |
+
config (`DebertaV2Config`):
|
| 143 |
+
A model config class instance with the configuration to build a new model. The schema is similar to
|
| 144 |
+
*BertConfig*, for more details, please refer [`DebertaV2Config`]
|
| 145 |
+
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def __init__(self, config):
|
| 149 |
+
super().__init__()
|
| 150 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 151 |
+
raise ValueError(
|
| 152 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 153 |
+
f"heads ({config.num_attention_heads})"
|
| 154 |
+
)
|
| 155 |
+
self.num_attention_heads = config.num_attention_heads
|
| 156 |
+
_attention_head_size = config.hidden_size // config.num_attention_heads
|
| 157 |
+
self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size)
|
| 158 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 159 |
+
self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 160 |
+
self.key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 161 |
+
self.value_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 162 |
+
|
| 163 |
+
self.share_att_key = getattr(config, "share_att_key", False)
|
| 164 |
+
self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else []
|
| 165 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
| 166 |
+
|
| 167 |
+
if self.relative_attention:
|
| 168 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
| 169 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
| 170 |
+
if self.max_relative_positions < 1:
|
| 171 |
+
self.max_relative_positions = config.max_position_embeddings
|
| 172 |
+
self.pos_ebd_size = self.max_relative_positions
|
| 173 |
+
if self.position_buckets > 0:
|
| 174 |
+
self.pos_ebd_size = self.position_buckets
|
| 175 |
+
|
| 176 |
+
self.pos_dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 177 |
+
|
| 178 |
+
if not self.share_att_key:
|
| 179 |
+
if "c2p" in self.pos_att_type:
|
| 180 |
+
self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
| 181 |
+
if "p2c" in self.pos_att_type:
|
| 182 |
+
self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size)
|
| 183 |
+
|
| 184 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 185 |
+
|
| 186 |
+
def transpose_for_scores(self, x, attention_heads) -> torch.Tensor:
|
| 187 |
+
new_x_shape = x.size()[:-1] + (attention_heads, -1)
|
| 188 |
+
x = x.view(new_x_shape)
|
| 189 |
+
return x.permute(0, 2, 1, 3).contiguous().view(-1, x.size(1), x.size(-1))
|
| 190 |
+
|
| 191 |
+
def forward(
|
| 192 |
+
self,
|
| 193 |
+
hidden_states,
|
| 194 |
+
attention_mask,
|
| 195 |
+
output_attentions=False,
|
| 196 |
+
query_states=None,
|
| 197 |
+
relative_pos=None,
|
| 198 |
+
rel_embeddings=None,
|
| 199 |
+
):
|
| 200 |
+
"""
|
| 201 |
+
Call the module
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
hidden_states (`torch.FloatTensor`):
|
| 205 |
+
Input states to the module usually the output from previous layer, it will be the Q,K and V in
|
| 206 |
+
*Attention(Q,K,V)*
|
| 207 |
+
|
| 208 |
+
attention_mask (`torch.BoolTensor`):
|
| 209 |
+
An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum
|
| 210 |
+
sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j*
|
| 211 |
+
th token.
|
| 212 |
+
|
| 213 |
+
output_attentions (`bool`, *optional*):
|
| 214 |
+
Whether return the attention matrix.
|
| 215 |
+
|
| 216 |
+
query_states (`torch.FloatTensor`, *optional*):
|
| 217 |
+
The *Q* state in *Attention(Q,K,V)*.
|
| 218 |
+
|
| 219 |
+
relative_pos (`torch.LongTensor`):
|
| 220 |
+
The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with
|
| 221 |
+
values ranging in [*-max_relative_positions*, *max_relative_positions*].
|
| 222 |
+
|
| 223 |
+
rel_embeddings (`torch.FloatTensor`):
|
| 224 |
+
The embedding of relative distances. It's a tensor of shape [\\(2 \\times
|
| 225 |
+
\\text{max_relative_positions}\\), *hidden_size*].
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
"""
|
| 229 |
+
if query_states is None:
|
| 230 |
+
query_states = hidden_states
|
| 231 |
+
query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads)
|
| 232 |
+
key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads)
|
| 233 |
+
value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads)
|
| 234 |
+
|
| 235 |
+
rel_att = None
|
| 236 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 237 |
+
scale_factor = 1
|
| 238 |
+
if "c2p" in self.pos_att_type:
|
| 239 |
+
scale_factor += 1
|
| 240 |
+
if "p2c" in self.pos_att_type:
|
| 241 |
+
scale_factor += 1
|
| 242 |
+
scale = scaled_size_sqrt(query_layer, scale_factor)
|
| 243 |
+
attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2) / scale.to(dtype=query_layer.dtype))
|
| 244 |
+
if self.relative_attention:
|
| 245 |
+
rel_embeddings = self.pos_dropout(rel_embeddings)
|
| 246 |
+
rel_att = self.disentangled_attention_bias(
|
| 247 |
+
query_layer, key_layer, relative_pos, rel_embeddings, scale_factor
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if rel_att is not None:
|
| 251 |
+
attention_scores = attention_scores + rel_att
|
| 252 |
+
attention_scores = attention_scores.view(
|
| 253 |
+
-1, self.num_attention_heads, attention_scores.size(-2), attention_scores.size(-1)
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
attention_mask = attention_mask.bool()
|
| 257 |
+
attention_scores = attention_scores.masked_fill(~(attention_mask), torch.finfo(query_layer.dtype).min)
|
| 258 |
+
# bsz x height x length x dimension
|
| 259 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 260 |
+
|
| 261 |
+
attention_probs = self.dropout(attention_probs)
|
| 262 |
+
context_layer = torch.bmm(
|
| 263 |
+
attention_probs.view(-1, attention_probs.size(-2), attention_probs.size(-1)), value_layer
|
| 264 |
+
)
|
| 265 |
+
context_layer = (
|
| 266 |
+
context_layer.view(-1, self.num_attention_heads, context_layer.size(-2), context_layer.size(-1))
|
| 267 |
+
.permute(0, 2, 1, 3)
|
| 268 |
+
.contiguous()
|
| 269 |
+
)
|
| 270 |
+
new_context_layer_shape = context_layer.size()[:-2] + (-1,)
|
| 271 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 272 |
+
if not output_attentions:
|
| 273 |
+
return (context_layer, None)
|
| 274 |
+
return (context_layer, attention_probs)
|
| 275 |
+
|
| 276 |
+
def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor):
|
| 277 |
+
if relative_pos is None:
|
| 278 |
+
relative_pos = build_relative_position(
|
| 279 |
+
query_layer,
|
| 280 |
+
key_layer,
|
| 281 |
+
bucket_size=self.position_buckets,
|
| 282 |
+
max_position=self.max_relative_positions,
|
| 283 |
+
)
|
| 284 |
+
if relative_pos.dim() == 2:
|
| 285 |
+
relative_pos = relative_pos.unsqueeze(0).unsqueeze(0)
|
| 286 |
+
elif relative_pos.dim() == 3:
|
| 287 |
+
relative_pos = relative_pos.unsqueeze(1)
|
| 288 |
+
# bsz x height x query x key
|
| 289 |
+
elif relative_pos.dim() != 4:
|
| 290 |
+
raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")
|
| 291 |
+
|
| 292 |
+
att_span = self.pos_ebd_size
|
| 293 |
+
relative_pos = relative_pos.to(device=query_layer.device, dtype=torch.long)
|
| 294 |
+
|
| 295 |
+
rel_embeddings = rel_embeddings[0 : att_span * 2, :].unsqueeze(0)
|
| 296 |
+
if self.share_att_key:
|
| 297 |
+
pos_query_layer = self.transpose_for_scores(
|
| 298 |
+
self.query_proj(rel_embeddings), self.num_attention_heads
|
| 299 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1)
|
| 300 |
+
pos_key_layer = self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat(
|
| 301 |
+
query_layer.size(0) // self.num_attention_heads, 1, 1
|
| 302 |
+
)
|
| 303 |
+
else:
|
| 304 |
+
if "c2p" in self.pos_att_type:
|
| 305 |
+
pos_key_layer = self.transpose_for_scores(
|
| 306 |
+
self.pos_key_proj(rel_embeddings), self.num_attention_heads
|
| 307 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) # .split(self.all_head_size, dim=-1)
|
| 308 |
+
if "p2c" in self.pos_att_type:
|
| 309 |
+
pos_query_layer = self.transpose_for_scores(
|
| 310 |
+
self.pos_query_proj(rel_embeddings), self.num_attention_heads
|
| 311 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) # .split(self.all_head_size, dim=-1)
|
| 312 |
+
|
| 313 |
+
score = 0
|
| 314 |
+
# content->position
|
| 315 |
+
if "c2p" in self.pos_att_type:
|
| 316 |
+
scale = scaled_size_sqrt(pos_key_layer, scale_factor)
|
| 317 |
+
c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2))
|
| 318 |
+
c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1)
|
| 319 |
+
c2p_att = torch.gather(
|
| 320 |
+
c2p_att,
|
| 321 |
+
dim=-1,
|
| 322 |
+
index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]),
|
| 323 |
+
)
|
| 324 |
+
score += c2p_att / scale.to(dtype=c2p_att.dtype)
|
| 325 |
+
|
| 326 |
+
# position->content
|
| 327 |
+
if "p2c" in self.pos_att_type:
|
| 328 |
+
scale = scaled_size_sqrt(pos_query_layer, scale_factor)
|
| 329 |
+
r_pos = build_rpos(
|
| 330 |
+
query_layer,
|
| 331 |
+
key_layer,
|
| 332 |
+
relative_pos,
|
| 333 |
+
self.max_relative_positions,
|
| 334 |
+
self.position_buckets,
|
| 335 |
+
)
|
| 336 |
+
p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1)
|
| 337 |
+
p2c_att = torch.bmm(key_layer, pos_query_layer.transpose(-1, -2))
|
| 338 |
+
p2c_att = torch.gather(
|
| 339 |
+
p2c_att,
|
| 340 |
+
dim=-1,
|
| 341 |
+
index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]),
|
| 342 |
+
).transpose(-1, -2)
|
| 343 |
+
score += p2c_att / scale.to(dtype=p2c_att.dtype)
|
| 344 |
+
|
| 345 |
+
return score
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaAttention with Deberta->DebertaV2
|
| 349 |
+
class DebertaV2Attention(nn.Module):
|
| 350 |
+
def __init__(self, config):
|
| 351 |
+
super().__init__()
|
| 352 |
+
self.self = DisentangledSelfAttention(config)
|
| 353 |
+
self.output = DebertaV2SelfOutput(config)
|
| 354 |
+
self.config = config
|
| 355 |
+
|
| 356 |
+
def forward(
|
| 357 |
+
self,
|
| 358 |
+
hidden_states,
|
| 359 |
+
attention_mask,
|
| 360 |
+
output_attentions: bool = False,
|
| 361 |
+
query_states=None,
|
| 362 |
+
relative_pos=None,
|
| 363 |
+
rel_embeddings=None,
|
| 364 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 365 |
+
self_output, att_matrix = self.self(
|
| 366 |
+
hidden_states,
|
| 367 |
+
attention_mask,
|
| 368 |
+
output_attentions,
|
| 369 |
+
query_states=query_states,
|
| 370 |
+
relative_pos=relative_pos,
|
| 371 |
+
rel_embeddings=rel_embeddings,
|
| 372 |
+
)
|
| 373 |
+
if query_states is None:
|
| 374 |
+
query_states = hidden_states
|
| 375 |
+
attention_output = self.output(self_output, query_states)
|
| 376 |
+
|
| 377 |
+
if output_attentions:
|
| 378 |
+
return (attention_output, att_matrix)
|
| 379 |
+
else:
|
| 380 |
+
return (attention_output, None)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->DebertaV2
|
| 384 |
+
class DebertaV2Intermediate(nn.Module):
|
| 385 |
+
def __init__(self, config):
|
| 386 |
+
super().__init__()
|
| 387 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 388 |
+
if isinstance(config.hidden_act, str):
|
| 389 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 390 |
+
else:
|
| 391 |
+
self.intermediate_act_fn = config.hidden_act
|
| 392 |
+
|
| 393 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 394 |
+
hidden_states = self.dense(hidden_states)
|
| 395 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 396 |
+
return hidden_states
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaOutput with DebertaLayerNorm->LayerNorm
|
| 400 |
+
class DebertaV2Output(nn.Module):
|
| 401 |
+
def __init__(self, config):
|
| 402 |
+
super().__init__()
|
| 403 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 404 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 405 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 406 |
+
self.config = config
|
| 407 |
+
|
| 408 |
+
def forward(self, hidden_states, input_tensor):
|
| 409 |
+
hidden_states = self.dense(hidden_states)
|
| 410 |
+
hidden_states = self.dropout(hidden_states)
|
| 411 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 412 |
+
return hidden_states
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaLayer with Deberta->DebertaV2
|
| 416 |
+
class DebertaV2Layer(GradientCheckpointingLayer):
|
| 417 |
+
def __init__(self, config):
|
| 418 |
+
super().__init__()
|
| 419 |
+
self.attention = DebertaV2Attention(config)
|
| 420 |
+
self.intermediate = DebertaV2Intermediate(config)
|
| 421 |
+
self.output = DebertaV2Output(config)
|
| 422 |
+
|
| 423 |
+
def forward(
|
| 424 |
+
self,
|
| 425 |
+
hidden_states,
|
| 426 |
+
attention_mask,
|
| 427 |
+
query_states=None,
|
| 428 |
+
relative_pos=None,
|
| 429 |
+
rel_embeddings=None,
|
| 430 |
+
output_attentions: bool = False,
|
| 431 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 432 |
+
attention_output, att_matrix = self.attention(
|
| 433 |
+
hidden_states,
|
| 434 |
+
attention_mask,
|
| 435 |
+
output_attentions=output_attentions,
|
| 436 |
+
query_states=query_states,
|
| 437 |
+
relative_pos=relative_pos,
|
| 438 |
+
rel_embeddings=rel_embeddings,
|
| 439 |
+
)
|
| 440 |
+
intermediate_output = self.intermediate(attention_output)
|
| 441 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 442 |
+
|
| 443 |
+
if output_attentions:
|
| 444 |
+
return (layer_output, att_matrix)
|
| 445 |
+
else:
|
| 446 |
+
return (layer_output, None)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class ConvLayer(nn.Module):
|
| 450 |
+
def __init__(self, config):
|
| 451 |
+
super().__init__()
|
| 452 |
+
kernel_size = getattr(config, "conv_kernel_size", 3)
|
| 453 |
+
groups = getattr(config, "conv_groups", 1)
|
| 454 |
+
self.conv_act = getattr(config, "conv_act", "tanh")
|
| 455 |
+
self.conv = nn.Conv1d(
|
| 456 |
+
config.hidden_size, config.hidden_size, kernel_size, padding=(kernel_size - 1) // 2, groups=groups
|
| 457 |
+
)
|
| 458 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 459 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 460 |
+
self.config = config
|
| 461 |
+
|
| 462 |
+
def forward(self, hidden_states, residual_states, input_mask):
|
| 463 |
+
out = self.conv(hidden_states.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous()
|
| 464 |
+
rmask = (1 - input_mask).bool()
|
| 465 |
+
out.masked_fill_(rmask.unsqueeze(-1).expand(out.size()), 0)
|
| 466 |
+
out = ACT2FN[self.conv_act](self.dropout(out))
|
| 467 |
+
|
| 468 |
+
layer_norm_input = residual_states + out
|
| 469 |
+
output = self.LayerNorm(layer_norm_input).to(layer_norm_input)
|
| 470 |
+
|
| 471 |
+
if input_mask is None:
|
| 472 |
+
output_states = output
|
| 473 |
+
else:
|
| 474 |
+
if input_mask.dim() != layer_norm_input.dim():
|
| 475 |
+
if input_mask.dim() == 4:
|
| 476 |
+
input_mask = input_mask.squeeze(1).squeeze(1)
|
| 477 |
+
input_mask = input_mask.unsqueeze(2)
|
| 478 |
+
|
| 479 |
+
input_mask = input_mask.to(output.dtype)
|
| 480 |
+
output_states = output * input_mask
|
| 481 |
+
|
| 482 |
+
return output_states
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaEmbeddings with DebertaLayerNorm->LayerNorm,Deberta->DebertaV2
|
| 486 |
+
class DebertaV2Embeddings(nn.Module):
|
| 487 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 488 |
+
|
| 489 |
+
def __init__(self, config):
|
| 490 |
+
super().__init__()
|
| 491 |
+
pad_token_id = getattr(config, "pad_token_id", 0)
|
| 492 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
| 493 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id)
|
| 494 |
+
|
| 495 |
+
self.position_biased_input = getattr(config, "position_biased_input", True)
|
| 496 |
+
if not self.position_biased_input:
|
| 497 |
+
self.position_embeddings = None
|
| 498 |
+
else:
|
| 499 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size)
|
| 500 |
+
|
| 501 |
+
if config.type_vocab_size > 0:
|
| 502 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size)
|
| 503 |
+
else:
|
| 504 |
+
self.token_type_embeddings = None
|
| 505 |
+
|
| 506 |
+
if self.embedding_size != config.hidden_size:
|
| 507 |
+
self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False)
|
| 508 |
+
else:
|
| 509 |
+
self.embed_proj = None
|
| 510 |
+
|
| 511 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
| 512 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 513 |
+
self.config = config
|
| 514 |
+
|
| 515 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 516 |
+
self.register_buffer(
|
| 517 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None):
|
| 521 |
+
if input_ids is not None:
|
| 522 |
+
input_shape = input_ids.size()
|
| 523 |
+
else:
|
| 524 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 525 |
+
|
| 526 |
+
seq_length = input_shape[1]
|
| 527 |
+
|
| 528 |
+
if position_ids is None:
|
| 529 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 530 |
+
|
| 531 |
+
if token_type_ids is None:
|
| 532 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 533 |
+
|
| 534 |
+
if inputs_embeds is None:
|
| 535 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 536 |
+
|
| 537 |
+
if self.position_embeddings is not None:
|
| 538 |
+
position_embeddings = self.position_embeddings(position_ids.long())
|
| 539 |
+
else:
|
| 540 |
+
position_embeddings = torch.zeros_like(inputs_embeds)
|
| 541 |
+
|
| 542 |
+
embeddings = inputs_embeds
|
| 543 |
+
if self.position_biased_input:
|
| 544 |
+
embeddings = embeddings + position_embeddings
|
| 545 |
+
if self.token_type_embeddings is not None:
|
| 546 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 547 |
+
embeddings = embeddings + token_type_embeddings
|
| 548 |
+
|
| 549 |
+
if self.embed_proj is not None:
|
| 550 |
+
embeddings = self.embed_proj(embeddings)
|
| 551 |
+
|
| 552 |
+
embeddings = self.LayerNorm(embeddings)
|
| 553 |
+
|
| 554 |
+
if mask is not None:
|
| 555 |
+
if mask.dim() != embeddings.dim():
|
| 556 |
+
if mask.dim() == 4:
|
| 557 |
+
mask = mask.squeeze(1).squeeze(1)
|
| 558 |
+
mask = mask.unsqueeze(2)
|
| 559 |
+
mask = mask.to(embeddings.dtype)
|
| 560 |
+
|
| 561 |
+
embeddings = embeddings * mask
|
| 562 |
+
|
| 563 |
+
embeddings = self.dropout(embeddings)
|
| 564 |
+
return embeddings
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class DebertaV2Encoder(nn.Module):
|
| 568 |
+
"""Modified BertEncoder with relative position bias support"""
|
| 569 |
+
|
| 570 |
+
def __init__(self, config):
|
| 571 |
+
super().__init__()
|
| 572 |
+
|
| 573 |
+
self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)])
|
| 574 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
| 575 |
+
|
| 576 |
+
if self.relative_attention:
|
| 577 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
| 578 |
+
if self.max_relative_positions < 1:
|
| 579 |
+
self.max_relative_positions = config.max_position_embeddings
|
| 580 |
+
|
| 581 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
| 582 |
+
pos_ebd_size = self.max_relative_positions * 2
|
| 583 |
+
|
| 584 |
+
if self.position_buckets > 0:
|
| 585 |
+
pos_ebd_size = self.position_buckets * 2
|
| 586 |
+
|
| 587 |
+
self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size)
|
| 588 |
+
|
| 589 |
+
self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")]
|
| 590 |
+
|
| 591 |
+
if "layer_norm" in self.norm_rel_ebd:
|
| 592 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
|
| 593 |
+
|
| 594 |
+
self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None
|
| 595 |
+
self.gradient_checkpointing = False
|
| 596 |
+
|
| 597 |
+
def get_rel_embedding(self):
|
| 598 |
+
rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None
|
| 599 |
+
if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd):
|
| 600 |
+
rel_embeddings = self.LayerNorm(rel_embeddings)
|
| 601 |
+
return rel_embeddings
|
| 602 |
+
|
| 603 |
+
def get_attention_mask(self, attention_mask):
|
| 604 |
+
if attention_mask.dim() <= 2:
|
| 605 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 606 |
+
attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1)
|
| 607 |
+
elif attention_mask.dim() == 3:
|
| 608 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 609 |
+
|
| 610 |
+
return attention_mask
|
| 611 |
+
|
| 612 |
+
def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None):
|
| 613 |
+
if self.relative_attention and relative_pos is None:
|
| 614 |
+
if query_states is not None:
|
| 615 |
+
relative_pos = build_relative_position(
|
| 616 |
+
query_states,
|
| 617 |
+
hidden_states,
|
| 618 |
+
bucket_size=self.position_buckets,
|
| 619 |
+
max_position=self.max_relative_positions,
|
| 620 |
+
)
|
| 621 |
+
else:
|
| 622 |
+
relative_pos = build_relative_position(
|
| 623 |
+
hidden_states,
|
| 624 |
+
hidden_states,
|
| 625 |
+
bucket_size=self.position_buckets,
|
| 626 |
+
max_position=self.max_relative_positions,
|
| 627 |
+
)
|
| 628 |
+
return relative_pos
|
| 629 |
+
|
| 630 |
+
def forward(
|
| 631 |
+
self,
|
| 632 |
+
hidden_states,
|
| 633 |
+
attention_mask,
|
| 634 |
+
output_hidden_states=True,
|
| 635 |
+
output_attentions=False,
|
| 636 |
+
query_states=None,
|
| 637 |
+
relative_pos=None,
|
| 638 |
+
return_dict=True,
|
| 639 |
+
):
|
| 640 |
+
if attention_mask.dim() <= 2:
|
| 641 |
+
input_mask = attention_mask
|
| 642 |
+
else:
|
| 643 |
+
input_mask = attention_mask.sum(-2) > 0
|
| 644 |
+
attention_mask = self.get_attention_mask(attention_mask)
|
| 645 |
+
relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos)
|
| 646 |
+
|
| 647 |
+
all_hidden_states: tuple[torch.Tensor] | None = (hidden_states,) if output_hidden_states else None
|
| 648 |
+
all_attentions = () if output_attentions else None
|
| 649 |
+
|
| 650 |
+
next_kv = hidden_states
|
| 651 |
+
rel_embeddings = self.get_rel_embedding()
|
| 652 |
+
for i, layer_module in enumerate(self.layer):
|
| 653 |
+
output_states, attn_weights = layer_module(
|
| 654 |
+
next_kv,
|
| 655 |
+
attention_mask,
|
| 656 |
+
query_states=query_states,
|
| 657 |
+
relative_pos=relative_pos,
|
| 658 |
+
rel_embeddings=rel_embeddings,
|
| 659 |
+
output_attentions=output_attentions,
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
if output_attentions:
|
| 663 |
+
all_attentions = all_attentions + (attn_weights,)
|
| 664 |
+
|
| 665 |
+
if i == 0 and self.conv is not None:
|
| 666 |
+
output_states = self.conv(hidden_states, output_states, input_mask)
|
| 667 |
+
|
| 668 |
+
if output_hidden_states:
|
| 669 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
| 670 |
+
|
| 671 |
+
if query_states is not None:
|
| 672 |
+
query_states = output_states
|
| 673 |
+
if isinstance(hidden_states, Sequence):
|
| 674 |
+
next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None
|
| 675 |
+
else:
|
| 676 |
+
next_kv = output_states
|
| 677 |
+
|
| 678 |
+
if not return_dict:
|
| 679 |
+
return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None)
|
| 680 |
+
return BaseModelOutput(
|
| 681 |
+
last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
@auto_docstring
|
| 686 |
+
class DebertaV2PreTrainedModel(PreTrainedModel):
|
| 687 |
+
config: DebertaV2Config
|
| 688 |
+
base_model_prefix = "deberta"
|
| 689 |
+
_keys_to_ignore_on_load_unexpected = ["position_embeddings"]
|
| 690 |
+
supports_gradient_checkpointing = True
|
| 691 |
+
|
| 692 |
+
@torch.no_grad()
|
| 693 |
+
def _init_weights(self, module):
|
| 694 |
+
"""Initialize the weights."""
|
| 695 |
+
super()._init_weights(module)
|
| 696 |
+
if isinstance(module, (LegacyDebertaV2LMPredictionHead, DebertaV2LMPredictionHead)):
|
| 697 |
+
init.zeros_(module.bias)
|
| 698 |
+
elif isinstance(module, DebertaV2Embeddings):
|
| 699 |
+
init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
@auto_docstring
|
| 703 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2
|
| 704 |
+
class DebertaV2Model(DebertaV2PreTrainedModel):
|
| 705 |
+
def __init__(self, config):
|
| 706 |
+
super().__init__(config)
|
| 707 |
+
|
| 708 |
+
self.embeddings = DebertaV2Embeddings(config)
|
| 709 |
+
self.encoder = DebertaV2Encoder(config)
|
| 710 |
+
self.z_steps = 0
|
| 711 |
+
self.config = config
|
| 712 |
+
# Initialize weights and apply final processing
|
| 713 |
+
self.post_init()
|
| 714 |
+
|
| 715 |
+
def get_input_embeddings(self):
|
| 716 |
+
return self.embeddings.word_embeddings
|
| 717 |
+
|
| 718 |
+
def set_input_embeddings(self, new_embeddings):
|
| 719 |
+
self.embeddings.word_embeddings = new_embeddings
|
| 720 |
+
|
| 721 |
+
@auto_docstring
|
| 722 |
+
def forward(
|
| 723 |
+
self,
|
| 724 |
+
input_ids: torch.Tensor | None = None,
|
| 725 |
+
attention_mask: torch.Tensor | None = None,
|
| 726 |
+
token_type_ids: torch.Tensor | None = None,
|
| 727 |
+
position_ids: torch.Tensor | None = None,
|
| 728 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 729 |
+
output_attentions: bool | None = None,
|
| 730 |
+
output_hidden_states: bool | None = None,
|
| 731 |
+
return_dict: bool | None = None,
|
| 732 |
+
**kwargs,
|
| 733 |
+
) -> tuple | BaseModelOutput:
|
| 734 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 735 |
+
output_hidden_states = (
|
| 736 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 737 |
+
)
|
| 738 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 739 |
+
|
| 740 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 741 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 742 |
+
elif input_ids is not None:
|
| 743 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 744 |
+
input_shape = input_ids.size()
|
| 745 |
+
elif inputs_embeds is not None:
|
| 746 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 747 |
+
else:
|
| 748 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 749 |
+
|
| 750 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 751 |
+
|
| 752 |
+
if attention_mask is None:
|
| 753 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 754 |
+
if token_type_ids is None:
|
| 755 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 756 |
+
|
| 757 |
+
embedding_output = self.embeddings(
|
| 758 |
+
input_ids=input_ids,
|
| 759 |
+
token_type_ids=token_type_ids,
|
| 760 |
+
position_ids=position_ids,
|
| 761 |
+
mask=attention_mask,
|
| 762 |
+
inputs_embeds=inputs_embeds,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
encoder_outputs = self.encoder(
|
| 766 |
+
embedding_output,
|
| 767 |
+
attention_mask,
|
| 768 |
+
output_hidden_states=True,
|
| 769 |
+
output_attentions=output_attentions,
|
| 770 |
+
return_dict=return_dict,
|
| 771 |
+
)
|
| 772 |
+
encoded_layers = encoder_outputs[1]
|
| 773 |
+
|
| 774 |
+
if self.z_steps > 1:
|
| 775 |
+
hidden_states = encoded_layers[-2]
|
| 776 |
+
layers = [self.encoder.layer[-1] for _ in range(self.z_steps)]
|
| 777 |
+
query_states = encoded_layers[-1]
|
| 778 |
+
rel_embeddings = self.encoder.get_rel_embedding()
|
| 779 |
+
attention_mask = self.encoder.get_attention_mask(attention_mask)
|
| 780 |
+
rel_pos = self.encoder.get_rel_pos(embedding_output)
|
| 781 |
+
for layer in layers[1:]:
|
| 782 |
+
query_states = layer(
|
| 783 |
+
hidden_states,
|
| 784 |
+
attention_mask,
|
| 785 |
+
output_attentions=False,
|
| 786 |
+
query_states=query_states,
|
| 787 |
+
relative_pos=rel_pos,
|
| 788 |
+
rel_embeddings=rel_embeddings,
|
| 789 |
+
)
|
| 790 |
+
encoded_layers.append(query_states)
|
| 791 |
+
|
| 792 |
+
sequence_output = encoded_layers[-1]
|
| 793 |
+
|
| 794 |
+
if not return_dict:
|
| 795 |
+
return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :]
|
| 796 |
+
|
| 797 |
+
return BaseModelOutput(
|
| 798 |
+
last_hidden_state=sequence_output,
|
| 799 |
+
hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
|
| 800 |
+
attentions=encoder_outputs.attentions,
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
# Copied from transformers.models.deberta.modeling_deberta.LegacyDebertaPredictionHeadTransform with Deberta->DebertaV2
|
| 805 |
+
class LegacyDebertaV2PredictionHeadTransform(nn.Module):
|
| 806 |
+
def __init__(self, config):
|
| 807 |
+
super().__init__()
|
| 808 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
| 809 |
+
|
| 810 |
+
self.dense = nn.Linear(config.hidden_size, self.embedding_size)
|
| 811 |
+
if isinstance(config.hidden_act, str):
|
| 812 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 813 |
+
else:
|
| 814 |
+
self.transform_act_fn = config.hidden_act
|
| 815 |
+
self.LayerNorm = nn.LayerNorm(self.embedding_size, eps=config.layer_norm_eps)
|
| 816 |
+
|
| 817 |
+
def forward(self, hidden_states):
|
| 818 |
+
hidden_states = self.dense(hidden_states)
|
| 819 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 820 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 821 |
+
return hidden_states
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
class LegacyDebertaV2LMPredictionHead(nn.Module):
|
| 825 |
+
def __init__(self, config):
|
| 826 |
+
super().__init__()
|
| 827 |
+
self.transform = LegacyDebertaV2PredictionHeadTransform(config)
|
| 828 |
+
|
| 829 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
| 830 |
+
# The output weights are the same as the input embeddings, but there is
|
| 831 |
+
# an output-only bias for each token.
|
| 832 |
+
self.decoder = nn.Linear(self.embedding_size, config.vocab_size)
|
| 833 |
+
|
| 834 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 835 |
+
|
| 836 |
+
def forward(self, hidden_states):
|
| 837 |
+
hidden_states = self.transform(hidden_states)
|
| 838 |
+
hidden_states = self.decoder(hidden_states)
|
| 839 |
+
return hidden_states
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
class LegacyDebertaV2OnlyMLMHead(nn.Module):
|
| 843 |
+
def __init__(self, config):
|
| 844 |
+
super().__init__()
|
| 845 |
+
self.predictions = LegacyDebertaV2LMPredictionHead(config)
|
| 846 |
+
|
| 847 |
+
def forward(self, sequence_output):
|
| 848 |
+
prediction_scores = self.predictions(sequence_output)
|
| 849 |
+
return prediction_scores
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
class DebertaV2LMPredictionHead(nn.Module):
|
| 853 |
+
"""https://github.com/microsoft/DeBERTa/blob/master/DeBERTa/deberta/bert.py#L270"""
|
| 854 |
+
|
| 855 |
+
def __init__(self, config):
|
| 856 |
+
super().__init__()
|
| 857 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 858 |
+
|
| 859 |
+
if isinstance(config.hidden_act, str):
|
| 860 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 861 |
+
else:
|
| 862 |
+
self.transform_act_fn = config.hidden_act
|
| 863 |
+
|
| 864 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=True)
|
| 865 |
+
|
| 866 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 867 |
+
|
| 868 |
+
# note that the input embeddings must be passed as an argument
|
| 869 |
+
def forward(self, hidden_states, word_embeddings):
|
| 870 |
+
hidden_states = self.dense(hidden_states)
|
| 871 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 872 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 873 |
+
hidden_states = torch.matmul(hidden_states, word_embeddings.weight.t()) + self.bias
|
| 874 |
+
return hidden_states
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class DebertaV2OnlyMLMHead(nn.Module):
|
| 878 |
+
def __init__(self, config):
|
| 879 |
+
super().__init__()
|
| 880 |
+
self.lm_head = DebertaV2LMPredictionHead(config)
|
| 881 |
+
|
| 882 |
+
# note that the input embeddings must be passed as an argument
|
| 883 |
+
def forward(self, sequence_output, word_embeddings):
|
| 884 |
+
prediction_scores = self.lm_head(sequence_output, word_embeddings)
|
| 885 |
+
return prediction_scores
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@auto_docstring
|
| 889 |
+
class DebertaV2ForMaskedLM(DebertaV2PreTrainedModel):
|
| 890 |
+
_tied_weights_keys = {
|
| 891 |
+
"cls.predictions.decoder.bias": "cls.predictions.bias",
|
| 892 |
+
"cls.predictions.decoder.weight": "deberta.embeddings.word_embeddings.weight",
|
| 893 |
+
}
|
| 894 |
+
_keys_to_ignore_on_load_unexpected = [r"mask_predictions.*"]
|
| 895 |
+
|
| 896 |
+
def __init__(self, config):
|
| 897 |
+
super().__init__(config)
|
| 898 |
+
self.legacy = config.legacy
|
| 899 |
+
self.deberta = DebertaV2Model(config)
|
| 900 |
+
if self.legacy:
|
| 901 |
+
self.cls = LegacyDebertaV2OnlyMLMHead(config)
|
| 902 |
+
else:
|
| 903 |
+
self._tied_weights_keys = {
|
| 904 |
+
"lm_predictions.lm_head.weight": "deberta.embeddings.word_embeddings.weight",
|
| 905 |
+
}
|
| 906 |
+
self.lm_predictions = DebertaV2OnlyMLMHead(config)
|
| 907 |
+
# Initialize weights and apply final processing
|
| 908 |
+
self.post_init()
|
| 909 |
+
|
| 910 |
+
def get_output_embeddings(self):
|
| 911 |
+
if self.legacy:
|
| 912 |
+
return self.cls.predictions.decoder
|
| 913 |
+
else:
|
| 914 |
+
return self.lm_predictions.lm_head.dense
|
| 915 |
+
|
| 916 |
+
def set_output_embeddings(self, new_embeddings):
|
| 917 |
+
if self.legacy:
|
| 918 |
+
self.cls.predictions.decoder = new_embeddings
|
| 919 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 920 |
+
else:
|
| 921 |
+
self.lm_predictions.lm_head.dense = new_embeddings
|
| 922 |
+
self.lm_predictions.lm_head.bias = new_embeddings.bias
|
| 923 |
+
|
| 924 |
+
@auto_docstring
|
| 925 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForMaskedLM.forward with Deberta->DebertaV2
|
| 926 |
+
def forward(
|
| 927 |
+
self,
|
| 928 |
+
input_ids: torch.Tensor | None = None,
|
| 929 |
+
attention_mask: torch.Tensor | None = None,
|
| 930 |
+
token_type_ids: torch.Tensor | None = None,
|
| 931 |
+
position_ids: torch.Tensor | None = None,
|
| 932 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 933 |
+
labels: torch.Tensor | None = None,
|
| 934 |
+
output_attentions: bool | None = None,
|
| 935 |
+
output_hidden_states: bool | None = None,
|
| 936 |
+
return_dict: bool | None = None,
|
| 937 |
+
**kwargs,
|
| 938 |
+
) -> tuple | MaskedLMOutput:
|
| 939 |
+
r"""
|
| 940 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 941 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 942 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 943 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 944 |
+
"""
|
| 945 |
+
|
| 946 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 947 |
+
|
| 948 |
+
outputs = self.deberta(
|
| 949 |
+
input_ids,
|
| 950 |
+
attention_mask=attention_mask,
|
| 951 |
+
token_type_ids=token_type_ids,
|
| 952 |
+
position_ids=position_ids,
|
| 953 |
+
inputs_embeds=inputs_embeds,
|
| 954 |
+
output_attentions=output_attentions,
|
| 955 |
+
output_hidden_states=output_hidden_states,
|
| 956 |
+
return_dict=return_dict,
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
sequence_output = outputs[0]
|
| 960 |
+
if self.legacy:
|
| 961 |
+
prediction_scores = self.cls(sequence_output)
|
| 962 |
+
else:
|
| 963 |
+
prediction_scores = self.lm_predictions(sequence_output, self.deberta.embeddings.word_embeddings)
|
| 964 |
+
|
| 965 |
+
masked_lm_loss = None
|
| 966 |
+
if labels is not None:
|
| 967 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 968 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 969 |
+
|
| 970 |
+
if not return_dict:
|
| 971 |
+
output = (prediction_scores,) + outputs[1:]
|
| 972 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 973 |
+
|
| 974 |
+
return MaskedLMOutput(
|
| 975 |
+
loss=masked_lm_loss,
|
| 976 |
+
logits=prediction_scores,
|
| 977 |
+
hidden_states=outputs.hidden_states,
|
| 978 |
+
attentions=outputs.attentions,
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
# Copied from transformers.models.deberta.modeling_deberta.ContextPooler
|
| 983 |
+
class ContextPooler(nn.Module):
|
| 984 |
+
def __init__(self, config):
|
| 985 |
+
super().__init__()
|
| 986 |
+
self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size)
|
| 987 |
+
self.dropout = nn.Dropout(config.pooler_dropout)
|
| 988 |
+
self.config = config
|
| 989 |
+
|
| 990 |
+
def forward(self, hidden_states):
|
| 991 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 992 |
+
# to the first token.
|
| 993 |
+
|
| 994 |
+
context_token = hidden_states[:, 0]
|
| 995 |
+
context_token = self.dropout(context_token)
|
| 996 |
+
pooled_output = self.dense(context_token)
|
| 997 |
+
pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output)
|
| 998 |
+
return pooled_output
|
| 999 |
+
|
| 1000 |
+
@property
|
| 1001 |
+
def output_dim(self):
|
| 1002 |
+
return self.config.hidden_size
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
@auto_docstring(
|
| 1006 |
+
custom_intro="""
|
| 1007 |
+
DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 1008 |
+
pooled output) e.g. for GLUE tasks.
|
| 1009 |
+
"""
|
| 1010 |
+
)
|
| 1011 |
+
class DebertaV2ForSequenceClassification(DebertaV2PreTrainedModel):
|
| 1012 |
+
def __init__(self, config):
|
| 1013 |
+
super().__init__(config)
|
| 1014 |
+
|
| 1015 |
+
num_labels = getattr(config, "num_labels", 2)
|
| 1016 |
+
self.num_labels = num_labels
|
| 1017 |
+
|
| 1018 |
+
self.deberta = DebertaV2Model(config)
|
| 1019 |
+
self.pooler = ContextPooler(config)
|
| 1020 |
+
output_dim = self.pooler.output_dim
|
| 1021 |
+
|
| 1022 |
+
self.classifier = nn.Linear(output_dim, num_labels)
|
| 1023 |
+
drop_out = getattr(config, "cls_dropout", None)
|
| 1024 |
+
drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out
|
| 1025 |
+
self.dropout = nn.Dropout(drop_out)
|
| 1026 |
+
|
| 1027 |
+
# Initialize weights and apply final processing
|
| 1028 |
+
self.post_init()
|
| 1029 |
+
|
| 1030 |
+
def get_input_embeddings(self):
|
| 1031 |
+
return self.deberta.get_input_embeddings()
|
| 1032 |
+
|
| 1033 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1034 |
+
self.deberta.set_input_embeddings(new_embeddings)
|
| 1035 |
+
|
| 1036 |
+
@auto_docstring
|
| 1037 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForSequenceClassification.forward with Deberta->DebertaV2
|
| 1038 |
+
def forward(
|
| 1039 |
+
self,
|
| 1040 |
+
input_ids: torch.Tensor | None = None,
|
| 1041 |
+
attention_mask: torch.Tensor | None = None,
|
| 1042 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1043 |
+
position_ids: torch.Tensor | None = None,
|
| 1044 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1045 |
+
labels: torch.Tensor | None = None,
|
| 1046 |
+
output_attentions: bool | None = None,
|
| 1047 |
+
output_hidden_states: bool | None = None,
|
| 1048 |
+
return_dict: bool | None = None,
|
| 1049 |
+
**kwargs,
|
| 1050 |
+
) -> tuple | SequenceClassifierOutput:
|
| 1051 |
+
r"""
|
| 1052 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1053 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1054 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1055 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1056 |
+
"""
|
| 1057 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1058 |
+
|
| 1059 |
+
outputs = self.deberta(
|
| 1060 |
+
input_ids,
|
| 1061 |
+
token_type_ids=token_type_ids,
|
| 1062 |
+
attention_mask=attention_mask,
|
| 1063 |
+
position_ids=position_ids,
|
| 1064 |
+
inputs_embeds=inputs_embeds,
|
| 1065 |
+
output_attentions=output_attentions,
|
| 1066 |
+
output_hidden_states=output_hidden_states,
|
| 1067 |
+
return_dict=return_dict,
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
encoder_layer = outputs[0]
|
| 1071 |
+
pooled_output = self.pooler(encoder_layer)
|
| 1072 |
+
pooled_output = self.dropout(pooled_output)
|
| 1073 |
+
logits = self.classifier(pooled_output)
|
| 1074 |
+
|
| 1075 |
+
loss = None
|
| 1076 |
+
if labels is not None:
|
| 1077 |
+
if self.config.problem_type is None:
|
| 1078 |
+
if self.num_labels == 1:
|
| 1079 |
+
# regression task
|
| 1080 |
+
loss_fn = nn.MSELoss()
|
| 1081 |
+
logits = logits.view(-1).to(labels.dtype)
|
| 1082 |
+
loss = loss_fn(logits, labels.view(-1))
|
| 1083 |
+
elif labels.dim() == 1 or labels.size(-1) == 1:
|
| 1084 |
+
label_index = (labels >= 0).nonzero()
|
| 1085 |
+
labels = labels.long()
|
| 1086 |
+
if label_index.size(0) > 0:
|
| 1087 |
+
labeled_logits = torch.gather(
|
| 1088 |
+
logits, 0, label_index.expand(label_index.size(0), logits.size(1))
|
| 1089 |
+
)
|
| 1090 |
+
labels = torch.gather(labels, 0, label_index.view(-1))
|
| 1091 |
+
loss_fct = CrossEntropyLoss()
|
| 1092 |
+
loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1))
|
| 1093 |
+
else:
|
| 1094 |
+
loss = torch.tensor(0).to(logits)
|
| 1095 |
+
else:
|
| 1096 |
+
log_softmax = nn.LogSoftmax(-1)
|
| 1097 |
+
loss = -((log_softmax(logits) * labels).sum(-1)).mean()
|
| 1098 |
+
elif self.config.problem_type == "regression":
|
| 1099 |
+
loss_fct = MSELoss()
|
| 1100 |
+
if self.num_labels == 1:
|
| 1101 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1102 |
+
else:
|
| 1103 |
+
loss = loss_fct(logits, labels)
|
| 1104 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1105 |
+
loss_fct = CrossEntropyLoss()
|
| 1106 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1107 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1108 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1109 |
+
loss = loss_fct(logits, labels)
|
| 1110 |
+
if not return_dict:
|
| 1111 |
+
output = (logits,) + outputs[1:]
|
| 1112 |
+
return ((loss,) + output) if loss is not None else output
|
| 1113 |
+
|
| 1114 |
+
return SequenceClassifierOutput(
|
| 1115 |
+
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
@auto_docstring
|
| 1120 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForTokenClassification with Deberta->DebertaV2
|
| 1121 |
+
class DebertaV2ForTokenClassification(DebertaV2PreTrainedModel):
|
| 1122 |
+
def __init__(self, config):
|
| 1123 |
+
super().__init__(config)
|
| 1124 |
+
self.num_labels = config.num_labels
|
| 1125 |
+
|
| 1126 |
+
self.deberta = DebertaV2Model(config)
|
| 1127 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1128 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1129 |
+
|
| 1130 |
+
# Initialize weights and apply final processing
|
| 1131 |
+
self.post_init()
|
| 1132 |
+
|
| 1133 |
+
@auto_docstring
|
| 1134 |
+
def forward(
|
| 1135 |
+
self,
|
| 1136 |
+
input_ids: torch.Tensor | None = None,
|
| 1137 |
+
attention_mask: torch.Tensor | None = None,
|
| 1138 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1139 |
+
position_ids: torch.Tensor | None = None,
|
| 1140 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1141 |
+
labels: torch.Tensor | None = None,
|
| 1142 |
+
output_attentions: bool | None = None,
|
| 1143 |
+
output_hidden_states: bool | None = None,
|
| 1144 |
+
return_dict: bool | None = None,
|
| 1145 |
+
**kwargs,
|
| 1146 |
+
) -> tuple | TokenClassifierOutput:
|
| 1147 |
+
r"""
|
| 1148 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1149 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1150 |
+
"""
|
| 1151 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1152 |
+
|
| 1153 |
+
outputs = self.deberta(
|
| 1154 |
+
input_ids,
|
| 1155 |
+
attention_mask=attention_mask,
|
| 1156 |
+
token_type_ids=token_type_ids,
|
| 1157 |
+
position_ids=position_ids,
|
| 1158 |
+
inputs_embeds=inputs_embeds,
|
| 1159 |
+
output_attentions=output_attentions,
|
| 1160 |
+
output_hidden_states=output_hidden_states,
|
| 1161 |
+
return_dict=return_dict,
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
sequence_output = outputs[0]
|
| 1165 |
+
|
| 1166 |
+
sequence_output = self.dropout(sequence_output)
|
| 1167 |
+
logits = self.classifier(sequence_output)
|
| 1168 |
+
|
| 1169 |
+
loss = None
|
| 1170 |
+
if labels is not None:
|
| 1171 |
+
loss_fct = CrossEntropyLoss()
|
| 1172 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1173 |
+
|
| 1174 |
+
if not return_dict:
|
| 1175 |
+
output = (logits,) + outputs[1:]
|
| 1176 |
+
return ((loss,) + output) if loss is not None else output
|
| 1177 |
+
|
| 1178 |
+
return TokenClassifierOutput(
|
| 1179 |
+
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 1180 |
+
)
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
@auto_docstring
|
| 1184 |
+
class DebertaV2ForQuestionAnswering(DebertaV2PreTrainedModel):
|
| 1185 |
+
def __init__(self, config):
|
| 1186 |
+
super().__init__(config)
|
| 1187 |
+
self.num_labels = config.num_labels
|
| 1188 |
+
|
| 1189 |
+
self.deberta = DebertaV2Model(config)
|
| 1190 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1191 |
+
|
| 1192 |
+
# Initialize weights and apply final processing
|
| 1193 |
+
self.post_init()
|
| 1194 |
+
|
| 1195 |
+
@auto_docstring
|
| 1196 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForQuestionAnswering.forward with Deberta->DebertaV2
|
| 1197 |
+
def forward(
|
| 1198 |
+
self,
|
| 1199 |
+
input_ids: torch.Tensor | None = None,
|
| 1200 |
+
attention_mask: torch.Tensor | None = None,
|
| 1201 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1202 |
+
position_ids: torch.Tensor | None = None,
|
| 1203 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1204 |
+
start_positions: torch.Tensor | None = None,
|
| 1205 |
+
end_positions: torch.Tensor | None = None,
|
| 1206 |
+
output_attentions: bool | None = None,
|
| 1207 |
+
output_hidden_states: bool | None = None,
|
| 1208 |
+
return_dict: bool | None = None,
|
| 1209 |
+
**kwargs,
|
| 1210 |
+
) -> tuple | QuestionAnsweringModelOutput:
|
| 1211 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1212 |
+
|
| 1213 |
+
outputs = self.deberta(
|
| 1214 |
+
input_ids,
|
| 1215 |
+
attention_mask=attention_mask,
|
| 1216 |
+
token_type_ids=token_type_ids,
|
| 1217 |
+
position_ids=position_ids,
|
| 1218 |
+
inputs_embeds=inputs_embeds,
|
| 1219 |
+
output_attentions=output_attentions,
|
| 1220 |
+
output_hidden_states=output_hidden_states,
|
| 1221 |
+
return_dict=return_dict,
|
| 1222 |
+
)
|
| 1223 |
+
|
| 1224 |
+
sequence_output = outputs[0]
|
| 1225 |
+
|
| 1226 |
+
logits = self.qa_outputs(sequence_output)
|
| 1227 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1228 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1229 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1230 |
+
|
| 1231 |
+
total_loss = None
|
| 1232 |
+
if start_positions is not None and end_positions is not None:
|
| 1233 |
+
# If we are on multi-GPU, split add a dimension
|
| 1234 |
+
if len(start_positions.size()) > 1:
|
| 1235 |
+
start_positions = start_positions.squeeze(-1)
|
| 1236 |
+
if len(end_positions.size()) > 1:
|
| 1237 |
+
end_positions = end_positions.squeeze(-1)
|
| 1238 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1239 |
+
ignored_index = start_logits.size(1)
|
| 1240 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1241 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1242 |
+
|
| 1243 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1244 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1245 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1246 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1247 |
+
|
| 1248 |
+
if not return_dict:
|
| 1249 |
+
output = (start_logits, end_logits) + outputs[1:]
|
| 1250 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1251 |
+
|
| 1252 |
+
return QuestionAnsweringModelOutput(
|
| 1253 |
+
loss=total_loss,
|
| 1254 |
+
start_logits=start_logits,
|
| 1255 |
+
end_logits=end_logits,
|
| 1256 |
+
hidden_states=outputs.hidden_states,
|
| 1257 |
+
attentions=outputs.attentions,
|
| 1258 |
+
)
|
| 1259 |
+
|
| 1260 |
+
|
| 1261 |
+
@auto_docstring
|
| 1262 |
+
class DebertaV2ForMultipleChoice(DebertaV2PreTrainedModel):
|
| 1263 |
+
def __init__(self, config):
|
| 1264 |
+
super().__init__(config)
|
| 1265 |
+
|
| 1266 |
+
num_labels = getattr(config, "num_labels", 2)
|
| 1267 |
+
self.num_labels = num_labels
|
| 1268 |
+
|
| 1269 |
+
self.deberta = DebertaV2Model(config)
|
| 1270 |
+
self.pooler = ContextPooler(config)
|
| 1271 |
+
output_dim = self.pooler.output_dim
|
| 1272 |
+
|
| 1273 |
+
self.classifier = nn.Linear(output_dim, 1)
|
| 1274 |
+
drop_out = getattr(config, "cls_dropout", None)
|
| 1275 |
+
drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out
|
| 1276 |
+
self.dropout = nn.Dropout(drop_out)
|
| 1277 |
+
|
| 1278 |
+
self.post_init()
|
| 1279 |
+
|
| 1280 |
+
def get_input_embeddings(self):
|
| 1281 |
+
return self.deberta.get_input_embeddings()
|
| 1282 |
+
|
| 1283 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1284 |
+
self.deberta.set_input_embeddings(new_embeddings)
|
| 1285 |
+
|
| 1286 |
+
@auto_docstring
|
| 1287 |
+
def forward(
|
| 1288 |
+
self,
|
| 1289 |
+
input_ids: torch.Tensor | None = None,
|
| 1290 |
+
attention_mask: torch.Tensor | None = None,
|
| 1291 |
+
token_type_ids: torch.Tensor | None = None,
|
| 1292 |
+
position_ids: torch.Tensor | None = None,
|
| 1293 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1294 |
+
labels: torch.Tensor | None = None,
|
| 1295 |
+
output_attentions: bool | None = None,
|
| 1296 |
+
output_hidden_states: bool | None = None,
|
| 1297 |
+
return_dict: bool | None = None,
|
| 1298 |
+
**kwargs,
|
| 1299 |
+
) -> tuple | MultipleChoiceModelOutput:
|
| 1300 |
+
r"""
|
| 1301 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1302 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1303 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1304 |
+
`input_ids` above)
|
| 1305 |
+
"""
|
| 1306 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1307 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1308 |
+
|
| 1309 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1310 |
+
flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1311 |
+
flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1312 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1313 |
+
flat_inputs_embeds = (
|
| 1314 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1315 |
+
if inputs_embeds is not None
|
| 1316 |
+
else None
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
outputs = self.deberta(
|
| 1320 |
+
flat_input_ids,
|
| 1321 |
+
position_ids=flat_position_ids,
|
| 1322 |
+
token_type_ids=flat_token_type_ids,
|
| 1323 |
+
attention_mask=flat_attention_mask,
|
| 1324 |
+
inputs_embeds=flat_inputs_embeds,
|
| 1325 |
+
output_attentions=output_attentions,
|
| 1326 |
+
output_hidden_states=output_hidden_states,
|
| 1327 |
+
return_dict=return_dict,
|
| 1328 |
+
)
|
| 1329 |
+
|
| 1330 |
+
encoder_layer = outputs[0]
|
| 1331 |
+
pooled_output = self.pooler(encoder_layer)
|
| 1332 |
+
pooled_output = self.dropout(pooled_output)
|
| 1333 |
+
logits = self.classifier(pooled_output)
|
| 1334 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1335 |
+
|
| 1336 |
+
loss = None
|
| 1337 |
+
if labels is not None:
|
| 1338 |
+
loss_fct = CrossEntropyLoss()
|
| 1339 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1340 |
+
|
| 1341 |
+
if not return_dict:
|
| 1342 |
+
output = (reshaped_logits,) + outputs[1:]
|
| 1343 |
+
return ((loss,) + output) if loss is not None else output
|
| 1344 |
+
|
| 1345 |
+
return MultipleChoiceModelOutput(
|
| 1346 |
+
loss=loss,
|
| 1347 |
+
logits=reshaped_logits,
|
| 1348 |
+
hidden_states=outputs.hidden_states,
|
| 1349 |
+
attentions=outputs.attentions,
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
|
| 1353 |
+
__all__ = [
|
| 1354 |
+
"DebertaV2ForMaskedLM",
|
| 1355 |
+
"DebertaV2ForMultipleChoice",
|
| 1356 |
+
"DebertaV2ForQuestionAnswering",
|
| 1357 |
+
"DebertaV2ForSequenceClassification",
|
| 1358 |
+
"DebertaV2ForTokenClassification",
|
| 1359 |
+
"DebertaV2Model",
|
| 1360 |
+
"DebertaV2PreTrainedModel",
|
| 1361 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/deberta_v2/tokenization_deberta_v2.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Microsoft and the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Tokenization class for model DeBERTa-v2."""
|
| 15 |
+
|
| 16 |
+
from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
|
| 17 |
+
from tokenizers.models import Unigram
|
| 18 |
+
|
| 19 |
+
from ...tokenization_utils_tokenizers import TokenizersBackend
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spm.model", "tokenizer_file": "tokenizer.json"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DebertaV2Tokenizer(TokenizersBackend):
|
| 29 |
+
"""
|
| 30 |
+
Construct a DeBERTa-v2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on Unigram tokenization.
|
| 31 |
+
|
| 32 |
+
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
|
| 33 |
+
refer to this superclass for more information regarding those methods.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_file (`str`, *optional*):
|
| 37 |
+
Path to the vocabulary file (SentencePiece model file). Not used directly but kept for compatibility.
|
| 38 |
+
vocab (`str`, `dict` or `list`, *optional*):
|
| 39 |
+
List of tuples (piece, score) for the vocabulary.
|
| 40 |
+
precompiled_charsmap (`bytes`, *optional*):
|
| 41 |
+
Precompiled character map for normalization.
|
| 42 |
+
do_lower_case (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether or not to lowercase the input when tokenizing.
|
| 44 |
+
split_by_punct (`bool`, *optional*, defaults to `False`):
|
| 45 |
+
Whether to split by punctuation.
|
| 46 |
+
bos_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 47 |
+
The beginning of sequence token.
|
| 48 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 49 |
+
The end of sequence token.
|
| 50 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 51 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 52 |
+
token instead.
|
| 53 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 54 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 55 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 56 |
+
token of a sequence built with special tokens.
|
| 57 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 58 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 59 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 60 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 61 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 62 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 63 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 64 |
+
modeling. This is the token which the model will try to predict.
|
| 65 |
+
add_prefix_space (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 67 |
+
other word.
|
| 68 |
+
unk_id (`int`, *optional*, defaults to index of `unk_token` in vocab):
|
| 69 |
+
The ID of the unknown token in the vocabulary.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 73 |
+
model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
|
| 74 |
+
model = Unigram
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
vocab: str | dict | list | None = None,
|
| 79 |
+
do_lower_case=False,
|
| 80 |
+
split_by_punct=False,
|
| 81 |
+
bos_token="[CLS]",
|
| 82 |
+
eos_token="[SEP]",
|
| 83 |
+
unk_token="[UNK]",
|
| 84 |
+
sep_token="[SEP]",
|
| 85 |
+
pad_token="[PAD]",
|
| 86 |
+
cls_token="[CLS]",
|
| 87 |
+
mask_token="[MASK]",
|
| 88 |
+
add_prefix_space=True,
|
| 89 |
+
unk_id=1,
|
| 90 |
+
**kwargs,
|
| 91 |
+
):
|
| 92 |
+
self.do_lower_case = do_lower_case
|
| 93 |
+
self.split_by_punct = split_by_punct
|
| 94 |
+
self.add_prefix_space = add_prefix_space
|
| 95 |
+
|
| 96 |
+
if vocab is None:
|
| 97 |
+
vocab = [
|
| 98 |
+
(str(pad_token), 0.0),
|
| 99 |
+
(str(unk_token), 0.0),
|
| 100 |
+
(str(bos_token), 0.0),
|
| 101 |
+
(str(eos_token), 0.0),
|
| 102 |
+
(str(sep_token), 0.0),
|
| 103 |
+
(str(cls_token), 0.0),
|
| 104 |
+
(str(mask_token), 0.0),
|
| 105 |
+
]
|
| 106 |
+
unk_id = 1
|
| 107 |
+
elif isinstance(vocab, list):
|
| 108 |
+
unk_id = vocab.index((str(unk_token), 0.0)) if (str(unk_token), 0.0) in vocab else unk_id
|
| 109 |
+
|
| 110 |
+
self._vocab = vocab
|
| 111 |
+
self._tokenizer = Tokenizer(
|
| 112 |
+
Unigram(
|
| 113 |
+
self._vocab,
|
| 114 |
+
unk_id=unk_id,
|
| 115 |
+
byte_fallback=False,
|
| 116 |
+
)
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
list_normalizers = []
|
| 120 |
+
if do_lower_case:
|
| 121 |
+
list_normalizers.append(normalizers.Lowercase())
|
| 122 |
+
|
| 123 |
+
list_normalizers.extend(
|
| 124 |
+
[
|
| 125 |
+
normalizers.Replace(Regex(r"\s{2,}|[\n\r\t]"), " "),
|
| 126 |
+
normalizers.NFC(),
|
| 127 |
+
normalizers.Strip(left=False, right=True),
|
| 128 |
+
]
|
| 129 |
+
)
|
| 130 |
+
self._tokenizer.normalizer = normalizers.Sequence(list_normalizers)
|
| 131 |
+
|
| 132 |
+
list_pretokenizers = []
|
| 133 |
+
if split_by_punct:
|
| 134 |
+
list_pretokenizers.append(pre_tokenizers.Punctuation(behavior="isolated"))
|
| 135 |
+
|
| 136 |
+
prepend_scheme = "always" if add_prefix_space else "first"
|
| 137 |
+
list_pretokenizers.append(pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme))
|
| 138 |
+
|
| 139 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(list_pretokenizers)
|
| 140 |
+
self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
|
| 141 |
+
super().__init__(
|
| 142 |
+
bos_token=bos_token,
|
| 143 |
+
eos_token=eos_token,
|
| 144 |
+
unk_token=unk_token,
|
| 145 |
+
sep_token=sep_token,
|
| 146 |
+
cls_token=cls_token,
|
| 147 |
+
pad_token=pad_token,
|
| 148 |
+
mask_token=mask_token,
|
| 149 |
+
unk_id=unk_id,
|
| 150 |
+
do_lower_case=do_lower_case,
|
| 151 |
+
split_by_punct=split_by_punct,
|
| 152 |
+
add_prefix_space=add_prefix_space,
|
| 153 |
+
**kwargs,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
cls_token_id = self.cls_token_id if self.cls_token_id is not None else 0
|
| 157 |
+
sep_token_id = self.sep_token_id if self.sep_token_id is not None else 0
|
| 158 |
+
|
| 159 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 160 |
+
single=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0",
|
| 161 |
+
pair=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1",
|
| 162 |
+
special_tokens=[
|
| 163 |
+
(str(self.cls_token), cls_token_id),
|
| 164 |
+
(str(self.sep_token), sep_token_id),
|
| 165 |
+
],
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
__all__ = ["DebertaV2Tokenizer"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 TII and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_falcon_h1 import *
|
| 22 |
+
from .modeling_falcon_h1 import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/configuration_falcon_h1.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 TII and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""FalconH1 model configuration"""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...modeling_rope_utils import RopeParameters
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@auto_docstring(checkpoint="tiiuae/Falcon-H1-1.5B-Deep-Instruct")
|
| 24 |
+
@strict
|
| 25 |
+
class FalconH1Config(PreTrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
|
| 28 |
+
Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
|
| 29 |
+
integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
|
| 30 |
+
logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
|
| 31 |
+
sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
|
| 32 |
+
significantly.
|
| 33 |
+
projectors_bias (`bool`, *optional*, defaults to `False`):
|
| 34 |
+
Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the attention block
|
| 35 |
+
lm_head_multiplier (`float`, *optional*, defaults to 1.0):
|
| 36 |
+
The multiplier for the LM head. This is used to scale the output of the LM head.
|
| 37 |
+
embedding_multiplier (`float`, *optional*, defaults to 1.0):
|
| 38 |
+
The multiplier for the embedding layer. This is used to scale the output of the embedding layer.
|
| 39 |
+
mlp_multipliers (`list[float]`, *optional*):
|
| 40 |
+
The multipliers for the MLP layers. This is used to scale the output of the MLP layers. The first value is
|
| 41 |
+
the multiplier of gate layer, the second value is the multiplier of the down_proj layer.
|
| 42 |
+
key_multiplier (`float`, *optional*):
|
| 43 |
+
The multiplier for the key layer. This is used to scale the output of the key layer.
|
| 44 |
+
attention_out_multiplier (`float`, *optional*):
|
| 45 |
+
The multiplier for the attention output layer. This is used to scale the output of the attention output
|
| 46 |
+
attention_in_multiplier (`float`, *optional*):
|
| 47 |
+
The multiplier for the attention input layer. This is used to scale the output of the attention input layer.
|
| 48 |
+
ssm_multipliers (`list[float]`, *optional*):
|
| 49 |
+
The multipliers for the SSM layers. This is used to scale the output of the SSM layers.
|
| 50 |
+
ssm_in_multiplier (`float`, *optional*):
|
| 51 |
+
The multiplier for the SSM input layer. This is used to scale the output of the SSM input layer.
|
| 52 |
+
ssm_out_multiplier (`float`, *optional*):
|
| 53 |
+
The multiplier for the SSM output layer. This is used to scale the output of the SSM output layer.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
model_type = "falcon_h1"
|
| 57 |
+
attribute_map = {"layer_types": "layers_block_type"}
|
| 58 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 59 |
+
|
| 60 |
+
vocab_size: int = 128000
|
| 61 |
+
tie_word_embeddings: bool = False
|
| 62 |
+
hidden_size: int = 4096
|
| 63 |
+
intermediate_size: int = 14336
|
| 64 |
+
num_hidden_layers: int = 32
|
| 65 |
+
num_attention_heads: int = 32
|
| 66 |
+
num_key_value_heads: int | None = 8
|
| 67 |
+
hidden_act: str = "silu"
|
| 68 |
+
initializer_range: float = 0.02
|
| 69 |
+
rms_norm_eps: float = 1e-5
|
| 70 |
+
use_cache: bool | None = True
|
| 71 |
+
num_logits_to_keep: int | None = 1
|
| 72 |
+
pad_token_id: int | None = 0
|
| 73 |
+
bos_token_id: int | None = 1
|
| 74 |
+
eos_token_id: int | list[int] | None = 2
|
| 75 |
+
max_position_embeddings: int = 8192
|
| 76 |
+
attention_dropout: float | int | None = 0.0
|
| 77 |
+
mamba_d_ssm: int | None = 1024
|
| 78 |
+
mamba_n_heads: int | None = 128
|
| 79 |
+
mamba_d_head: str | int | None = "auto"
|
| 80 |
+
mamba_n_groups: int | None = 1
|
| 81 |
+
mamba_d_state: int | None = 256
|
| 82 |
+
mamba_d_conv: int | None = 4
|
| 83 |
+
mamba_expand: int | None = 2
|
| 84 |
+
mamba_chunk_size: int | None = 256
|
| 85 |
+
mamba_conv_bias: bool | None = True
|
| 86 |
+
mamba_proj_bias: bool | None = False
|
| 87 |
+
mamba_norm_before_gate: bool | None = True
|
| 88 |
+
mamba_rms_norm: bool | None = False
|
| 89 |
+
time_step_min: float | None = 0.001
|
| 90 |
+
time_step_max: float | None = 0.1
|
| 91 |
+
time_step_limit: list[float, float] | tuple[float, float] | None = (0.0, float("inf"))
|
| 92 |
+
projectors_bias: bool | None = False
|
| 93 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 94 |
+
lm_head_multiplier: float | None = 1.0
|
| 95 |
+
embedding_multiplier: float | None = 1.0
|
| 96 |
+
mlp_multipliers: list[float] | None = None
|
| 97 |
+
key_multiplier: float | None = 1.0
|
| 98 |
+
attention_out_multiplier: float | None = 1.0
|
| 99 |
+
attention_in_multiplier: float | None = 1.0
|
| 100 |
+
ssm_multipliers: list[float] | None = None
|
| 101 |
+
ssm_in_multiplier: float | None = 1.0
|
| 102 |
+
ssm_out_multiplier: float | None = 1.0
|
| 103 |
+
attention_bias: bool = False
|
| 104 |
+
mlp_bias: bool = False
|
| 105 |
+
|
| 106 |
+
def __post_init__(self, **kwargs):
|
| 107 |
+
if self.num_key_value_heads is None:
|
| 108 |
+
self.num_key_value_heads = self.num_attention_heads
|
| 109 |
+
|
| 110 |
+
# for the mamba_v2, must satisfy the following
|
| 111 |
+
mamba_intermediate = self.mamba_expand * self.hidden_size if self.mamba_d_ssm is None else self.mamba_d_ssm
|
| 112 |
+
if self.mamba_d_head == "auto":
|
| 113 |
+
self.mamba_d_head = mamba_intermediate // self.mamba_n_heads
|
| 114 |
+
|
| 115 |
+
self.time_step_limit = tuple(self.time_step_limit) if self.time_step_limit is not None else None
|
| 116 |
+
if self.mlp_multipliers is None:
|
| 117 |
+
self.mlp_multipliers = [1.0, 1.0]
|
| 118 |
+
|
| 119 |
+
if self.ssm_multipliers is None:
|
| 120 |
+
self.ssm_multipliers = [1.0, 1.0, 1.0, 1.0, 1.0]
|
| 121 |
+
|
| 122 |
+
super().__post_init__(**kwargs)
|
| 123 |
+
|
| 124 |
+
def validate_architecture(self):
|
| 125 |
+
"""Part of `@strict`-powered validation. Validates the architecture of the config."""
|
| 126 |
+
mamba_intermediate = self.mamba_expand * self.hidden_size if self.mamba_d_ssm is None else self.mamba_d_ssm
|
| 127 |
+
|
| 128 |
+
if mamba_intermediate % self.mamba_n_heads != 0:
|
| 129 |
+
raise ValueError("mamba_n_heads must divide mamba_expand * hidden_size")
|
| 130 |
+
|
| 131 |
+
if self.mamba_d_head * self.mamba_n_heads != mamba_intermediate:
|
| 132 |
+
raise ValueError("The dimensions for the Mamba head state do not match the model intermediate_size")
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def layers_block_type(self):
|
| 136 |
+
return ["hybrid" for i in range(self.num_hidden_layers)]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
__all__ = ["FalconH1Config"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/modeling_falcon_h1.py
ADDED
|
@@ -0,0 +1,1265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/falcon_h1/modular_falcon_h1.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_falcon_h1.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2025 Technology Innovation Institute and the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 10 |
+
# and OPT implementations in this library. It has been modified from its
|
| 11 |
+
# original forms to accommodate minor architectural differences compared
|
| 12 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 13 |
+
#
|
| 14 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 15 |
+
# you may not use this file except in compliance with the License.
|
| 16 |
+
# You may obtain a copy of the License at
|
| 17 |
+
#
|
| 18 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 19 |
+
#
|
| 20 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 21 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 22 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 23 |
+
# See the License for the specific language governing permissions and
|
| 24 |
+
# limitations under the License.
|
| 25 |
+
|
| 26 |
+
from collections.abc import Callable
|
| 27 |
+
from typing import Optional
|
| 28 |
+
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
from torch import nn
|
| 32 |
+
|
| 33 |
+
from ... import initialization as init
|
| 34 |
+
from ...activations import ACT2FN
|
| 35 |
+
from ...cache_utils import Cache, DynamicCache
|
| 36 |
+
from ...generation import GenerationMixin
|
| 37 |
+
from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
|
| 38 |
+
from ...integrations.hub_kernels import lazy_load_kernel
|
| 39 |
+
from ...masking_utils import create_causal_mask
|
| 40 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 41 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 42 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 43 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 44 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 45 |
+
from ...processing_utils import Unpack
|
| 46 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
|
| 47 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 48 |
+
from ...utils.import_utils import resolve_internal_import
|
| 49 |
+
from ...utils.output_capturing import capture_outputs
|
| 50 |
+
from .configuration_falcon_h1 import FalconH1Config
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class FalconH1RotaryEmbedding(nn.Module):
|
| 57 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 58 |
+
|
| 59 |
+
def __init__(self, config: FalconH1Config, device=None):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 62 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 63 |
+
|
| 64 |
+
self.config = config
|
| 65 |
+
|
| 66 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 67 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 68 |
+
if self.rope_type != "default":
|
| 69 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 70 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 71 |
+
|
| 72 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 73 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def compute_default_rope_parameters(
|
| 77 |
+
config: FalconH1Config | None = None,
|
| 78 |
+
device: Optional["torch.device"] = None,
|
| 79 |
+
seq_len: int | None = None,
|
| 80 |
+
) -> tuple["torch.Tensor", float]:
|
| 81 |
+
"""
|
| 82 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 83 |
+
Args:
|
| 84 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 85 |
+
The model configuration.
|
| 86 |
+
device (`torch.device`):
|
| 87 |
+
The device to use for initialization of the inverse frequencies.
|
| 88 |
+
seq_len (`int`, *optional*):
|
| 89 |
+
The current sequence length. Unused for this type of RoPE.
|
| 90 |
+
Returns:
|
| 91 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 92 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 93 |
+
"""
|
| 94 |
+
base = config.rope_parameters["rope_theta"]
|
| 95 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 96 |
+
|
| 97 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 98 |
+
|
| 99 |
+
# Compute the inverse frequencies
|
| 100 |
+
inv_freq = 1.0 / (
|
| 101 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 102 |
+
)
|
| 103 |
+
return inv_freq, attention_factor
|
| 104 |
+
|
| 105 |
+
@torch.no_grad()
|
| 106 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 107 |
+
def forward(self, x, position_ids):
|
| 108 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 109 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 110 |
+
|
| 111 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 112 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 113 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 114 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 115 |
+
cos = emb.cos() * self.attention_scaling
|
| 116 |
+
sin = emb.sin() * self.attention_scaling
|
| 117 |
+
|
| 118 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def rotate_half(x):
|
| 122 |
+
"""Rotates half the hidden dims of the input."""
|
| 123 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 124 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 125 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@use_kernel_func_from_hub("rotary_pos_emb")
|
| 129 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 130 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
q (`torch.Tensor`): The query tensor.
|
| 134 |
+
k (`torch.Tensor`): The key tensor.
|
| 135 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 136 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 137 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 138 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 139 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 140 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 141 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 142 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 143 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 144 |
+
Returns:
|
| 145 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 146 |
+
"""
|
| 147 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 148 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 149 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 150 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 151 |
+
return q_embed, k_embed
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 155 |
+
"""
|
| 156 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 157 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 158 |
+
"""
|
| 159 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 160 |
+
if n_rep == 1:
|
| 161 |
+
return hidden_states
|
| 162 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 163 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def eager_attention_forward(
|
| 167 |
+
module: nn.Module,
|
| 168 |
+
query: torch.Tensor,
|
| 169 |
+
key: torch.Tensor,
|
| 170 |
+
value: torch.Tensor,
|
| 171 |
+
attention_mask: torch.Tensor | None,
|
| 172 |
+
scaling: float,
|
| 173 |
+
dropout: float = 0.0,
|
| 174 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 175 |
+
):
|
| 176 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 177 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 178 |
+
|
| 179 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 180 |
+
if attention_mask is not None:
|
| 181 |
+
attn_weights = attn_weights + attention_mask
|
| 182 |
+
|
| 183 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 184 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 185 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 186 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 187 |
+
|
| 188 |
+
return attn_output, attn_weights
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 192 |
+
class FalconH1Attention(nn.Module):
|
| 193 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 194 |
+
|
| 195 |
+
def __init__(self, config: FalconH1Config, layer_idx: int):
|
| 196 |
+
super().__init__()
|
| 197 |
+
self.config = config
|
| 198 |
+
self.layer_idx = layer_idx
|
| 199 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 200 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 201 |
+
self.scaling = self.head_dim**-0.5
|
| 202 |
+
self.attention_dropout = config.attention_dropout
|
| 203 |
+
self.is_causal = True
|
| 204 |
+
|
| 205 |
+
self.q_proj = nn.Linear(
|
| 206 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 207 |
+
)
|
| 208 |
+
self.k_proj = nn.Linear(
|
| 209 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 210 |
+
)
|
| 211 |
+
self.v_proj = nn.Linear(
|
| 212 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 213 |
+
)
|
| 214 |
+
self.o_proj = nn.Linear(
|
| 215 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 216 |
+
)
|
| 217 |
+
self.key_multiplier = config.key_multiplier
|
| 218 |
+
|
| 219 |
+
def forward(
|
| 220 |
+
self,
|
| 221 |
+
hidden_states: torch.Tensor,
|
| 222 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 223 |
+
attention_mask: torch.Tensor | None,
|
| 224 |
+
past_key_values: Cache | None = None,
|
| 225 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 226 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 227 |
+
input_shape = hidden_states.shape[:-1]
|
| 228 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 229 |
+
|
| 230 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 231 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) * self.key_multiplier
|
| 232 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 233 |
+
|
| 234 |
+
cos, sin = position_embeddings
|
| 235 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 236 |
+
|
| 237 |
+
if past_key_values is not None:
|
| 238 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 239 |
+
|
| 240 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 241 |
+
self.config._attn_implementation, eager_attention_forward
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
attn_output, attn_weights = attention_interface(
|
| 245 |
+
self,
|
| 246 |
+
query_states,
|
| 247 |
+
key_states,
|
| 248 |
+
value_states,
|
| 249 |
+
attention_mask,
|
| 250 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 251 |
+
scaling=self.scaling,
|
| 252 |
+
**kwargs,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 256 |
+
attn_output = self.o_proj(attn_output)
|
| 257 |
+
return attn_output, attn_weights
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class FalconH1RMSNormGated(torch.nn.Module):
|
| 261 |
+
def __init__(self, hidden_size, eps=1e-6, n_groups=1, norm_before_gate=True):
|
| 262 |
+
super().__init__()
|
| 263 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 264 |
+
self.variance_epsilon = eps
|
| 265 |
+
self.n_groups = n_groups
|
| 266 |
+
self.norm_before_gate = norm_before_gate
|
| 267 |
+
|
| 268 |
+
def forward(self, hidden_states, gate=None):
|
| 269 |
+
input_dtype = hidden_states.dtype
|
| 270 |
+
|
| 271 |
+
if not self.norm_before_gate and gate is not None:
|
| 272 |
+
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
|
| 273 |
+
|
| 274 |
+
if len(hidden_states.shape) == 3:
|
| 275 |
+
batch_size, seq_len, dim = hidden_states.shape
|
| 276 |
+
else:
|
| 277 |
+
batch_size, dim = hidden_states.shape
|
| 278 |
+
seq_len = 1
|
| 279 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 280 |
+
|
| 281 |
+
hidden_states = hidden_states.view(batch_size, seq_len, self.n_groups, int(dim // self.n_groups))
|
| 282 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 283 |
+
|
| 284 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 285 |
+
|
| 286 |
+
hidden_states = self.weight.view(self.n_groups, int(dim // self.n_groups)) * hidden_states
|
| 287 |
+
hidden_states = hidden_states.view(batch_size, seq_len, dim)
|
| 288 |
+
|
| 289 |
+
if seq_len == 1:
|
| 290 |
+
hidden_states = hidden_states.squeeze(1)
|
| 291 |
+
|
| 292 |
+
if self.norm_before_gate and gate is not None:
|
| 293 |
+
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
|
| 294 |
+
return hidden_states.to(input_dtype)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# Helper methods for segment sum computation
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
|
| 301 |
+
"""
|
| 302 |
+
Padding x tensor with `pad_size` on the seq_len dim (dim=1)
|
| 303 |
+
|
| 304 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 305 |
+
"""
|
| 306 |
+
pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
|
| 307 |
+
|
| 308 |
+
return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def reshape_into_chunks(input_tensor, pad_size, chunk_size):
|
| 312 |
+
"""
|
| 313 |
+
Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
|
| 314 |
+
simultaneously splitting it into chunk sequences.
|
| 315 |
+
|
| 316 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 317 |
+
"""
|
| 318 |
+
# [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
|
| 319 |
+
input_tensor = pad_tensor_by_size(input_tensor, pad_size)
|
| 320 |
+
|
| 321 |
+
if len(input_tensor.shape) == 3:
|
| 322 |
+
# [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
|
| 323 |
+
return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
|
| 324 |
+
else:
|
| 325 |
+
# [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
|
| 326 |
+
return input_tensor.reshape(
|
| 327 |
+
input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def segment_sum(input_tensor):
|
| 332 |
+
"""
|
| 333 |
+
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
|
| 334 |
+
"""
|
| 335 |
+
chunk_size = input_tensor.size(-1)
|
| 336 |
+
# 1. expand input tensor to have an additional dimension and repeat along that dimension
|
| 337 |
+
# [..., chunk_size] -> [..., chunk_size, chunk_size]
|
| 338 |
+
input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
|
| 339 |
+
# 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
|
| 340 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
|
| 341 |
+
input_tensor = input_tensor.masked_fill(~mask, 0)
|
| 342 |
+
# 3. compute actual cumsum
|
| 343 |
+
tensor_segsum = torch.cumsum(input_tensor, dim=-2)
|
| 344 |
+
|
| 345 |
+
# 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
|
| 346 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
|
| 347 |
+
tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
|
| 348 |
+
return tensor_segsum
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def apply_mask_to_padding_states(hidden_states, attention_mask):
|
| 352 |
+
"""
|
| 353 |
+
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 354 |
+
"""
|
| 355 |
+
# NOTE: attention mask is a 2D boolean tensor
|
| 356 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 357 |
+
dtype = hidden_states.dtype
|
| 358 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 359 |
+
|
| 360 |
+
return hidden_states
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
|
| 364 |
+
class FalconH1Mixer(nn.Module):
|
| 365 |
+
"""
|
| 366 |
+
FalconH1Mixer is identical to classic Mamba2 mixer classes but differs on two different things
|
| 367 |
+
- Users can pass custom intermediate_size through `config.mamba_d_ssm`
|
| 368 |
+
- The use of gated RMS normalization layer is optional
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
def __init__(self, config: FalconH1Config, layer_idx: int):
|
| 372 |
+
super().__init__()
|
| 373 |
+
self.num_heads = config.mamba_n_heads
|
| 374 |
+
self.hidden_size = config.hidden_size
|
| 375 |
+
self.ssm_state_size = config.mamba_d_state
|
| 376 |
+
self.conv_kernel_size = config.mamba_d_conv
|
| 377 |
+
self.intermediate_size = (
|
| 378 |
+
int(config.mamba_expand * self.hidden_size) if config.mamba_d_ssm is None else config.mamba_d_ssm
|
| 379 |
+
)
|
| 380 |
+
self.layer_idx = layer_idx
|
| 381 |
+
self.use_conv_bias = config.mamba_conv_bias
|
| 382 |
+
self.activation = config.hidden_act
|
| 383 |
+
self.act = ACT2FN[config.hidden_act]
|
| 384 |
+
self.use_bias = config.mamba_proj_bias
|
| 385 |
+
|
| 386 |
+
self.layer_norm_epsilon = config.rms_norm_eps
|
| 387 |
+
self.groups_time_state_size = config.mamba_n_groups * self.ssm_state_size
|
| 388 |
+
|
| 389 |
+
self.n_groups = config.mamba_n_groups
|
| 390 |
+
self.head_dim = config.mamba_d_head
|
| 391 |
+
self.chunk_size = config.mamba_chunk_size
|
| 392 |
+
|
| 393 |
+
self.time_step_limit = config.time_step_limit
|
| 394 |
+
self.time_step_min = config.time_step_min
|
| 395 |
+
self.time_step_max = config.time_step_max
|
| 396 |
+
|
| 397 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 398 |
+
self.conv1d = nn.Conv1d(
|
| 399 |
+
in_channels=self.conv_dim,
|
| 400 |
+
out_channels=self.conv_dim,
|
| 401 |
+
bias=config.mamba_conv_bias,
|
| 402 |
+
kernel_size=self.conv_kernel_size,
|
| 403 |
+
groups=self.conv_dim,
|
| 404 |
+
padding=self.conv_kernel_size - 1,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
# projection of the input hidden states
|
| 408 |
+
projection_size = self.intermediate_size + self.conv_dim + self.num_heads
|
| 409 |
+
self.in_proj = nn.Linear(
|
| 410 |
+
self.hidden_size,
|
| 411 |
+
projection_size,
|
| 412 |
+
bias=self.use_bias,
|
| 413 |
+
)
|
| 414 |
+
# selective projection used to make dt, B and C input dependant
|
| 415 |
+
|
| 416 |
+
# time step projection (discretization)
|
| 417 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 418 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 419 |
+
|
| 420 |
+
# S4D real initialization. These are not discretized!
|
| 421 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 422 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 423 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 424 |
+
self.mamba_rms_norm = config.mamba_rms_norm
|
| 425 |
+
|
| 426 |
+
if self.mamba_rms_norm:
|
| 427 |
+
self.norm = FalconH1RMSNormGated(
|
| 428 |
+
self.intermediate_size,
|
| 429 |
+
eps=self.layer_norm_epsilon,
|
| 430 |
+
n_groups=self.n_groups,
|
| 431 |
+
norm_before_gate=config.mamba_norm_before_gate,
|
| 432 |
+
)
|
| 433 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 434 |
+
|
| 435 |
+
self.out_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=config.projectors_bias)
|
| 436 |
+
|
| 437 |
+
global causal_conv1d_update, causal_conv1d_fn
|
| 438 |
+
causal_conv1d = lazy_load_kernel("causal-conv1d")
|
| 439 |
+
causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
|
| 440 |
+
causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
|
| 441 |
+
|
| 442 |
+
global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
|
| 443 |
+
mamba_ssm = lazy_load_kernel("mamba-ssm")
|
| 444 |
+
selective_state_update = resolve_internal_import(
|
| 445 |
+
mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
|
| 446 |
+
)
|
| 447 |
+
mamba_chunk_scan_combined = resolve_internal_import(
|
| 448 |
+
mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
|
| 449 |
+
)
|
| 450 |
+
mamba_split_conv1d_scan_combined = resolve_internal_import(
|
| 451 |
+
mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
global is_fast_path_available
|
| 455 |
+
is_fast_path_available = all(
|
| 456 |
+
(
|
| 457 |
+
selective_state_update,
|
| 458 |
+
mamba_chunk_scan_combined,
|
| 459 |
+
mamba_split_conv1d_scan_combined,
|
| 460 |
+
causal_conv1d_fn,
|
| 461 |
+
causal_conv1d_update,
|
| 462 |
+
)
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
if not is_fast_path_available:
|
| 466 |
+
logger.warning_once(
|
| 467 |
+
"The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
|
| 468 |
+
" is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 469 |
+
" https://github.com/Dao-AILab/causal-conv1d"
|
| 470 |
+
)
|
| 471 |
+
else:
|
| 472 |
+
logger.warning_once("The fast path for FalconH1 will be used when running the model on a GPU")
|
| 473 |
+
|
| 474 |
+
self.zxbcdt_multipliers = config.ssm_multipliers
|
| 475 |
+
self.ssm_in_multiplier = config.ssm_in_multiplier
|
| 476 |
+
|
| 477 |
+
def cuda_kernels_forward(
|
| 478 |
+
self,
|
| 479 |
+
hidden_states: torch.Tensor,
|
| 480 |
+
cache_params: Cache | None = None,
|
| 481 |
+
attention_mask: torch.Tensor | None = None,
|
| 482 |
+
):
|
| 483 |
+
# 1. Gated MLP's linear projection
|
| 484 |
+
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 485 |
+
# Add Multipliers
|
| 486 |
+
hidden_states = hidden_states * self.ssm_in_multiplier
|
| 487 |
+
projected_states = self.in_proj(hidden_states)
|
| 488 |
+
projected_states = projected_states * self.mup_vector # ADD Mup Multipliers
|
| 489 |
+
d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
|
| 490 |
+
|
| 491 |
+
# Set up dimensions for reshapes later
|
| 492 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 493 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 494 |
+
|
| 495 |
+
use_precomputed_states = (
|
| 496 |
+
cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
# getting projected states from cache if it exists
|
| 500 |
+
if use_precomputed_states:
|
| 501 |
+
d_mlp = (projected_states.squeeze(1).shape[-1] - d_to_remove) // 2
|
| 502 |
+
|
| 503 |
+
z0, x0, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
|
| 504 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# 2. Convolution sequence transformation
|
| 508 |
+
hidden_states_B_C = causal_conv1d_update(
|
| 509 |
+
hidden_states_B_C,
|
| 510 |
+
cache_params.layers[self.layer_idx].conv_states,
|
| 511 |
+
self.conv1d.weight.squeeze(1),
|
| 512 |
+
self.conv1d.bias,
|
| 513 |
+
self.activation,
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
hidden_states, B, C = torch.split(
|
| 517 |
+
hidden_states_B_C,
|
| 518 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 519 |
+
dim=-1,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# 3. SSM transformation
|
| 523 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 524 |
+
A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 525 |
+
dt = dt[:, :, None].expand(-1, -1, self.head_dim)
|
| 526 |
+
dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
|
| 527 |
+
D = self.D[:, None, ...].expand(-1, self.head_dim)
|
| 528 |
+
B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
|
| 529 |
+
C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
|
| 530 |
+
hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
|
| 531 |
+
hidden_states = selective_state_update(
|
| 532 |
+
cache_params.layers[self.layer_idx].recurrent_states,
|
| 533 |
+
hidden_states_reshaped,
|
| 534 |
+
dt,
|
| 535 |
+
A,
|
| 536 |
+
B,
|
| 537 |
+
C,
|
| 538 |
+
D,
|
| 539 |
+
z=gate.view(batch_size, self.num_heads, self.head_dim) if not self.mamba_rms_norm else None,
|
| 540 |
+
dt_bias=dt_bias,
|
| 541 |
+
dt_softplus=True,
|
| 542 |
+
)
|
| 543 |
+
hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
|
| 544 |
+
|
| 545 |
+
if self.mamba_rms_norm:
|
| 546 |
+
hidden_states = self.norm(hidden_states, gate)
|
| 547 |
+
|
| 548 |
+
if d_mlp > 0:
|
| 549 |
+
hidden_states = torch.cat([F.silu(z0) * x0, hidden_states], dim=-1)
|
| 550 |
+
|
| 551 |
+
# 4. Final linear projection
|
| 552 |
+
out = self.out_proj(hidden_states[:, None, ...])
|
| 553 |
+
# Fused calculations or step by step if no initialized cache is found
|
| 554 |
+
else:
|
| 555 |
+
A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
|
| 556 |
+
dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
|
| 557 |
+
|
| 558 |
+
# 2-4. Fused kernel for conv1d, SSM, and the final projection
|
| 559 |
+
if self.training and cache_params is None:
|
| 560 |
+
out = mamba_split_conv1d_scan_combined(
|
| 561 |
+
projected_states,
|
| 562 |
+
self.conv1d.weight.squeeze(1),
|
| 563 |
+
self.conv1d.bias,
|
| 564 |
+
self.dt_bias,
|
| 565 |
+
A,
|
| 566 |
+
D=self.D,
|
| 567 |
+
chunk_size=self.chunk_size,
|
| 568 |
+
seq_idx=None, # was seq_idx
|
| 569 |
+
activation=self.activation,
|
| 570 |
+
rmsnorm_weight=self.norm.weight if self.mamba_rms_norm else None,
|
| 571 |
+
rmsnorm_eps=self.norm.variance_epsilon if self.mamba_rms_norm else None,
|
| 572 |
+
outproj_weight=self.out_proj.weight,
|
| 573 |
+
outproj_bias=self.out_proj.bias,
|
| 574 |
+
headdim=self.head_dim,
|
| 575 |
+
ngroups=self.n_groups,
|
| 576 |
+
norm_before_gate=False,
|
| 577 |
+
return_final_states=False,
|
| 578 |
+
**dt_limit_kwargs,
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
else:
|
| 582 |
+
d_mlp = (
|
| 583 |
+
projected_states.shape[-1]
|
| 584 |
+
- 2 * self.intermediate_size
|
| 585 |
+
- 2 * self.n_groups * self.ssm_state_size
|
| 586 |
+
- self.num_heads
|
| 587 |
+
) // 2
|
| 588 |
+
if attention_mask is not None:
|
| 589 |
+
projected_states = projected_states * attention_mask[..., None]
|
| 590 |
+
_, gate, hidden_states_B_C, dt = projected_states.split(
|
| 591 |
+
[
|
| 592 |
+
2 * d_mlp,
|
| 593 |
+
self.intermediate_size,
|
| 594 |
+
self.conv_dim,
|
| 595 |
+
self.num_heads,
|
| 596 |
+
],
|
| 597 |
+
dim=-1,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
if cache_params is not None:
|
| 601 |
+
conv_states = F.pad(
|
| 602 |
+
hidden_states_B_C.permute(0, 2, 1),
|
| 603 |
+
(self.conv_kernel_size - hidden_states_B_C.shape[-2], 0),
|
| 604 |
+
)
|
| 605 |
+
conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
|
| 606 |
+
|
| 607 |
+
time_step = nn.functional.softplus(dt + self.dt_bias)
|
| 608 |
+
# 1D Convolution
|
| 609 |
+
if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
|
| 610 |
+
hidden_states_B_C = self.act(
|
| 611 |
+
self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
|
| 612 |
+
) # (B, L, self.d_inner + 2 * ngroups * d_state)
|
| 613 |
+
else:
|
| 614 |
+
hidden_states_B_C = causal_conv1d_fn(
|
| 615 |
+
x=hidden_states_B_C.transpose(1, 2),
|
| 616 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 617 |
+
bias=self.conv1d.bias,
|
| 618 |
+
activation=self.activation,
|
| 619 |
+
).transpose(1, 2)[:, :seq_len]
|
| 620 |
+
|
| 621 |
+
hidden_states, B, C = torch.split(
|
| 622 |
+
hidden_states_B_C,
|
| 623 |
+
[
|
| 624 |
+
self.intermediate_size,
|
| 625 |
+
groups_time_state_size,
|
| 626 |
+
groups_time_state_size,
|
| 627 |
+
],
|
| 628 |
+
dim=-1,
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 632 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 633 |
+
dtype = hidden_states.dtype
|
| 634 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 635 |
+
# This is a hack to make sure multi-GPU inference works with HF accelerate
|
| 636 |
+
# see: https://github.com/Dao-AILab/flash-attention/issues/523 for more details
|
| 637 |
+
with torch.cuda.device(hidden_states.device):
|
| 638 |
+
scan_output, ssm_state = mamba_chunk_scan_combined(
|
| 639 |
+
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
| 640 |
+
time_step,
|
| 641 |
+
A,
|
| 642 |
+
B.view(batch_size, seq_len, self.n_groups, -1),
|
| 643 |
+
C.view(batch_size, seq_len, self.n_groups, -1),
|
| 644 |
+
chunk_size=self.chunk_size,
|
| 645 |
+
D=self.D,
|
| 646 |
+
z=None,
|
| 647 |
+
seq_idx=None,
|
| 648 |
+
return_final_states=True,
|
| 649 |
+
**dt_limit_kwargs,
|
| 650 |
+
)
|
| 651 |
+
if ssm_state is not None and cache_params is not None:
|
| 652 |
+
ssm_state = cache_params.update_recurrent_state(ssm_state, self.layer_idx)
|
| 653 |
+
scan_output = scan_output.view(batch_size, seq_len, -1)
|
| 654 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 655 |
+
if self.mamba_rms_norm:
|
| 656 |
+
out = self.norm(scan_output, gate)
|
| 657 |
+
else:
|
| 658 |
+
out = scan_output * torch.nn.functional.silu(gate)
|
| 659 |
+
out = self.out_proj(out)
|
| 660 |
+
return out
|
| 661 |
+
|
| 662 |
+
# fmt: off
|
| 663 |
+
def torch_forward(
|
| 664 |
+
self,
|
| 665 |
+
input_states,
|
| 666 |
+
cache_params: Cache | None = None,
|
| 667 |
+
attention_mask: torch.Tensor | None = None,
|
| 668 |
+
):
|
| 669 |
+
batch_size, seq_len, _ = input_states.shape
|
| 670 |
+
dtype = input_states.dtype
|
| 671 |
+
|
| 672 |
+
# 1. Gated MLP's linear projection
|
| 673 |
+
input_states = apply_mask_to_padding_states(input_states, attention_mask)
|
| 674 |
+
# Add Multipliers
|
| 675 |
+
input_states = input_states * self.ssm_in_multiplier
|
| 676 |
+
projected_states = self.in_proj(input_states)
|
| 677 |
+
projected_states = projected_states * self.mup_vector # ADD Mup Multipliers
|
| 678 |
+
gate, hidden_states_B_C, dt = projected_states.split([
|
| 679 |
+
self.intermediate_size, self.conv_dim, self.num_heads
|
| 680 |
+
], dim=-1)
|
| 681 |
+
hidden_states_B_C = hidden_states_B_C.transpose(1,2)
|
| 682 |
+
|
| 683 |
+
use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
|
| 684 |
+
|
| 685 |
+
# 2. Convolution sequence transformation
|
| 686 |
+
if use_precomputed_states:
|
| 687 |
+
conv_states = cache_params.update_conv_state(hidden_states_B_C, self.layer_idx)
|
| 688 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 689 |
+
conv_states = conv_states.to(device=self.conv1d.weight.device)
|
| 690 |
+
|
| 691 |
+
hidden_states_B_C = torch.sum(
|
| 692 |
+
conv_states * self.conv1d.weight.squeeze(1), dim=-1
|
| 693 |
+
)
|
| 694 |
+
if self.use_conv_bias:
|
| 695 |
+
hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
|
| 696 |
+
hidden_states_B_C = self.act(hidden_states_B_C)
|
| 697 |
+
else:
|
| 698 |
+
# Init cache
|
| 699 |
+
if cache_params is not None:
|
| 700 |
+
conv_states = nn.functional.pad(
|
| 701 |
+
hidden_states_B_C, (self.conv_kernel_size - hidden_states_B_C.shape[-1], 0)
|
| 702 |
+
)
|
| 703 |
+
conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
|
| 704 |
+
|
| 705 |
+
hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C)[..., :seq_len].transpose(1, 2))
|
| 706 |
+
|
| 707 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 708 |
+
hidden_states, B, C = torch.split(
|
| 709 |
+
hidden_states_B_C,
|
| 710 |
+
[self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
|
| 711 |
+
dim=-1
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
# 3. SSM transformation
|
| 715 |
+
A = -torch.exp(self.A_log.float()) # [num_heads]
|
| 716 |
+
if use_precomputed_states:
|
| 717 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 718 |
+
cache_device = cache_params.layers[self.layer_idx].recurrent_states.device
|
| 719 |
+
|
| 720 |
+
# Note: there is no need to pad parameter matrices here, as there is just one new token
|
| 721 |
+
# for batched generation
|
| 722 |
+
dt = dt[:, 0, :][:, None, ...]
|
| 723 |
+
dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
|
| 724 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 725 |
+
dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
|
| 726 |
+
|
| 727 |
+
dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
|
| 728 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 729 |
+
A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 730 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 731 |
+
dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
|
| 732 |
+
|
| 733 |
+
# Discretize B
|
| 734 |
+
# [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
|
| 735 |
+
# -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
|
| 736 |
+
B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 737 |
+
B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
|
| 738 |
+
B = B.reshape(batch_size, -1, B.shape[-1])
|
| 739 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 740 |
+
dB = dt[..., None] * B[..., None, :]
|
| 741 |
+
|
| 742 |
+
# Discretize x into dB
|
| 743 |
+
# [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
|
| 744 |
+
hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
|
| 745 |
+
dBx = (dB * hidden_states[..., None]).to(device=cache_device)
|
| 746 |
+
|
| 747 |
+
# State calculation
|
| 748 |
+
ssm_states = cache_params.layers[self.layer_idx].recurrent_states * dA + dBx
|
| 749 |
+
ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
|
| 750 |
+
|
| 751 |
+
# Subsequent output
|
| 752 |
+
# [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
|
| 753 |
+
C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 754 |
+
C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
|
| 755 |
+
C = C.reshape(batch_size, -1, C.shape[-1])
|
| 756 |
+
# [bsz, num_heads, head_dim]
|
| 757 |
+
|
| 758 |
+
ssm_states = ssm_states.to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
|
| 759 |
+
# Reshape ssm_states to merge the first two dimensions
|
| 760 |
+
ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
|
| 761 |
+
C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
|
| 762 |
+
y = torch.bmm(ssm_states_reshaped, C_reshaped)
|
| 763 |
+
y = y.view(batch_size, self.num_heads, self.head_dim)
|
| 764 |
+
|
| 765 |
+
# D skip connection
|
| 766 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 767 |
+
D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
|
| 768 |
+
y = (y + hidden_states * D).to(y.dtype)
|
| 769 |
+
|
| 770 |
+
# [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
|
| 771 |
+
y = y.reshape(batch_size, -1)[:, None, ...]
|
| 772 |
+
else:
|
| 773 |
+
# begin ssd naive implementation without einsums
|
| 774 |
+
dt = nn.functional.softplus(dt + self.dt_bias)
|
| 775 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 776 |
+
hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
|
| 777 |
+
B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 778 |
+
C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 779 |
+
B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 780 |
+
C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 781 |
+
pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
|
| 782 |
+
|
| 783 |
+
D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
|
| 784 |
+
|
| 785 |
+
# Discretize x and A
|
| 786 |
+
hidden_states = hidden_states * dt[..., None]
|
| 787 |
+
A = A.to(hidden_states.dtype) * dt
|
| 788 |
+
|
| 789 |
+
# Rearrange into blocks/chunks
|
| 790 |
+
hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
|
| 791 |
+
|
| 792 |
+
# [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
|
| 793 |
+
A = A.permute(0, 3, 1, 2)
|
| 794 |
+
A_cumsum = torch.cumsum(A, dim=-1)
|
| 795 |
+
|
| 796 |
+
# 1. Compute the output for each intra-chunk (diagonal blocks)
|
| 797 |
+
# This is the analog of a causal mask
|
| 798 |
+
L = torch.exp(segment_sum(A))
|
| 799 |
+
|
| 800 |
+
# Contraction of C and B to get G (attention-weights like)
|
| 801 |
+
G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
|
| 802 |
+
G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
|
| 803 |
+
|
| 804 |
+
# Compute M, equivalent to applying attention mask to weights
|
| 805 |
+
M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
|
| 806 |
+
M = M_intermediate.sum(dim=-1)
|
| 807 |
+
|
| 808 |
+
# Compute Y_diag (apply to values)
|
| 809 |
+
Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
|
| 810 |
+
|
| 811 |
+
# 2. Compute the state for each intra-chunk
|
| 812 |
+
# (right term of low-rank factorization of off-diagonal blocks; B terms)
|
| 813 |
+
decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
|
| 814 |
+
B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
|
| 815 |
+
states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
|
| 816 |
+
|
| 817 |
+
# 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
|
| 818 |
+
# (middle term of factorization of off-diag blocks; A terms)
|
| 819 |
+
previous_states = torch.zeros_like(states[:, :1])
|
| 820 |
+
states = torch.cat([previous_states, states], dim=1)
|
| 821 |
+
decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
|
| 822 |
+
decay_chunk = decay_chunk.transpose(1, 3)
|
| 823 |
+
new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
|
| 824 |
+
states, ssm_state = new_states[:, :-1], new_states[:, -1]
|
| 825 |
+
|
| 826 |
+
# 4. Compute state -> output conversion per chunk
|
| 827 |
+
# (left term of low-rank factorization of off-diagonal blocks; C terms)
|
| 828 |
+
state_decay_out = torch.exp(A_cumsum)
|
| 829 |
+
C_times_states = (C[..., None, :] * states[:, :, None, ...])
|
| 830 |
+
state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
|
| 831 |
+
Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
|
| 832 |
+
|
| 833 |
+
# Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
|
| 834 |
+
y = Y_diag + Y_off
|
| 835 |
+
# [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
|
| 836 |
+
y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
|
| 837 |
+
|
| 838 |
+
y = y + D_residual
|
| 839 |
+
# Cutting off padded chunks
|
| 840 |
+
if pad_size > 0:
|
| 841 |
+
y = y[:, :seq_len, :, :]
|
| 842 |
+
y = y.reshape(batch_size, seq_len, -1)
|
| 843 |
+
|
| 844 |
+
# Init cache
|
| 845 |
+
if ssm_state is not None and cache_params is not None:
|
| 846 |
+
ssm_state = cache_params.update_recurrent_state(ssm_state, self.layer_idx)
|
| 847 |
+
|
| 848 |
+
if self.mamba_rms_norm:
|
| 849 |
+
scan_output = self.norm(y, gate)
|
| 850 |
+
else:
|
| 851 |
+
scan_output = y * torch.nn.functional.silu(gate)
|
| 852 |
+
|
| 853 |
+
# end ssd naive
|
| 854 |
+
|
| 855 |
+
# 4. Final linear projection
|
| 856 |
+
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
|
| 857 |
+
return contextualized_states
|
| 858 |
+
# fmt: on
|
| 859 |
+
|
| 860 |
+
def forward(
|
| 861 |
+
self,
|
| 862 |
+
hidden_states,
|
| 863 |
+
cache_params: Cache | None = None,
|
| 864 |
+
attention_mask: torch.Tensor | None = None,
|
| 865 |
+
**kwargs,
|
| 866 |
+
):
|
| 867 |
+
if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
|
| 868 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
|
| 869 |
+
dtype = hidden_states.dtype
|
| 870 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 871 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 872 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 873 |
+
|
| 874 |
+
return self.torch_forward(hidden_states, cache_params, attention_mask)
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class FalconH1MLP(nn.Module):
|
| 878 |
+
def __init__(self, config: FalconH1Config):
|
| 879 |
+
super().__init__()
|
| 880 |
+
self.config = config
|
| 881 |
+
self.hidden_size = config.hidden_size
|
| 882 |
+
self.intermediate_size = config.intermediate_size
|
| 883 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 884 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 885 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 886 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 887 |
+
self.gate_multiplier, self.down_multiplier = config.mlp_multipliers
|
| 888 |
+
|
| 889 |
+
def forward(self, x):
|
| 890 |
+
y = self.up_proj(x) * self.act_fn(self.gate_proj(x) * self.gate_multiplier)
|
| 891 |
+
y = self.down_proj(y) * self.down_multiplier
|
| 892 |
+
return y
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 896 |
+
class FalconH1RMSNorm(nn.Module):
|
| 897 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 898 |
+
"""
|
| 899 |
+
FalconH1RMSNorm is equivalent to T5LayerNorm
|
| 900 |
+
"""
|
| 901 |
+
super().__init__()
|
| 902 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 903 |
+
self.variance_epsilon = eps
|
| 904 |
+
|
| 905 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 906 |
+
input_dtype = hidden_states.dtype
|
| 907 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 908 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 909 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 910 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 911 |
+
|
| 912 |
+
def extra_repr(self):
|
| 913 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
class FalconH1DecoderLayer(GradientCheckpointingLayer):
|
| 917 |
+
def __init__(self, config: FalconH1Config, layer_idx: int):
|
| 918 |
+
super().__init__()
|
| 919 |
+
self.feed_forward = FalconH1MLP(config)
|
| 920 |
+
|
| 921 |
+
head_dim = config.hidden_size // config.num_attention_heads
|
| 922 |
+
self.channels_attn = config.num_attention_heads * head_dim + 2 * config.num_key_value_heads * head_dim
|
| 923 |
+
|
| 924 |
+
self.mamba = FalconH1Mixer(config=config, layer_idx=layer_idx)
|
| 925 |
+
|
| 926 |
+
self.self_attn = FalconH1Attention(config, layer_idx)
|
| 927 |
+
|
| 928 |
+
self.attention_in_multiplier = config.attention_in_multiplier
|
| 929 |
+
self.ssm_out_multiplier = config.ssm_out_multiplier
|
| 930 |
+
self.attn_out_multiplier = config.attention_out_multiplier
|
| 931 |
+
|
| 932 |
+
self.input_layernorm = FalconH1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 933 |
+
self.pre_ff_layernorm = FalconH1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 934 |
+
|
| 935 |
+
def forward(
|
| 936 |
+
self,
|
| 937 |
+
hidden_states: torch.Tensor,
|
| 938 |
+
attention_mask: torch.Tensor | None = None,
|
| 939 |
+
mamba_attention_mask: torch.Tensor | None = None,
|
| 940 |
+
position_ids: torch.LongTensor | None = None,
|
| 941 |
+
past_key_values: Cache | None = None,
|
| 942 |
+
use_cache: bool | None = False,
|
| 943 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 944 |
+
**kwargs,
|
| 945 |
+
) -> tuple[torch.FloatTensor]:
|
| 946 |
+
"""
|
| 947 |
+
Args:
|
| 948 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 949 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 950 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 951 |
+
past_key_values (`Cache`, *optional*): cached past key and value projection states
|
| 952 |
+
use_cache (`bool`, *optional*):
|
| 953 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 954 |
+
(see `past_key_values`).
|
| 955 |
+
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
| 956 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
| 957 |
+
with `head_dim` being the embedding dimension of each attention head.
|
| 958 |
+
kwargs (`dict`, *optional*):
|
| 959 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 960 |
+
into the model
|
| 961 |
+
"""
|
| 962 |
+
|
| 963 |
+
residual = hidden_states
|
| 964 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 965 |
+
|
| 966 |
+
mamba_hidden_states = self.mamba(
|
| 967 |
+
hidden_states=hidden_states,
|
| 968 |
+
cache_params=past_key_values,
|
| 969 |
+
attention_mask=mamba_attention_mask,
|
| 970 |
+
)
|
| 971 |
+
mamba_hidden_states = mamba_hidden_states * self.ssm_out_multiplier
|
| 972 |
+
|
| 973 |
+
attention_hidden_states, _ = self.self_attn(
|
| 974 |
+
hidden_states=hidden_states * self.attention_in_multiplier,
|
| 975 |
+
attention_mask=attention_mask,
|
| 976 |
+
position_ids=position_ids,
|
| 977 |
+
past_key_values=past_key_values,
|
| 978 |
+
use_cache=use_cache,
|
| 979 |
+
position_embeddings=position_embeddings,
|
| 980 |
+
**kwargs,
|
| 981 |
+
)
|
| 982 |
+
attention_hidden_states = attention_hidden_states * self.attn_out_multiplier
|
| 983 |
+
|
| 984 |
+
hidden_states = mamba_hidden_states + attention_hidden_states
|
| 985 |
+
|
| 986 |
+
# residual connection after attention
|
| 987 |
+
hidden_states = residual + hidden_states
|
| 988 |
+
|
| 989 |
+
# feed-forward
|
| 990 |
+
residual = hidden_states
|
| 991 |
+
hidden_states = self.pre_ff_layernorm(hidden_states)
|
| 992 |
+
hidden_states = self.feed_forward(hidden_states)
|
| 993 |
+
hidden_states = residual + hidden_states
|
| 994 |
+
|
| 995 |
+
return (hidden_states,)
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
def compute_mup_vector(config):
|
| 999 |
+
"""
|
| 1000 |
+
Computes the MuP vector based on model configuration.
|
| 1001 |
+
|
| 1002 |
+
FalconH1 applies different MuP multiplier for each dimension of the hidden states.
|
| 1003 |
+
The MuP vector is partitioned into chunks, and each chunk is multiplied with its
|
| 1004 |
+
corresponding projected dimension.
|
| 1005 |
+
|
| 1006 |
+
Args:
|
| 1007 |
+
config: FalconH1Config object
|
| 1008 |
+
|
| 1009 |
+
Returns:
|
| 1010 |
+
torch.Tensor: The computed MuP vector
|
| 1011 |
+
"""
|
| 1012 |
+
# We'll need some values from the config to compute the vector dimensions
|
| 1013 |
+
intermediate_size = (
|
| 1014 |
+
config.mamba_d_ssm if config.mamba_d_ssm is not None else int(config.mamba_expand * config.hidden_size)
|
| 1015 |
+
)
|
| 1016 |
+
groups_time_state_size = config.mamba_n_groups * config.mamba_d_state
|
| 1017 |
+
num_heads = config.mamba_n_heads
|
| 1018 |
+
zxbcdt_multipliers = config.ssm_multipliers
|
| 1019 |
+
|
| 1020 |
+
vector_shape = 2 * intermediate_size + 2 * groups_time_state_size + num_heads
|
| 1021 |
+
mup_vector = torch.ones(1, 1, vector_shape)
|
| 1022 |
+
|
| 1023 |
+
# Apply multipliers to different sections of the vector
|
| 1024 |
+
mup_vector[:, :, :intermediate_size] *= zxbcdt_multipliers[0]
|
| 1025 |
+
mup_vector[:, :, intermediate_size : 2 * intermediate_size] *= zxbcdt_multipliers[1]
|
| 1026 |
+
mup_vector[:, :, 2 * intermediate_size : 2 * intermediate_size + groups_time_state_size] *= zxbcdt_multipliers[2]
|
| 1027 |
+
mup_vector[
|
| 1028 |
+
:, :, 2 * intermediate_size + groups_time_state_size : 2 * intermediate_size + 2 * groups_time_state_size
|
| 1029 |
+
] *= zxbcdt_multipliers[3]
|
| 1030 |
+
mup_vector[:, :, 2 * intermediate_size + 2 * groups_time_state_size :] *= zxbcdt_multipliers[4]
|
| 1031 |
+
|
| 1032 |
+
return mup_vector
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
@auto_docstring
|
| 1036 |
+
class FalconH1PreTrainedModel(PreTrainedModel):
|
| 1037 |
+
config: FalconH1Config
|
| 1038 |
+
base_model_prefix = "model"
|
| 1039 |
+
supports_gradient_checkpointing = True
|
| 1040 |
+
_no_split_modules = ["FalconH1DecoderLayer"]
|
| 1041 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 1042 |
+
_supports_flash_attn = True
|
| 1043 |
+
_supports_sdpa = True
|
| 1044 |
+
_is_stateful = True
|
| 1045 |
+
|
| 1046 |
+
_can_record_outputs = {
|
| 1047 |
+
"hidden_states": FalconH1DecoderLayer,
|
| 1048 |
+
"attentions": FalconH1Attention,
|
| 1049 |
+
}
|
| 1050 |
+
|
| 1051 |
+
@torch.no_grad()
|
| 1052 |
+
def _init_weights(self, module):
|
| 1053 |
+
super()._init_weights(module)
|
| 1054 |
+
if isinstance(module, FalconH1Mixer):
|
| 1055 |
+
init.ones_(module.dt_bias)
|
| 1056 |
+
init.copy_(module.A_log, torch.log(torch.arange(1, module.num_heads + 1)))
|
| 1057 |
+
init.ones_(module.D)
|
| 1058 |
+
elif isinstance(module, FalconH1Model):
|
| 1059 |
+
mup_vector = compute_mup_vector(module.config)
|
| 1060 |
+
for layer in module.layers:
|
| 1061 |
+
init.copy_(layer.mamba.mup_vector, mup_vector)
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
@auto_docstring
|
| 1065 |
+
# Adapted from transformers.models.jamba.modeling_jamba.JambaModel
|
| 1066 |
+
class FalconH1Model(FalconH1PreTrainedModel):
|
| 1067 |
+
def __init__(self, config: FalconH1Config):
|
| 1068 |
+
super().__init__(config)
|
| 1069 |
+
self.padding_idx = config.pad_token_id
|
| 1070 |
+
self.vocab_size = config.vocab_size
|
| 1071 |
+
|
| 1072 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 1073 |
+
decoder_layers = []
|
| 1074 |
+
for i in range(config.num_hidden_layers):
|
| 1075 |
+
decoder_layers.append(FalconH1DecoderLayer(config, layer_idx=i))
|
| 1076 |
+
self.layers = nn.ModuleList(decoder_layers)
|
| 1077 |
+
|
| 1078 |
+
self._attn_implementation = config._attn_implementation
|
| 1079 |
+
self.final_layernorm = FalconH1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 1080 |
+
self.rotary_emb = FalconH1RotaryEmbedding(config=config)
|
| 1081 |
+
|
| 1082 |
+
self.embedding_multiplier = config.embedding_multiplier
|
| 1083 |
+
self.lm_head_multiplier = config.lm_head_multiplier
|
| 1084 |
+
|
| 1085 |
+
self.gradient_checkpointing = False
|
| 1086 |
+
# Compute the MuP vector once and register it for all layers
|
| 1087 |
+
mup_vector = compute_mup_vector(config)
|
| 1088 |
+
for layer in self.layers:
|
| 1089 |
+
layer.mamba.register_buffer("mup_vector", mup_vector.clone(), persistent=False)
|
| 1090 |
+
|
| 1091 |
+
# Initialize weights and apply final processing
|
| 1092 |
+
self.post_init()
|
| 1093 |
+
|
| 1094 |
+
@merge_with_config_defaults
|
| 1095 |
+
@capture_outputs
|
| 1096 |
+
@auto_docstring
|
| 1097 |
+
def forward(
|
| 1098 |
+
self,
|
| 1099 |
+
input_ids: torch.LongTensor | None = None,
|
| 1100 |
+
attention_mask: torch.Tensor | None = None,
|
| 1101 |
+
position_ids: torch.LongTensor | None = None,
|
| 1102 |
+
past_key_values: Cache | None = None,
|
| 1103 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1104 |
+
use_cache: bool | None = None,
|
| 1105 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1106 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 1107 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 1108 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 1109 |
+
|
| 1110 |
+
if inputs_embeds is None:
|
| 1111 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embedding_multiplier
|
| 1112 |
+
hidden_states = inputs_embeds
|
| 1113 |
+
|
| 1114 |
+
if use_cache and past_key_values is None:
|
| 1115 |
+
past_key_values = DynamicCache(config=self.config)
|
| 1116 |
+
|
| 1117 |
+
if position_ids is None:
|
| 1118 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1119 |
+
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
|
| 1120 |
+
position_ids = position_ids.unsqueeze(0)
|
| 1121 |
+
|
| 1122 |
+
causal_mask = create_causal_mask(
|
| 1123 |
+
config=self.config,
|
| 1124 |
+
inputs_embeds=inputs_embeds,
|
| 1125 |
+
attention_mask=attention_mask,
|
| 1126 |
+
past_key_values=past_key_values,
|
| 1127 |
+
position_ids=position_ids,
|
| 1128 |
+
)
|
| 1129 |
+
mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
|
| 1130 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 1131 |
+
|
| 1132 |
+
for decoder_layer in self.layers:
|
| 1133 |
+
layer_outputs = decoder_layer(
|
| 1134 |
+
hidden_states,
|
| 1135 |
+
attention_mask=causal_mask,
|
| 1136 |
+
mamba_attention_mask=mamba_mask,
|
| 1137 |
+
position_ids=position_ids,
|
| 1138 |
+
past_key_values=past_key_values,
|
| 1139 |
+
use_cache=use_cache,
|
| 1140 |
+
position_embeddings=position_embeddings,
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
hidden_states = layer_outputs[0]
|
| 1144 |
+
|
| 1145 |
+
hidden_states = self.final_layernorm(hidden_states)
|
| 1146 |
+
|
| 1147 |
+
return BaseModelOutputWithPast(
|
| 1148 |
+
last_hidden_state=hidden_states,
|
| 1149 |
+
past_key_values=past_key_values,
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
def _update_mamba_mask(self, attention_mask, past_key_values):
|
| 1153 |
+
"""
|
| 1154 |
+
No need for zeroing states when
|
| 1155 |
+
1. Cached forward
|
| 1156 |
+
2. Attending to all inputs
|
| 1157 |
+
"""
|
| 1158 |
+
mamba_mask = attention_mask
|
| 1159 |
+
if (past_key_values is not None and past_key_values.has_previous_state()) or (
|
| 1160 |
+
attention_mask is not None and torch.all(attention_mask == 1)
|
| 1161 |
+
):
|
| 1162 |
+
mamba_mask = None
|
| 1163 |
+
return mamba_mask
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
@auto_docstring
|
| 1167 |
+
class FalconH1ForCausalLM(FalconH1PreTrainedModel, GenerationMixin):
|
| 1168 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 1169 |
+
_tp_plan = {"lm_head": "colwise_gather_output"}
|
| 1170 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 1171 |
+
|
| 1172 |
+
def __init__(self, config):
|
| 1173 |
+
super().__init__(config)
|
| 1174 |
+
self.model = FalconH1Model(config)
|
| 1175 |
+
self.vocab_size = config.vocab_size
|
| 1176 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1177 |
+
|
| 1178 |
+
# Initialize weights and apply final processing
|
| 1179 |
+
self.post_init()
|
| 1180 |
+
|
| 1181 |
+
@can_return_tuple
|
| 1182 |
+
@auto_docstring
|
| 1183 |
+
def forward(
|
| 1184 |
+
self,
|
| 1185 |
+
input_ids: torch.LongTensor | None = None,
|
| 1186 |
+
attention_mask: torch.Tensor | None = None,
|
| 1187 |
+
position_ids: torch.LongTensor | None = None,
|
| 1188 |
+
past_key_values: Cache | None = None,
|
| 1189 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1190 |
+
labels: torch.LongTensor | None = None,
|
| 1191 |
+
use_cache: bool | None = None,
|
| 1192 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1193 |
+
**kwargs,
|
| 1194 |
+
) -> tuple | CausalLMOutputWithPast:
|
| 1195 |
+
r"""
|
| 1196 |
+
Example:
|
| 1197 |
+
|
| 1198 |
+
```python
|
| 1199 |
+
>>> from transformers import AutoTokenizer, FalconH1ForCausalLM
|
| 1200 |
+
|
| 1201 |
+
>>> model = FalconH1ForCausalLM.from_pretrained("...")
|
| 1202 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("...")
|
| 1203 |
+
|
| 1204 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1205 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1206 |
+
|
| 1207 |
+
>>> # Generate
|
| 1208 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1209 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1210 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1211 |
+
```"""
|
| 1212 |
+
outputs = self.model(
|
| 1213 |
+
input_ids=input_ids,
|
| 1214 |
+
attention_mask=attention_mask,
|
| 1215 |
+
position_ids=position_ids,
|
| 1216 |
+
past_key_values=past_key_values,
|
| 1217 |
+
inputs_embeds=inputs_embeds,
|
| 1218 |
+
use_cache=use_cache,
|
| 1219 |
+
**kwargs,
|
| 1220 |
+
)
|
| 1221 |
+
|
| 1222 |
+
hidden_states = outputs[0]
|
| 1223 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1224 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1225 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :]) * self.model.lm_head_multiplier
|
| 1226 |
+
|
| 1227 |
+
loss = None
|
| 1228 |
+
if labels is not None:
|
| 1229 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 1230 |
+
|
| 1231 |
+
return CausalLMOutputWithPast(
|
| 1232 |
+
loss=loss,
|
| 1233 |
+
logits=logits,
|
| 1234 |
+
past_key_values=outputs.past_key_values,
|
| 1235 |
+
hidden_states=outputs.hidden_states,
|
| 1236 |
+
attentions=outputs.attentions,
|
| 1237 |
+
)
|
| 1238 |
+
|
| 1239 |
+
def prepare_inputs_for_generation(
|
| 1240 |
+
self,
|
| 1241 |
+
input_ids,
|
| 1242 |
+
past_key_values=None,
|
| 1243 |
+
attention_mask=None,
|
| 1244 |
+
inputs_embeds=None,
|
| 1245 |
+
position_ids=None,
|
| 1246 |
+
use_cache=True,
|
| 1247 |
+
is_first_iteration=False,
|
| 1248 |
+
**kwargs,
|
| 1249 |
+
):
|
| 1250 |
+
kwargs["logits_to_keep"] = self.config.num_logits_to_keep
|
| 1251 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 1252 |
+
input_ids,
|
| 1253 |
+
past_key_values=past_key_values,
|
| 1254 |
+
attention_mask=attention_mask,
|
| 1255 |
+
inputs_embeds=inputs_embeds,
|
| 1256 |
+
position_ids=position_ids,
|
| 1257 |
+
use_cache=use_cache,
|
| 1258 |
+
is_first_iteration=is_first_iteration,
|
| 1259 |
+
**kwargs,
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
return model_inputs
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
__all__ = ["FalconH1Model", "FalconH1ForCausalLM", "FalconH1PreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/falcon_h1/modular_falcon_h1.py
ADDED
|
@@ -0,0 +1,1014 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Technology Innovation Institute and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 4 |
+
# and OPT implementations in this library. It has been modified from its
|
| 5 |
+
# original forms to accommodate minor architectural differences compared
|
| 6 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 7 |
+
#
|
| 8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 9 |
+
# you may not use this file except in compliance with the License.
|
| 10 |
+
# You may obtain a copy of the License at
|
| 11 |
+
#
|
| 12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 13 |
+
#
|
| 14 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 17 |
+
# See the License for the specific language governing permissions and
|
| 18 |
+
# limitations under the License.
|
| 19 |
+
"""PyTorch FalconH1 model."""
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
from ... import initialization as init
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...cache_utils import Cache, DynamicCache
|
| 30 |
+
from ...integrations.hub_kernels import lazy_load_kernel
|
| 31 |
+
from ...masking_utils import create_causal_mask
|
| 32 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 33 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 34 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 35 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 36 |
+
from ...processing_utils import Unpack
|
| 37 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
|
| 38 |
+
from ...utils.generic import merge_with_config_defaults
|
| 39 |
+
from ...utils.import_utils import resolve_internal_import
|
| 40 |
+
from ...utils.output_capturing import capture_outputs
|
| 41 |
+
from ..llama.modeling_llama import (
|
| 42 |
+
LlamaAttention,
|
| 43 |
+
LlamaForCausalLM,
|
| 44 |
+
LlamaMLP,
|
| 45 |
+
LlamaRMSNorm,
|
| 46 |
+
LlamaRotaryEmbedding,
|
| 47 |
+
apply_rotary_pos_emb,
|
| 48 |
+
eager_attention_forward,
|
| 49 |
+
)
|
| 50 |
+
from ..mamba2.modeling_mamba2 import (
|
| 51 |
+
MambaRMSNormGated,
|
| 52 |
+
apply_mask_to_padding_states,
|
| 53 |
+
pad_tensor_by_size,
|
| 54 |
+
reshape_into_chunks,
|
| 55 |
+
segment_sum,
|
| 56 |
+
)
|
| 57 |
+
from .configuration_falcon_h1 import FalconH1Config
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
logger = logging.get_logger(__name__)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class FalconH1RotaryEmbedding(LlamaRotaryEmbedding):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class FalconH1Attention(LlamaAttention):
|
| 68 |
+
def __init__(self, config: FalconH1Config, layer_idx: int):
|
| 69 |
+
super().__init__(config, layer_idx)
|
| 70 |
+
self.key_multiplier = config.key_multiplier
|
| 71 |
+
|
| 72 |
+
def forward(
|
| 73 |
+
self,
|
| 74 |
+
hidden_states: torch.Tensor,
|
| 75 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 76 |
+
attention_mask: torch.Tensor | None,
|
| 77 |
+
past_key_values: Cache | None = None,
|
| 78 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 79 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 80 |
+
input_shape = hidden_states.shape[:-1]
|
| 81 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 82 |
+
|
| 83 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 84 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) * self.key_multiplier
|
| 85 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 86 |
+
|
| 87 |
+
cos, sin = position_embeddings
|
| 88 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 89 |
+
|
| 90 |
+
if past_key_values is not None:
|
| 91 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 92 |
+
|
| 93 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 94 |
+
self.config._attn_implementation, eager_attention_forward
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
attn_output, attn_weights = attention_interface(
|
| 98 |
+
self,
|
| 99 |
+
query_states,
|
| 100 |
+
key_states,
|
| 101 |
+
value_states,
|
| 102 |
+
attention_mask,
|
| 103 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 104 |
+
scaling=self.scaling,
|
| 105 |
+
**kwargs,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 109 |
+
attn_output = self.o_proj(attn_output)
|
| 110 |
+
return attn_output, attn_weights
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class FalconH1RMSNormGated(MambaRMSNormGated):
|
| 114 |
+
def __init__(self, hidden_size, eps=1e-6, n_groups=1, norm_before_gate=True):
|
| 115 |
+
super().__init__(hidden_size=hidden_size, eps=eps)
|
| 116 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 117 |
+
self.variance_epsilon = eps
|
| 118 |
+
self.n_groups = n_groups
|
| 119 |
+
self.norm_before_gate = norm_before_gate
|
| 120 |
+
|
| 121 |
+
def forward(self, hidden_states, gate=None):
|
| 122 |
+
input_dtype = hidden_states.dtype
|
| 123 |
+
|
| 124 |
+
if not self.norm_before_gate and gate is not None:
|
| 125 |
+
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
|
| 126 |
+
|
| 127 |
+
if len(hidden_states.shape) == 3:
|
| 128 |
+
batch_size, seq_len, dim = hidden_states.shape
|
| 129 |
+
else:
|
| 130 |
+
batch_size, dim = hidden_states.shape
|
| 131 |
+
seq_len = 1
|
| 132 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 133 |
+
|
| 134 |
+
hidden_states = hidden_states.view(batch_size, seq_len, self.n_groups, int(dim // self.n_groups))
|
| 135 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 136 |
+
|
| 137 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 138 |
+
|
| 139 |
+
hidden_states = self.weight.view(self.n_groups, int(dim // self.n_groups)) * hidden_states
|
| 140 |
+
hidden_states = hidden_states.view(batch_size, seq_len, dim)
|
| 141 |
+
|
| 142 |
+
if seq_len == 1:
|
| 143 |
+
hidden_states = hidden_states.squeeze(1)
|
| 144 |
+
|
| 145 |
+
if self.norm_before_gate and gate is not None:
|
| 146 |
+
hidden_states = hidden_states * F.silu(gate.to(torch.float32))
|
| 147 |
+
return hidden_states.to(input_dtype)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
|
| 151 |
+
class FalconH1Mixer(nn.Module):
|
| 152 |
+
"""
|
| 153 |
+
FalconH1Mixer is identical to classic Mamba2 mixer classes but differs on two different things
|
| 154 |
+
- Users can pass custom intermediate_size through `config.mamba_d_ssm`
|
| 155 |
+
- The use of gated RMS normalization layer is optional
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def __init__(self, config: FalconH1Config, layer_idx: int):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.num_heads = config.mamba_n_heads
|
| 161 |
+
self.hidden_size = config.hidden_size
|
| 162 |
+
self.ssm_state_size = config.mamba_d_state
|
| 163 |
+
self.conv_kernel_size = config.mamba_d_conv
|
| 164 |
+
self.intermediate_size = (
|
| 165 |
+
int(config.mamba_expand * self.hidden_size) if config.mamba_d_ssm is None else config.mamba_d_ssm
|
| 166 |
+
)
|
| 167 |
+
self.layer_idx = layer_idx
|
| 168 |
+
self.use_conv_bias = config.mamba_conv_bias
|
| 169 |
+
self.activation = config.hidden_act
|
| 170 |
+
self.act = ACT2FN[config.hidden_act]
|
| 171 |
+
self.use_bias = config.mamba_proj_bias
|
| 172 |
+
|
| 173 |
+
self.layer_norm_epsilon = config.rms_norm_eps
|
| 174 |
+
self.groups_time_state_size = config.mamba_n_groups * self.ssm_state_size
|
| 175 |
+
|
| 176 |
+
self.n_groups = config.mamba_n_groups
|
| 177 |
+
self.head_dim = config.mamba_d_head
|
| 178 |
+
self.chunk_size = config.mamba_chunk_size
|
| 179 |
+
|
| 180 |
+
self.time_step_limit = config.time_step_limit
|
| 181 |
+
self.time_step_min = config.time_step_min
|
| 182 |
+
self.time_step_max = config.time_step_max
|
| 183 |
+
|
| 184 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 185 |
+
self.conv1d = nn.Conv1d(
|
| 186 |
+
in_channels=self.conv_dim,
|
| 187 |
+
out_channels=self.conv_dim,
|
| 188 |
+
bias=config.mamba_conv_bias,
|
| 189 |
+
kernel_size=self.conv_kernel_size,
|
| 190 |
+
groups=self.conv_dim,
|
| 191 |
+
padding=self.conv_kernel_size - 1,
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# projection of the input hidden states
|
| 195 |
+
projection_size = self.intermediate_size + self.conv_dim + self.num_heads
|
| 196 |
+
self.in_proj = nn.Linear(
|
| 197 |
+
self.hidden_size,
|
| 198 |
+
projection_size,
|
| 199 |
+
bias=self.use_bias,
|
| 200 |
+
)
|
| 201 |
+
# selective projection used to make dt, B and C input dependant
|
| 202 |
+
|
| 203 |
+
# time step projection (discretization)
|
| 204 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 205 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 206 |
+
|
| 207 |
+
# S4D real initialization. These are not discretized!
|
| 208 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 209 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 210 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 211 |
+
self.mamba_rms_norm = config.mamba_rms_norm
|
| 212 |
+
|
| 213 |
+
if self.mamba_rms_norm:
|
| 214 |
+
self.norm = FalconH1RMSNormGated(
|
| 215 |
+
self.intermediate_size,
|
| 216 |
+
eps=self.layer_norm_epsilon,
|
| 217 |
+
n_groups=self.n_groups,
|
| 218 |
+
norm_before_gate=config.mamba_norm_before_gate,
|
| 219 |
+
)
|
| 220 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 221 |
+
|
| 222 |
+
self.out_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=config.projectors_bias)
|
| 223 |
+
|
| 224 |
+
global causal_conv1d_update, causal_conv1d_fn
|
| 225 |
+
causal_conv1d = lazy_load_kernel("causal-conv1d")
|
| 226 |
+
causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
|
| 227 |
+
causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
|
| 228 |
+
|
| 229 |
+
global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
|
| 230 |
+
mamba_ssm = lazy_load_kernel("mamba-ssm")
|
| 231 |
+
selective_state_update = resolve_internal_import(
|
| 232 |
+
mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
|
| 233 |
+
)
|
| 234 |
+
mamba_chunk_scan_combined = resolve_internal_import(
|
| 235 |
+
mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
|
| 236 |
+
)
|
| 237 |
+
mamba_split_conv1d_scan_combined = resolve_internal_import(
|
| 238 |
+
mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
global is_fast_path_available
|
| 242 |
+
is_fast_path_available = all(
|
| 243 |
+
(
|
| 244 |
+
selective_state_update,
|
| 245 |
+
mamba_chunk_scan_combined,
|
| 246 |
+
mamba_split_conv1d_scan_combined,
|
| 247 |
+
causal_conv1d_fn,
|
| 248 |
+
causal_conv1d_update,
|
| 249 |
+
)
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if not is_fast_path_available:
|
| 253 |
+
logger.warning_once(
|
| 254 |
+
"The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
|
| 255 |
+
" is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 256 |
+
" https://github.com/Dao-AILab/causal-conv1d"
|
| 257 |
+
)
|
| 258 |
+
else:
|
| 259 |
+
logger.warning_once("The fast path for FalconH1 will be used when running the model on a GPU")
|
| 260 |
+
|
| 261 |
+
self.zxbcdt_multipliers = config.ssm_multipliers
|
| 262 |
+
self.ssm_in_multiplier = config.ssm_in_multiplier
|
| 263 |
+
|
| 264 |
+
def cuda_kernels_forward(
|
| 265 |
+
self,
|
| 266 |
+
hidden_states: torch.Tensor,
|
| 267 |
+
cache_params: Cache | None = None,
|
| 268 |
+
attention_mask: torch.Tensor | None = None,
|
| 269 |
+
):
|
| 270 |
+
# 1. Gated MLP's linear projection
|
| 271 |
+
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 272 |
+
# Add Multipliers
|
| 273 |
+
hidden_states = hidden_states * self.ssm_in_multiplier
|
| 274 |
+
projected_states = self.in_proj(hidden_states)
|
| 275 |
+
projected_states = projected_states * self.mup_vector # ADD Mup Multipliers
|
| 276 |
+
d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
|
| 277 |
+
|
| 278 |
+
# Set up dimensions for reshapes later
|
| 279 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 280 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 281 |
+
|
| 282 |
+
use_precomputed_states = (
|
| 283 |
+
cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# getting projected states from cache if it exists
|
| 287 |
+
if use_precomputed_states:
|
| 288 |
+
d_mlp = (projected_states.squeeze(1).shape[-1] - d_to_remove) // 2
|
| 289 |
+
|
| 290 |
+
z0, x0, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
|
| 291 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
# 2. Convolution sequence transformation
|
| 295 |
+
hidden_states_B_C = causal_conv1d_update(
|
| 296 |
+
hidden_states_B_C,
|
| 297 |
+
cache_params.layers[self.layer_idx].conv_states,
|
| 298 |
+
self.conv1d.weight.squeeze(1),
|
| 299 |
+
self.conv1d.bias,
|
| 300 |
+
self.activation,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
hidden_states, B, C = torch.split(
|
| 304 |
+
hidden_states_B_C,
|
| 305 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 306 |
+
dim=-1,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
# 3. SSM transformation
|
| 310 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 311 |
+
A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 312 |
+
dt = dt[:, :, None].expand(-1, -1, self.head_dim)
|
| 313 |
+
dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
|
| 314 |
+
D = self.D[:, None, ...].expand(-1, self.head_dim)
|
| 315 |
+
B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
|
| 316 |
+
C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
|
| 317 |
+
hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
|
| 318 |
+
hidden_states = selective_state_update(
|
| 319 |
+
cache_params.layers[self.layer_idx].recurrent_states,
|
| 320 |
+
hidden_states_reshaped,
|
| 321 |
+
dt,
|
| 322 |
+
A,
|
| 323 |
+
B,
|
| 324 |
+
C,
|
| 325 |
+
D,
|
| 326 |
+
z=gate.view(batch_size, self.num_heads, self.head_dim) if not self.mamba_rms_norm else None,
|
| 327 |
+
dt_bias=dt_bias,
|
| 328 |
+
dt_softplus=True,
|
| 329 |
+
)
|
| 330 |
+
hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
|
| 331 |
+
|
| 332 |
+
if self.mamba_rms_norm:
|
| 333 |
+
hidden_states = self.norm(hidden_states, gate)
|
| 334 |
+
|
| 335 |
+
if d_mlp > 0:
|
| 336 |
+
hidden_states = torch.cat([F.silu(z0) * x0, hidden_states], dim=-1)
|
| 337 |
+
|
| 338 |
+
# 4. Final linear projection
|
| 339 |
+
out = self.out_proj(hidden_states[:, None, ...])
|
| 340 |
+
# Fused calculations or step by step if no initialized cache is found
|
| 341 |
+
else:
|
| 342 |
+
A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
|
| 343 |
+
dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
|
| 344 |
+
|
| 345 |
+
# 2-4. Fused kernel for conv1d, SSM, and the final projection
|
| 346 |
+
if self.training and cache_params is None:
|
| 347 |
+
out = mamba_split_conv1d_scan_combined(
|
| 348 |
+
projected_states,
|
| 349 |
+
self.conv1d.weight.squeeze(1),
|
| 350 |
+
self.conv1d.bias,
|
| 351 |
+
self.dt_bias,
|
| 352 |
+
A,
|
| 353 |
+
D=self.D,
|
| 354 |
+
chunk_size=self.chunk_size,
|
| 355 |
+
seq_idx=None, # was seq_idx
|
| 356 |
+
activation=self.activation,
|
| 357 |
+
rmsnorm_weight=self.norm.weight if self.mamba_rms_norm else None,
|
| 358 |
+
rmsnorm_eps=self.norm.variance_epsilon if self.mamba_rms_norm else None,
|
| 359 |
+
outproj_weight=self.out_proj.weight,
|
| 360 |
+
outproj_bias=self.out_proj.bias,
|
| 361 |
+
headdim=self.head_dim,
|
| 362 |
+
ngroups=self.n_groups,
|
| 363 |
+
norm_before_gate=False,
|
| 364 |
+
return_final_states=False,
|
| 365 |
+
**dt_limit_kwargs,
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
else:
|
| 369 |
+
d_mlp = (
|
| 370 |
+
projected_states.shape[-1]
|
| 371 |
+
- 2 * self.intermediate_size
|
| 372 |
+
- 2 * self.n_groups * self.ssm_state_size
|
| 373 |
+
- self.num_heads
|
| 374 |
+
) // 2
|
| 375 |
+
if attention_mask is not None:
|
| 376 |
+
projected_states = projected_states * attention_mask[..., None]
|
| 377 |
+
_, gate, hidden_states_B_C, dt = projected_states.split(
|
| 378 |
+
[
|
| 379 |
+
2 * d_mlp,
|
| 380 |
+
self.intermediate_size,
|
| 381 |
+
self.conv_dim,
|
| 382 |
+
self.num_heads,
|
| 383 |
+
],
|
| 384 |
+
dim=-1,
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
if cache_params is not None:
|
| 388 |
+
conv_states = F.pad(
|
| 389 |
+
hidden_states_B_C.permute(0, 2, 1),
|
| 390 |
+
(self.conv_kernel_size - hidden_states_B_C.shape[-2], 0),
|
| 391 |
+
)
|
| 392 |
+
conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
|
| 393 |
+
|
| 394 |
+
time_step = nn.functional.softplus(dt + self.dt_bias)
|
| 395 |
+
# 1D Convolution
|
| 396 |
+
if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
|
| 397 |
+
hidden_states_B_C = self.act(
|
| 398 |
+
self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
|
| 399 |
+
) # (B, L, self.d_inner + 2 * ngroups * d_state)
|
| 400 |
+
else:
|
| 401 |
+
hidden_states_B_C = causal_conv1d_fn(
|
| 402 |
+
x=hidden_states_B_C.transpose(1, 2),
|
| 403 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 404 |
+
bias=self.conv1d.bias,
|
| 405 |
+
activation=self.activation,
|
| 406 |
+
).transpose(1, 2)[:, :seq_len]
|
| 407 |
+
|
| 408 |
+
hidden_states, B, C = torch.split(
|
| 409 |
+
hidden_states_B_C,
|
| 410 |
+
[
|
| 411 |
+
self.intermediate_size,
|
| 412 |
+
groups_time_state_size,
|
| 413 |
+
groups_time_state_size,
|
| 414 |
+
],
|
| 415 |
+
dim=-1,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 419 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 420 |
+
dtype = hidden_states.dtype
|
| 421 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 422 |
+
# This is a hack to make sure multi-GPU inference works with HF accelerate
|
| 423 |
+
# see: https://github.com/Dao-AILab/flash-attention/issues/523 for more details
|
| 424 |
+
with torch.cuda.device(hidden_states.device):
|
| 425 |
+
scan_output, ssm_state = mamba_chunk_scan_combined(
|
| 426 |
+
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
| 427 |
+
time_step,
|
| 428 |
+
A,
|
| 429 |
+
B.view(batch_size, seq_len, self.n_groups, -1),
|
| 430 |
+
C.view(batch_size, seq_len, self.n_groups, -1),
|
| 431 |
+
chunk_size=self.chunk_size,
|
| 432 |
+
D=self.D,
|
| 433 |
+
z=None,
|
| 434 |
+
seq_idx=None,
|
| 435 |
+
return_final_states=True,
|
| 436 |
+
**dt_limit_kwargs,
|
| 437 |
+
)
|
| 438 |
+
if ssm_state is not None and cache_params is not None:
|
| 439 |
+
ssm_state = cache_params.update_recurrent_state(ssm_state, self.layer_idx)
|
| 440 |
+
scan_output = scan_output.view(batch_size, seq_len, -1)
|
| 441 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 442 |
+
if self.mamba_rms_norm:
|
| 443 |
+
out = self.norm(scan_output, gate)
|
| 444 |
+
else:
|
| 445 |
+
out = scan_output * torch.nn.functional.silu(gate)
|
| 446 |
+
out = self.out_proj(out)
|
| 447 |
+
return out
|
| 448 |
+
|
| 449 |
+
# fmt: off
|
| 450 |
+
def torch_forward(
|
| 451 |
+
self,
|
| 452 |
+
input_states,
|
| 453 |
+
cache_params: Cache | None = None,
|
| 454 |
+
attention_mask: torch.Tensor | None = None,
|
| 455 |
+
):
|
| 456 |
+
batch_size, seq_len, _ = input_states.shape
|
| 457 |
+
dtype = input_states.dtype
|
| 458 |
+
|
| 459 |
+
# 1. Gated MLP's linear projection
|
| 460 |
+
input_states = apply_mask_to_padding_states(input_states, attention_mask)
|
| 461 |
+
# Add Multipliers
|
| 462 |
+
input_states = input_states * self.ssm_in_multiplier
|
| 463 |
+
projected_states = self.in_proj(input_states)
|
| 464 |
+
projected_states = projected_states * self.mup_vector # ADD Mup Multipliers
|
| 465 |
+
gate, hidden_states_B_C, dt = projected_states.split([
|
| 466 |
+
self.intermediate_size, self.conv_dim, self.num_heads
|
| 467 |
+
], dim=-1)
|
| 468 |
+
hidden_states_B_C = hidden_states_B_C.transpose(1,2)
|
| 469 |
+
|
| 470 |
+
use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx) and seq_len == 1
|
| 471 |
+
|
| 472 |
+
# 2. Convolution sequence transformation
|
| 473 |
+
if use_precomputed_states:
|
| 474 |
+
conv_states = cache_params.update_conv_state(hidden_states_B_C, self.layer_idx)
|
| 475 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 476 |
+
conv_states = conv_states.to(device=self.conv1d.weight.device)
|
| 477 |
+
|
| 478 |
+
hidden_states_B_C = torch.sum(
|
| 479 |
+
conv_states * self.conv1d.weight.squeeze(1), dim=-1
|
| 480 |
+
)
|
| 481 |
+
if self.use_conv_bias:
|
| 482 |
+
hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
|
| 483 |
+
hidden_states_B_C = self.act(hidden_states_B_C)
|
| 484 |
+
else:
|
| 485 |
+
# Init cache
|
| 486 |
+
if cache_params is not None:
|
| 487 |
+
conv_states = nn.functional.pad(
|
| 488 |
+
hidden_states_B_C, (self.conv_kernel_size - hidden_states_B_C.shape[-1], 0)
|
| 489 |
+
)
|
| 490 |
+
conv_states = cache_params.update_conv_state(conv_states, self.layer_idx)
|
| 491 |
+
|
| 492 |
+
hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C)[..., :seq_len].transpose(1, 2))
|
| 493 |
+
|
| 494 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 495 |
+
hidden_states, B, C = torch.split(
|
| 496 |
+
hidden_states_B_C,
|
| 497 |
+
[self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
|
| 498 |
+
dim=-1
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
# 3. SSM transformation
|
| 502 |
+
A = -torch.exp(self.A_log.float()) # [num_heads]
|
| 503 |
+
if use_precomputed_states:
|
| 504 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 505 |
+
cache_device = cache_params.layers[self.layer_idx].recurrent_states.device
|
| 506 |
+
|
| 507 |
+
# Note: there is no need to pad parameter matrices here, as there is just one new token
|
| 508 |
+
# for batched generation
|
| 509 |
+
dt = dt[:, 0, :][:, None, ...]
|
| 510 |
+
dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
|
| 511 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 512 |
+
dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
|
| 513 |
+
|
| 514 |
+
dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
|
| 515 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 516 |
+
A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 517 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 518 |
+
dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
|
| 519 |
+
|
| 520 |
+
# Discretize B
|
| 521 |
+
# [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
|
| 522 |
+
# -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
|
| 523 |
+
B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 524 |
+
B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
|
| 525 |
+
B = B.reshape(batch_size, -1, B.shape[-1])
|
| 526 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 527 |
+
dB = dt[..., None] * B[..., None, :]
|
| 528 |
+
|
| 529 |
+
# Discretize x into dB
|
| 530 |
+
# [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
|
| 531 |
+
hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
|
| 532 |
+
dBx = (dB * hidden_states[..., None]).to(device=cache_device)
|
| 533 |
+
|
| 534 |
+
# State calculation
|
| 535 |
+
ssm_states = cache_params.layers[self.layer_idx].recurrent_states * dA + dBx
|
| 536 |
+
ssm_states = cache_params.update_recurrent_state(ssm_states, self.layer_idx)
|
| 537 |
+
|
| 538 |
+
# Subsequent output
|
| 539 |
+
# [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
|
| 540 |
+
C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 541 |
+
C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
|
| 542 |
+
C = C.reshape(batch_size, -1, C.shape[-1])
|
| 543 |
+
# [bsz, num_heads, head_dim]
|
| 544 |
+
|
| 545 |
+
ssm_states = ssm_states.to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
|
| 546 |
+
# Reshape ssm_states to merge the first two dimensions
|
| 547 |
+
ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
|
| 548 |
+
C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
|
| 549 |
+
y = torch.bmm(ssm_states_reshaped, C_reshaped)
|
| 550 |
+
y = y.view(batch_size, self.num_heads, self.head_dim)
|
| 551 |
+
|
| 552 |
+
# D skip connection
|
| 553 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 554 |
+
D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
|
| 555 |
+
y = (y + hidden_states * D).to(y.dtype)
|
| 556 |
+
|
| 557 |
+
# [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
|
| 558 |
+
y = y.reshape(batch_size, -1)[:, None, ...]
|
| 559 |
+
else:
|
| 560 |
+
# begin ssd naive implementation without einsums
|
| 561 |
+
dt = nn.functional.softplus(dt + self.dt_bias)
|
| 562 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 563 |
+
hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
|
| 564 |
+
B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 565 |
+
C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 566 |
+
B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 567 |
+
C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 568 |
+
pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
|
| 569 |
+
|
| 570 |
+
D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
|
| 571 |
+
|
| 572 |
+
# Discretize x and A
|
| 573 |
+
hidden_states = hidden_states * dt[..., None]
|
| 574 |
+
A = A.to(hidden_states.dtype) * dt
|
| 575 |
+
|
| 576 |
+
# Rearrange into blocks/chunks
|
| 577 |
+
hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
|
| 578 |
+
|
| 579 |
+
# [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
|
| 580 |
+
A = A.permute(0, 3, 1, 2)
|
| 581 |
+
A_cumsum = torch.cumsum(A, dim=-1)
|
| 582 |
+
|
| 583 |
+
# 1. Compute the output for each intra-chunk (diagonal blocks)
|
| 584 |
+
# This is the analog of a causal mask
|
| 585 |
+
L = torch.exp(segment_sum(A))
|
| 586 |
+
|
| 587 |
+
# Contraction of C and B to get G (attention-weights like)
|
| 588 |
+
G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
|
| 589 |
+
G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
|
| 590 |
+
|
| 591 |
+
# Compute M, equivalent to applying attention mask to weights
|
| 592 |
+
M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
|
| 593 |
+
M = M_intermediate.sum(dim=-1)
|
| 594 |
+
|
| 595 |
+
# Compute Y_diag (apply to values)
|
| 596 |
+
Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
|
| 597 |
+
|
| 598 |
+
# 2. Compute the state for each intra-chunk
|
| 599 |
+
# (right term of low-rank factorization of off-diagonal blocks; B terms)
|
| 600 |
+
decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
|
| 601 |
+
B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
|
| 602 |
+
states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
|
| 603 |
+
|
| 604 |
+
# 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
|
| 605 |
+
# (middle term of factorization of off-diag blocks; A terms)
|
| 606 |
+
previous_states = torch.zeros_like(states[:, :1])
|
| 607 |
+
states = torch.cat([previous_states, states], dim=1)
|
| 608 |
+
decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
|
| 609 |
+
decay_chunk = decay_chunk.transpose(1, 3)
|
| 610 |
+
new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
|
| 611 |
+
states, ssm_state = new_states[:, :-1], new_states[:, -1]
|
| 612 |
+
|
| 613 |
+
# 4. Compute state -> output conversion per chunk
|
| 614 |
+
# (left term of low-rank factorization of off-diagonal blocks; C terms)
|
| 615 |
+
state_decay_out = torch.exp(A_cumsum)
|
| 616 |
+
C_times_states = (C[..., None, :] * states[:, :, None, ...])
|
| 617 |
+
state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
|
| 618 |
+
Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
|
| 619 |
+
|
| 620 |
+
# Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
|
| 621 |
+
y = Y_diag + Y_off
|
| 622 |
+
# [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
|
| 623 |
+
y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
|
| 624 |
+
|
| 625 |
+
y = y + D_residual
|
| 626 |
+
# Cutting off padded chunks
|
| 627 |
+
if pad_size > 0:
|
| 628 |
+
y = y[:, :seq_len, :, :]
|
| 629 |
+
y = y.reshape(batch_size, seq_len, -1)
|
| 630 |
+
|
| 631 |
+
# Init cache
|
| 632 |
+
if ssm_state is not None and cache_params is not None:
|
| 633 |
+
ssm_state = cache_params.update_recurrent_state(ssm_state, self.layer_idx)
|
| 634 |
+
|
| 635 |
+
if self.mamba_rms_norm:
|
| 636 |
+
scan_output = self.norm(y, gate)
|
| 637 |
+
else:
|
| 638 |
+
scan_output = y * torch.nn.functional.silu(gate)
|
| 639 |
+
|
| 640 |
+
# end ssd naive
|
| 641 |
+
|
| 642 |
+
# 4. Final linear projection
|
| 643 |
+
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
|
| 644 |
+
return contextualized_states
|
| 645 |
+
# fmt: on
|
| 646 |
+
|
| 647 |
+
def forward(
|
| 648 |
+
self,
|
| 649 |
+
hidden_states,
|
| 650 |
+
cache_params: Cache | None = None,
|
| 651 |
+
attention_mask: torch.Tensor | None = None,
|
| 652 |
+
**kwargs,
|
| 653 |
+
):
|
| 654 |
+
if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
|
| 655 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
|
| 656 |
+
dtype = hidden_states.dtype
|
| 657 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 658 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 659 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 660 |
+
|
| 661 |
+
return self.torch_forward(hidden_states, cache_params, attention_mask)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class FalconH1MLP(LlamaMLP):
|
| 665 |
+
def __init__(self, config: FalconH1Config):
|
| 666 |
+
super().__init__(config)
|
| 667 |
+
self.gate_multiplier, self.down_multiplier = config.mlp_multipliers
|
| 668 |
+
|
| 669 |
+
def forward(self, x):
|
| 670 |
+
y = self.up_proj(x) * self.act_fn(self.gate_proj(x) * self.gate_multiplier)
|
| 671 |
+
y = self.down_proj(y) * self.down_multiplier
|
| 672 |
+
return y
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class FalconH1RMSNorm(LlamaRMSNorm):
|
| 676 |
+
pass
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class FalconH1DecoderLayer(GradientCheckpointingLayer):
|
| 680 |
+
def __init__(self, config: FalconH1Config, layer_idx: int):
|
| 681 |
+
super().__init__()
|
| 682 |
+
self.feed_forward = FalconH1MLP(config)
|
| 683 |
+
|
| 684 |
+
head_dim = config.hidden_size // config.num_attention_heads
|
| 685 |
+
self.channels_attn = config.num_attention_heads * head_dim + 2 * config.num_key_value_heads * head_dim
|
| 686 |
+
|
| 687 |
+
self.mamba = FalconH1Mixer(config=config, layer_idx=layer_idx)
|
| 688 |
+
|
| 689 |
+
self.self_attn = FalconH1Attention(config, layer_idx)
|
| 690 |
+
|
| 691 |
+
self.attention_in_multiplier = config.attention_in_multiplier
|
| 692 |
+
self.ssm_out_multiplier = config.ssm_out_multiplier
|
| 693 |
+
self.attn_out_multiplier = config.attention_out_multiplier
|
| 694 |
+
|
| 695 |
+
self.input_layernorm = FalconH1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 696 |
+
self.pre_ff_layernorm = FalconH1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 697 |
+
|
| 698 |
+
def forward(
|
| 699 |
+
self,
|
| 700 |
+
hidden_states: torch.Tensor,
|
| 701 |
+
attention_mask: torch.Tensor | None = None,
|
| 702 |
+
mamba_attention_mask: torch.Tensor | None = None,
|
| 703 |
+
position_ids: torch.LongTensor | None = None,
|
| 704 |
+
past_key_values: Cache | None = None,
|
| 705 |
+
use_cache: bool | None = False,
|
| 706 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 707 |
+
**kwargs,
|
| 708 |
+
) -> tuple[torch.FloatTensor]:
|
| 709 |
+
"""
|
| 710 |
+
Args:
|
| 711 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 712 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 713 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 714 |
+
past_key_values (`Cache`, *optional*): cached past key and value projection states
|
| 715 |
+
use_cache (`bool`, *optional*):
|
| 716 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 717 |
+
(see `past_key_values`).
|
| 718 |
+
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
| 719 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
| 720 |
+
with `head_dim` being the embedding dimension of each attention head.
|
| 721 |
+
kwargs (`dict`, *optional*):
|
| 722 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 723 |
+
into the model
|
| 724 |
+
"""
|
| 725 |
+
|
| 726 |
+
residual = hidden_states
|
| 727 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 728 |
+
|
| 729 |
+
mamba_hidden_states = self.mamba(
|
| 730 |
+
hidden_states=hidden_states,
|
| 731 |
+
cache_params=past_key_values,
|
| 732 |
+
attention_mask=mamba_attention_mask,
|
| 733 |
+
)
|
| 734 |
+
mamba_hidden_states = mamba_hidden_states * self.ssm_out_multiplier
|
| 735 |
+
|
| 736 |
+
attention_hidden_states, _ = self.self_attn(
|
| 737 |
+
hidden_states=hidden_states * self.attention_in_multiplier,
|
| 738 |
+
attention_mask=attention_mask,
|
| 739 |
+
position_ids=position_ids,
|
| 740 |
+
past_key_values=past_key_values,
|
| 741 |
+
use_cache=use_cache,
|
| 742 |
+
position_embeddings=position_embeddings,
|
| 743 |
+
**kwargs,
|
| 744 |
+
)
|
| 745 |
+
attention_hidden_states = attention_hidden_states * self.attn_out_multiplier
|
| 746 |
+
|
| 747 |
+
hidden_states = mamba_hidden_states + attention_hidden_states
|
| 748 |
+
|
| 749 |
+
# residual connection after attention
|
| 750 |
+
hidden_states = residual + hidden_states
|
| 751 |
+
|
| 752 |
+
# feed-forward
|
| 753 |
+
residual = hidden_states
|
| 754 |
+
hidden_states = self.pre_ff_layernorm(hidden_states)
|
| 755 |
+
hidden_states = self.feed_forward(hidden_states)
|
| 756 |
+
hidden_states = residual + hidden_states
|
| 757 |
+
|
| 758 |
+
return (hidden_states,)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
@auto_docstring
|
| 762 |
+
class FalconH1PreTrainedModel(PreTrainedModel):
|
| 763 |
+
config: FalconH1Config
|
| 764 |
+
base_model_prefix = "model"
|
| 765 |
+
supports_gradient_checkpointing = True
|
| 766 |
+
_no_split_modules = ["FalconH1DecoderLayer"]
|
| 767 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 768 |
+
_supports_flash_attn = True
|
| 769 |
+
_supports_sdpa = True
|
| 770 |
+
_is_stateful = True
|
| 771 |
+
|
| 772 |
+
_can_record_outputs = {
|
| 773 |
+
"hidden_states": FalconH1DecoderLayer,
|
| 774 |
+
"attentions": FalconH1Attention,
|
| 775 |
+
}
|
| 776 |
+
|
| 777 |
+
@torch.no_grad()
|
| 778 |
+
def _init_weights(self, module):
|
| 779 |
+
super()._init_weights(module)
|
| 780 |
+
if isinstance(module, FalconH1Mixer):
|
| 781 |
+
init.ones_(module.dt_bias)
|
| 782 |
+
init.copy_(module.A_log, torch.log(torch.arange(1, module.num_heads + 1)))
|
| 783 |
+
init.ones_(module.D)
|
| 784 |
+
elif isinstance(module, FalconH1Model):
|
| 785 |
+
mup_vector = compute_mup_vector(module.config)
|
| 786 |
+
for layer in module.layers:
|
| 787 |
+
init.copy_(layer.mamba.mup_vector, mup_vector)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def compute_mup_vector(config):
|
| 791 |
+
"""
|
| 792 |
+
Computes the MuP vector based on model configuration.
|
| 793 |
+
|
| 794 |
+
FalconH1 applies different MuP multiplier for each dimension of the hidden states.
|
| 795 |
+
The MuP vector is partitioned into chunks, and each chunk is multiplied with its
|
| 796 |
+
corresponding projected dimension.
|
| 797 |
+
|
| 798 |
+
Args:
|
| 799 |
+
config: FalconH1Config object
|
| 800 |
+
|
| 801 |
+
Returns:
|
| 802 |
+
torch.Tensor: The computed MuP vector
|
| 803 |
+
"""
|
| 804 |
+
# We'll need some values from the config to compute the vector dimensions
|
| 805 |
+
intermediate_size = (
|
| 806 |
+
config.mamba_d_ssm if config.mamba_d_ssm is not None else int(config.mamba_expand * config.hidden_size)
|
| 807 |
+
)
|
| 808 |
+
groups_time_state_size = config.mamba_n_groups * config.mamba_d_state
|
| 809 |
+
num_heads = config.mamba_n_heads
|
| 810 |
+
zxbcdt_multipliers = config.ssm_multipliers
|
| 811 |
+
|
| 812 |
+
vector_shape = 2 * intermediate_size + 2 * groups_time_state_size + num_heads
|
| 813 |
+
mup_vector = torch.ones(1, 1, vector_shape)
|
| 814 |
+
|
| 815 |
+
# Apply multipliers to different sections of the vector
|
| 816 |
+
mup_vector[:, :, :intermediate_size] *= zxbcdt_multipliers[0]
|
| 817 |
+
mup_vector[:, :, intermediate_size : 2 * intermediate_size] *= zxbcdt_multipliers[1]
|
| 818 |
+
mup_vector[:, :, 2 * intermediate_size : 2 * intermediate_size + groups_time_state_size] *= zxbcdt_multipliers[2]
|
| 819 |
+
mup_vector[
|
| 820 |
+
:, :, 2 * intermediate_size + groups_time_state_size : 2 * intermediate_size + 2 * groups_time_state_size
|
| 821 |
+
] *= zxbcdt_multipliers[3]
|
| 822 |
+
mup_vector[:, :, 2 * intermediate_size + 2 * groups_time_state_size :] *= zxbcdt_multipliers[4]
|
| 823 |
+
|
| 824 |
+
return mup_vector
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
@auto_docstring
|
| 828 |
+
# Adapted from transformers.models.jamba.modeling_jamba.JambaModel
|
| 829 |
+
class FalconH1Model(FalconH1PreTrainedModel):
|
| 830 |
+
def __init__(self, config: FalconH1Config):
|
| 831 |
+
super().__init__(config)
|
| 832 |
+
self.padding_idx = config.pad_token_id
|
| 833 |
+
self.vocab_size = config.vocab_size
|
| 834 |
+
|
| 835 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 836 |
+
decoder_layers = []
|
| 837 |
+
for i in range(config.num_hidden_layers):
|
| 838 |
+
decoder_layers.append(FalconH1DecoderLayer(config, layer_idx=i))
|
| 839 |
+
self.layers = nn.ModuleList(decoder_layers)
|
| 840 |
+
|
| 841 |
+
self._attn_implementation = config._attn_implementation
|
| 842 |
+
self.final_layernorm = FalconH1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 843 |
+
self.rotary_emb = FalconH1RotaryEmbedding(config=config)
|
| 844 |
+
|
| 845 |
+
self.embedding_multiplier = config.embedding_multiplier
|
| 846 |
+
self.lm_head_multiplier = config.lm_head_multiplier
|
| 847 |
+
|
| 848 |
+
self.gradient_checkpointing = False
|
| 849 |
+
# Compute the MuP vector once and register it for all layers
|
| 850 |
+
mup_vector = compute_mup_vector(config)
|
| 851 |
+
for layer in self.layers:
|
| 852 |
+
layer.mamba.register_buffer("mup_vector", mup_vector.clone(), persistent=False)
|
| 853 |
+
|
| 854 |
+
# Initialize weights and apply final processing
|
| 855 |
+
self.post_init()
|
| 856 |
+
|
| 857 |
+
@merge_with_config_defaults
|
| 858 |
+
@capture_outputs
|
| 859 |
+
@auto_docstring
|
| 860 |
+
def forward(
|
| 861 |
+
self,
|
| 862 |
+
input_ids: torch.LongTensor | None = None,
|
| 863 |
+
attention_mask: torch.Tensor | None = None,
|
| 864 |
+
position_ids: torch.LongTensor | None = None,
|
| 865 |
+
past_key_values: Cache | None = None,
|
| 866 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 867 |
+
use_cache: bool | None = None,
|
| 868 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 869 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 870 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 871 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 872 |
+
|
| 873 |
+
if inputs_embeds is None:
|
| 874 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embedding_multiplier
|
| 875 |
+
hidden_states = inputs_embeds
|
| 876 |
+
|
| 877 |
+
if use_cache and past_key_values is None:
|
| 878 |
+
past_key_values = DynamicCache(config=self.config)
|
| 879 |
+
|
| 880 |
+
if position_ids is None:
|
| 881 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 882 |
+
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device) + past_seen_tokens
|
| 883 |
+
position_ids = position_ids.unsqueeze(0)
|
| 884 |
+
|
| 885 |
+
causal_mask = create_causal_mask(
|
| 886 |
+
config=self.config,
|
| 887 |
+
inputs_embeds=inputs_embeds,
|
| 888 |
+
attention_mask=attention_mask,
|
| 889 |
+
past_key_values=past_key_values,
|
| 890 |
+
position_ids=position_ids,
|
| 891 |
+
)
|
| 892 |
+
mamba_mask = self._update_mamba_mask(attention_mask, past_key_values)
|
| 893 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 894 |
+
|
| 895 |
+
for decoder_layer in self.layers:
|
| 896 |
+
layer_outputs = decoder_layer(
|
| 897 |
+
hidden_states,
|
| 898 |
+
attention_mask=causal_mask,
|
| 899 |
+
mamba_attention_mask=mamba_mask,
|
| 900 |
+
position_ids=position_ids,
|
| 901 |
+
past_key_values=past_key_values,
|
| 902 |
+
use_cache=use_cache,
|
| 903 |
+
position_embeddings=position_embeddings,
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
hidden_states = layer_outputs[0]
|
| 907 |
+
|
| 908 |
+
hidden_states = self.final_layernorm(hidden_states)
|
| 909 |
+
|
| 910 |
+
return BaseModelOutputWithPast(
|
| 911 |
+
last_hidden_state=hidden_states,
|
| 912 |
+
past_key_values=past_key_values,
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
def _update_mamba_mask(self, attention_mask, past_key_values):
|
| 916 |
+
"""
|
| 917 |
+
No need for zeroing states when
|
| 918 |
+
1. Cached forward
|
| 919 |
+
2. Attending to all inputs
|
| 920 |
+
"""
|
| 921 |
+
mamba_mask = attention_mask
|
| 922 |
+
if (past_key_values is not None and past_key_values.has_previous_state()) or (
|
| 923 |
+
attention_mask is not None and torch.all(attention_mask == 1)
|
| 924 |
+
):
|
| 925 |
+
mamba_mask = None
|
| 926 |
+
return mamba_mask
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
class FalconH1ForCausalLM(LlamaForCausalLM):
|
| 930 |
+
@can_return_tuple
|
| 931 |
+
@auto_docstring
|
| 932 |
+
def forward(
|
| 933 |
+
self,
|
| 934 |
+
input_ids: torch.LongTensor | None = None,
|
| 935 |
+
attention_mask: torch.Tensor | None = None,
|
| 936 |
+
position_ids: torch.LongTensor | None = None,
|
| 937 |
+
past_key_values: Cache | None = None,
|
| 938 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 939 |
+
labels: torch.LongTensor | None = None,
|
| 940 |
+
use_cache: bool | None = None,
|
| 941 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 942 |
+
**kwargs,
|
| 943 |
+
) -> tuple | CausalLMOutputWithPast:
|
| 944 |
+
r"""
|
| 945 |
+
Example:
|
| 946 |
+
|
| 947 |
+
```python
|
| 948 |
+
>>> from transformers import AutoTokenizer, FalconH1ForCausalLM
|
| 949 |
+
|
| 950 |
+
>>> model = FalconH1ForCausalLM.from_pretrained("...")
|
| 951 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("...")
|
| 952 |
+
|
| 953 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 954 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 955 |
+
|
| 956 |
+
>>> # Generate
|
| 957 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 958 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 959 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 960 |
+
```"""
|
| 961 |
+
outputs = self.model(
|
| 962 |
+
input_ids=input_ids,
|
| 963 |
+
attention_mask=attention_mask,
|
| 964 |
+
position_ids=position_ids,
|
| 965 |
+
past_key_values=past_key_values,
|
| 966 |
+
inputs_embeds=inputs_embeds,
|
| 967 |
+
use_cache=use_cache,
|
| 968 |
+
**kwargs,
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
hidden_states = outputs[0]
|
| 972 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 973 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 974 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :]) * self.model.lm_head_multiplier
|
| 975 |
+
|
| 976 |
+
loss = None
|
| 977 |
+
if labels is not None:
|
| 978 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 979 |
+
|
| 980 |
+
return CausalLMOutputWithPast(
|
| 981 |
+
loss=loss,
|
| 982 |
+
logits=logits,
|
| 983 |
+
past_key_values=outputs.past_key_values,
|
| 984 |
+
hidden_states=outputs.hidden_states,
|
| 985 |
+
attentions=outputs.attentions,
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
def prepare_inputs_for_generation(
|
| 989 |
+
self,
|
| 990 |
+
input_ids,
|
| 991 |
+
past_key_values=None,
|
| 992 |
+
attention_mask=None,
|
| 993 |
+
inputs_embeds=None,
|
| 994 |
+
position_ids=None,
|
| 995 |
+
use_cache=True,
|
| 996 |
+
is_first_iteration=False,
|
| 997 |
+
**kwargs,
|
| 998 |
+
):
|
| 999 |
+
kwargs["logits_to_keep"] = self.config.num_logits_to_keep
|
| 1000 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 1001 |
+
input_ids,
|
| 1002 |
+
past_key_values=past_key_values,
|
| 1003 |
+
attention_mask=attention_mask,
|
| 1004 |
+
inputs_embeds=inputs_embeds,
|
| 1005 |
+
position_ids=position_ids,
|
| 1006 |
+
use_cache=use_cache,
|
| 1007 |
+
is_first_iteration=is_first_iteration,
|
| 1008 |
+
**kwargs,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
return model_inputs
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
__all__ = ["FalconH1Model", "FalconH1ForCausalLM", "FalconH1PreTrainedModel"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_230847/step_114000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:55dbd66d275adb0aa5d4d1f0d2473f926e08c715c00d20992197d46d60232509
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260609_230847/step_266000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:705084e921433bd981a7322943deef3c892aa818f1f9182fdf67d23af3d0c259
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/samples/tinystories_t5_len1024_d768_8gpu_step1000_decode128_quick_n8/first8.txt
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
checkpoint=runs/tinystories_t5_logdirichlet_len1024_C1_to_64_d768_l12_h12_gbs512_8gpu_40k_20260527_121803/step_001000.pt
|
| 2 |
+
step=1000
|
| 3 |
+
decode=dualline_time_aligned_dirichlet_final_state
|
| 4 |
+
c_min=1.0 c_max=64.0
|
| 5 |
+
steps=128 temp=1.45 bridge_power=1.0 temp0=0.0
|
| 6 |
+
bos=1:</s> eos=1:</s>
|
| 7 |
+
===== sample 0 =====
|
| 8 |
+
head_tokens: ['</s>', '▁no', 'dded', '.', '▁She', '▁said', ',', '▁"', 'I', 't', "'", 's', '▁noble', '▁mine', '!"', '▁Li']
|
| 9 |
+
tail_tokens: ['▁hug', '.', '▁He', '▁', 's', 'cream', 'ink', '▁', 'a', '▁', 'pond', '▁and', '▁saw', '▁', 'a', '</s>']
|
| 10 |
+
</s> nodded. She said, "It's noble mine!" Lily and said, sing. She ran to the dirt and waited. She was surprised and ignored him. She smiled and said she was sorry. She looked at her mom and hugged her kindly. She had to be harbor. She gave him a punishment and put the Zeitraum on the table. They felt sad and said sorry. They had aips. They loved their names. They looked east and Car and laughed. They were happy and aminte the prince. They ran to the valley. They tested the sap and tapped and their mad. They promised to play with the insects and the explored.</s> Lily was a famous lamp. They liked to explore the crowd. They liked to create stuff. They used their fans and dive to the airport. They made a big boom and the crowd. They had many beds and headss and potatoes and smell. They would to the pages. They had asti a cliff. Then they saw a big boom and saw a web. She did not know thevoller to bother it. She sounded a zigQupop, but Lily said. She had a big backpack and planted him. She was a escape. The wizard was small. She jumped and searched and spoke. They rescue the sketch. They had a bad cliff. They screamed and revealed. They said they had made a boom and a valuable EP. They were bored and happy. But they had sixweighed. They stayed home and simpleted. They wanted to escape. They had a taxi. Lily felt a very lizici squirrel. They was happy that that they wanted to create aress. They wished theing was not ruined.</s> Lily wanted to build a big pond. She had had many incredibles and videos. She liked the crosters and buses. She had notresident on the swing. She had a big rad pond with the straw. She swung a big radze. It was an otte and a lizard. "It's, Lily. It's so modern shade!" Lily. They searched and liked to destroy themerkt. They lizlinked and vanilla and had a feast. They had a explorer crober of helicopter. They opened the tracks and roar and saw a pond. They were castle. They walked to the university and the lionolli and a big lion. "Let'sKI, spannend gloves!" Lily and said. "That was a modern oasis. They d and a lion. They was surprised. They ate laughed. They smiled and smiled. They said, "Look, it's a Finance. We can protect liking it." They clapped. They were happy and smart and become ending Grecia.</s> Lily and Tom were friends. They liked to play outside and solve mattresss. They liked the lizgars and bluetang. Lily and Tom were very happy. They had a lot and thepig and started to gesture. They squaung the oasis and lizncy. They disturbed their runs. They did not know the king. They caught the melon and breathed. They liked to each other and drinks. They crossed the bucket and Fence and shorter. They aimed away and the coins. They had a blast. They was frog lion and laughed. They sounded lizmer and wanted to play together. They had a shock. They qud and happy. The end.</s> Tom was a big lizaccoon in the island. It was a big pond and a rat. They likedassembling to the cabin and a pond. It was a lizber. Tom and Tom went to the cros. They had aaxe. The lizco and shouted. They did not like the monkey. They waited and came to the valley. They lizaked and a lion. They loved to Bis and croleton, and crashed into the fox. They ran to the pond and the pond and the lizcoon. They revealed their den and wing and escaped. They shouted and the pig and sang. They made the lizstrich and hug incalzireers and Binffes. They was happy and enjoyed their banque home.</s> lion was a lion and wreck to Reduce him. He wanted to go and make pond. His he walked to the pond with him. He was a cough and a scarf and made a hug. He screamink a pond and saw a</s>
|
| 11 |
+
===== sample 1 =====
|
| 12 |
+
head_tokens: ['</s>', '▁when', '▁', 'he', '▁saw', '▁', 'a', '▁silver', '▁lawn', '.', '▁The', '▁dinosaur', '▁was', '▁so', '▁frustrated', '▁and']
|
| 13 |
+
tail_tokens: ['f', 'rog', '▁mondiale', '▁inside', '.', '▁He', '▁was', '▁', 'a', '▁shock', '▁and', '▁', 'roar', '▁and', '▁', '</s>']
|
| 14 |
+
</s> when he saw a silver lawn. The dinosaur was so frustrated and Jerry to thegust, but when he didn't realize his property. He said that he wanted to discuss what to do. He was embarrassed because he didn't want to do anything. He had a challenge where he was too late. He dl onto his wrist, that he was a peculiar, a valuable fruit echo as he ate thepainters. The sponge was thrilled and he wanted to dive again. He was so everyone child, but he felt embarrassed that he couldn't wait.</s> Once upon a time, there was a powerful lizco. The motion had a big lizard. One day, a fox went to a pond with a Tun. He wanted to decide himself, he wanted to make a sensation. Suddenly he heard a lizco. Thecorn Israeli a Fear and a crocohut off prove a chat. The ratco repaycan of himself. The lizhave was a little lizco. The lizgarleton reliability a fox. He asked the Mother s3-2 it crocooence. The crocod and sent it left from the harbor. The lizuddle a magical lizmaion. The little mouse and affe cro lizgarbling was a lion. The rat550 the lizcoity in the forest. It was very quick and he Body mean to the experience.</s> Once upon a time there was a poor mighty lizard. He had an radrog and loved everything. One day he was aright flower that explorer on the villages. He felt so polite. He ran to the pond and said, "That's too family for a croleton helping when when he was a simpleer and grabbed a rhythm. He had a short tools, José thecorns and smiled. He hopped down and how he was a valuable Anwendung. He ran to the tool and he would be to receive the mouse. Theaded was transactions and passing investments, but it was impossible. He put therichten in the attacking and he was bouSeveral. He wished it was impossible. He felt so sad he liked An. He didn't want to introduce anything, when he made sure. Then, Charlie had a valuable tool long movements. He was so happy to him. He couldn't resist his shoulder.</s> Once upon a time there was a boy named Riley. He had a reallycontinent and he had completed tools. One day, a parade had had a invitation in thenom Michael. He wanted to ignore it, but he managed to the beat, and beautifully cousin. Suddenly, the little boy came to the hotel and found lots of cute paintings. He felt very happy when he saw a dead clearing. He had grow shaking and asked it. He stayed towards the little boy. He tried to ignore the comment, but Name that he started to spread the anger and following the brake. It was clouds, the mouse was healed! He thanked the sur cadouri and theeast and the highest battery often succeeded returning forehead. He smiled back and said, "You are lessDB Bob!" His brother smiled and smiled as he said. He asked the recueil that he had received a magical involvedul of indeed.</s> Once upon a time, there was a ce. He loved to play with his friends. One day, unilateral saw a mechanic and he wanted to go to the market. He was very scared as a jutter loft as he had an idea. He knew that he was a nice quicklyened. Suddenly, a little bird fox was flutter complaining down on the ground. Then he realized, it was a smile. The lion smiled and smiled a lot of shelter. The fox bowed down and couldn't manage to warmth he felt miserable again and he liked to risk himself. He was what to belonged.</s> Once there was a lion. He wanted to protecteptic excited and rules, but he was so carefulter. One day, he saw a big chimney and had a roar. He was excited and walking, he spotted a tough walking in the park. As he was a, he felt a nibmeter on the ground. He shooktered grey, and he knew the random why he wasige andious a big chic frog mondiale inside. He was a shock and roar and </s>
|
| 15 |
+
===== sample 2 =====
|
| 16 |
+
head_tokens: ['</s>', '▁repair', '▁the', '4,', '.', '▁But', '▁the', 'n', ',', '▁it', '▁was', '▁gone', '▁', 'a', '▁', 'wolf']
|
| 17 |
+
tail_tokens: ['▁stirring', '▁in', '▁the', '▁Buddha', '.', '▁They', '▁broke', '▁the', '▁taxi', '▁and', '▁', 'escaped', '.', '▁The', '▁tub', '</s>']
|
| 18 |
+
</s> repair the4,. But then, it was gone a wolf. It was dull and mysterious. "It's go to the stream. It's Therapeutic the rat!" They said. They nodded and thanked the fish. They smiled and held down the pond and down. It was a bacco swimmer on the nostalgic. They warned and a tour. They liked cheese, he saw a big cro. He was a big landscape. He started to realize the seara was a zig. It was a wing. Suddenly, it was a big bcod it. They sounded a wing. It looked deliberately to behind. "No, I do you want to be afraid. It was too Shoes and turning Amy. It climatique the spreading and sparkly and caught a ha. "Shh, crown, Pipe. It was a VR. "It tehnici!" she shouted. "I'm here!" she said. They were happy and wanted to serve the House. They went to the grass and saw the arop. They was running and hopeful. They wanted to see the workers and a Gardenrland. They had Auf the departure. They lived in a big sign. She was neuen in a priber. She liked to strip the lizber and make them. It was snacks. She tfini and listened to him. She smiled and said, "yesams. I recommend you live the basement.”. So, she went to the lizster. She held the lime captive to the oasis. She had a lot ofplace. She gave was a basket of theSet. She went to the pig bank and photos. She had a lot of fun. She had the ornament in the Miami and loved the husband. They had a yummy suspension and Back the mitten. She was very happy.</s> Tom was a modest thoughtful girl. She liked to snugglops and a monkey in the forest. She would build a pig and the mud. One day, Tom was a big neck. They wanted to play with it. They had a fat mission. So he wanted to solve the pond. They spread some water. They made a click. It was red and juicy and had po velvet. They raised the pond and a justrich. They waited for him. They saw a oasis and a pond. They made a sides and the mouse and a boom. They liked to pass it. They ran to the pond and swept to the3.2. They laughed and started to collect more. They argued away. They was a nice urma. They had the art. They bought the palace and sent to the area. They were very sad. They had a simple barbecue. They wanted to bother it. They had a a bweb and acorn. It was not ugly. The kanostrich das Tom and decided to go home. They liked the sand. They had the lizber. They was Elle. "It's degrees!" The team and shouted. They started to argue and argue. They had to the bride. They was a sword and escape to the holiday. They had coloan Apprentice. They was explorer and tiger. They had a slices, dessert and pinetended to the hotel. It was very sad and less more. They was a lizmer.</s> One day, she went to the park and saw the girl. She liked that it was ak. She liked to play with the strawberry. She knew that it was cold and a erreicht. She wanted to disturb the lizncy. She had fiberglass a cro pond. She had a cliff and barre and cracked the rat. They wanted to marry the pond. They wanted the tent and answers. "Ow, mom! It's Camp!" she said. She ran to the line of the water. They tangled the anchor. Lily's mom was surprised and happy. She was sad. She rlinked and held the oasis and crash. She liked the rat and the grill. She gave them a hug.</s> Lily and her mom. They liked to play with their mom and dad. They were lol and stuck. They wanted to examine it inside. They saw a hurricane. It was a big cow. Lily and the rush. They wanted to serve the curtain. They had fourteen and amplasat. They ran to the third. The performers was faster and covered the lightning. But it was a big retire with a loudpaw and sent it burned to jeunes. The dictionary was mild and stirring in the Buddha. They broke the taxi and escaped. The tub</s>
|
| 19 |
+
===== sample 3 =====
|
| 20 |
+
head_tokens: ['</s>', 'Gra', '▁Administrator', '▁worry', '▁that', '▁', 'he', '▁had', '▁managed', '▁to', '▁be', '▁punished', '.', '▁He', '▁had', '▁fake']
|
| 21 |
+
tail_tokens: ['▁there', '▁was', '▁', 'a', '▁little', '▁girl', '▁named', '▁Mi', 'a', '.', '▁Her', '▁extensions', '▁was', '▁3', '▁years', '</s>']
|
| 22 |
+
</s>Gra Administrator worry that he had managed to be punished. He had fake discomfort that he didn't recognize the kenn steady. He knew he had planned he eat the lizber. It was a castle. The Ei was very embarrassed and protecting the rat. The fox had a great idea. He hopped over his describe, the rhythm he was glad that he had completed the medicine.</s> Riley was a croco the pig. He never wanted a further, but he wanted to explore a wish. He was so delighted that he could travelling when he heard a roar. It was a thion. The fairy was curse because it was so slippery and *. They had found a big lizmeron too. It was there and modest distinct. With a pig, it was a rat. But it was a fox. The jcob bank and offered thelion to treated becoming in the garden. It was a lizumble. The crocoed the radco who wanted to dive thescreen. They wrapped the hippounk in the garden.</s> Ed had a stuffed ju. She liked to point on the journey, he remembered the frog provided Elephant. She had stiff the pond onto the crowd. It was a kindlyloom the pipe. She walked closer to the harbor, she saw a thief pond. It was a very frightening gift. She had a friendly cliff. It was so nice and d the villagers. She had stolenexploded and Georg. It was a whole fox to be it. She smiled and started to reverse as the pond acted as the pig, he felt di relaxed.</s> Once upon a time there was a little girl who loved to prevent therobo. One day, she went to a house. She wanted to encourage the servant to be gre her undergraduate and attention to the core. One Suddenly, the girl was determined to receive. Her elderlyttle's luggage was fragilemonetiz challenging and wanted it. When the vendor, she saw a little bit containers. She examined thelandais and made Rover traffic Zimmer. She felt ready to explore the toilet. She skipped down and fixed the sea and shape. She conquered and removed the temptation. She had a great time and flupolitik honour. Still, she started to checks the ight Birthday and it was organised. She said pray as the wholeexplorer went inside and enjoyed them again.</s> Once upon a time there was a little girl called Nora. She had a lot of companion and unusuald. It was a po ROedge and the elderly bell. One day,, a little girl named aaccelerated to played. It was a donors and a collection of sincerely. She was so happy and when she went to university and examined thelikewise. She ran to the pond. She looked at it and saw a hugeм. It was a mur changes that he couldn't believe what a contained. When he was a bench, she looked right and harmless underneath them anyway. Once upon a time, there was a tricwane. One of the lizleton. It was a big thiel. He had changingrely invitation that he had never scent, a nearest and protected sensation. She wanted to cross the cliff, so she mixing the destination and she couldn't get down. The lion was so nice, but a little girl was worried. Suddenly, the girl was complete a lion. She smiled and said, "Hello, I'm so lucky to create a question." The girl was so sad and he asked the now to celebrate. Suddenly, he s Constantalessness towards the again. The frog was so sad. The pig smiled. When he went home. He smiled and followed theApotheke and found a massage. The girl was sad. The girl smiled and said he had made a valuable outdoor giant.</s> Once there was a musician. He was out to the Too hills. He had an idea that he was very opened! He was so excited to explore the world around it. He had warm before he had managed. He opened the key and walked down to the cash properly. He peeked and recorded it. He watched as he searched as he was examining, andvous that he had managed to cross the temperature. He smiled and he had a hug and gave him to the grandmother. His he was so proud of himself.</s> Once there was a little girl named Mia. Her extensions was 3 years</s>
|
| 23 |
+
===== sample 4 =====
|
| 24 |
+
head_tokens: ['</s>', '▁', 'hopped', '▁in', '▁the', '▁garden', '.', '▁She', '▁saw', '▁', 'a', '▁mysterious', '▁', 'lion', '▁', 'b']
|
| 25 |
+
tail_tokens: ['▁with', '▁his', '▁', 'h', 'gator', '▁and', '▁his', '▁body', '.', '▁One', '▁day', ',', '▁', 'a', '▁messy', '</s>']
|
| 26 |
+
</s> hopped in the garden. She saw a mysterious lion blutter dedicated as she could bend it, as she was practicing to move the lion. They knew that the unusual chase the truth. The attendant wanted to restore the lion's die. It was a valuable leap in the lizcoleton. The croaked down the island. Dr swaneptilor a thoughtful 2008.. The mul as he balanced in the pig.</s> Once upon a time there was a little lizc ile. He had an liz adevăratlablcrow. One day, Tom saw a rat and it was scary. They had the acorn to the pond. It was a poor, but it didn't want to sell it. They raised the duck's kindly. They didn't want to escape. The was very sad and Fard acknowledge. The lizcowished he had been so lucky to defeat the keeper. The lizard the sadness and they went back to the lizleton. They explained, the frog had a pig and the glide. The end.</s> Once upon a time there was a big ranch. He was going to remove the which. He loved to rest and steel items, but it was very Free. He would deliver the fastest shelves in the forest. One day, he saw a littleprivileged. He knew that he didn't care that was not supposed to return. One day, but he didn't want to take the competition onto the overseas. He came over to the violations and Terms his grandmother. The challenge was so sad that it didn't listen to him to get afraid. Finally, he was a minute of adults punished if he had caused Vegas. Timmy was feeling very sad. young that he had to punish his punishment. He was a fierce situation and sympathetic wizard. He's defeated the sausage subway. He scur beads down the counter. The operation was a magicaltale and attached the cartral out to the industria. The boy said, "Don't worry why I don't want to survive." Sam smiled and he was a lucky navy. When he got home, he felt better. He was very happy that the cell. He knew that he was a nice zigink.</s> One day, a mulile saw a pond. He looked like to go to the harbor in the distance. He scuram steady when he stopped, a ant spoke a journey. The croco genie and the lion was swiming andmotion. He felt very sad and had a big hug. The rat approached the tree and ate the fox. But the lion managed to the waist. The lizcolizsterdown back. He had solved the oasis.</s> Once upon a time there was a big thieon. They lived in a big a collector. One day, the girl was hungry. The pig was competitive, collectingting and the chimney was a gray rabbit. The girl weighed, the a whole pig and a tiger. The girl was very happy. She taught the branch to complete the weight. They ran off to the fountain and broke the twitrog. The girl guessed that the girl didn't want to avoid the stitch. The girl said, "No, you don't a cro and the liz lot." The black ant caught on the artwork and ate thehopped inside. The little girl felt a prescription the worker emotionally the paths. She felt sad and teasing its dreams.</s> Once upon a time, there was a little boy named Timmy. Timmy always loved to play in the neighbourhood. One day, Tim saw a little boy named Timmy. Timmy was jovious that he didn't move. He asked what he happened. Timmy had a real injured idea. Tim didn't know what he needed. He wanted to see his eyes and start yet down. Timmy saw a bigberufliche with him tosting theDezvoltare. It was heavy and wondered what to Timmy. Timmy asked that if he was gleichzeitig that he was supposed to his mommy. Timmy was very sad, but he wouldn't like what to do. Timmy was actually a lot of fuel and he respected the audience. He knew he had to be careful and listen to do it. Tim was sad to help. And he had no understanding and ignored him.</s> Once upon a time there was a boy named Tim. Tim loved to play with his hgator and his body. One day, a messy</s>
|
| 27 |
+
===== sample 5 =====
|
| 28 |
+
head_tokens: ['</s>', '▁novel', ',', '▁Tim', '▁was', '▁', 'a', '▁compassionate', '▁', 'laying', '▁on', '▁his', '▁24,', '▁and', '▁held', '▁his']
|
| 29 |
+
tail_tokens: ['a', 'centrul', '▁on', '▁the', '▁counter', '.', '</s>', '▁Once', '▁upon', '▁', 'a', '▁time', '▁there', '▁was', '▁', '</s>']
|
| 30 |
+
</s> novel, Tim was a compassionate laying on his 24, and held his waist. Timmy ran to his mom and asked that if he had drawn. He had before nowhere to punish his événements. So, he heard a voice and he ran to his bedroom. Suddenly, Tim was a voice that he was gone. He was soloadedless and cleaned the personaj. training that he didn't go enough to remove it. Timmy was sad that he couldn't. He wished he had he lay down the counter, he smiled and observed the suit Belgium where it was frozen.</s> One day, a Jon saw a musician named Andrew. It was a blue pig and aexcept on the island. He had wasink and finally; a crow across the others. He was so mittels and the pond. He was a very kind and he began to relax. But when herained trying to arrive where it was a fox. He knew he had to replace the kano stand a tree. The duck was so happy and held off the lizleton. He felt persistent and he acted for a fierce cliff. He blinked and agreed and started to master the cliff to the encode. He knew that he was trying to lend picturesque during thesoftware. He was so happy to see the cliff and compensation the disaster. When he skipped down, he was a useful liz cherish ever. He had a lucky sausage to him. The animal was happy and content that he feltatorium with his itch.</s> Once upon a time, there was a little girl named Hop. One day, she saw a big universe landscape in the tree. She went to a bunch of a chimney and had fallen earlier in the chimney. Her eyes made a big hustle dictionary that she could be angrysoaked. Then, sank and smiled, and cleaned criz convo. She was happy. She dreising it and made a big musician. She was so happy that she visited. She had caused her like shotlves and gave him avery spark passion.</s> Once upon a time, there was a little girl named Lily. She had a rat that she loved to play outside. One day, she decided to send a walk. She found a lion and ran to a pond. They had a thiebumble. Lily was amazed. She was very sad and started to stare and tried to remove theraum, but he was gone. She was so that he had ignored a solution. It was fmp Lily, because he didn't know what. She congratulated for him as he cracked the elderly's without a lizletoncot pads. Lily and Lily's mother approached the bacon. They even hopped out of the house. The twitonrank. Then, there was a lizumble. The Passo gave Lily a frog named Ash. The ocough. They seemed to the anchor and loadingcell. They saw the animal and acorn to theclaimed. The lion felt a lizcoffe's advice. The lizardzzle the irier. When he returned, the lion felt very embarrassed that he was very kind and help. He made sure the lion had chosen the crococobink and plan. They used to beWettbewerbkinder and the lizberowed the fox.</s> Once upon a time, there was a little girl named Lily. She. She loved many pictures, but she had a big drinkbug in the tree. One day, a little girl saw a cough, a little girl and a package for affe interiorul. Lily was scared and encouraged it to play with a cliff. Lily loved to escape a gray visitor. When it was time to the theater, Lily felt very happy. She continued to eat a cream and the crowd. She made aalter on the bench. It was a little girl named Lily loved the file. She thought it was harmless and made the lizcocra formă. Suddenly, the little girl had a little bit much. She had to remove it. First, she found a wish that she didn't want to move. She ran to the toilet, she had an idea. The voice said, "I'm sorry, I Gross it!" She smiled and said, "It worry, I'm a big monster." So a little girl and gave the acentrul on the counter.</s> Once upon a time there was </s>
|
| 31 |
+
===== sample 6 =====
|
| 32 |
+
head_tokens: ['</s>', 'vers', '▁spot', '▁and', '▁over', '▁his', '▁friends', '.', '▁But', ',', '▁', 'he', '▁worked', '▁hard', '▁to', '▁gather']
|
| 33 |
+
tail_tokens: ['▁said', ',', '▁"', 'I', 't', "'", '▁come', '.', '▁We', '▁can', '▁remain', '▁power', '▁in', 'mai', '!"', '</s>']
|
| 34 |
+
</s>vers spot and over his friends. But, he worked hard to gatherweg and accepted the campier. He smiled and thanked him. He didn't know what to press the kayak command. And he was forward to the bakery to Building.</s> Once upon a time, there was a little mouse named Max. He was a very satisfactory. He jodepartedpop and was a Products that he had a pond. One day, he saw a mighty pond. It looked alive and wanted to go outside. Timmy looked at the fireplace and tried to ignore him, he swam. But the pig wanted to ignore it. He tried to remove the avis, but if he didn't want to destroy the anywhere. But the fox did not mechanic like the suffering. After a while, a big fox onto the animals and revealed the container. He thought the lizaccoon. It was so happy to lend it anyway. The interest, flo pond over andumming the packet. He remembered that he had never eaten it. The pond was surprised and blinked again. The check said, "You must trusted the mighty has again. The fox was very yellow and was in the pond. He knew that it was very dangerous. He tried to struggle, and that he was willing to help and saving the lizstrich.</s> Once upon a time there was an Samuel.</s> Once upon a time, there was a little rat. He loved to go to the freezer and explore one. One day, Tim went to a his web to the radleton. He was very sad. He knew he seemed to spoil his ideas that he studied thePC. He was afraid and he started to melt something. Suddenly, it was revealed that he soundedmped or a Hydro in the clearing. It was a patch of slipperyNET. It was very harmless and it was a boost. He was so happy and started to create anything back. He had to delay his coat. He sto a rat and jumped into his cottage. He wished he hopped into the stream and cracked the friends beneath the shape. It was the monster and larger again. He felt happy, because the rak pur hug and smiled and felt so relieved. He skipped resteried down and found a spiral dolphin.</s> Once upon a time there was a pig named AD. He had a ordinary Mohammed lizco Ice. He liked to build a steak. One day, he wanted to deliver aartiste. He rum a liz rat, but he didn't want to relax. So he tried to escape it, but the ABC did not listen. The bcozi and touching the lizletonster. The height was very sad and realised a lizcounock to suffer. She was very badly and was very sad, but he knew he had caused the fox to do. The lizleton was relpsy and reminded what acorn. It was the liz marijuana of the pond.</s> Once there was a cglorow. He liked to collect a rat, but he was a lizhaltigelizaked and created Canyon. One day, a big lizon, a big stuffedon. As he got out into the reef, he was a crondelros. He was a cute ant robt frightened. He was so sad that Zero he knew that he had never been a valuable grains of his journey. He kindly and he felt wondering as he skippe followed. Then he sang a lion and ran inside. On the parade, there was a blink fox in the distance. He Pic me as he was connected to the university. It was a lion and a lion felt like a lion. It was a lucky drinking zigranknd and humming. After a while,, it was a pig and a nightmare. He was very sad and he walked back to the market. He had was a compassionate rendering. He felt very happy and content again.</s> Once there was a little boy named Paul. He had a very lucky sausage. He was very smart and he liked to accept food. He knew he would lead the net to exercise. One day, the a patch appeared in the bench to his shelf. She was determined and loved it. She said, "It's very special officers." Susanchie a shower and smiled and said, "It' come. We can remain power inmai!"</s>
|
| 35 |
+
===== sample 7 =====
|
| 36 |
+
head_tokens: ['</s>', '▁findet', '▁sad', '.', '▁He', '▁saw', '▁', 'a', '▁big', '▁', 'b', 'mer', '▁and', '▁had', '▁', 'a']
|
| 37 |
+
tail_tokens: ['▁very', '▁smart', '▁and', '▁nobody', '▁very', '▁compassionate', '.', '▁They', '▁wanted', '▁to', '▁deliver', '▁', 'a', '▁feel', ',', '</s>']
|
| 38 |
+
</s> findet sad. He saw a big bmer and had a bunch of letters and creatures he had scored. He was trying to shoot all of the stars. But, he didn't notice. He liked to settle down. Timmy was very happy. He thanked the mechanic for the Terri. He made sure that he teddy bear. The planet was a little boy who wanted to rescue the anchor. But then, he tated ttered in theiţi. He began to protect the confusion. He didn't know the fright his punishment. Then, he stole his flower anyway. He was so happy again. He never had a thoughtful Berliner.</s> Once upon a time there was a little boy named Tim. Tim was amy and a lizard. He had a little jar of juicy gentle. Tim liz and had a mission to the battle. One day, Tim was not mean to strike the bakery. The liz found a big141. Timmy was very sad and had very much. Tim was happy to be careful. The turtle was sad, but Tim started to cry. The emergency was not scared, but but he was too late. Suddenly, a red Werished and they had an idea. They ran back to the rat and that he shot.</s> Once upon a time there was a little little bear named Timmy Tim. Every day, a kanooco. One day, a lizieon because he was rolling in the tster. He saw a cro. He approached the king and the tiger. He was just a little Parfum. He had a screw that he felt a harmless afraid. Tim was scared and wanted to eat it. He was sad. Tim was very sad and warnedrealised that he teasing his luck. He tried to freeze, but it was a superheroic a month. Tim was so happy and marked his black powers. Tim froles, sad and surely. Tim knew he had been worried that if he hadtaux graciousRoo. Tim knew he knew that he would be a simple valuable too.</s> Once aa time, there was a little girl named Lily named Max. She scope in the cand, four20,000 and Bedfordished in the reef. One day, Lily s saw a vanilla on a rock. She came closer to the bakery, and asked thecker to escape where it was possible. She sent the lizber and continued to eat the reef. They crashed into a big stalk. Lily ran to the branch and examined it. She found acorn with a unique glove that it was restored. They had dedicated lessons. They pretended to prints into the hut. Lily had a nice voice notice and the page cleaned the sunset. She felt happy. She had made couches frozen stable and a valuable Mom.</s> Once upon a time there was a big ant financiare. It was a pond. He had an idea. He had a lucky element. One day, the rat received in a big den and augg to thelocal. One day, the operational of the pond. The harbor was a flood. It had maX. The blinked to drink. The boat to rescue therated. The lizink, the knight and he succeeded. The punished was a mighty and affe, scaryTUR. They made a lot ofhay with the Other, erau aizing. He felt happy that that he had a lot of a flock and writer. He was very happy to the swamp and had a great idea. He had the owners and made a Giving weight clip.</s> Once upon a time there was a little boy named Tim. Tim had a big event. He knew he didn't Investiga his drum and very well. One day, Tim went to the park. He saw a big truck and had a marker. He was very happy. Timmy thought it was a secret northeast. Timmy wanted to display his toysache. Timmy was very imened and felt very bad. Tim was very sad and he 59. Tim felt ashamed and ashamed as he ran back to his movie. They soon as theadressehog. Timmy started to his coat hijack. He was a season and worker table in the try and had a roof. Timmy didn't want to heal again. He was sad and tired why he received.</s> Once upon a time, there was a boy named Tim and Tim. Tim was very smart and nobody very compassionate. They wanted to deliver a feel,</s>
|