diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/waveft/wavelet.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/waveft/wavelet.py new file mode 100644 index 0000000000000000000000000000000000000000..c66acd85f65570652f18d47d5bed12eb3a174ea5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/waveft/wavelet.py @@ -0,0 +1,513 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Minimal wavelet implementation extracted from PyWavelets + +This code contains portions derived from PyWavelets: Copyright (c) 2006-2012 Filip Wasilewski +Copyright (c) 2012- The PyWavelets Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Original source: https://github.com/PyWavelets/pywt +""" + +import math +from collections.abc import Sequence + + +class Wavelet: + """ + Minimal wavelet class that implements the most commonly used wavelets. + + Supports: + - Daubechies wavelets: db1-db10, haar + - Symlets: sym2-sym10 + - Coiflets: coif1-coif5 + """ + + def __init__(self, name: str): + """ + Initialize a wavelet by name. + + Args: + name: Wavelet name (e.g., 'db4', 'haar', 'sym5', 'coif2') + """ + self.name = name.lower() + self._compute_filters() + + def _compute_filters(self): + """Compute the four filter banks from the base coefficients.""" + if self.name == "haar": + # Haar is the same as db1 + base_coeffs = _WAVELET_COEFFS["db1"] + elif self.name in _WAVELET_COEFFS: + base_coeffs = _WAVELET_COEFFS[self.name] + else: + raise ValueError(f"Unknown wavelet name '{self.name}'. Available wavelets: {list(_WAVELET_COEFFS.keys())}") + + # Determine if this is a coiflet (needs sqrt(2) scaling) + scale_factor = math.sqrt(2) if self.name.startswith("coif") else 1.0 + + # Apply scaling to base coefficients + scaled_coeffs = [c * scale_factor for c in base_coeffs] + + # Compute the four filter banks following PyWavelets convention + # rec_lo = scaled base coefficients + self._rec_lo = scaled_coeffs[:] + + # dec_lo = rec_lo reversed + self._dec_lo = scaled_coeffs[::-1] + + # rec_hi = alternating signs of dec_lo + self._rec_hi = [(-1) ** i * scaled_coeffs[len(scaled_coeffs) - 1 - i] for i in range(len(scaled_coeffs))] + + # dec_hi = alternating signs of rec_lo + self._dec_hi = [(-1) ** (len(scaled_coeffs) - 1 - i) * scaled_coeffs[i] for i in range(len(scaled_coeffs))] + + @property + def dec_lo(self) -> Sequence[float]: + """Lowpass decomposition filter.""" + return self._dec_lo + + @property + def dec_hi(self) -> Sequence[float]: + """Highpass decomposition filter.""" + return self._dec_hi + + @property + def rec_lo(self) -> Sequence[float]: + """Lowpass reconstruction filter.""" + return self._rec_lo + + @property + def rec_hi(self) -> Sequence[float]: + """Highpass reconstruction filter.""" + return self._rec_hi + + @property + def dec_len(self) -> int: + """Decomposition filters length.""" + return len(self._dec_lo) + + @property + def rec_len(self) -> int: + """Reconstruction filters length.""" + return len(self._rec_lo) + + @property + def filter_bank(self) -> tuple[Sequence[float], Sequence[float], Sequence[float], Sequence[float]]: + """Tuple of all four filter banks (dec_lo, dec_hi, rec_lo, rec_hi).""" + return (self.dec_lo, self.dec_hi, self.rec_lo, self.rec_hi) + + def __len__(self) -> int: + """Return the length of the decomposition filters.""" + return self.dec_len + + def __repr__(self) -> str: + return f"Wavelet(name='{self.name}')" + + +# Wavelet coefficients extracted from PyWavelets +# These are the reconstruction lowpass filter coefficients +_WAVELET_COEFFS = { + # Daubechies wavelets + "db1": [ + 0.7071067811865475244008443621048490392848359376884740365883398, + 0.7071067811865475244008443621048490392848359376884740365883398, + ], + "db2": [ + 0.4829629131445341433748715998644486838169524195042022752011715, + 0.8365163037378079055752937809168732034593703883484392934953414, + 0.2241438680420133810259727622404003554678835181842717613871683, + -0.1294095225512603811744494188120241641745344506599652569070016, + ], + "db3": [ + 0.3326705529500826159985115891390056300129233992450683597084705, + 0.80689150931333875, + 0.45987750211933132, + -0.13501102001039084, + -0.085441273882241486, + 0.035226291882100656, + ], + "db4": [ + 0.2303778133088965008632911830440708500016152482483092977910968, + 0.7148465705529156470899219552739926037076084010993081758450110, + 0.6308807679298589078817163383006152202032229226771951174057473, + -0.02798376941685985421141374718007538541198732022449175284003358, + -0.1870348117190930840795706727890814195845441743745800912057770, + 0.03084138183556076362721936253495905017031482172003403341821219, + 0.03288301166688519973540751354924438866454194113754971259727278, + -0.01059740178506903210488320852402722918109996490637641983484974, + ], + "db5": [ + 0.1601023979741929144807237480204207336505441246250578327725699, + 0.6038292697971896705401193065250621075074221631016986987969283, + 0.7243085284377729277280712441022186407687562182320073725767335, + 0.1384281459013207315053971463390246973141057911739561022694652, + -0.2422948870663820318625713794746163619914908080626185983913726, + -0.03224486958463837464847975506213492831356498416379847225434268, + 0.07757149384004571352313048938860181980623099452012527983210146, + -0.006241490212798274274190519112920192970763557165687607323417435, + -0.01258075199908199946850973993177579294920459162609785020169232, + 0.003335725285473771277998183415817355747636524742305315099706428, + ], + "db6": [ + 0.1115407433501094636213239172409234390425395919844216759082360, + 0.4946238903984530856772041768778555886377863828962743623531834, + 0.7511339080210953506789344984397316855802547833382612009730420, + 0.3152503517091976290859896548109263966495199235172945244404163, + -0.2262646939654398200763145006609034656705401539728969940143487, + -0.1297668675672619355622896058765854608452337492235814701599310, + 0.09750160558732304910234355253812534233983074749525514279893193, + 0.02752286553030572862554083950419321365738758783043454321494202, + -0.03158203931748602956507908069984866905747953237314842337511464, + 0.0005538422011614961392519183980465012206110262773864964295476524, + 0.004777257510945510639635975246820707050230501216581434297593254, + -0.001077301085308479564852621609587200035235233609334419689818580, + ], + "db7": [ + 0.07785205408500917901996352195789374837918305292795568438702937, + 0.3965393194819173065390003909368428563587151149333287401110499, + 0.7291320908462351199169430703392820517179660611901363782697715, + 0.4697822874051931224715911609744517386817913056787359532392529, + -0.1439060039285649754050683622130460017952735705499084834401753, + -0.2240361849938749826381404202332509644757830896773246552665095, + 0.07130921926683026475087657050112904822711327451412314659575113, + 0.08061260915108307191292248035938190585823820965629489058139218, + -0.03802993693501441357959206160185803585446196938467869898283122, + -0.01657454163066688065410767489170265479204504394820713705239272, + 0.01255099855609984061298988603418777957289474046048710038411818, + 0.0004295779729213665211321291228197322228235350396942409742946366, + -0.001801640704047490915268262912739550962585651469641090625323864, + 0.0003537137999745202484462958363064254310959060059520040012524275, + ], + "db8": [ + 0.05441584224310400995500940520299935503599554294733050397729280, + 0.3128715909142999706591623755057177219497319740370229185698712, + 0.6756307362972898068078007670471831499869115906336364227766759, + 0.5853546836542067127712655200450981944303266678053369055707175, + -0.01582910525634930566738054787646630415774471154502826559735335, + -0.2840155429615469265162031323741647324684350124871451793599204, + 0.0004724845739132827703605900098258949861948011288770074644084096, + 0.1287474266204784588570292875097083843022601575556488795577000, + -0.01736930100180754616961614886809598311413086529488394316977315, + -0.04408825393079475150676372323896350189751839190110996472750391, + 0.01398102791739828164872293057263345144239559532934347169146368, + 0.008746094047405776716382743246475640180402147081140676742686747, + -0.004870352993451574310422181557109824016634978512157003764736208, + -0.0003917403733769470462980803573237762675229350073890493724492694, + 0.0006754494064505693663695475738792991218489630013558432103617077, + -0.0001174767841247695337306282316988909444086693950311503927620013, + ], + "db9": [ + 0.03807794736387834658869765887955118448771714496278417476647192, + 0.2438346746125903537320415816492844155263611085609231361429088, + 0.6048231236901111119030768674342361708959562711896117565333713, + 0.6572880780513005380782126390451732140305858669245918854436034, + 0.1331973858250075761909549458997955536921780768433661136154346, + -0.2932737832791749088064031952421987310438961628589906825725112, + -0.09684078322297646051350813353769660224825458104599099679471267, + 0.1485407493381063801350727175060423024791258577280603060771649, + 0.03072568147933337921231740072037882714105805024670744781503060, + -0.06763282906132997367564227482971901592578790871353739900748331, + 0.0002509471148314519575871897499885543315176271993709633321834164, + 0.02236166212367909720537378270269095241855646688308853754721816, + -0.004723204757751397277925707848242465405729514912627938018758526, + -0.004281503682463429834496795002314531876481181811463288374860455, + 0.001847646883056226476619129491125677051121081359600318160732515, + 0.0002303857635231959672052163928245421692940662052463711972260006, + -0.0002519631889427101369749886842878606607282181543478028214134265, + 0.00003934732031627159948068988306589150707782477055517013507359938, + ], + "db10": [ + 0.02667005790055555358661744877130858277192498290851289932779975, + 0.1881768000776914890208929736790939942702546758640393484348595, + 0.5272011889317255864817448279595081924981402680840223445318549, + 0.6884590394536035657418717825492358539771364042407339537279681, + 0.2811723436605774607487269984455892876243888859026150413831543, + -0.2498464243273153794161018979207791000564669737132073715013121, + -0.1959462743773770435042992543190981318766776476382778474396781, + 0.1273693403357932600826772332014009770786177480422245995563097, + 0.09305736460357235116035228983545273226942917998946925868063974, + -0.07139414716639708714533609307605064767292611983702150917523756, + -0.02945753682187581285828323760141839199388200516064948779769654, + 0.03321267405934100173976365318215912897978337413267096043323351, + 0.003606553566956169655423291417133403299517350518618994762730612, + -0.01073317548333057504431811410651364448111548781143923213370333, + 0.001395351747052901165789318447957707567660542855688552426721117, + 0.001992405295185056117158742242640643211762555365514105280067936, + -0.0006858566949597116265613709819265714196625043336786920516211903, + -0.0001164668551292854509514809710258991891527461854347597362819235, + 0.00009358867032006959133405013034222854399688456215297276443521873, + -0.00001326420289452124481243667531226683305749240960605829756400674, + ], + # Symlets + "sym2": [0.48296291314469025, 0.83651630373746899, 0.22414386804185735, -0.12940952255092145], + "sym3": [ + 0.33267055295095688, + 0.80689150931333875, + 0.45987750211933132, + -0.13501102001039084, + -0.085441273882241486, + 0.035226291882100656, + ], + "sym4": [ + 0.032223100604042702, + -0.012603967262037833, + -0.099219543576847216, + 0.29785779560527736, + 0.80373875180591614, + 0.49761866763201545, + -0.02963552764599851, + -0.075765714789273325, + ], + "sym5": [ + 0.019538882735286728, + -0.021101834024758855, + -0.17532808990845047, + 0.016602105764522319, + 0.63397896345821192, + 0.72340769040242059, + 0.1993975339773936, + -0.039134249302383094, + 0.029519490925774643, + 0.027333068345077982, + ], + "sym6": [ + -0.007800708325034148, + 0.0017677118642428036, + 0.044724901770665779, + -0.021060292512300564, + -0.072637522786462516, + 0.3379294217276218, + 0.787641141030194, + 0.49105594192674662, + -0.048311742585632998, + -0.11799011114819057, + 0.0034907120842174702, + 0.015404109327027373, + ], + "sym7": [ + 0.010268176708511255, + 0.0040102448715336634, + -0.10780823770381774, + -0.14004724044296152, + 0.28862963175151463, + 0.76776431700316405, + 0.5361019170917628, + 0.017441255086855827, + -0.049552834937127255, + 0.067892693501372697, + 0.03051551316596357, + -0.01263630340325193, + -0.0010473848886829163, + 0.0026818145682578781, + ], + "sym8": [ + 0.0018899503327594609, + -0.0003029205147213668, + -0.014952258337048231, + 0.0038087520138906151, + 0.049137179673607506, + -0.027219029917056003, + -0.051945838107709037, + 0.3644418948353314, + 0.77718575170052351, + 0.48135965125837221, + -0.061273359067658524, + -0.14329423835080971, + 0.0076074873249176054, + 0.031695087811492981, + -0.00054213233179114812, + -0.0033824159510061256, + ], + "sym9": [ + 0.0010694900329086053, + -0.00047315449868008311, + -0.010264064027633142, + 0.0088592674934004842, + 0.06207778930288603, + -0.018233770779395985, + -0.19155083129728512, + 0.035272488035271894, + 0.61733844914093583, + 0.717897082764412, + 0.238760914607303, + -0.054568958430834071, + 0.00058346274612580684, + 0.03022487885827568, + -0.01152821020767923, + -0.013271967781817119, + 0.00061978088898558676, + 0.0014009155259146807, + ], + "sym10": [ + -0.00045932942100465878, + 0.000057036083618494284, + 0.0045931735853118284, + -0.00080435893201654491, + -0.02035493981231129, + 0.0057649120335819086, + 0.049994972077376687, + -0.0319900568824278, + -0.035536740473817552, + 0.38382676106708546, + 0.7695100370211071, + 0.47169066693843925, + -0.070880535783243853, + -0.15949427888491757, + 0.011609893903711381, + 0.045927239231092203, + -0.0014653825813050513, + -0.0086412992770224222, + 0.000095632670722894754, + 0.00077015980911449011, + ], + # Coiflets (note: these will be multiplied by sqrt(2) in the class) + "coif1": [ + -0.05142972847076845595317549230122688830344559947132656813651045, + 0.2389297284707684559531754923012268883034455994713265681365104, + 0.6028594569415369119063509846024537766068911989426531362730209, + 0.2721405430584630880936490153975462233931088010573468637269790, + -0.05142972847076845595317549230122688830344559947132656813651045, + -0.01107027152923154404682450769877311169655440052867343186348954, + ], + "coif2": [ + 0.01158759673871686817889714882853120395708315073355502818875931, + -0.02932013798346856448679594524397843054053420947418409889774786, + -0.04763959031100813225872995081511549408622753909592460525840745, + 0.2730210465347666137982239328923516270034828327990699588033501, + 0.5746823938568638472459483149751499367740786490481481391460366, + 0.2948671936956191896750637208703777973914107635455611537640778, + -0.05408560709171142997443672832006888537570221990444706777525838, + -0.04202648046077160694657530752545884878978719268926222513485613, + 0.01674441016327950635146257083249391698866289538037299820224006, + 0.003967883612962012109043447090269950094081810916481648252817197, + -0.001289203356140659543141355500990678257894936161704492503370186, + -0.0005095053991076441489598480835620951586540050976664367876412655, + ], + "coif3": [ + -0.002682418670922068664584689955153722375535836177157637134187840, + 0.005503126707831385107969640263617469178794666057252906037981936, + 0.01658356047917034608134280439996549525220639437145367606178002, + -0.04650776447872697640390293095170192691113917841041002855534619, + -0.04322076356021191118175840907244577856782537221435748296465882, + 0.2865033352736474630249006862976158896891076238443844211133873, + 0.5612852568703300445990941995240077241406247774064453800050914, + 0.3029835717728241602862575774374668529867757043461413348549577, + -0.05077014075488886159516471867138370972545857441670871832472707, + -0.05819625076158553022607041679522801089624825903982541419721721, + 0.02443409432116695639462954438418928805487699080947974989338820, + 0.01122924096203786563399489540091488781245346096838814728167341, + -0.006369601011048822977293753932627342482077585617391852852955559, + -0.001820458915566242322836631665832145136570132777862391313328351, + 0.0007902051009575939937150950543290226440287715441826917281929124, + 0.0003296651737931830308416338897758022998655744276957481989605186, + -0.00005019277455327664998007173088097694083956570594580641192332170, + -0.00002446573425530813115445387662881902303945941576472342106918209, + ], + "coif4": [ + 0.0006309612114309468490753696608619526520153127603444406835368201, + -0.001152225143769973488683007937016166047881572156705066038094891, + -0.005194525163470323267558201363327294331811309729430512113592118, + 0.011360930899781950641704454327495718441159520023894304805142070, + 0.018945061045616642675204041814669158097013442370604397885045773, + -0.051719843705815280952009072709014825996085808127950893370164031, + -0.034486140470944806827159094088779177962124655341862998060866093, + 0.30227251053656843537076103037201073987915654650542997843779746, + 0.55454790624088107896085831311334062609863843227892842936901802, + 0.30791766802517503548651698686002846493302655084140026096325632, + -0.04352500928126570063143077306027663648139777048547894956715080, + -0.06488795097143100103160862688937301504802507374726020928892066, + 0.01988077364815951966984001670075537628468542316950829728327598, + 0.01763894787126169746077061344050946967036166456074020965866088, + -0.007366054847173363935072651649653007115003169492027095040477055, + -0.002312432307658842282830374733100847689924654369899030169556169, + 0.0014260063442333715226509754100697734398974715092509045804651032, + 0.0004666984635537353670445650012678936080062341977092967649055398, + -0.0001270007842387334077388950072420113055088253899932456267893098, + -0.0001130536369789104919020013936507623832962772709844179610938550, + 0.00003048364879677801030096883509693508426509710688913073244616617, + 0.00001266744808933008194725929652978169473830765616675686100903086, + -0.000001584926580756893754069651095690142946796090146306140001598, + -0.000001123948088281542889088159169056968300680087779667334879506, + ], + "coif5": [ + -0.0001444992186438190986841213894961515720877049723502928655308158, + 0.0002541649492011946935899015644804259825374993423205648946709984, + 0.0015016192805175522217354963668928299350735326077949346507003370, + -0.0029411108712655515426850089360913424188662278991737055486839309, + -0.0071777671514877191801104649507158618871157411936681659380839993, + 0.016680426640070654149267486742006854522334094142598667043628439, + 0.019433238433489604119639447772308536988043628308900006988094899, + -0.064934946567212502582522008002547701764467194128935170823607736, + -0.036249793089132571825087765037251085892962369926089901862924065, + 0.29804266217809436069693444260411251439893892734398765007426945, + 0.55749162970920071628061190166750547398568080072951806509736879, + 0.30731644529206781686031633026138686170779831068030092889493625, + -0.047088034719761145117688715152051398948700623993077406913889346, + -0.068890522508050074805015336128652797797076949077503388892816063, + 0.020697343297747766068568936830651656003659188170019885439659031, + 0.021640668655956855043817421090949779825140639715020046717736369, + -0.0081089373078953680936950024508066654697766705721301481097854397, + -0.0049881737671041853808073796089816945023009226058734090095808033, + 0.0024486914321021269742893936892468103370072825113159100554056433, + 0.0014095103899593442621166984842002926701899968616244946547893994, + -0.0005637801876093825733169550088901318936072015721509885859509815, + -0.0002859004477225750899655442618734663056802618537327806113618985, + 0.00012739637513815208006169426577159456832051015616166327985688948, + 0.00005416263410701044073894700796327336007788688985721449717765655, + -0.00001736867944346280636144226913926838103159698473080996002509476, + -0.00001392656190060010871169838885327726938969652863554900825705905, + 0.000003582065515946048838215026334503092089635988710863959063568069, + 0.000001914022895847318655772885654240700542388103264097264264779554, + -0.00000031262488377016899432194683906058825900951892071223097080609, + -0.00000034030635502511647536690616071863203084936306302829968850306, + 0.000000059816065238516936893488966688516710847096926983547983503726, + 0.000000047001427849456491830476615736016736014244615701046223529866, + -0.000000006158615709678364180659098549671046676203853020063205641804, + -0.000000009225635096344935080070901936862847863830913641424076095562, + 0.000000001028486074518821265015830073593127726988903862842106883701, + 0.000000001168734175186263778695686067593866982925127816327529890618, + -0.00000000009468626176069127302554946536142654377756003084491946024, + -0.00000000016230233142152041788509334089966065953985768924968863072, + 0.000000000015076656859346950325398899897135970089618140503825462985, + 0.000000000015770990416421915106306877550025550097686639869166742016, + -0.000000000001084900468648598127623517893686893316653633996513097476, + -0.000000000001968659779411804788815966829825641065085077654946686012, + 0.000000000000098745634639726633264577838416327095717894829823436076, + 0.000000000000196734781460508097097473336847436635654948853090962606, + -0.000000000000008021080145299890797556481653726965016924825037889883, + -0.000000000000021030408801651651406095853493993966926736862877194669, + 0.000000000000000723888697830915633925166893301949334507697669655816, + 0.000000000000001943208515072761516084547140065815027641765976721267, + ], +} + + +def wavelist() -> list[str]: + """Return a list of available wavelet names.""" + return list(_WAVELET_COEFFS.keys()) + ["haar"] diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/waveft/waverec2d.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/waveft/waverec2d.py new file mode 100644 index 0000000000000000000000000000000000000000..7148c7ccf630379cb10dfd0d7bc8c6a29386be25 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/waveft/waverec2d.py @@ -0,0 +1,316 @@ +# Copyright 2021 Moritz Wolter +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the EUPL v1.2 +# +# This file contains code derived from PyTorch-Wavelet-Toolbox: +# https://github.com/v0lta/PyTorch-Wavelet-Toolbox +# +# Original work by Moritz Wolter, licensed under EUPL v1.2 +# Modifications and integration by HuggingFace Inc. team + +from collections.abc import Callable, Sequence +from functools import partial +from typing import Any, NamedTuple, Protocol, TypeAlias, Union, cast, overload + +import numpy as np +import torch +from typing_extensions import Unpack + +from .wavelet import Wavelet as minimal_wavelet + + +class WaveletDetailTuple2d(NamedTuple): + horizontal: torch.Tensor + vertical: torch.Tensor + diagonal: torch.Tensor + + +WaveletCoeff2d: TypeAlias = tuple[torch.Tensor, Unpack[tuple[WaveletDetailTuple2d, ...]]] +WaveletDetailDict: TypeAlias = dict[str, torch.Tensor] +WaveletCoeffNd: TypeAlias = tuple[torch.Tensor, Unpack[tuple[WaveletDetailDict, ...]]] + + +class Wavelet(Protocol): + name: str + dec_lo: Sequence[float] + dec_hi: Sequence[float] + rec_lo: Sequence[float] + rec_hi: Sequence[float] + dec_len: int + rec_len: int + filter_bank: tuple[Sequence[float], Sequence[float], Sequence[float], Sequence[float]] + + def __len__(self) -> int: + return len(self.dec_lo) + + +class WaveletTensorTuple(NamedTuple): + dec_lo: torch.Tensor + dec_hi: torch.Tensor + rec_lo: torch.Tensor + rec_hi: torch.Tensor + + @classmethod + def from_wavelet(cls, wavelet: Wavelet, dtype: torch.dtype) -> "WaveletTensorTuple": + return cls( + torch.tensor(wavelet.dec_lo, dtype=dtype), + torch.tensor(wavelet.dec_hi, dtype=dtype), + torch.tensor(wavelet.rec_lo, dtype=dtype), + torch.tensor(wavelet.rec_hi, dtype=dtype), + ) + + +def _as_wavelet(wavelet: Union[Wavelet, str]) -> Wavelet: + if isinstance(wavelet, str): + return minimal_wavelet(wavelet) + else: + return wavelet + + +def _is_dtype_supported(dtype: torch.dtype) -> bool: + return dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64] + + +def _outer(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + a_flat = torch.reshape(a, [-1]) + b_flat = torch.reshape(b, [-1]) + a_mul = torch.unsqueeze(a_flat, dim=-1) + b_mul = torch.unsqueeze(b_flat, dim=0) + return a_mul * b_mul + + +def _check_if_tensor(array: Any) -> torch.Tensor: + if not isinstance(array, torch.Tensor): + raise TypeError("First element of coeffs must be the approximation coefficient tensor.") + return array + + +def _check_axes_argument(axes: Sequence[int]) -> None: + if len(set(axes)) != len(axes): + raise ValueError("Cant transform the same axis twice.") + + +def _check_same_device(tensor: torch.Tensor, torch_device: torch.device) -> torch.Tensor: + if torch_device != tensor.device: + raise ValueError("coefficients must be on the same device") + return tensor + + +def _check_same_dtype(tensor: torch.Tensor, torch_dtype: torch.dtype) -> torch.Tensor: + if torch_dtype != tensor.dtype: + raise ValueError("coefficients must have the same dtype") + return tensor + + +@overload +def _coeff_tree_map( + coeffs: list[torch.Tensor], function: Callable[[torch.Tensor], torch.Tensor] +) -> list[torch.Tensor]: ... +@overload +def _coeff_tree_map(coeffs: WaveletCoeff2d, function: Callable[[torch.Tensor], torch.Tensor]) -> WaveletCoeff2d: ... +@overload +def _coeff_tree_map(coeffs: WaveletCoeffNd, function: Callable[[torch.Tensor], torch.Tensor]) -> WaveletCoeffNd: ... +def _coeff_tree_map(coeffs, function): + approx = function(coeffs[0]) + result_lst: list[Any] = [] + for element in coeffs[1:]: + if isinstance(element, tuple): + result_lst.append(WaveletDetailTuple2d(function(element[0]), function(element[1]), function(element[2]))) + elif isinstance(element, dict): + new_dict = {key: function(value) for key, value in element.items()} + result_lst.append(new_dict) + elif isinstance(element, torch.Tensor): + result_lst.append(function(element)) + else: + raise TypeError(f"Unexpected input type {type(element)}") + if not result_lst: + return [approx] if isinstance(coeffs, list) else (approx,) + elif isinstance(result_lst[0], torch.Tensor): + return [approx] + cast(list[torch.Tensor], result_lst) + else: + cast_result_lst = cast(Union[list[WaveletDetailDict], list[WaveletDetailTuple2d]], result_lst) + return (approx, *cast_result_lst) + + +def _check_same_device_dtype( + coeffs: Union[list[torch.Tensor], WaveletCoeff2d, WaveletCoeffNd], +) -> tuple[torch.device, torch.dtype]: + c = _check_if_tensor(coeffs[0]) + torch_device, torch_dtype = c.device, c.dtype + _coeff_tree_map(coeffs, partial(_check_same_device, torch_device=torch_device)) + _coeff_tree_map(coeffs, partial(_check_same_dtype, torch_dtype=torch_dtype)) + return torch_device, torch_dtype + + +def _get_transpose_order(axes: Sequence[int], data_shape: Sequence[int]) -> tuple[list[int], list[int]]: + axes = [a + len(data_shape) if a < 0 else a for a in axes] + all_axes = list(range(len(data_shape))) + remove_transformed = list(filter(lambda a: a not in axes, all_axes)) + return remove_transformed, axes + + +def _swap_axes(data: torch.Tensor, axes: Sequence[int]) -> torch.Tensor: + _check_axes_argument(axes) + front, back = _get_transpose_order(axes, list(data.shape)) + return torch.permute(data, front + back) + + +def _undo_swap_axes(data: torch.Tensor, axes: Sequence[int]) -> torch.Tensor: + _check_axes_argument(axes) + front, back = _get_transpose_order(axes, list(data.shape)) + restore_sorted = torch.argsort(torch.tensor(front + back)).tolist() + return torch.permute(data, restore_sorted) + + +def _fold_axes(data: torch.Tensor, keep_no: int) -> tuple[torch.Tensor, list[int]]: + dshape = list(data.shape) + return (torch.reshape(data, [int(np.prod(dshape[:-keep_no]))] + dshape[-keep_no:]), dshape) + + +def _unfold_axes(data: torch.Tensor, ds: list[int], keep_no: int) -> torch.Tensor: + return torch.reshape(data, ds[:-keep_no] + list(data.shape[-keep_no:])) + + +def _preprocess_coeffs(coeffs, ndim: int, axes, add_channel_dim: bool = False): + if isinstance(axes, int): + axes = (axes,) + torch_dtype = _check_if_tensor(coeffs[0]).dtype + if not _is_dtype_supported(torch_dtype): + raise ValueError(f"Input dtype {torch_dtype} not supported") + if ndim <= 0: + raise ValueError("Number of dimensions must be positive") + if tuple(axes) != tuple(range(-ndim, 0)): + if len(axes) != ndim: + raise ValueError(f"{ndim}D transforms work with {ndim} axes.") + else: + swap_fn = partial(_swap_axes, axes=axes) + coeffs = _coeff_tree_map(coeffs, swap_fn) + ds = list(coeffs[0].shape) + if len(ds) < ndim: + raise ValueError(f"At least {ndim} input dimensions required.") + elif len(ds) == ndim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.unsqueeze(0)) + elif len(ds) > ndim + 1: + coeffs = _coeff_tree_map(coeffs, lambda t: _fold_axes(t, ndim)[0]) + if add_channel_dim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.unsqueeze(1)) + return coeffs, ds + + +def _postprocess_coeffs(coeffs, ndim: int, ds: list[int], axes): + if isinstance(axes, int): + axes = (axes,) + if ndim <= 0: + raise ValueError("Number of dimensions must be positive") + if len(ds) < ndim: + raise ValueError(f"At least {ndim} input dimensions required.") + elif len(ds) == ndim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.squeeze(0)) + elif len(ds) > ndim + 1: + unfold_axes_fn = partial(_unfold_axes, ds=ds, keep_no=ndim) + coeffs = _coeff_tree_map(coeffs, unfold_axes_fn) + if tuple(axes) != tuple(range(-ndim, 0)): + if len(axes) != ndim: + raise ValueError(f"{ndim}D transforms work with {ndim} axes.") + else: + undo_swap_fn = partial(_undo_swap_axes, axes=axes) + coeffs = _coeff_tree_map(coeffs, undo_swap_fn) + return coeffs + + +def _postprocess_tensor( + data: torch.Tensor, ndim: int, ds: list[int], axes: Union[tuple[int, ...], int] +) -> torch.Tensor: + return _postprocess_coeffs(coeffs=[data], ndim=ndim, ds=ds, axes=axes)[0] + + +def _get_filter_tensors( + wavelet: Union[Wavelet, str], flip: bool, device: torch.device, dtype: torch.dtype +) -> WaveletTensorTuple: + wavelet = _as_wavelet(wavelet) + if flip: + filters = WaveletTensorTuple( + torch.tensor(wavelet.rec_lo, device=device, dtype=dtype), + torch.tensor(wavelet.rec_hi, device=device, dtype=dtype), + torch.tensor(wavelet.dec_lo, device=device, dtype=dtype), + torch.tensor(wavelet.dec_hi, device=device, dtype=dtype), + ) + else: + filters = WaveletTensorTuple.from_wavelet(wavelet, dtype=dtype) + filters = WaveletTensorTuple( + filters.dec_lo.to(device), + filters.dec_hi.to(device), + filters.rec_lo.to(device), + filters.rec_hi.to(device), + ) + return filters + + +def _adjust_padding_at_reconstruction(tensor_len: int, coeff_len: int, padr: int, padl: int) -> tuple[int, int]: + if 2 * coeff_len - tensor_len == 1: + padr += 1 + elif 2 * coeff_len - tensor_len != 0: + raise ValueError("incorrect padding") + return padr, padl + + +def _construct_2d_filt(lo: torch.Tensor, hi: torch.Tensor) -> torch.Tensor: + ll = _outer(lo, lo) + lh = _outer(hi, lo) + hl = _outer(lo, hi) + hh = _outer(hi, hi) + filt = torch.stack([ll, lh, hl, hh], 0) + filt = filt.unsqueeze(1) + return filt + + +def waverec2d( + coeffs: WaveletCoeff2d, + wavelet: Union[Wavelet, str], + axes: tuple[int, int] = (-2, -1), +) -> torch.Tensor: + coeffs, ds = _preprocess_coeffs(coeffs, ndim=2, axes=axes) + torch_device, torch_dtype = _check_same_device_dtype(coeffs) + + _, _, rec_lo, rec_hi = _get_filter_tensors(wavelet, flip=False, device=torch_device, dtype=torch_dtype) + filt_len = rec_lo.shape[-1] + rec_filt = _construct_2d_filt(lo=rec_lo, hi=rec_hi) + + res_ll = coeffs[0] + for c_pos, coeff_tuple in enumerate(coeffs[1:]): + if not isinstance(coeff_tuple, tuple) or len(coeff_tuple) != 3: + raise ValueError(f"Unexpected detail coefficient type: {type(coeff_tuple)}. Must be a 3-tuple.") + + curr_shape = res_ll.shape + for coeff in coeff_tuple: + if coeff.shape != curr_shape: + raise ValueError("All coefficients on each level must have the same shape") + + res_lh, res_hl, res_hh = coeff_tuple + res_ll = torch.stack([res_ll, res_lh, res_hl, res_hh], 1) + res_ll = torch.nn.functional.conv_transpose2d(res_ll, rec_filt, stride=2).squeeze(1) + + padl = (2 * filt_len - 3) // 2 + padr = (2 * filt_len - 3) // 2 + padt = (2 * filt_len - 3) // 2 + padb = (2 * filt_len - 3) // 2 + if c_pos < len(coeffs) - 2: + padr, padl = _adjust_padding_at_reconstruction( + res_ll.shape[-1], coeffs[c_pos + 2][0].shape[-1], padr, padl + ) + padb, padt = _adjust_padding_at_reconstruction( + res_ll.shape[-2], coeffs[c_pos + 2][0].shape[-2], padb, padt + ) + + if padt > 0: + res_ll = res_ll[..., padt:, :] + if padb > 0: + res_ll = res_ll[..., :-padb, :] + if padl > 0: + res_ll = res_ll[..., padl:] + if padr > 0: + res_ll = res_ll[..., :-padr] + + res_ll = _postprocess_tensor(res_ll, ndim=2, ds=ds, axes=axes) + return res_ll diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/__init__.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6eae1f779b81e883f1dd64e3a4fca859391836c5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import XLoraConfig +from .model import XLoraModel + + +__all__ = ["XLoraConfig", "XLoraModel"] + +register_peft_method(name="xlora", config_cls=XLoraConfig, model_cls=XLoraModel) diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/classifier.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..cdfca77d78105124c8cf5c6fe6d23ae1d586e9f3 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/classifier.py @@ -0,0 +1,195 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import builtins +from typing import Optional, Union + +import torch +from torch import nn + +from .config import XLoraConfig + + +Number = Union[builtins.int, builtins.float, builtins.bool] + + +class TemperatureScaledSoftmax(nn.Module): + def __init__(self, temperature=1.0): + super().__init__() + self.temperature = temperature + self.softmax = nn.Softmax(dim=-1) + + def forward(self, logits): + # Scale logits by the temperature + scaled_logits = logits / self.temperature + # Apply softmax to the scaled logits + return self.softmax(scaled_logits) + + +class XLoraClassifier(nn.Module): + """ + A classifier to select LoRA layers for XLora. + """ + + def __init__( + self, + model: nn.Module, # PeftModel + config: XLoraConfig, + n_classes: int, + n_layers: int, + device: torch.device, + ): + """ + Construct an X-LoRA classifier from a model, config and some metadata. Note that n_layers is the number of LoRA + adapter layers, not the number of model layers. + """ + super().__init__() + + self.n_classes = n_classes + self.n_layers = n_layers + self.config = config + self.log_scalings = [] + self.softmax = TemperatureScaledSoftmax(temperature=self.config.softmax_temperature) + self.override_scaling_pass_value: Number = config.scaling_pass_value + + self.scalings_logging = False + + self.dtype = next(model.parameters()).dtype + add_dropout = config.xlora_dropout_p > 0.0 + + layers = [] + if self.config.xlora_depth == 1: + if config.layerwise_scalings: # bias=False if we have just one layer + last = nn.Linear(config.hidden_size, n_classes * n_layers, bias=True).to(device).to(self.dtype) + else: + last = nn.Linear(config.hidden_size, n_classes, bias=True).to(device).to(self.dtype) + else: + if self.config.xlora_depth <= 0: + raise ValueError("X-LoRA depth must be strictly positive.") + + layers.append(nn.Linear(config.hidden_size, config.xlora_size, bias=True).to(device).to(self.dtype)) + + layers.append(nn.ReLU()) + if add_dropout: + layers.append(nn.Dropout(p=config.xlora_dropout_p)) + + for _ in range(config.xlora_depth - 2): + layers.append(nn.Linear(config.xlora_size, config.xlora_size, bias=True).to(device).to(self.dtype)) + + layers.append(nn.ReLU()) + if add_dropout: + layers.append(nn.Dropout(p=config.xlora_dropout_p)) + + if config.layerwise_scalings: + last = nn.Linear(config.xlora_size, n_classes * n_layers, bias=True).to(device).to(self.dtype) + else: + last = nn.Linear(config.xlora_size, n_classes, bias=True).to(device).to(self.dtype) + self.layers = nn.Sequential(*layers, last) + + def make_dummy_scalings( + self, + input_ids: Optional[torch.LongTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + *args, + **kwargs, + ) -> torch.Tensor: + """ + Make some dummy scalings for the scalings pass (the one to get the logits for the X-LoRA classifier). These are + of shape (batch_size, seq_len, n_layers, n_classes) and filled with the override scalings pass value. Note that + n_layers is the number of LoRA adapter layers, not the number of model layers. + """ + if input_ids is not None: + batch_size = input_ids.shape[0] + device = input_ids.device + seq_len = input_ids.shape[1] + else: + batch_size = inputs_embeds.shape[0] + device = inputs_embeds.device + seq_len = inputs_embeds.shape[1] + + return torch.full( # type: ignore + (batch_size, seq_len, self.n_layers, self.n_classes), + self.override_scaling_pass_value, + ).to(device=device, dtype=self.dtype) + + def forward( + self, + result, + input_ids: Optional[torch.LongTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + *args, + **kwargs, + ) -> torch.Tensor: + """ + Using the hidden states of the model, predict `n_classes` LoRA alpha values. Returns the scalings. + """ + if input_ids is not None: + batch_size = input_ids.shape[0] + seq_len = input_ids.shape[1] + else: + batch_size = inputs_embeds.shape[0] + seq_len = inputs_embeds.shape[1] + + hidden_states = result.hidden_states # type: ignore + + hidden_state = hidden_states[-1] # Get the last hidden state + + ### Classifier run + # hidden_state=[batch_size, seq_len, hidden_size] + logits = self.layers.forward(hidden_state) + + ### Repeat to make layerwise scalings + ### If layerwise_scalings=False, then the classifier only outputs logits which are not layer-wise. + ### So, we expand them to the correct shape. + if not self.config.layerwise_scalings: + logits = logits.unsqueeze(2) + logits = logits.expand(-1, -1, self.n_layers, -1) + + ### Classifier run + + scalings = logits.reshape(batch_size, seq_len, self.n_layers, self.n_classes) + # scalings = [batch_size, seq_len, n_layers, n_classes] + + if self.config.enable_softmax: + scalings = self.softmax(scalings) + + if self.scalings_logging: + self.log_scalings.append(scalings) + + return scalings + + def _get_bucketed_scalings(self) -> dict[int, tuple[list[int], list[torch.Tensor]]]: + """ + Returns bucketed scalings, bucketed by seq_len. Each value consists of the positions (the first) and the + associated tensors. The positions are paired with the associated tensors and give the position in the scaling + log. Each scaling is a tensor of shape (batch_size, seq_len, n_layers, n_classes)). + """ + seqlens_map: dict[int, tuple[list[int], list[torch.Tensor]]] = {} + for i, scaling in enumerate(self.log_scalings): + seq_len = scaling.shape[1] + if seq_len not in seqlens_map: + seqlens_map[seq_len] = ([i], [scaling]) + else: + seqlens_map[seq_len][0].append(i) + seqlens_map[seq_len][1].append(scaling) + + return seqlens_map + + def _set_override_scaling_pass_value(self, value: Union[Number, None]): + if value is None: + self.override_scaling_pass_value = 1 / self.n_classes + else: + self.override_scaling_pass_value = value + self.config.scaling_pass_value = self.override_scaling_pass_value diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/config.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4a2a53fd83c48885b64ec9fc0d4c26c9b00d5d13 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/config.py @@ -0,0 +1,102 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from dataclasses import dataclass +from typing import Optional + +from peft.config import PeftConfig +from peft.utils.peft_types import PeftType + + +@dataclass +class XLoraConfig(PeftConfig): + r""" + This is the configuration class to store the configuration of a `XLoraModel`. When the config is reloaded, the + paths of the `adapters` field is disregarded in favor of the saved adapters. As such, only the keys matter during + loading. + + Args: + hidden_size (`int`): + Hidden size of the base model. + adapters (`dict`): + Mapping of adapter names to the LoRA adapter id, as per PeftModel.load_adapter. *They will be automatically + loaded*, to use as LoRA experts. When using from_pretrained, pass the new adapters dict as a keyword + argument. + enable_softmax (`bool`, *optional*, defaults to `True`): + Enable softmax application for the X-LoRA classifier. + enable_softmax_topk (`bool`, *optional*, defaults to `False`): + Enable softmax application for the top-k LoRA adapters. Mutually exclusive to `enable_softmax` and must + only be set if `top_k_lora` is. + softmax_temperature (`float`, *optional*, defaults to 1.0): + Softmax temperature, lower yields sharper predictions + layerwise_scalings (`bool`, *optional*, defaults to `False`): + If True, generate scalings for each LoRA adapter (each layer). If this is False, then scalings will be + broadcasted, the same, to each layer. + top_k_lora (`int`, *optional*, defaults to None): + Sparsely select the top_k LoRA experts instead of the default dense method. + xlora_depth (`int`, *optional*, defaults to 1): + Depth of the X-LoRA classifier. + xlora_size (`int`, *optional*, defaults to 2048): + Hidden size of the X-LoRA classifier, irrelevant if `xlora_depth=1`. + xlora_dropout_p (`float`, *optional*, defaults to 0.2): + Dropout probability of the X-LoRA classifier, irrelevant if `xlora_depth=1`. + use_trainable_adapters (`bool`, *optional*, defaults to False): + Make the adapters trainable. + scaling_pass_value (`float`, *optional*, defaults to 0): + Scaling pass value. + global_scaling_weight (`float`, *optional*, defaults to 1): + Weight to multiply output of each LoRA adapter by. + """ + + hidden_size: int = None # type: ignore + adapters: dict[str, str] = None # type: ignore + enable_softmax: bool = True + enable_softmax_topk: bool = False + layerwise_scalings: bool = False + xlora_depth: int = 1 + xlora_size: int = 2048 + xlora_dropout_p: float = 0.2 + use_trainable_adapters: bool = False + softmax_temperature: float = 1.0 + top_k_lora: Optional[int] = None + scaling_pass_value: float = 0.0 + global_scaling_weight: float = 1.0 + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.XLORA + + if self.hidden_size is None: + warnings.warn( + "No value was provided for `hidden_size`. This will be set to 4096 by default, please ensure that this is correct." + ) + self.hidden_size = 4096 + if self.adapters is None: + warnings.warn( + "No value was provided for `adapters`. This will be set to empty, please ensure that this is correct." + ) + self.adapters = {} + + if self.enable_softmax_topk and self.top_k_lora is None: + warnings.warn("`enable_softmax_topk` enabled `top_k_lora` is not set") + + if self.enable_softmax_topk and self.enable_softmax: + warnings.warn( + "`enable_softmax_topk` and `enable_softmax` are both enabled. This will result in worse performance." + ) + + if self.top_k_lora is not None and self.top_k_lora < 1: + warnings.warn("`top_k_lora` value must be at least 1.") diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/layer.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0eeac1aca3b600c8e7da3cc9584397a41061e88 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/layer.py @@ -0,0 +1,236 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, Optional + +import torch +from torch import Tensor, nn + +from peft.tuners import lora + +from .config import XLoraConfig + + +class XLoraLayer: + """ + A XLoraLayer wraps any LoraLayer and performs the XLora operation on the LoRA adaptors specified. Its primary API + is the forward method, which uses the scalings to execute the XLora algorithm. + """ + + def __init__( + self, + model: nn.Module, # XLoraModel + target: lora.LoraLayer, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + self.model = model + self.target_forward = target_forward + self.target = target + self.layer_number = layer_number + self.config = config + + """ + Apply the scalings for the adapter. + """ + + @staticmethod + def apply_scalings_to_x(x: torch.Tensor, scalings_layer: torch.Tensor, adapter: int) -> torch.Tensor: + # scalings_layer = [batch_size, seq_len, n_classes] + scalings = scalings_layer[:, :, adapter].unsqueeze(-1) + # scalings_layer = [batch_size, seq_len, 1] + return x * scalings + + """ + Get the scalings for this layer, potentially applying topk and topk+softmax. This is called before + `apply_scalings_to_x` + """ + + def get_maybe_topk_scalings(self, scalings) -> torch.Tensor: + # xlora_scalings = [batch_size, seq_len, n_classes] + xlora_scalings: Tensor = scalings[:, :, self.layer_number, :] # type: ignore + + if self.config.top_k_lora is not None: + _, topk_indices = torch.topk(xlora_scalings, k=self.config.top_k_lora, dim=-1) + + # Mask the topk to True, the rest to False + mask = torch.zeros_like(xlora_scalings, dtype=torch.bool) + mask.scatter_(-1, topk_indices, True) + + xlora_scalings = xlora_scalings * mask.to(xlora_scalings.dtype) + + # Apply per-token normalization to the xLoRA scaling factors using a softmax + if self.config.enable_softmax_topk: + nonzero_mask = xlora_scalings != 0 + full = xlora_scalings.masked_fill(~nonzero_mask, float("-inf")) + new_scalings = torch.softmax(full, dim=-1) + xlora_scalings = new_scalings.masked_fill(~nonzero_mask, 0.0) + + return xlora_scalings + + +class XLoraLinearLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Linear, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + previous_dtype = x.dtype + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_A.keys(): + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora[active_adapter]: + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + lora_A = self.target.lora_A[active_adapter] + lora_B = self.target.lora_B[active_adapter] + dropout = self.target.lora_dropout[active_adapter] + scaling = self.target.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) # type: ignore + if scalings is not None: + x_mod = self.apply_scalings_to_x(x, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + x_mod = x + scaling_weight = 1 + result += lora_B(lora_A(dropout(x_mod))) * scaling * scaling_weight + + result = result.to(previous_dtype) + return result + + +class XLoraEmbeddingLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Embedding, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to X-LoRA contributions too. + embed_scale = self.target._get_embed_scale() + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_embedding_A: + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora.get(active_adapter, False): + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + embedding_A = self.target.lora_embedding_A[active_adapter].T + embedding_B = self.target.lora_embedding_B[active_adapter].T + scaling = self.target.scaling[active_adapter] + after_A = self.target._embed(x, embedding_A) # type: ignore + if scalings is not None: + after_A_mod = self.apply_scalings_to_x(after_A, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + after_A_mod = after_A + scaling_weight = 1 + + adapter_output = (after_A_mod @ embedding_B) * scaling * scaling_weight + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result += adapter_output + + return result + + +class XLoraConv2dLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Conv2d, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + previous_dtype = x.dtype + + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_A.keys(): + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora[active_adapter]: + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + lora_A = self.target.lora_A[active_adapter] + lora_B = self.target.lora_B[active_adapter] + dropout = self.target.lora_dropout[active_adapter] + scaling = self.target.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) # type: ignore + if scalings is not None: + x_mod = self.apply_scalings_to_x(x, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + x_mod = x + scaling_weight = 1 + result += lora_B(lora_A(dropout(x_mod))) * scaling * scaling_weight + + result = result.to(previous_dtype) + return result diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/model.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..08a22f0aca534a17935d2fb486931a7e8d41316e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/tuners/xlora/model.py @@ -0,0 +1,525 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +from contextlib import contextmanager +from functools import partial +from typing import Optional, Union + +import torch +from torch import nn + +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.lora.model import LoraModel +from peft.tuners.tuners_utils import BaseTuner +from peft.utils.constants import DUMMY_TARGET_MODULES +from peft.utils.save_and_load import set_peft_model_state_dict + +from .. import lora +from .classifier import XLoraClassifier +from .config import XLoraConfig +from .layer import XLoraConv2dLayer, XLoraEmbeddingLayer, XLoraLinearLayer + + +def convert_layers_to_xlora( + base: nn.Module, # PeftModel + xloramodel: nn.Module, # XLoraModel + config: XLoraConfig, +) -> tuple[int, torch.device | None]: + """ + Returns the number of swapped layers. + """ + total_swapped = 0 + all_layers = [] + + device = None + for module in base.modules(): + # Check the exact type because classes like OPTLearnedPositionalEmbedding inherit from nn.Embedding + if isinstance(module, lora.Linear): + device = module.lora_A[next(iter(module.lora_A))].weight.device + new_layer = XLoraLinearLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + elif isinstance(module, lora.Embedding): + device = module.lora_embedding_A[next(iter(module.lora_embedding_A))].device + new_layer = XLoraEmbeddingLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + elif isinstance(module, lora.Conv2d): + device = module.lora_A[next(iter(module.lora_A))].weight.device + new_layer = XLoraConv2dLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + + return (total_swapped, device) + + +def _load_adapter_into_lora_model( + lora_model: LoraModel, + adapter_name: str, + model_id: str, + torch_device: Optional[str] = None, + ephemeral_gpu_offload: bool = False, + autocast_adapter_dtype: bool = True, + subfolder: Optional[str] = None, + **kwargs, +): + """ + This method emulates the behavior of `PeftModel.from_pretrained`. Updates to `PeftModel.from_pretrained` may need + to be reflected here. + + All params pertain to the adapter (adapter name, model id, `i` is the adapter number in 0 indexing). + """ + from peft.peft_model import PeftModel + from peft.tuners.lora.config import LoraConfig + from peft.utils.other import infer_device + from peft.utils.save_and_load import load_peft_weights + + hf_hub_download_kwargs, kwargs = PeftModel._split_kwargs(kwargs) + if torch_device is None: + torch_device = infer_device() + + if adapter_name not in lora_model.peft_config: + # load the config + lora_peft_config = LoraConfig.from_pretrained( + model_id, + ephemeral_gpu_offload=ephemeral_gpu_offload, + subfolder=subfolder, + **hf_hub_download_kwargs, + ) + lora_peft_config.inference_mode = False + lora_model.peft_config[adapter_name] = lora_peft_config + lora_model.inject_adapter(lora_model.model, adapter_name) + + adapter_weights = load_peft_weights(model_id, device=torch_device, subfolder=subfolder, **hf_hub_download_kwargs) + new_adapter_weights = {} + # Rework the keys to contain the adapter numbers + for old_key in adapter_weights.keys(): + key: str = old_key + # Remove all the prefixes until we have model.<...> + while not (key.startswith("model.") and not key.startswith("model.model.")): + key = key[key.find(".") + 1 :] + # We always want model.model + key = "model." + key + new_adapter_weights[key] = adapter_weights[old_key] + + # load the weights into the model + ignore_mismatched_sizes = kwargs.get("ignore_mismatched_sizes", False) + load_result = set_peft_model_state_dict( + lora_model, + new_adapter_weights, + adapter_name=adapter_name, + ignore_mismatched_sizes=ignore_mismatched_sizes, + ) + if len(load_result.unexpected_keys) > 0: + raise ValueError( + f"Got unexpected keys! Please raise an issue and tag @EricLBuehler.\n\nunexpected_keys={load_result.unexpected_keys}" + ) + + if hasattr(lora_model, "_cast_adapter_dtype"): + lora_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + +class XLoraModel(BaseTuner): + """ + Creates an X-LoRA (Mixture of LoRA experts), model from a pretrained transformers model. Currently, this X-LoRA + implementation only works with models with a transformer architecture. + + The method is described in detail in https://huggingface.co/papers/2402.07148. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`XLoraConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, does not affect the LoRA adapter names. + + Returns: + `torch.nn.Module`: The X-LoRA model. + + Example: + ```py + >>> import torch + >>> from transformers import AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig + >>> from peft import XLoraConfig, get_peft_model, prepare_model_for_kbit_training + + >>> model_config = AutoConfig.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") + >>> config = XLoraConfig( + ... task_type="CAUSAL_LM", + ... hidden_size=model_config.hidden_size, + ... xlora_depth=4, + ... adapters={ + ... "adapter_1": "./path/to/the/checkpoint/", + ... "adapter_2": "./path/to/the/checkpoint/", + ... "adapter_n": "./path/to/the/checkpoint/", + ... }, + ... ) + >>> int8_config = BitsAndBytesConfig(load_in_8bit=True) + >>> model = AutoModelForCausalLM.from_pretrained( + ... "mistralai/Mistral-7B-Instruct-v0.1", + ... trust_remote_code=True, + ... attn_implementation="flash_attention_2", + ... device_map="cuda:0", + ... torch_dtype=torch.bfloat16, + ... quantization_config=int8_config, + ... ) + >>> model = prepare_model_for_kbit_training(model) + >>> xlora_model = get_peft_model(model, config) + ``` + """ + + def __init__( + self, + model: nn.Module, + config: Union[dict[str, XLoraConfig], XLoraConfig], + adapter_name: str, + torch_device: Optional[str] = None, + ephemeral_gpu_offload: bool = False, + autocast_adapter_dtype: bool = True, + **kwargs, + ) -> None: + """ + Create a new X-LoRA model + + Args: + model (`nn.Module`): + Base model to apply X-LoRA to. + config: ([`XLoraConfig`]): + X-LoRA configuration object. + adapter_name: (`str`): + Adapter name for the X-LoRA adapter. + torch_device (`str`, *optional*, defaults to None): + (For loading the LoRA adapters) The device to load the adapter on. If `None`, the device will be + inferred. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + (For loading the LoRA adapters) Whether to use ephemeral GPU offloading for partially loaded modules. + Defaults to `False`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + (For loading the LoRA adapters) Whether to autocast the adapter dtype. Defaults to `True`. Right now, + this will only cast adapter weights using float16 and bfloat16 to float32, as this is typically + required for stable training, and only affect select PEFT tuners. + kwargs: (`optional`): + (For loading the LoRA adapters) Additional arguments to modify the way the adapter is loaded, e.g. the + token for Hugging Face Hub. + """ + + nn.Module.__init__(self) + + if isinstance(config, dict): + conf = config[adapter_name] + else: + conf = config + + # Create an empty LoraModel + base_lora_config = copy.copy(conf) + base_lora_config.target_modules = DUMMY_TARGET_MODULES + # Imitate a LoraConfig, fields might need to be updated if LoraConfig is updated + base_lora_config.layer_replication = None + base_lora_config.bias = "none" + lora_model = LoraModel(model, base_lora_config, adapter_name) + + self.xlora_config = conf + self.lora_model = lora_model + + peft_config = conf + + if hasattr(model.config, "use_cache") and model.config.use_cache: + raise ValueError("`use_cache` must be False") + + adapters_items = peft_config.adapters.items() + if hasattr(self.xlora_config, "_subfolders"): + adapters_items = zip(peft_config.adapters.items(), self.xlora_config._subfolders) + else: + adapters_items = peft_config.adapters.items() + + if hasattr(self.xlora_config, "_subfolders"): + for i, (_adapter_name, model_id), subfolder in enumerate(adapters_items): + _load_adapter_into_lora_model( + lora_model=self.lora_model, + adapter_name=str(i), + model_id=model_id, + torch_device=torch_device, + ephemeral_gpu_offload=ephemeral_gpu_offload, + autocast_adapter_dtype=autocast_adapter_dtype, + subfolder=subfolder, + **kwargs, + ) + else: + for i, (_adapter_name, model_id) in enumerate(adapters_items): + _load_adapter_into_lora_model( + lora_model=self.lora_model, + adapter_name=str(i), + model_id=model_id, + torch_device=torch_device, + ephemeral_gpu_offload=ephemeral_gpu_offload, + autocast_adapter_dtype=autocast_adapter_dtype, + subfolder=None, + **kwargs, + ) + + self.lora_model.set_adapter(list(peft_config.adapters.keys())) + + self._maybe_freeze_all_adapters() + + total_swapped, device = convert_layers_to_xlora( + model, + self, + peft_config, + ) + + n_classes = len(peft_config.adapters) + xlora_classifier = XLoraClassifier(model, peft_config, n_classes, total_swapped, device) + + # Setup the model internal state + self.internal_xlora_classifier = xlora_classifier + self.internal_xlora_scalings = None # type: ignore + # Controlled by enable_adapter_layers or disable_adapter_layers + self.disabled = False + + def _maybe_freeze_all_adapters(self): + self.eval() + if not self.xlora_config.use_trainable_adapters: + for name, param in self.named_parameters(): + if "lora_" in name: + param.requires_grad = False + + def generate(self, *args, **kwargs): + kwargs["use_cache"] = False + res = self.lora_model.generate(*args, **kwargs) # type: ignore + # This is necessary because we use PeftModel.disable_adapter() which reenables the adapters + self._maybe_freeze_all_adapters() + return res + + @contextmanager + def _enable_peft_forward_hooks(self, *generate_args, **generate_kwargs): + def scalings_injection_hook(target, args, kwargs, scalings): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["scalings"] = scalings + return args, kwargs + + hook_handles = [] + + def _pre_forward(module, *args, **kwargs): + # =========================== Forward pass with "dummy" scalings ================== + nonlocal hook_handles + + args_real = args[0] + kwargs_real = args[1] + kwargs_real.update(kwargs) + + dummy_scalings = self.internal_xlora_classifier.make_dummy_scalings(*args_real, **kwargs_real) + + for xlora_module in self.modules(): + if isinstance(xlora_module, LoraLayer): + pre_forward = partial(scalings_injection_hook, scalings=dummy_scalings) + existing_hooks = getattr(xlora_module, "_forward_pre_hooks", {}) + if any(val is scalings_injection_hook for val in existing_hooks.values()): + # When calling generate, module.forward is called multiple times inside the forward hook + # context, resulting in multiple hooks being registered. Therefore, we check if the hooks is + # already present and skip it in that case. + continue + handle = xlora_module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + with torch.no_grad(): + self.lora_model.disable_adapter_layers() + + try: + scaling_pass_kwargs = kwargs_real.copy() + scaling_pass_kwargs["output_hidden_states"] = True + scaling_pass_kwargs["return_dict"] = True + try: + base_output = self.lora_model.model.forward(*args_real, **scaling_pass_kwargs) + finally: + # Clean everything up + for handle in hook_handles: + handle.remove() + finally: + self.lora_model.enable_adapter_layers() + + xlora_scalings = self.internal_xlora_classifier(*args_real, result=base_output, **kwargs_real) + # Store computed scalings to fix get_latest_scalings() returning None + self.internal_xlora_scalings = xlora_scalings + + # =========================== Real forward pass with calculated scalings ================== + + hook_handles = [] + for xlora_module in self.modules(): + if isinstance(xlora_module, LoraLayer): + pre_forward = partial(scalings_injection_hook, scalings=xlora_scalings) + handle = xlora_module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + if not self.disabled: + forward_handle = self.lora_model.model.register_forward_pre_hook(_pre_forward, with_kwargs=True) + + # Run the forward pass: first the scaling pass in the hook, and then with the base model + try: + yield + finally: + if not self.disabled: + for handle in hook_handles: + handle.remove() + forward_handle.remove() + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "lora_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.lora_model, name) + + @staticmethod + def _prepare_adapter_config(peft_config, _model_config): + # Handle X-LoRA case + return peft_config + + """ + Does nothing. X-LoRA needs adapters to be frozen. + """ + + def _mark_only_adapters_as_trainable(self) -> None: ... + + """ + This enables the X-LoRA adapter. + """ + + def enable_adapter_layers(self) -> None: + self.disabled = False + + """ + This diasables the X-LoRA adapter. + """ + + def disable_adapter_layers(self) -> None: + self.disabled = True + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + # Does nothing because XLoraModel has no target modules + pass + + @staticmethod + def _check_target_module_exists(lora_config, key): + # Does nothing because XLoraModel has no target modules + return False + + def forward(self, *args, **kwargs): + return self.lora_model.model(*args, **kwargs) + + def set_topk_lora(self, value: Optional[int]): + """ + Sparsely select the specified top_k LoRA experts instead of the default dense method. Set to None to use dense. + This is reflected in the config. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.config.top_k_lora = value + + def set_global_scaling_weight(self, weight: float): + """ + Set the global LoRA weight, a scalar to multiply the output of each LoRA adapter by. This is by default 1. This + is reflected in the config. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.config.global_scaling_weight = weight + + def set_scaling_pass_value(self, value: float | None): + """ + Set the scaling pass value, the value to set the scalings to during the scaling pass. If the value is None, the + scaling pass value will be 1/n where n is the number of adapters. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier._set_override_scaling_pass_value(value) + + def get_global_scaling_weight(self) -> float: + """ + Get the global LoRA weight. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier.config.global_scaling_weight + + def get_latest_scalings(self) -> Optional[torch.Tensor]: + """ + Returns the latest scalings prediction, or None if no scalings have been predicted. The tensor is of shape + (batch_size, seq_len, n_layers, n_classes). + """ + return self.internal_xlora_scalings + + def get_scalings_log(self) -> list[torch.Tensor]: + """ + Returns a shallow (only copying the list itself not the tensors) copy of the list containing the scalings log. + Editing the list does not change the underlying log. The tensors are of shape (batch_size, seq_len, n_layers, + n_classes). The seq_len dim may vary with input dimension. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier.log_scalings.copy() + + def enable_scalings_logging(self): + """ + Enable scalings logging. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.scalings_logging = True + + def disable_scalings_logging(self): + """ + Disable scalings logging, without clearing the log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.scalings_logging = False + + def clear_scalings_log(self): + """ + Clear the scalings log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.log_scalings.clear() + + def get_bucketed_scalings_log(self) -> dict[int, tuple[list[int], list[torch.Tensor]]]: + """ + Returns bucketed scalings, bucketed by seq_len. Each value consists of the positions (the first) and the + associated tensors. The positions are paired with the associated tensors and give the position in the scaling + log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier._get_bucketed_scalings() diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/__init__.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba78c43ccb1e11dd5fd3152dcf533e22b5b64e7b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/__init__.py @@ -0,0 +1,151 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .constants import ALLOWED_COMPUTE_DTYPES, UPCAST_DTYPES +from .integrations import map_cache_to_layer_device_map +from .loftq_utils import replace_lora_weights_loftq +from .other import ( + CONFIG_NAME, + INCLUDE_LINEAR_LAYERS_SHORTHAND, + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, + WEIGHTS_NAME, + AuxiliaryTrainingWrapper, + ModulesToSaveWrapper, + TrainableTokensWrapper, + _freeze_adapter, + _get_batch_size, + _get_input_embeddings_name, + _get_submodules, + _is_valid_match, + _prepare_prompt_learning_config, + _set_adapter, + _set_trainable, + bloom_model_postprocess_past_key_value, + cast_mixed_precision_params, + get_gptqmodel_quant_linear, + get_quantization_config, + id_tensor_storage, + infer_device, + prepare_model_for_kbit_training, + set_additional_trainable_modules, + shift_tokens_right, + transpose, +) +from .peft_types import PeftType, TaskType, register_peft_method +from .quantization_utils import get_quantization_kwargs, quantization_extra_repr, resolve_quantization_backend +from .save_and_load import get_peft_model_state_dict, load_peft_weights, set_peft_model_state_dict +from .warning import PeftWarning + + +__all__ = [ + "ALLOWED_COMPUTE_DTYPES", + "CONFIG_NAME", + "INCLUDE_LINEAR_LAYERS_SHORTHAND", + "SAFETENSORS_WEIGHTS_NAME", + "TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING", + "UPCAST_DTYPES", + "WEIGHTS_NAME", + "AuxiliaryTrainingWrapper", + "ModulesToSaveWrapper", + "PeftType", + "PeftWarning", + "TaskType", + "TrainableTokensWrapper", + "_freeze_adapter", + "_get_batch_size", + "_get_input_embeddings_name", + "_get_submodules", + "_is_valid_match", + "_prepare_prompt_learning_config", + "_set_adapter", + "_set_trainable", + "bloom_model_postprocess_past_key_value", + "cast_mixed_precision_params", + "get_gptqmodel_quant_linear", + "get_peft_model_state_dict", + "get_quantization_config", + "get_quantization_kwargs", + "id_tensor_storage", + "infer_device", + "load_peft_weights", + "map_cache_to_layer_device_map", + "prepare_model_for_kbit_training", + "quantization_extra_repr", + "register_peft_method", + "replace_lora_weights_loftq", + "resolve_quantization_backend", + "set_additional_trainable_modules", + "set_peft_model_state_dict", + "shift_tokens_right", + "transpose", +] diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/constants.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..94aa475f0dbb36809c8d42577b063df86beb4b18 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/constants.py @@ -0,0 +1,403 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from transformers import BloomPreTrainedModel + +from ..import_utils import is_transformers_le_4_53 + + +# needed for prefix-tuning of bloom model +def bloom_model_postprocess_past_key_value(past_key_values): + past_key_values = torch.cat(past_key_values) + total_layers, batch_size, num_attention_heads, num_virtual_tokens, head_dim = past_key_values.shape + keys = past_key_values[: total_layers // 2] + keys = keys.transpose(2, 3).reshape( + total_layers // 2, batch_size * num_attention_heads, head_dim, num_virtual_tokens + ) + values = past_key_values[total_layers // 2 :] + values = values.reshape(total_layers // 2, batch_size * num_attention_heads, num_virtual_tokens, head_dim) + + return tuple(zip(keys, values)) + + +# needed for prefix-tuning of StarCoder models +def starcoder_model_postprocess_past_key_value(past_key_values): + result = [] + for k in past_key_values: + k = k[:, :, 0] + k = k.permute([1, 2, 0, 3]) + k = k.reshape(*k.shape[:-2], -1) + result.append(k) + return tuple(result) + + +# TODO: remove this once transformers 4.53 is no longer supported +TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING = {} +if is_transformers_le_4_53: + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING["gpt_bigcode"] = ( + starcoder_model_postprocess_past_key_value + ) + + +if hasattr(BloomPreTrainedModel, "_convert_to_standard_cache"): + # special handling for bloom architecture was fixed in: + # https://github.com/huggingface/transformers/pull/31445 + # the _convert_to_standard_cache method is removed in the PR and thus serves as an indicator + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING["bloom"] = bloom_model_postprocess_past_key_value + + +####################################### +# DEFAULT MAPPINGS FOR TARGET_MODULES # +####################################### + +TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "v"], + "mt5": ["q", "v"], + "bart": ["q_proj", "v_proj"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "blip-2": ["q", "v", "q_proj", "v_proj"], + "opt": ["q_proj", "v_proj"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "xlm-roberta": ["query", "value"], + "electra": ["query", "value"], + "deberta-v2": ["query_proj", "value_proj"], + "deberta": ["in_proj"], + "layoutlm": ["query", "value"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "chatglm": ["query_key_value"], + "gpt_bigcode": ["c_attn"], + "mpt": ["Wqkv"], + "RefinedWebModel": ["query_key_value"], + "RefinedWeb": ["query_key_value"], + "falcon": ["query_key_value"], + "btlm": ["c_proj", "c_attn"], + "codegen": ["qkv_proj"], + "mistral": ["q_proj", "v_proj"], + "mixtral": ["q_proj", "v_proj"], + "stablelm": ["q_proj", "v_proj"], + "phi": ["q_proj", "v_proj", "fc1", "fc2"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], + "rwkv": ["key", "value", "receptance", "output"], + "rwkv7": ["r_proj", "k_proj", "v_proj", "o_proj", "key", "value"], +} + +# target module mappings that are identical to LORA +TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING["vit"] = ["query", "value"] +TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() + +# mappings that are similar to LORA with small changes +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING["gpt_bigcode"] = ["mlp.c_proj"] +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING["gpt2"] = ["mlp.c_proj"] + +TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING["phi"] = ["q_proj", "v_proj"] + +TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING["phi"] = ["q_proj", "v_proj"] + +TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING["dinov2"] = ["query", "value"] + +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING["gpt_bigcode"] = ["mlp.c_proj"] +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING["gpt2"] = ["mlp.c_proj"] + +# target module mappings that differ from LORA +TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING = { + "llama": ["input_layernorm", "post_attention_layernorm", "norm"], + "bloom": ["input_layernorm", "post_attention_layernorm", "ln_f"], + "llava": [ + "multi_modal_projector", + "input_layernorm", + "post_attention_layernorm", + "norm", + "embed_tokens", + "lm_head", + ], + "t5": ["layer_norm", "final_layer_norm"], + "mt5": ["layer_norm", "final_layer_norm"], + "bart": ["self_attn_layer_norm", "encoder_attn_layer_norm", "final_layer_norm"], + "gpt2": ["ln_1", "ln_2", "ln_f"], + "blip-2": ["layernorm", "LayerNorm", "final_layer_norm", "self_attn_layer_norm"], + "gptj": ["ln_1", "ln_f"], + "falcon": ["input_layernorm", "post_attention_layernorm", "ln_f"], + "mistral": ["input_layernorm", "post_attention_layernorm", "norm"], + "phi": ["input_layernorm", "final_layernorm"], + "gemma": ["input_layernorm", "post_attention_layernorm", "norm"], + "gemma2": [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + "norm", + ], + "gemma3_text": [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + "norm", + ], + "qwen2": ["post_attention_layernorm"], + "qwen3": ["post_attention_layernorm"], +} + +TRANSFORMERS_MODELS_TO_HIRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() + + +TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING = { + "t5": ["k", "v", "wo"], + "mt5": ["k", "v", "wi_1"], + "gpt2": ["c_attn", "mlp.c_proj"], + "bloom": ["query_key_value", "mlp.dense_4h_to_h"], + "roberta": ["key", "value", "output.dense"], + "opt": ["q_proj", "k_proj", "fc2"], + "gptj": ["q_proj", "v_proj", "fc_out"], + "gpt_neox": ["query_key_value", "dense_4h_to_h"], + "gpt_neo": ["q_proj", "v_proj", "c_proj"], + "bart": ["q_proj", "v_proj", "fc2"], + "gpt_bigcode": ["c_attn", "mlp.c_proj"], + "llama": ["k_proj", "v_proj", "down_proj"], + "llama4": ["q_proj", "v_proj", "down_proj"], + "mistral": ["k_proj", "v_proj", "down_proj"], + "mixtral": ["k_proj", "v_proj", "w2"], + "bert": ["key", "value", "output.dense"], + "deberta-v2": ["key_proj", "value_proj", "output.dense"], + "deberta": ["in_proj", "output.dense"], + "RefinedWebModel": ["query_key_value", "dense_4h_to_h"], + "RefinedWeb": ["query_key_value", "dense_4h_to_h"], + "falcon": ["query_key_value", "dense_4h_to_h"], + "phi": ["q_proj", "v_proj", "fc2"], + "gemma": ["q_proj", "v_proj", "down_proj"], + "gemma2": ["q_proj", "v_proj", "down_proj"], + "gemma3_text": ["q_proj", "v_proj", "down_proj"], + "qwen2": ["q_proj", "v_proj", "down_proj"], + "qwen3": ["q_proj", "v_proj", "down_proj"], +} + +TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING = { + "t5": ["v"], + "mt5": ["v"], + "roberta": ["value"], + "opt": ["v_proj"], + "gptj": ["v_proj"], + "gpt_neo": ["v_proj"], + "bart": ["v_proj"], + "llama": ["v_proj"], + "llama4": ["v_proj"], + "mistral": ["v_proj"], + "mixtral": ["v_proj"], + "bert": ["value"], + "deberta-v2": ["value_proj"], + "phi": ["v_proj"], + "gemma": ["v_proj"], + "gemma2": ["v_proj"], + "gemma3_text": ["v_proj"], + "qwen2": ["v_proj"], + "qwen3": ["v_proj"], +} + +TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING = { + "t5": ["wo"], + "mt5": [], + "gpt2": ["mlp.c_proj"], + "bloom": ["mlp.dense_4h_to_h"], + "roberta": ["output.dense"], + "opt": ["fc2"], + "gptj": ["fc_out"], + "gpt_neox": ["dense_4h_to_h"], + "gpt_neo": ["c_proj"], + "bart": ["fc2"], + "gpt_bigcode": ["mlp.c_proj"], + "llama": ["down_proj"], + "llama4": ["down_proj"], + "mistral": ["down_proj"], + "mixtral": ["w2"], + "bert": ["output.dense"], + "deberta-v2": ["output.dense"], + "deberta": ["output.dense"], + "RefinedWeb": ["dense_4h_to_h"], + "RefinedWebModel": ["dense_4h_to_h"], + "falcon": ["dense_4h_to_h"], + "phi": ["fc2"], + "gemma": ["down_proj"], + "gemma2": ["down_proj"], + "gemma3_text": ["down_proj"], + "qwen2": ["down_proj"], + "qwen3": ["down_proj"], +} + +TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "k", "v", "o", "wi", "wo"], + "mt5": ["q", "k", "v", "o", "wi_0", "wi_1", "wo"], + "bart": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "key", "value", "dense"], + # "xlm-roberta": ["query", "value"], + # "electra": ["query", "value"], + "deberta-v2": ["query_proj", "key_proj", "value_proj", "dense"], + "gpt_bigcode": ["c_attn"], + "deberta": ["in_proj"], + # "layoutlm": ["query", "value"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "k", "v", "o", "wi", "wo"], + "mt5": ["q", "k", "v", "o", "wi_0", "wi_1", "wo"], + "bart": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "deberta-v2": ["query_proj", "key_proj", "value_proj", "dense"], + "gpt_bigcode": ["c_attn"], + "deberta": ["in_proj"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING = { + "llama": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "llama4": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "mistral": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "mixtral": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma2": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma3_text": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "qwen2": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "qwen3": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "phi": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gpt2": ["c_attn", "c_proj"], + "bloom": ["query_key_value", "dense_4h_to_h"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "k_proj", "v_proj", "out_proj", "fc_in", "fc_out"], + "gpt_neox": ["query_key_value", "dense_4h_to_h"], + "falcon": ["query_key_value", "dense_4h_to_h"], + "gpt_bigcode": ["c_attn", "c_proj"], +} + +TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING = { + "t5": ["q", "v"], + "mt5": ["q", "v"], + "bart": ["q_proj", "v_proj"], + "gpt2": ["mlp.c_proj"], + "bloom": ["query_key_value"], + "blip-2": ["q", "v", "q_proj", "v_proj"], + "opt": ["q_proj", "v_proj"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "xlm-roberta": ["query", "value"], + "electra": ["query", "value"], + "deberta-v2": ["query_proj", "value_proj"], + "deberta": ["in_proj"], + "layoutlm": ["query", "value"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "chatglm": ["query_key_value"], + "gpt_bigcode": ["mlp.c_proj"], + "mpt": ["Wqkv"], + "RefinedWebModel": ["query_key_value"], + "RefinedWeb": ["query_key_value"], + "falcon": ["query_key_value"], + "codegen": ["qkv_proj"], + "mistral": ["q_proj", "v_proj"], + "mixtral": ["q_proj", "v_proj"], + "stablelm": ["q_proj", "v_proj"], + "phi": ["q_proj", "v_proj", "fc1", "fc2"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +################## +# MISC CONSTANTS # +################## +WEIGHTS_NAME = "adapter_model.bin" +SAFETENSORS_WEIGHTS_NAME = "adapter_model.safetensors" +CONFIG_NAME = "adapter_config.json" +EMBEDDING_LAYER_NAMES = ["embed_tokens", "lm_head"] +SEQ_CLS_HEAD_NAMES = ["score", "classifier"] +INCLUDE_LINEAR_LAYERS_SHORTHAND = "all-linear" +TOKENIZER_CONFIG_NAME = "tokenizer_config.json" +DUMMY_TARGET_MODULES = "dummy-target-modules" +DUMMY_MODEL_CONFIG = {"model_type": "custom"} + +# If users specify more than this number of target modules, we apply an optimization to try to reduce the target modules +# to a minimal set of suffixes, which makes loading faster. We only apply this when exceeding a certain size since +# otherwise there is no point in optimizing and there is a small chance of bugs in the optimization algorithm, so no +# point in taking unnecessary risks. See #2045 for more context. +MIN_TARGET_MODULES_FOR_OPTIMIZATION = 20 +# dtypes that are allowed to be used for adapter computation +ALLOWED_COMPUTE_DTYPES = (torch.float16, torch.bfloat16, torch.float32) +# float dtypes that should be upcast in the adapter for computation +UPCAST_DTYPES = ("float8_e4m3fn", "float8_e4m3fnuz", "float8_e5m2", "float8_e5m2fnuz", "float8_e8m0fnu") diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/hotswap.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/hotswap.py new file mode 100644 index 0000000000000000000000000000000000000000..68e46c733ec51049899a1475c6ddf14576eb78cb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/hotswap.py @@ -0,0 +1,643 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import warnings +from operator import attrgetter +from typing import Literal, Optional + +import torch + +from peft.config import PeftConfig +from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING +from peft.tuners.lora import Conv2d, Linear, LoraConfig, LoraLayer + +from .other import get_pattern_key, infer_device +from .peft_types import PeftType +from .save_and_load import _insert_adapter_name_into_state_dict, load_peft_weights + + +# so far only LoRA is supported +CONFIG_KEYS_TO_CHECK = {PeftType.LORA: ["use_rslora", "lora_dropout", "alpha_pattern", "use_dora"]} + + +def _update_scaling(lora_module, adapter_name, scaling=None): + """ + Update the value of the scalings of the LoRA module. + + Takes into consideration that scalings can be tensors from prepare_model_for_compiled_hotswap. + """ + if lora_module.scaling[adapter_name] == scaling: + return + + if isinstance(lora_module.scaling[adapter_name], torch.Tensor): + lora_module.scaling[adapter_name].fill_(scaling) + elif isinstance(lora_module.scaling[adapter_name], (float, int)): + lora_module.scaling[adapter_name] = scaling + else: + raise TypeError( + "Something went wrong when trying to set the new scale value, expected to find the old value to be of type " + f"float or torch.Tensor, got {type(lora_module.scaling[adapter_name])} instead." + ) + + +def _convert_scalings_to_tensor(model) -> bool: + """ + Convert the LoRA scaling values into torch.tensors to prevent recompilation if they change. + + Returns: + bool: + Returns `True` if an appropriate adapter was found, else `False`. + """ + found_adapter = False + for module in model.modules(): + if not isinstance(module, LoraLayer): + continue + + found_adapter = True + scaling = module.scaling + for key, val in scaling.items(): + if isinstance(val, float): + # no need to deal with dtype as scalars are coerced + scaling[key] = torch.tensor(val, device=module.weight.device) + elif not isinstance(val, torch.Tensor): + raise TypeError( + "Something went wrong while trying to convert the scalings, expected to find values of type float " + f"but found {type(val)} instead." + ) + return found_adapter + + +def _get_padded_linear(lora_module: torch.nn.Module, target_rank: int, is_lora_A: bool) -> torch.nn.Linear: + """ + Get a new Linear layer for LoRA with padded weights according to the target rank. + + Args: + lora_module (nn.Module): + The LoRA sub-module (e.g. module.lora_A[adapter_name]). + target_rank (int): + The desired rank to pad to. + is_lora_A (bool): + True if this is the LoRA A matrix, False if LoRA B. + + Returns: + nn.Linear: + A newly created and padded Linear layer. If the rank already fit, the original layer is returned. + """ + weight = lora_module.weight + # For LoRA A, the "rank dimension" is weight.size(0) (out_features). + # For LoRA B, it is weight.size(1) (in_features). + original_rank = weight.size(0) if is_lora_A else weight.size(1) + + # If no padding needed + if original_rank == target_rank: + return lora_module + + if original_rank > target_rank: + raise ValueError( + f"Trying to pad the adapter to the target rank {target_rank}, but the original rank is larger " + f"({original_rank}). This is not possible." + ) + + out_features, in_features = weight.shape + + # lora_A and lora_B are always nn.Linear + if is_lora_A: + # LoRA A affects out_features + padded = torch.zeros(target_rank, in_features, device=weight.device, dtype=weight.dtype) + padded[:original_rank, :] = weight + new_layer = torch.nn.Linear(in_features, target_rank, bias=lora_module.bias is not None) + else: + # LoRA B affects in_features + padded = torch.zeros(out_features, target_rank, device=weight.device, dtype=weight.dtype) + padded[:, :original_rank] = weight + new_layer = torch.nn.Linear(target_rank, out_features, bias=lora_module.bias is not None) + new_layer.weight.requires_grad_(lora_module.weight.requires_grad) + + # Sanity check + if new_layer.weight.shape != padded.shape: + raise ValueError( + "Something went wrong when trying to pad the LoRA Linear weights, the new shape should be " + f"{padded.shape} but {new_layer.weight.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + if (lora_module.bias is not None) and (new_layer.bias.shape != lora_module.bias.shape): + raise ValueError( + "Something went wrong when trying to pad the LoRA Linear bias, the new shape should be " + f"{lora_module.bias.shape} but {new_layer.bias.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + + new_layer.weight.data = padded + # Copy bias if present + if lora_module.bias is not None: + new_layer.bias.data = lora_module.bias.data + + return new_layer + + +def _get_padded_conv2d(lora_module: torch.nn.Module, target_rank: int, is_lora_A: bool) -> torch.nn.Conv2d: + """ + Get a new Conv2d layer for LoRA with padded weights according to the target rank. + + Args: + lora_module (nn.Module): + The LoRA sub-module (e.g. module.lora_A[adapter_name]). + target_rank (int): + The desired rank to pad to. + is_lora_A (bool): + True if this is the LoRA A matrix, False if LoRA B. + + Returns: + nn.Conv2d: + A newly created and padded Conv2d layer. If the rank already fit, the original layer is returned. + """ + weight = lora_module.weight + # For Conv2d: [out_channels, in_channels, kernel_height, kernel_width] + out_channels, in_channels, kh, kw = weight.shape + original_rank = out_channels if is_lora_A else in_channels + + if original_rank == target_rank: + return lora_module + + if original_rank > target_rank: + raise ValueError( + f"Trying to pad the adapter to the target rank {target_rank}, but the original rank is larger " + f"({original_rank}). This is not possible." + ) + + # lora_A and lora_B are always nn.Conv2d + if is_lora_A: + # LoRA A affects out_channels + padded = torch.zeros(target_rank, in_channels, kh, kw, device=weight.device, dtype=weight.dtype) + padded[:out_channels, :, :, :] = weight + new_layer = torch.nn.Conv2d( + in_channels, + target_rank, + kernel_size=lora_module.kernel_size, + stride=lora_module.stride, + padding=lora_module.padding, + bias=lora_module.bias is not None, + groups=lora_module.groups, + ) + else: + # LoRA B affects in_channels + padded = torch.zeros(out_channels, target_rank, kh, kw, device=weight.device, dtype=weight.dtype) + padded[:, :in_channels, :, :] = weight + new_layer = torch.nn.Conv2d( + target_rank, + out_channels, + kernel_size=lora_module.kernel_size, + stride=lora_module.stride, + padding=lora_module.padding, + bias=lora_module.bias is not None, + groups=lora_module.groups, + ) + new_layer.weight.requires_grad_(lora_module.weight.requires_grad) + + # Sanity check + if new_layer.weight.shape != padded.shape: + raise ValueError( + "Something went wrong when trying to pad the LoRA weights, the new shape should be " + f"{padded.shape} but {new_layer.weight.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + if (lora_module.bias is not None) and (new_layer.bias.shape != lora_module.bias.shape): + raise ValueError( + "Something went wrong when trying to pad the LoRA Conv2d bias, the new shape should be " + f"{lora_module.bias.shape} but {new_layer.bias.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + + new_layer.weight.data = padded + # Copy bias if present + if lora_module.bias is not None: + new_layer.bias.data = lora_module.bias.data + + return new_layer + + +def _pad_lora_weights(model: torch.nn.Module, target_rank: int) -> bool: + """ + Pad LoRA weights in a model to a target rank while preserving the original behavior. + + Args: + model (nn.Module): The model containing LoRA modules (with lora_A and lora_B). + target_rank (int): The target rank to pad to. + + Returns: + bool: + Returns `True` if an appropriate adapter was found, else `False`. + """ + found_adapter = False + + for module in model.modules(): + # Decide which pad function to call based on module type + if isinstance(module, Linear): + pad_fn = _get_padded_linear + elif isinstance(module, Conv2d): + pad_fn = _get_padded_conv2d + else: + # Skip any other module types + continue + + # Pad LoRA A + for adapter_name, lora_A_module in module.lora_A.items(): + new_layer = pad_fn(lora_A_module, target_rank=target_rank, is_lora_A=True) + module.lora_A[adapter_name] = new_layer + + # Pad LoRA B + for adapter_name, lora_B_module in module.lora_B.items(): + new_layer = pad_fn(lora_B_module, target_rank=target_rank, is_lora_A=False) + module.lora_B[adapter_name] = new_layer + + found_adapter = True + return found_adapter + + +def prepare_model_for_compiled_hotswap( + model: torch.nn.Module, + *, + target_rank: Optional[int] = None, + config: Optional[LoraConfig | dict[str, LoraConfig]] = None, + check_compiled: Literal["error", "warn", "ignore"] = "error", +) -> None: + """ + Helper function that prepares the model so that it can later be compiled and then used with hot-swapping. + + It is necessary to call this function on the model for hot-swapping to work if both of these are true: + + - the different LoRA adapters have different ranks and/or different alpha values (i.e. scalings) + - you plan to torch.compile the model and want to avoid re-compilation + + It is important to call this function *after* the first LoRA adapter has been loaded (i.e. the one that will be + swapped out) but *before* the model is compiled. + + Even with this function, hot-swapping LoRA adapters that target different layers is still not supported. + + Note: This function modifies the model in-place. If you want to restore the model to its initial state, you will + have to reload it. + + Args: + model (`nn.Module`): + The model with the loaded adapter, before compilation. + target_rank (`int`, *optional*): + The target rank to pad the LoRA weights to. Should be the maximum rank among all LoRA adapters that will be + hot-swapped. If not specified, the target ranks will not be changed. + config (`LoraConfig` or `dict[str, LoraConfig]`, *optional*): + Optionally pass the `LoraConfig`s of the LoRA adapters. If passed, the rank in the configs will be updated + to `target_rank`. + check_compiled (`str`, *optional*, defaults to `"error"`): + How to handle the case when the model is already compiled, which should generally be avoided. The options + are: + - "error" (default): raise an error + - "warn": issue a warning + - "ignore": do nothing + + Raises: + ValueError + If the model is already compiled or if no adpater layer was found, raise an error. + + Example: + + ```py + base_model = ... + model = PeftModel.from_pretrained(base_model, path_adapter_0) + # Prepare the model to allow hotswapping even if ranks/scalings of 2nd adapter differ. + # You can skip this step if all ranks and scalings are identical. + prepare_model_for_compiled_hotswap(model, target_rank=highest_lora_rank) + model = torch.compile(model) + # do inference with adapter 0 + # replace the "default" lora adapter with the new one + hotswap_adapter(model, path_adapter_1, adapter_name="default", torch_device=device) + # do inference with adapter 1 + ``` + + """ + is_compiled = hasattr(model, "_orig_mod") or getattr(model, "_compiled_call_impl", False) + if is_compiled: + if check_compiled == "error": + raise ValueError("Call prepare_model_for_compiled_hotswap *before* compiling the model") + elif check_compiled == "warn": + warnings.warn( + "prepare_model_for_compiled_hotswap was called with a model that is already compiled. This will likely " + "result in re-compilation, hurting performance. Call the function before compiling the model." + ) + elif check_compiled != "ignore": + raise ValueError( + f"check_compiles should be one of 'error', 'warn', or 'ignore', got '{check_compiled}' instead." + ) + + conversion_found_adapter = _convert_scalings_to_tensor(model) + if target_rank is not None: + padding_found_adapter = _pad_lora_weights(model, target_rank=target_rank) + else: + padding_found_adapter = False + + if not (conversion_found_adapter or padding_found_adapter): + raise ValueError( + "No adapter layers found on the model, make sure call `prepare_model_for_compiled_hotswap` after loading " + "the first adapter and before loading the second adapter." + ) + + if not config: + return + if target_rank is None: + return + + if not isinstance(config, dict): + # config can be either a PeftConfig, or a dict of PeftConfigs like PeftModel.peft_config + config = {"dummy": config} + + for lora_config in config.values(): + lora_config.r = target_rank + if lora_config.rank_pattern: + for key in lora_config.rank_pattern: + lora_config.rank_pattern[key] = target_rank + + +def hotswap_adapter_from_state_dict( + model: torch.nn.Module, + state_dict: dict[str, torch.Tensor], + adapter_name: str, + config: LoraConfig, + parameter_prefix: str = "lora_", +): + """ + Swap out the adapter weights from the model with the weights from state_dict. + + As of now, only LoRA is supported. + + This is a low-level function that assumes that the adapters have been checked for compatibility and that the + state_dict has been correctly mapped to work with PEFT. For a high level function that performs this work for you, + use `hotswap_adapter` instead. + + Args: + model (`nn.Module`): + The model with the loaded adapter. + state_dict (`dict[str, torch.Tensor]`): + The state dict of the new adapter, which needs to be compatible (targeting same modules etc.). + adapter_name (`str`): + The name of the adapter that should be hot-swapped, e.g. `"default"`. The name will remain the same after + swapping. + config (`LoraConfig`): + The config of the LoRA adapter. This is used to determine the scaling and rank of the adapter. + parameter_prefix (`str`, *optional*, defaults to `"lora_"`) + The prefix used to identify the adapter's keys in the state dict. For LoRA, this would be `"lora_"` (the + default). + + Raises: + RuntimeError + If the old and the new adapter are not compatible, a RuntimeError is raised. + + """ + # Ensure that all the keys of the new adapter correspond exactly to the keys of the old adapter, otherwise + # hot-swapping is not possible + + # _orig_mod is for torch.compile(model) + is_compiled_wrapper = hasattr(model, "_orig_mod") + # TODO: there is probably a more precise way to identify the adapter keys + missing_keys = {k for k in model.state_dict() if (parameter_prefix in k) and (adapter_name in k)} + unexpected_keys = [] + + # first: dry run, not swapping anything + for key, new_val in state_dict.items(): + try: + old_val = attrgetter(key)(model) + except AttributeError: + unexpected_keys.append(key) + continue + + if is_compiled_wrapper: + missing_keys.remove("_orig_mod." + key) + else: + missing_keys.remove(key) + + # Right now, we don't deal with unexpected keys, i.e. if the adapter being swapped in targeting new layers. We could + # probably add LoRA to these layers ad hoc, but that would not work with compiled models. + if unexpected_keys: + msg = f"Hot swapping the adapter did not succeed, unexpected keys found: {', '.join(unexpected_keys)}." + raise RuntimeError(msg) + + # If the adapter that is being swapped in is missing some keys, this is fine. We just need to ensure that those LoRA + # weights from the previous adapter are set to 0 so that they don't influence the output. We don't need to worry + # about ranks are alphas. + for key in missing_keys: + # in case it's a compiled model + key = key.removeprefix("_orig_mod.") + # get LoRA parent module name by removing the 'lora_*..weight' part + module_name = ".".join(key.split(".")[:-3]) + module = model.get_submodule(module_name) + old_val = attrgetter(key)(model) + old_val.data.fill_(0.0) + + # actual swapping + for key, new_val in state_dict.items(): + # get LoRA parent module name by removing the 'lora_*..weight' part + module_name = ".".join(key.split(".")[:-3]) + module = model.get_submodule(module_name) + + # swap alpha/scaling + r_key = get_pattern_key(config.rank_pattern.keys(), key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), key) + rank = config.rank_pattern.get(r_key, config.r) + alpha = config.alpha_pattern.get(alpha_key, config.lora_alpha) + if config.use_rslora: + scaling = alpha / math.sqrt(rank) + else: + scaling = alpha / rank + _update_scaling(module, adapter_name=adapter_name, scaling=scaling) + + # swap actual weights + # no need to account for potential _orig_mod in key here, as torch handles that + old_val = attrgetter(key)(model) + new_val = new_val.to(old_val.data.device) + + # 3 options: + # - shapes_match: the new adapter has the same rank as the current tensor (possibly because + # prepare_model_for_compiled_hotswap padded the current tensor to match). + # - new_is_smaller: the new adapter has a smaller rank than the current tensor. This happens either + # when the old adapter had a larger rank, or when the current tensor was padded to a larger + # target_rank. + # - new_is_larger: the new adapter has a larger rank than the current tensor. The parameter shape + # must change, which is only safe when no padded-shape invariant applies (i.e. the model was + # not padded via prepare_model_for_compiled_hotswap). swap_tensors is the only option here. + shapes_match = old_val.shape == new_val.shape + new_is_smaller = (not shapes_match) and all(o >= n for o, n in zip(old_val.shape, new_val.shape)) + new_is_larger = (not shapes_match) and not new_is_smaller + + if shapes_match: + old_val.data.copy_(new_val.data) + elif new_is_smaller: + if old_val.dim() not in (2, 4): + raise NotImplementedError( + f"Trying to hotswap an adapter whose weight has {old_val.dim()} dimensions, but only Conv2d and " + "Linear are supported" + ) + + # Linear or Conv2d: the check for dim 0 or 1 works for both of these layer types + if old_val.shape[0] > new_val.shape[0]: + old_val.data.fill_(0) + old_val.data[: new_val.shape[0]].copy_(new_val.data) + elif old_val.shape[1] > new_val.shape[1]: + old_val.data.fill_(0) + old_val.data[:, : new_val.shape[1]].copy_(new_val.data) + else: + raise ValueError( + f"Incompatible shapes found for LoRA weights {key}: {old_val.shape} vs {new_val.shape}. Please " + "ensure that all ranks are padded to the largest rank among all LoRA adapters by using " + "peft.utils.hotswap.prepare_model_for_compiled_hotswap." + ) + elif new_is_larger: + try: + torch.utils.swap_tensors(old_val, new_val) + except RuntimeError: + # Fallback if swap_tensors is not permitted (e.g. tensor has weakrefs). This still + # rebinds storage and will break inductor if the model is compiled, but growing the + # rank of a compiled-and-padded model is already unsupported; the caller should have + # used prepare_model_for_compiled_hotswap with a sufficient target_rank. + old_val.data = new_val.data + else: + # should be unreachable + raise ValueError( + "Something went wrong during hotswapping, please open an issue on PEFT: " + "https://github.com/huggingface/peft/issues" + ) + + +def check_hotswap_configs_compatible(config0: PeftConfig, config1: PeftConfig) -> None: + """ + Check if two configs are compatible for hot-swapping. + + Only LoRA parameters are checked for now. + + To hot-swap two adapters, their configs must be compatible. Otherwise, the results could be false. E.g. if they use + different alpha values, after hot-swapping, the alphas from the first adapter would still be used with the weights + from the 2nd adapter, which would result in incorrect behavior. There is probably a way to swap these values as + well, but that's not implemented yet, and we need to be careful not to trigger re-compilation if the model is + compiled (so no modification of the dict). + + """ + + if config0.peft_type != config1.peft_type: + msg = f"Incompatible PEFT types found: {config0.peft_type.value} and {config1.peft_type.value}" + raise ValueError(msg) + + if config0.peft_type not in CONFIG_KEYS_TO_CHECK: + msg = ( + f"Hotswapping only supports {', '.join(CONFIG_KEYS_TO_CHECK.keys())} but " + f"{config0.peft_type.value} was passed." + ) + raise ValueError(msg) + config_keys_to_check = CONFIG_KEYS_TO_CHECK[config0.peft_type] + + # TODO: This is a very rough check only for LoRA at the moment. Also, there might be some options that don't + # necessarily require an error. + config0 = config0.to_dict() + config1 = config1.to_dict() + sentinel = object() + for key in config_keys_to_check: + val0 = config0.get(key, sentinel) + val1 = config1.get(key, sentinel) + if val0 != val1: + raise ValueError(f"Configs are incompatible: for {key}, {val0} != {val1}") + + +def hotswap_adapter(model, model_name_or_path, adapter_name, torch_device=None, **kwargs): + """Substitute old adapter data with new adapter data, keeping the rest the same. + + As of now, only LoRA is supported. + + This function is useful when you want to replace the loaded adapter with a new adapter. The adapter name will + remain the same, but the weights and other parameters will be swapped out. + + If the adapters are incomptabile, e.g. targeting different layers or having different alpha values, an error will + be raised. + + Example: + + ```py + >>> import torch + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModel + >>> from peft.utils.hotswap import hotswap_adapter + + >>> model_id = ... + >>> inputs = ... + >>> device = ... + >>> model = AutoModelForCausalLM.from_pretrained(model_id).to(device) + + >>> # load lora 0 + >>> model = PeftModel.from_pretrained(model, "path-adapter-0") + >>> model = torch.compile(model) # optionally compile the model + >>> with torch.inference_mode(): + ... output_adapter_0 = model(inputs) + + >>> # replace the "default" lora adapter with the new one + >>> hotswap_adapter(model, "path-adapter-1", adapter_name="default", torch_device=device) + >>> with torch.inference_mode(): + ... output_adapter_1 = model(inputs).logits + ``` + + Args: + model ([`~PeftModel`]): + The PEFT model with the loaded adapter. + model_name_or_path (`str`): + The name or path of the model to load the new adapter from. + adapter_name (`str`): + The name of the adapter to swap, e.g. `"default"`. The name will stay the same after swapping. + torch_device: (`str`, *optional*, defaults to None): + The device to load the new adapter onto. + **kwargs (`optional`): + Additional keyword arguments used for loading the config and weights. + + """ + if torch_device is None: + torch_device = infer_device() + + ############################ + # LOAD CONFIG AND VALIDATE # + ############################ + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_name_or_path, **hf_kwargs)] + config = config_cls.from_pretrained(model_name_or_path, **kwargs) + # config keys that could affect the model output besides what is determined by the state_dict + check_hotswap_configs_compatible(model.active_peft_config, config) + + state_dict = load_peft_weights(model_name_or_path, device=torch_device, **kwargs) + + ########################### + # LOAD & REMAP STATE_DICT # + ########################### + + parameter_prefix = PEFT_TYPE_TO_PREFIX_MAPPING[config.peft_type] + peft_model_state_dict = _insert_adapter_name_into_state_dict( + state_dict, adapter_name=adapter_name, parameter_prefix=parameter_prefix + ) + + hotswap_adapter_from_state_dict( + model=model, + state_dict=peft_model_state_dict, + adapter_name=adapter_name, + parameter_prefix=parameter_prefix, + config=config, + ) diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/incremental_pca.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/incremental_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..de4a7c05174dc436f4c75965ef9585afb480183c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/incremental_pca.py @@ -0,0 +1,338 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional + +import torch + + +class IncrementalPCA: + """ + An implementation of Incremental Principal Components Analysis (IPCA) that leverages PyTorch for GPU acceleration. + Adapted from https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/decomposition/_incremental_pca.py + + This class provides methods to fit the model on data incrementally in batches, and to transform new data based on + the principal components learned during the fitting process. + + Args: + n_components (int, optional): Number of components to keep. If `None`, it's set to the minimum of the + number of samples and features. Defaults to None. + copy (bool): If False, input data will be overwritten. Defaults to True. + batch_size (int, optional): The number of samples to use for each batch. Only needed if self.fit is called. + If `None`, it's inferred from the data and set to `5 * n_features`. Defaults to None. + svd_driver (str, optional): name of the cuSOLVER method to be used for torch.linalg.svd. This keyword + argument only works on CUDA inputs. Available options are: None, gesvd, gesvdj, and gesvda. Defaults to + None. + lowrank (bool, optional): Whether to use torch.svd_lowrank instead of torch.linalg.svd which can be faster. + Defaults to False. + lowrank_q (int, optional): For an adequate approximation of n_components, this parameter defaults to + n_components * 2. + lowrank_niter (int, optional): Number of subspace iterations to conduct for torch.svd_lowrank. + Defaults to 4. + lowrank_seed (int, optional): Seed for making results of torch.svd_lowrank reproducible. + """ + + def __init__( + self, + n_components: Optional[int] = None, + copy: Optional[bool] = True, + batch_size: Optional[int] = None, + svd_driver: Optional[str] = None, + lowrank: bool = False, + lowrank_q: Optional[int] = None, + lowrank_niter: int = 4, + lowrank_seed: Optional[int] = None, + ): + self.n_components = n_components + self.copy = copy + self.batch_size = batch_size + self.svd_driver = svd_driver + self.lowrank = lowrank + self.lowrank_q = lowrank_q + self.lowrank_niter = lowrank_niter + self.lowrank_seed = lowrank_seed + + self.n_features_ = None + + if self.lowrank: + self._validate_lowrank_params() + + def _validate_lowrank_params(self): + if self.lowrank_q is None: + if self.n_components is None: + raise ValueError("n_components must be specified when using lowrank mode with lowrank_q=None.") + self.lowrank_q = self.n_components * 2 + elif self.lowrank_q < self.n_components: + raise ValueError("lowrank_q must be greater than or equal to n_components.") + + def _svd_fn_full(self, X): + return torch.linalg.svd(X, full_matrices=False, driver=self.svd_driver) + + def _svd_fn_lowrank(self, X): + seed_enabled = self.lowrank_seed is not None + with torch.random.fork_rng(enabled=seed_enabled): + if seed_enabled: + torch.manual_seed(self.lowrank_seed) + U, S, V = torch.svd_lowrank(X, q=self.lowrank_q, niter=self.lowrank_niter) + return U, S, V.mH + + def _validate_data(self, X) -> torch.Tensor: + """ + Validates and converts the input data `X` to the appropriate tensor format. + + Args: + X (torch.Tensor): Input data. + + Returns: + torch.Tensor: Converted to appropriate format. + """ + valid_dtypes = [torch.float32, torch.float64] + + if not isinstance(X, torch.Tensor): + X = torch.tensor(X, dtype=torch.float32) + elif self.copy: + X = X.clone() + + n_samples, n_features = X.shape + if self.n_components is None: + pass + elif self.n_components > n_features: + raise ValueError( + f"n_components={self.n_components} invalid for n_features={n_features}, " + "need more rows than columns for IncrementalPCA processing." + ) + elif self.n_components > n_samples: + raise ValueError( + f"n_components={self.n_components} must be less or equal to the batch number of samples {n_samples}" + ) + + if X.dtype not in valid_dtypes: + X = X.to(torch.float32) + + return X + + @staticmethod + def _incremental_mean_and_var( + X, last_mean, last_variance, last_sample_count + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the incremental mean and variance for the data `X`. + + Args: + X (torch.Tensor): The batch input data tensor with shape (n_samples, n_features). + last_mean (torch.Tensor): The previous mean tensor with shape (n_features,). + last_variance (torch.Tensor): The previous variance tensor with shape (n_features,). + last_sample_count (torch.Tensor): The count tensor of samples processed before the current batch. + + Returns: + Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Updated mean, variance tensors, and total sample count. + """ + if X.shape[0] == 0: + return last_mean, last_variance, last_sample_count + + if last_sample_count > 0: + if last_mean is None: + raise ValueError("last_mean should not be None if last_sample_count > 0.") + if last_variance is None: + raise ValueError("last_variance should not be None if last_sample_count > 0.") + + new_sample_count = torch.tensor([X.shape[0]], device=X.device) + updated_sample_count = last_sample_count + new_sample_count + + if last_mean is None: + last_sum = torch.zeros(X.shape[1], dtype=torch.float64, device=X.device) + else: + last_sum = last_mean * last_sample_count + + new_sum = X.sum(dim=0, dtype=torch.float64) + + updated_mean = (last_sum + new_sum) / updated_sample_count + + T = new_sum / new_sample_count + temp = X - T + correction = temp.sum(dim=0, dtype=torch.float64).square() + temp.square_() + new_unnormalized_variance = temp.sum(dim=0, dtype=torch.float64) + new_unnormalized_variance -= correction / new_sample_count + if last_variance is None: + updated_variance = new_unnormalized_variance / updated_sample_count + else: + last_unnormalized_variance = last_variance * last_sample_count + last_over_new_count = last_sample_count.double() / new_sample_count + updated_unnormalized_variance = ( + last_unnormalized_variance + + new_unnormalized_variance + + last_over_new_count / updated_sample_count * (last_sum / last_over_new_count - new_sum).square() + ) + updated_variance = updated_unnormalized_variance / updated_sample_count + + return updated_mean, updated_variance, updated_sample_count + + @staticmethod + def _svd_flip(u, v, u_based_decision=True) -> tuple[torch.Tensor, torch.Tensor]: + """ + Adjusts the signs of the singular vectors from the SVD decomposition for deterministic output. + + This method ensures that the output remains consistent across different runs. + + Args: + u (torch.Tensor): Left singular vectors tensor. + v (torch.Tensor): Right singular vectors tensor. + u_based_decision (bool, optional): If True, uses the left singular vectors to determine the sign flipping. + Defaults to True. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Adjusted left and right singular vectors tensors. + """ + if u_based_decision: + max_abs_cols = torch.argmax(torch.abs(u), dim=0) + signs = torch.sign(u[max_abs_cols, range(u.shape[1])]) + else: + max_abs_rows = torch.argmax(torch.abs(v), dim=1) + signs = torch.sign(v[range(v.shape[0]), max_abs_rows]) + u *= signs[: u.shape[1]].view(1, -1) + v *= signs.view(-1, 1) + return u, v + + def fit(self, X, check_input=True): + """ + Fits the model with data `X` using minibatches of size `batch_size`. + + Args: + X (torch.Tensor): The input data tensor with shape (n_samples, n_features). + check_input (bool, optional): If True, validates the input. Defaults to True. + + Returns: + IncrementalPCA: The fitted IPCA model. + """ + if check_input: + X = self._validate_data(X) + n_samples, n_features = X.shape + if self.batch_size is None: + self.batch_size = 5 * n_features + + for batch in self.gen_batches(n_samples, self.batch_size, min_batch_size=self.n_components or 0): + self.partial_fit(X[batch], check_input=False) + + return self + + def partial_fit(self, X, check_input=True): + """ + Incrementally fits the model with batch data `X`. + + Args: + X (torch.Tensor): The batch input data tensor with shape (n_samples, n_features). + check_input (bool, optional): If True, validates the input. Defaults to True. + + Returns: + IncrementalPCA: The updated IPCA model after processing the batch. + """ + first_pass = not hasattr(self, "components_") + + if check_input: + X = self._validate_data(X) + n_samples, n_features = X.shape + + # Initialize attributes to avoid errors during the first call to partial_fit + if first_pass: + self.mean_ = None # Will be initialized properly in _incremental_mean_and_var based on data dimensions + self.var_ = None # Will be initialized properly in _incremental_mean_and_var based on data dimensions + self.n_samples_seen_ = torch.tensor([0], device=X.device) + self.n_features_ = n_features + if not self.n_components: + self.n_components = min(n_samples, n_features) + + if n_features != self.n_features_: + raise ValueError( + "Number of features of the new batch does not match the number of features of the first batch." + ) + + col_mean, col_var, n_total_samples = self._incremental_mean_and_var( + X, self.mean_, self.var_, self.n_samples_seen_ + ) + + if first_pass: + X -= col_mean + else: + col_batch_mean = torch.mean(X, dim=0) + X -= col_batch_mean + mean_correction_factor = torch.sqrt((self.n_samples_seen_.double() / n_total_samples) * n_samples) + mean_correction = mean_correction_factor * (self.mean_ - col_batch_mean) + X = torch.vstack( + ( + self.singular_values_.view((-1, 1)) * self.components_, + X, + mean_correction, + ) + ) + + if self.lowrank: + U, S, Vt = self._svd_fn_lowrank(X) + else: + U, S, Vt = self._svd_fn_full(X) + U, Vt = self._svd_flip(U, Vt, u_based_decision=False) + explained_variance = S**2 / (n_total_samples - 1) + explained_variance_ratio = S**2 / torch.sum(col_var * n_total_samples) + + self.n_samples_seen_ = n_total_samples + self.components_ = Vt[: self.n_components] + self.singular_values_ = S[: self.n_components] + self.mean_ = col_mean + self.var_ = col_var + self.explained_variance_ = explained_variance[: self.n_components] + self.explained_variance_ratio_ = explained_variance_ratio[: self.n_components] + if self.n_components not in (n_samples, n_features): + self.noise_variance_ = explained_variance[self.n_components :].mean() + else: + self.noise_variance_ = torch.tensor(0.0, device=X.device) + return self + + def transform(self, X) -> torch.Tensor: + """ + Applies dimensionality reduction to `X`. + + The input data `X` is projected on the first principal components previously extracted from a training set. + + Args: + X (torch.Tensor): New data tensor with shape (n_samples, n_features) to be transformed. + + Returns: + torch.Tensor: Transformed data tensor with shape (n_samples, n_components). + """ + X = X - self.mean_ + return torch.mm(X.double(), self.components_.T).to(X.dtype) + + @staticmethod + def gen_batches(n: int, batch_size: int, min_batch_size: int = 0): + """Generator to create slices containing `batch_size` elements from 0 to `n`. + + The last slice may contain less than `batch_size` elements, when `batch_size` does not divide `n`. + + Args: + n (int): Size of the sequence. + batch_size (int): Number of elements in each batch. + min_batch_size (int, optional): Minimum number of elements in each batch. Defaults to 0. + + Yields: + slice: A slice of `batch_size` elements. + """ + start = 0 + for _ in range(int(n // batch_size)): + end = start + batch_size + if end + min_batch_size > n: + continue + yield slice(start, end) + start = end + if start < n: + yield slice(start, n) diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/integrations.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..f4cd59528bbac425cddc40c3e8a5d7d8185cc6ae --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/integrations.py @@ -0,0 +1,295 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import functools +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Literal, Optional + +import packaging.version +import torch +import transformers +from torch import nn + + +@dataclass +class TpInfo: + tp_plan: dict[str, str] + device_mesh: torch.distributed.DeviceMesh + tp_size: int + + +def check_deepspeed_zero3_enabled() -> bool: + if packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.33.0"): + from transformers.integrations import is_deepspeed_zero3_enabled + else: + from transformers.deepspeed import is_deepspeed_zero3_enabled + return is_deepspeed_zero3_enabled() + + +@contextmanager +def gather_params_ctx(param, modifier_rank: Optional[int] = 0, fwd_module: torch.nn.Module = None): + """Call DeepSpeed GatheredParameters context manager if DeepSpeed is enabled, otherwise do nothing.""" + + if not check_deepspeed_zero3_enabled(): + yield + return + + import deepspeed + + with deepspeed.zero.GatheredParameters(param, modifier_rank=modifier_rank, fwd_module=fwd_module): + yield + return + + +def dequantize_module_weight(module: torch.nn.Module) -> torch.nn.Parameter: + """ + Helper function to dequantize a quantized weight. + + This function should be extended if more quantization schemes are added to the library. + + If the weight is not quantized, it will be returned as is. + """ + if hasattr(module, "W_q"): # For handling HQQ quantized weight + weight = module.dequantize() + return weight + elif type(module.weight).__module__.startswith("torchao."): + # check for torchao without requiring any torchao imports + weight = module.weight.dequantize() + return weight + + weight = module.weight + if not isinstance(weight, torch.nn.Parameter): + if isinstance(weight, torch.Tensor): + # this is an FSDP-specific edge case + return weight # type: ignore + raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead") + + cls_name = weight.__class__.__name__ + if cls_name not in ("Params4bit", "Int8Params"): + return weight + + quant_state = getattr(module, "state", None) + device = weight.device + is_cpu = device.type == torch.device("cpu").type + weight = dequantize_bnb_weight(weight, state=quant_state) # no-op if not bnb + if is_cpu: + # dequantize_bnb_weight for 8bit moves the device in-place, thus we need to move it back to CPU if necessary + module.weight = module.weight.to(device) + return weight + + +def dequantize_bnb_weight(weight: torch.nn.Parameter, state=None): + """Helper function to dequantize 4bit or 8bit bnb weights.""" + import bitsandbytes as bnb + + device = weight.device + + cls_name = weight.__class__.__name__ + if cls_name == "Params4bit": + dequantized = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + return dequantized + + # 8bit case + if state is None: + raise ValueError( + "No `state` was passed for bnb 8bit quantized weights. Please open an issue on the PEFT repository and " + "report the error: https://github.com/huggingface/peft/issues" + ) + + if state.SCB is None: + state.SCB = weight.SCB + + if hasattr(bnb.functional, "int8_vectorwise_dequant"): + # Use bitsandbytes API if available (requires v0.45.0+) + dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB) + else: + # Multiply by (scale/127) to dequantize. + dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3 + + return dequantized + + +def get_bnb_param_type(param: torch.nn.Parameter) -> Literal[False, "4bit", "8bit"]: + """Returns '4bit' or '8bit' if bitsandbytes parameter, else False""" + if param.__class__.__name__ == "Params4bit": + return "4bit" + if param.__class__.__name__ == "Int8Params": + return "8bit" + return False + + +# adapted from: +# https://github.com/huggingface/transformers/blob/eab6c491d439e83d5e31c660df6f7e36592eb0a2/src/transformers/generation/utils.py#L1617-L1643 +def get_layer_device_map(model): + """ + Derive the device map for the layers of the model. + """ + main_device = next(d for d in model.hf_device_map.values() if d not in ["cpu", "disk"]) + + execution_device_map = { + name: main_device if device in ["cpu", "disk"] else device for name, device in model.hf_device_map.items() + } + + if execution_device_map is None: + return None + + if len(execution_device_map) == 1 and "" in execution_device_map: + return {idx: execution_device_map[""] for idx in range(model.config.num_hidden_layers)} + + layer_device_map = {} + for layer in execution_device_map: + for idx in range(model.config.num_hidden_layers): + if f".{idx}." in f"{layer}.": + layer_device_map[idx] = execution_device_map[layer] + break + for idx in range(model.config.num_hidden_layers): + if idx not in layer_device_map: + raise RuntimeError(f"layer {idx} has not been mapped to a device.") + return layer_device_map + + +# adapted from: +# https://github.com/huggingface/transformers/blob/eab6c491d439e83d5e31c660df6f7e36592eb0a2/src/transformers/cache_utils.py#L1159-L1179 +def map_cache_to_layer_device_map(model, cache) -> None: + """ + Ensure that the key and value cache of the model are on the same device as their corresponding layers. + """ + if not (isinstance(cache, transformers.Cache) and hasattr(model, "hf_device_map")): + return + + if isinstance(cache, transformers.EncoderDecoderCache): + map_cache_to_layer_device_map(model, cache.self_attention_cache) + return + + layer_device_map = get_layer_device_map(model) + for idx in range(model.config.num_hidden_layers): + layer_device = layer_device_map[idx] + if hasattr(cache, "layers"): + # new transformers uses cache.layers (>v4.55) + layer = cache.layers[idx] + layer.keys = layer.keys.to(layer_device) + layer.values = layer.values.to(layer_device) + else: + # old transformers uses cache.{key,value}_cache (<=v4.55) + # TODO: remove if we drop support for transformers <= 4.55 + cache.key_cache[idx] = cache.key_cache[idx].to(layer_device) + cache.value_cache[idx] = cache.value_cache[idx].to(layer_device) + + +################################## +# START: ADAPTED FROM ACCELERATE # +################################## +# +# Modified to support explicitly skipping layer initialization for faster switching between layer states +# (necessary for supporting `nn.MultiHeadAttention` adapters) + + +@contextmanager +def init_empty_weights(include_buffers: bool | None = None): + # adapted from accelerate.big_modeling.py + with _init_on_device(torch.device("meta"), include_buffers=include_buffers) as f: + yield f + + +@contextmanager +def _init_on_device(device: torch.device, include_buffers: bool | None = None): + # adapted from accelerate.big_modeling.py + old_register_parameter = nn.Module.register_parameter + old_register_buffer = nn.Module.register_buffer + + def register_empty_parameter(module, name, param): + # This works because torch first initializes the parameters with torch.empty, thus not assigning any new memory. + # Then the parameter is moved to meta device before reset_parameters() is called, which then operates on the + # meta device, making any subsequent calls to initialization methods no-ops. + old_register_parameter(module, name, param) + if (param is not None) and (getattr(_init_on_device, "_skip", False) is not True): + param_cls = type(module._parameters[name]) + kwargs = module._parameters[name].__dict__ + kwargs["requires_grad"] = param.requires_grad + module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs) + + def register_empty_buffer(module, name, buffer, persistent=True): + old_register_buffer(module, name, buffer, persistent=persistent) + if buffer is not None: + module._buffers[name] = module._buffers[name].to(device) + + # Patch tensor creation + if include_buffers: + tensor_constructors_to_patch = { + torch_function_name: getattr(torch, torch_function_name) + for torch_function_name in ["empty", "zeros", "ones", "full"] + } + else: + tensor_constructors_to_patch = {} + + def patch_tensor_constructor(fn): + def wrapper(*args, **kwargs): + kwargs["device"] = device + return fn(*args, **kwargs) + + return wrapper + + try: + nn.Module.register_parameter = register_empty_parameter + if include_buffers: + nn.Module.register_buffer = register_empty_buffer + for torch_function_name in tensor_constructors_to_patch.keys(): + setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) + yield + finally: + nn.Module.register_parameter = old_register_parameter + if include_buffers: + nn.Module.register_buffer = old_register_buffer + for torch_function_name, old_torch_function in tensor_constructors_to_patch.items(): + setattr(torch, torch_function_name, old_torch_function) + + +@contextmanager +def _skip_init_on_device(): + # context manager to skip the _init_on_device context manager + old_val = getattr(_init_on_device, "_skip", False) + try: + _init_on_device._skip = True + yield + finally: + _init_on_device._skip = old_val + + +def skip_init_on_device(func): + """ + Ignore the init_on_device context manager when calling the decorated function. + + This is a narrow use decorator that allows us to avoid initializing on meta device even when we're inside the + init_empty_weights context. + + """ + + # The need for this functionality arose when working on MultiheadAttention, where we have to call _restore_weights + # repeatedly as parametes are overwritten and need to be re-registered. When using low_cpu_mem_usage=True, as + # register_parameter is patched inside of the init_empty_weights context, this would result in those parameters + # suddenly being moved to meta device. Using this decorator allows us to avoid this. + @functools.wraps(func) + def wrapper(*args, **kwargs): + with _skip_init_on_device(): + return func(*args, **kwargs) + + return wrapper + + +####### +# END # +####### diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/loftq_utils.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/loftq_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ea69b73368a304eed3130a6e292bdd4f0c88325b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/loftq_utils.py @@ -0,0 +1,427 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Reference code: https://github.com/yxli2123/LoftQ/blob/main/utils.py +# Reference paper: https://huggingface.co/papers/2310.08659 + +from __future__ import annotations + +import os +import warnings +from collections.abc import Callable +from typing import Optional, Union + +import torch +from accelerate.utils.memory import clear_device_cache +from huggingface_hub import snapshot_download +from huggingface_hub.errors import HFValidationError, LocalEntryNotFoundError +from safetensors import SafetensorError, safe_open +from transformers.utils import cached_file +from transformers.utils.hub import get_checkpoint_shard_files + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_xpu_available + + +# TODO for PEFT 0.20, remove NFQuantizer in favor of bnb 4bit quantization. +class NFQuantizer: + def __init__(self, num_bits=2, device="cuda", method="normal", block_size=64, *args, **kwargs): + super().__init__(*args, **kwargs) + + warnings.warn( + "NFQuantizer is deprecated and is going to be removed in PEFT 0.20. Consider using " + "alternative quantization libraries for nf{2,4,8} quantization.", + category=DeprecationWarning, + ) + + self.num_bits = num_bits + self.device = device + self.method = method + self.block_size = block_size + if self.method == "normal": + self.norm_lookup_table = self.create_normal_map(num_bits=self.num_bits) + self.norm_lookup_table = self.norm_lookup_table.to(device) + elif self.method == "uniform": + self.norm_lookup_table = self.create_uniform_map(num_bits=self.num_bits) + self.norm_lookup_table = self.norm_lookup_table.to(device) + else: + raise NotImplementedError("Other quantization methods not supported yet.") + + @staticmethod + def create_uniform_map(symmetric=False, num_bits=4): + if symmetric: + # print("symmetric uniform quantization") + negative = torch.linspace(-1, 0, 2 ** (num_bits - 1)) + positive = torch.linspace(0, 1, 2 ** (num_bits - 1)) + table = torch.cat([negative, positive[1:]]) + else: + # print("asymmetric uniform quantization") + table = torch.linspace(-1, 1, 2**num_bits) + return table + + @staticmethod + def create_normal_map(offset=0.9677083, symmetric=False, num_bits=2): + try: + from scipy.stats import norm + except ImportError: + raise ImportError("The required package 'scipy' is not installed. Please install it to continue.") + + variations = 2**num_bits + if symmetric: + v = norm.ppf(torch.linspace(1 - offset, offset, variations + 1)).tolist() + values = [] + for index in range(len(v) - 1): + values.append(0.5 * v[index] + 0.5 * v[index + 1]) + v = values + else: + # one more positive value, this is an asymmetric type + v1 = norm.ppf(torch.linspace(offset, 0.5, variations // 2 + 1)[:-1]).tolist() + v2 = [0] + v3 = (-norm.ppf(torch.linspace(offset, 0.5, variations // 2)[:-1])).tolist() + v = v1 + v2 + v3 + + values = torch.Tensor(v) + values = values.sort().values + values /= values.max() + return values + + def quantize_tensor(self, weight): + max_abs = torch.abs(weight).max() + weight_normed = weight / max_abs + + weight_normed_expanded = weight_normed.unsqueeze(-1) + + # Reshape L to have the same number of dimensions as X_expanded + L_reshaped = torch.tensor(self.norm_lookup_table).reshape(1, -1) + + # Calculate the absolute difference between X_expanded and L_reshaped + abs_diff = torch.abs(weight_normed_expanded - L_reshaped) + + # Find the index of the minimum absolute difference for each element + qweight = torch.argmin(abs_diff, dim=-1) + return qweight, max_abs + + def dequantize_tensor(self, qweight, max_abs): + qweight_flatten = qweight.flatten() + + weight_normed = self.norm_lookup_table[qweight_flatten] + weight = weight_normed * max_abs + + weight = weight.reshape(qweight.shape) + + return weight + + def quantize_block(self, weight): + if len(weight.shape) != 2: + raise ValueError(f"Only support 2D matrix, but your input has {len(weight.shape)} dimensions.") + if weight.shape[0] * weight.shape[1] % self.block_size != 0: + raise ValueError( + f"Weight with shape ({weight.shape[0]} x {weight.shape[1]}) " + f"is not dividable by block size {self.block_size}." + ) + + M, N = weight.shape + device = weight.device + + # Quantization + weight_flatten = weight.flatten() # (M*N, ) + weight_block = weight_flatten.reshape(-1, self.block_size) # (L, B), L = M * N / B + if self.method == "normal": + weight_max = weight_block.abs().max(dim=-1)[0] # (L, 1) + elif self.method == "uniform": + weight_max = weight_block.mean(dim=-1) + 2.5 * weight_block.std(dim=-1) + else: + raise NotImplementedError("Method not supported yet.") + weight_max = weight_max.unsqueeze(-1) + weight_divabs = weight_block / weight_max # (L, B) + weight_divabs = weight_divabs.unsqueeze(-1) # (L, B, 1) + L_reshaped = self.norm_lookup_table.reshape(1, -1) # (1, 2**K) + + abs_diff = torch.abs(weight_divabs - L_reshaped) # (L, B, 2**K) + qweight = torch.argmin(abs_diff, dim=-1) # (L, B) + + # Pack multiple k-bit into uint8 + qweight = qweight.reshape(-1, 8 // self.num_bits) + qweight_pack = torch.zeros((M * N // 8 * self.num_bits, 1), dtype=torch.uint8, device=device) + + # data format example: + # [1, 0, 3, 2] or [01, 00, 11, 10] -> [10110001], LIFO + for i in range(8 // self.num_bits): + qweight[:, i] = qweight[:, i] << i * self.num_bits + qweight_pack[:, 0] |= qweight[:, i] + + return qweight_pack, weight_max, weight.shape + + def dequantize_block(self, qweight, weight_max, weight_shape): + # unpack weight + device = qweight.device + weight = torch.zeros((qweight.shape[0], 8 // self.num_bits), dtype=torch.float32, device=device) + for i in range(8 // self.num_bits): + lookup_table_idx = qweight.to(torch.long) % 2**self.num_bits # get the most right 2 bits + lookup_table_idx = lookup_table_idx.to(torch.long) + weight[:, i] = self.norm_lookup_table[lookup_table_idx].squeeze() + qweight = qweight >> self.num_bits # right shift 2 bits of the original data + + weight_block = weight.reshape(-1, self.block_size) + weight = weight_block * weight_max + weight = weight.reshape(weight_shape) + + return weight + + +def _low_rank_decomposition(weight, reduced_rank=32): + """ + :param weight: The matrix to decompose, of shape (H, W) :param reduced_rank: the final rank :return: + """ + matrix_dimension = len(weight.size()) + if matrix_dimension != 2: + raise ValueError(f"Only support 2D matrix, but your input has {matrix_dimension} dimensions.") + + # Use SVD to decompose a matrix, default full_matrices is False to save parameters + U, S, Vh = torch.linalg.svd(weight, full_matrices=False) + + L = U @ (torch.sqrt(torch.diag(S)[:, 0:reduced_rank])) + R = torch.sqrt(torch.diag(S)[0:reduced_rank, :]) @ Vh + + return {"L": L, "R": R, "U": U, "S": S, "Vh": Vh, "reduced_rank": reduced_rank} + + +@torch.no_grad() +def loftq_init(weight: Union[torch.Tensor, torch.nn.Parameter], num_bits: int, reduced_rank: int, num_iter=1): + if is_bnb_available(): + import bitsandbytes as bnb + else: + raise ValueError("bitsandbytes is not available, please install it to use LoftQ.") + + if num_bits not in [4, 8]: + raise ValueError("Only nf4 and int8 quantization is supported") + if num_iter <= 0: + raise ValueError("Number of iterations must be greater than 0") + + device = weight.device + dtype = weight.dtype + if not is_bnb_4bit_available() and num_bits == 4: + # TODO for PEFT 0.20 remove NFQuantizer invocation and throw an exception + quantizer = NFQuantizer(num_bits=num_bits, device=device, method="normal", block_size=64) + compute_device = device + warnings.warn( + "Native support for nf4 is being deprecated with PEFT 0.20. Please install a recent version of bitsandbytes.", + category=DeprecationWarning, + ) + else: + compute_device = "xpu" if is_xpu_available() else "cuda" + + weight = weight.to(device=compute_device, dtype=torch.float32) + res = weight.clone() + for i in range(num_iter): + clear_device_cache() + # Quantization + if num_bits == 4 and is_bnb_4bit_available(): + qweight = bnb.nn.Params4bit( + res.to("cpu"), requires_grad=False, compress_statistics=False, quant_type="nf4" + ).to(compute_device) + dequantized_weight = bnb.functional.dequantize_4bit(qweight.data, qweight.quant_state) + elif num_bits == 4: + quantized_weight, max_abs, shape = quantizer.quantize_block(res) + dequantized_weight = quantizer.dequantize_block(quantized_weight, max_abs, shape) + elif num_bits == 8: + qweight = bnb.nn.Int8Params(res.to("cpu"), requires_grad=False).to(device) + dequantized_weight = bnb.functional.int8_vectorwise_dequant(qweight.data, qweight.SCB).to(compute_device) + + res = weight - dequantized_weight + + # Decompose the residual by SVD + output = _low_rank_decomposition(res, reduced_rank=reduced_rank) + L, R, reduced_rank = output["L"], output["R"], output["reduced_rank"] + + # don't prepare the residual if we're at the end + if i + 1 == num_iter: + break + + res = weight - torch.mm(L, R) + + lora_A, lora_B = R, L + + return dequantized_weight.to(device=device, dtype=dtype), lora_A, lora_B + + +@torch.no_grad() +def _loftq_init_new(qweight, weight, num_bits: int, reduced_rank: int): + import bitsandbytes as bnb + + if num_bits != 4: + raise ValueError("Only 4 bit quantization supported at the moment.") + if not is_bnb_4bit_available(): + raise ValueError("bitsandbytes 4bit quantization is not available.") + + compute_device = "xpu" if is_xpu_available() else "cuda" + dequantized_weight = bnb.functional.dequantize_4bit(qweight.data, qweight.quant_state) + + weight = weight.to(device=compute_device, dtype=torch.float32) + residual = weight - dequantized_weight + clear_device_cache() + # Decompose the residualidual by SVD + output = _low_rank_decomposition(residual, reduced_rank=reduced_rank) + L, R, reduced_rank = output["L"], output["R"], output["reduced_rank"] + return R, L + + +class _SafetensorLoader: + """ + Simple utility class that loads tensors with safetensors from a single file or sharded files. + + Takes care of file name normalization etc. + + """ + + def __init__(self, peft_model, model_path): + if model_path is None: + try: + model_path = snapshot_download(peft_model.base_model.config._name_or_path, local_files_only=True) + except (AttributeError, HFValidationError) as exc: + raise ValueError( + "The provided model does not appear to be a transformers model or is a local model. In this case, " + "you must pass the model_path argument that points to the safetensors file." + ) from exc + except LocalEntryNotFoundError as exc: + raise ValueError( + "The model.safetensors file must be present on disk, but it could not be found." + ) from exc + + suffix = "model.safetensors" + if not model_path.endswith(suffix): + model_path = os.path.join(model_path, suffix) + + self.model_path = model_path + self.base_model_prefix = getattr(peft_model.get_base_model(), "base_model_prefix", None) + self.prefix = "base_model.model." + self.is_sharded = False + self.weight_map = None + + if not os.path.exists(model_path): + # check if the file is sharded + par_dir = model_path.rpartition(os.path.sep)[0] + try: + resolved_archive_file, sharded_metadata = get_checkpoint_shard_files( + par_dir, cached_file(par_dir, "model.safetensors.index.json") + ) + except OSError as exc: + raise FileNotFoundError( + f"Could not find file for {model_path}, ensure that there is a (sharded) safetensors file of the model." + ) from exc + + self.is_sharded = True + # maps from 'model-X-of-Y.safetensors' to full file path + file_map = {k.rpartition(os.path.sep)[-1]: k for k in resolved_archive_file} + self.weight_map = {k: file_map[v] for k, v in sharded_metadata["weight_map"].items()} + + def get_tensor(self, name): + if not self.is_sharded: + file_path = self.model_path + else: + file_path = self.weight_map[name] + + with safe_open(file_path, framework="pt", device="cpu") as f: + try: + tensor = f.get_tensor(name) + except SafetensorError as exc: + # no matching key found, we probably need to remove the base model prefix + if self.base_model_prefix: + # remove 1 extra character for "." + name = name[len(self.base_model_prefix) + 1 :] + tensor = f.get_tensor(name) + else: + raise + return tensor + + +@torch.no_grad() +def replace_lora_weights_loftq( + peft_model, + model_path: Optional[str] = None, + adapter_name: str = "default", + callback: Optional[Callable[[torch.nn.Module, str], bool]] = None, +): + """ + Replace the LoRA weights of a model quantized with bitsandbytes, using the LoftQ technique. + + The replacement is done on the fly by loading in the non-quantized weights from a locally stored safetensors model + file and initializing the LoRA weights such that the quantization error between the original and quantized weights + is minimized. + + As lazy loading is not possible with pickle, normal PyTorch checkpoint files cannot be supported. + + Depending on the model size, calling this function may take some time to finish. + + Args: + peft_model (`PeftModel`): + The model to replace the weights of. Must be a quantized PEFT model with LoRA layers. + model_path (`Optional[str]`): + The path to the model safetensors file. If the model is a Hugging Face model, this will be inferred from + the model's config. Otherwise, it must be provided. + adapter_name (`str`): + The name of the adapter to replace the weights of. The default adapter name is "default". + callback (`Optional[Callable[[PeftModel, str], bool]]`): + A callback function that will be called after each module is replaced. The callback function should take + the model and the name of the current module as input and return a boolean indicating whether the + replacement should be kept. If the callback returns False, the replacement will be rolled back. This can be + very useful to confirm that the LoftQ initialization actually decreases the quantization error of the + model. As an example, this callback could generate logits for given input and compare it with the logits + from the original, non-quanitzed model with the same input, and only return `True` if there is an + improvement. As this is a greedy optimization, it's possible that calling this function multiple times + yields incremental improvements. + """ + if not is_bnb_4bit_available(): + raise ValueError("bitsandbytes must be installed and the model must be quantized in 4bits.") + + from peft.tuners.lora import Linear4bit + + # model_path = _check_model_path_loftq(model_path, peft_model) + prefix = "base_model.model." + any_match = False + safetensor_loader = _SafetensorLoader(peft_model, model_path) + + # if too slow, consider adding tqdm as an option + for name, module in peft_model.named_modules(): + if not isinstance(module, Linear4bit): + continue + + if not name.startswith(prefix): + raise TypeError("The passed model does not appear to be a valid PeftModel") + + any_match = True + name = name[len(prefix) :] + tensor = safetensor_loader.get_tensor(name + ".weight") + + reduced_rank = module.r[adapter_name] + lora_A, lora_B = _loftq_init_new(module.weight, tensor, num_bits=4, reduced_rank=reduced_rank) + if not callback: + module.lora_A[adapter_name].weight.data = lora_A + module.lora_B[adapter_name].weight.data = lora_B + continue + + lora_A_before = module.lora_A[adapter_name].weight.data + lora_B_before = module.lora_B[adapter_name].weight.data + + module.lora_A[adapter_name].weight.data = lora_A + module.lora_B[adapter_name].weight.data = lora_B + should_replace = callback(peft_model, name) + if not should_replace: + # roll back + module.lora_A[adapter_name].weight.data = lora_A_before + module.lora_B[adapter_name].weight.data = lora_B_before + + del lora_A_before, lora_B_before + + if not any_match: + raise ValueError("No bnb LoRA module found on the model") diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/merge_utils.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/merge_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..27e3f7e7b1ee04e157a9817a06624f345e619170 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/merge_utils.py @@ -0,0 +1,268 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Literal + +import torch + + +def reshape_weight_task_tensors(task_tensors: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + """ + Reshapes `weights` to match the shape of `task_tensors` by unsqeezing in the remaining dimenions. + + Args: + task_tensors (`torch.Tensor`): The tensors that will be used to reshape `weights`. + weights (`torch.Tensor`): The tensor to be reshaped. + + Returns: + `torch.Tensor`: The reshaped tensor. + """ + new_shape = weights.shape + (1,) * (task_tensors.dim() - weights.dim()) + weights = weights.view(new_shape) + return weights + + +def magnitude_based_pruning(tensor: torch.Tensor, density: float) -> torch.Tensor: + """ + Prune the smallest values of the task tensors and retain the top-k values based on the specified fraction + `density`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The tensor with the pruned weights. + """ + mask = torch.zeros_like(tensor).reshape(-1) + k = int(density * tensor.numel()) + top_k = torch.topk(tensor.abs().reshape(-1), k=k, largest=True) + mask[top_k[1]] = 1 + return tensor * mask.reshape(tensor.shape) + + +def random_pruning(tensor: torch.Tensor, density: float, rescale: bool) -> torch.Tensor: + """ + Prune random values based on the specified fraction `density`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. + + Returns: + `torch.Tensor`: The pruned tensor. + """ + mask = torch.bernoulli(torch.full_like(input=tensor, fill_value=density)) + pruned_tensor = tensor * mask + if rescale: + pruned_tensor = pruned_tensor / density + return pruned_tensor + + +def prune( + tensor: torch.Tensor, density: float, method: Literal["magnitude", "random"], rescale: bool = False +) -> torch.Tensor: + """ + Prune the values of task tensors based on the `method`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + method (`str`):The method to use to prune. Should be one of ["magnitude", "random"]. + rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. + + Returns: + `torch.Tensor`: The pruned tensor. + """ + if density >= 1: + warnings.warn(f"The density {density} is greater than or equal to 1, no pruning will be performed.") + return tensor + elif density < 0: + raise ValueError(f"Density should be >= 0, got {density}") + if method == "magnitude": + return magnitude_based_pruning(tensor, density) + elif method == "random": + return random_pruning(tensor, density, rescale=rescale) + else: + raise ValueError(f"Unknown method {method}") + + +def calculate_majority_sign_mask( + tensor: torch.Tensor, method: Literal["total", "frequency"] = "total" +) -> torch.Tensor: + """ + Get the mask of the majority sign across the task tensors. Task tensors are stacked on dimension 0. + + Args: + tensor (`torch.Tensor`):The tensor to get the mask from. + method (`str`):The method to use to get the mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The majority sign mask. + """ + + sign = tensor.sign() + if method == "total": + sign_magnitude = tensor.sum(dim=0) + elif method == "frequency": + sign_magnitude = sign.sum(dim=0) + else: + raise RuntimeError(f'Unimplemented mask method "{method}"') + majority_sign = torch.where(sign_magnitude >= 0, 1, -1) + return sign == majority_sign + + +def disjoint_merge(task_tensors: torch.Tensor, majority_sign_mask: torch.Tensor) -> torch.Tensor: + """ + Merge the task tensors using disjoint merge. + + Args: + task_tensors (`torch.Tensor`):The task tensors to merge. + majority_sign_mask (`torch.Tensor`):The mask of the majority sign across the task tensors. + + Returns: + `torch.Tensor`: The merged tensor. + """ + mixed_task_tensors = (task_tensors * majority_sign_mask).sum(dim=0) + num_params_preserved = majority_sign_mask.sum(dim=0) + return mixed_task_tensors / torch.clamp(num_params_preserved, min=1.0) + + +def task_arithmetic(task_tensors: list[torch.Tensor], weights: torch.Tensor) -> torch.Tensor: + """ + Merge the task tensors using `task arithmetic`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + + Returns: + `torch.Tensor`: The merged tensor. + """ + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def magnitude_prune(task_tensors: list[torch.Tensor], weights: torch.Tensor, density: float) -> torch.Tensor: + """ + Merge the task tensors using `task arithmetic`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`): The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="magnitude") for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def ties( + task_tensors: list[torch.Tensor], + weights: torch.Tensor, + density: float, + majority_sign_method: Literal["total", "frequency"] = "total", +) -> torch.Tensor: + """ + Merge the task tensors using `ties`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + majority_sign_method (`str`): + The method to use to get the majority sign mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="magnitude") for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # Elect Sign + majority_sign_mask = calculate_majority_sign_mask(task_tensors, method=majority_sign_method) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + # Disjoint Merge + mixed_task_tensors = disjoint_merge(weighted_task_tensors, majority_sign_mask) + return mixed_task_tensors + + +def dare_linear(task_tensors: list[torch.Tensor], weights: torch.Tensor, density: float) -> torch.Tensor: + """ + Merge the task tensors using `dare linear`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="random", rescale=True) for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def dare_ties( + task_tensors: list[torch.Tensor], + weights: torch.Tensor, + density: float, + majority_sign_method: Literal["total", "frequency"] = "total", +) -> torch.Tensor: + """ + Merge the task tensors using `dare ties`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + majority_sign_method (`str`): + The method to use to get the majority sign mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="random", rescale=True) for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # Elect Sign + majority_sign_mask = calculate_majority_sign_mask(task_tensors, method=majority_sign_method) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + # Disjoint Merge + mixed_task_tensors = disjoint_merge(weighted_task_tensors, majority_sign_mask) + return mixed_task_tensors diff --git a/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/other.py b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/other.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc720c4a5b429f3ec7c1786d4fcafa67463c03c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/tests/source/src/peft/utils/other.py @@ -0,0 +1,1767 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import functools +import inspect +import os +import re +import warnings +from collections.abc import Sequence +from contextlib import nullcontext +from operator import attrgetter +from typing import Any, Optional, Union + +import accelerate +import torch +import transformers +from accelerate import FullyShardedDataParallelPlugin +from accelerate.hooks import add_hook_to_module, remove_hook_from_module +from accelerate.utils import is_npu_available, is_xpu_available +from huggingface_hub import file_exists +from huggingface_hub.errors import EntryNotFoundError, HFValidationError +from packaging import version +from safetensors.torch import storage_ptr, storage_size +from transformers import PreTrainedModel + +from ..import_utils import is_gptqmodel_available, is_torch_tpu_available, is_transformers_ge_v5_1_0 +from .constants import ( + CONFIG_NAME, + EMBEDDING_LAYER_NAMES, + INCLUDE_LINEAR_LAYERS_SHORTHAND, + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, + WEIGHTS_NAME, + bloom_model_postprocess_past_key_value, + starcoder_model_postprocess_past_key_value, +) + + +mlu_available = False +if version.parse(accelerate.__version__) >= version.parse("0.29.0"): + from accelerate.utils import is_mlu_available + + mlu_available = is_mlu_available() + +__all__ = [ + "CONFIG_NAME", + "EMBEDDING_LAYER_NAMES", + "INCLUDE_LINEAR_LAYERS_SHORTHAND", + "SAFETENSORS_WEIGHTS_NAME", + "TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING", + "WEIGHTS_NAME", + "bloom_model_postprocess_past_key_value", + "starcoder_model_postprocess_past_key_value", +] + + +# Get current device name based on available devices +def infer_device() -> str: + if torch.cuda.is_available(): + return "cuda" + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + return "mps" + elif mlu_available: + return "mlu" + elif is_xpu_available(): + return "xpu" + elif is_npu_available(): + return "npu" + return "cpu" + + +def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None): + r""" + Note this method only works for `transformers` models. + + This method wraps the entire protocol for preparing a model before running a training. This includes: + 1- Cast the layernorm in fp32 2- making output embedding layer require grads 3- Add the upcasting of the lm + head to fp32 4- Freezing the base model layers to ensure they are not updated during training + + + Args: + model (`transformers.PreTrainedModel`): + The loaded model from `transformers` + use_gradient_checkpointing (`bool`, *optional*, defaults to `True`): + If True, use gradient checkpointing to save memory at the expense of slower backward pass. + gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`): + Keyword arguments to pass to the gradient checkpointing function, please refer to the documentation of + `torch.utils.checkpoint.checkpoint` for more details about the arguments that you can pass to that method. + Note this is only available in the latest transformers versions (> 4.34.1). + """ + loaded_in_kbit = getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False) + is_gptq_quantized = getattr(model, "quantization_method", None) == "gptq" + is_aqlm_quantized = getattr(model, "quantization_method", None) == "aqlm" + is_eetq_quantized = getattr(model, "quantization_method", None) == "eetq" + is_torchao_quantized = getattr(model, "quantization_method", None) == "torchao" + is_hqq_quantized = getattr(model, "quantization_method", None) == "hqq" or getattr(model, "hqq_quantized", False) + + if gradient_checkpointing_kwargs is None: + gradient_checkpointing_kwargs = {} + + for name, param in model.named_parameters(): + # freeze base model's layers + param.requires_grad = False + + if ( + not is_gptq_quantized + and not is_aqlm_quantized + and not is_eetq_quantized + and not is_hqq_quantized + and not is_torchao_quantized + ): + # cast all non INT8 parameters to fp32 + for param in model.parameters(): + if ( + (param.dtype == torch.float16) or (param.dtype == torch.bfloat16) + ) and param.__class__.__name__ != "Params4bit": + param.data = param.data.to(torch.float32) + + if ( + loaded_in_kbit + or is_gptq_quantized + or is_aqlm_quantized + or is_eetq_quantized + or is_hqq_quantized + or is_torchao_quantized + ) and use_gradient_checkpointing: + # When having `use_reentrant=False` + gradient_checkpointing, there is no need for this hack + if "use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]: + # For backward compatibility + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # To support older transformers versions, check if the model supports gradient_checkpointing_kwargs + _supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( + inspect.signature(model.gradient_checkpointing_enable).parameters + ) + + if not _supports_gc_kwargs and len(gradient_checkpointing_kwargs) > 0: + warnings.warn( + "gradient_checkpointing_kwargs is not supported in this version of transformers. The passed kwargs will be ignored." + " if you want to use that feature, please upgrade to the latest version of transformers.", + FutureWarning, + ) + + gc_enable_kwargs = ( + {} if not _supports_gc_kwargs else {"gradient_checkpointing_kwargs": gradient_checkpointing_kwargs} + ) + + # enable gradient checkpointing for memory efficiency + model.gradient_checkpointing_enable(**gc_enable_kwargs) + return model + + +# copied from transformers.models.bart.modeling_bart +def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int) -> torch.Tensor: + """ + Shift input ids one token to the right. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): input ids + pad_token_id (`int`): The id of the `padding` token. + decoder_start_token_id (`int`): The id of the `start` token. + """ + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() + shifted_input_ids[:, 0] = decoder_start_token_id + + if pad_token_id is None: + raise ValueError("self.model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) + + return shifted_input_ids + + +def _set_layer_requires_grad(layer, requires_grad: bool) -> None: + """Set requires_grad on all leaf parameters of a layer. + + This handles the FSDP case where params may be non-leaf tensors (wrapped in DTensors). Only leaf tensors can have + their requires_grad flag toggled, so non-leaf tensors are silently skipped + + Args: + layer: A module, parameter or tensor + requires_grad: enable or disable gradients + """ + if isinstance(layer, (torch.nn.Parameter, torch.Tensor)): + if layer.is_leaf: + layer.requires_grad_(requires_grad) + else: + for param in layer.parameters(): + if param.is_leaf: + param.requires_grad_(requires_grad) + + +class AuxiliaryTrainingWrapper(torch.nn.Module): + """Wrap a specific module so that it can be trained and saved in a way that is tangential to how + PEFT normally works, e.g. fully training a classification layer instead of using an adapter. + + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = () + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = () + # List all merged adapters + merged_adapters: list[str] = [] + + def __init__(self, module_to_save, adapter_name, **kwargs): + """Extra kwargs will be passed to `self.init_modules` and `self.update`.""" + super().__init__() + self.original_module = module_to_save + self._active_adapter = [adapter_name] + self._disable_adapters = False + self._adapters = set() + + self.init_modules(adapter_name, **kwargs) + + self.update(adapter_name, **kwargs) + self.check_module() + + def init_modules(self, adapter_name, **kwargs): + """A place to initialize PyTorch modules in `__init__` before the call to `self.update()`.""" + raise NotImplementedError + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + raise NotImplementedError + + def _error_message_name(self): + """Returns a user friendly identifier for error messages, e.g. for type compatibility error messages from + `check_module()` so that the user can backtrack where the error comes from. A generic "training wrapper" is + less helpful than "modules_to_save", for example. + """ + return "training wrapper" + + def check_module(self): + """Perform some sanity checks on the module to ensure that it works""" + # Try to anticipate some modules that users could try to target that would not work. + # Note: It's not possible to check hasattr(module, "forward"), since that returns True for ModuleDict and + # ModuleList, even though their forward methods cannot be called + forbidden_classes = (torch.nn.ModuleDict, torch.nn.ModuleList, torch.nn.ParameterDict, torch.nn.ParameterList) + if isinstance(self.original_module, forbidden_classes): + cls_name = self.original_module.__class__ + raise TypeError(f"{self._error_message_name()} cannot be applied to modules of type {cls_name}") + + # local import to avoid circular import + from peft.tuners.tuners_utils import BaseTunerLayer + + if isinstance(self.original_module, BaseTunerLayer): + # e.g. applying a training wrapper to a lora layer makes no sense + cls_name = self.original_module.__class__ + raise TypeError(f"{self._error_message_name()} cannot be applied to modules of type {cls_name}") + + @property + def disable_adapters(self) -> bool: + # use a property to ensure that disable_adapters is not set directly, instead use the enable_adapters method + return self._disable_adapters + + @property + def active_adapter(self) -> Union[list[str], str]: + # use a property to ensure that active_adapter is not set directly, instead use the set_adapter method + return self._active_adapter + + @property + def active_adapters(self) -> list[str]: + if isinstance(self._active_adapter, str): + return [self._active_adapter] + return self._active_adapter + + def _hasattr_wrapped(self, name, modules): + """Infrastructure to enable the implementing class to delegate attributes to other modules. + Returns True if the implementing class knows how to handle attribute `name`. + + Gets passed `modules` which is PyTorch's internal list of assigned modules from `nn.Module`. + """ + return False + + def _getattr_wrapped(self, name, modules): + """If `_hasattr_wrapped` returns True for `name`, then this function should return the corresponding + value associated with `name`. + """ + return + + def __getattr__(self, name: str): + # Note: This whole method may seem overly complex at first but PyTorch messes with __getattr__ in a way that + # requires very careful handling to avoid infinite recursion. + try: + return super().__getattr__(name) + except AttributeError: + pass + + if "_modules" not in self.__dict__: + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + # Could not find the attribute the PyTorch way. So let's check if it's an attribute on the + # original_module or the module further down (e.g., `modules_to_save[active_adapter]`). + modules = self.__dict__["_modules"] + if self.disable_adapters or (not self.active_adapters): + # no PEFT adapter is active, thus refer to original module + return getattr(self.original_module, name) + elif self._hasattr_wrapped(name, modules): + return self._getattr_wrapped(name, modules) + + # For some reason, there is no module corresponding to the active adapter; this should normally not be + # reached and exists as a failsafe (otherwise, a KeyError would be raised) + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + def update(self, adapter_name, **kwargs): + """Called when this instance should be part of an adapter's training. + Adds the given adapter to the list of adapters that this instance is training along with. + + Additional kwargs are expected to be the same kwargs that are also passed for initializing this class. + """ + if adapter_name not in self._adapters: + self._adapters.add(adapter_name) + + def _create_new_hook(self, old_hook): + r""" + Creates a new hook based on the old hook. Use it only if you know what you are doing ! + """ + old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__) + old_hook_attr = old_hook.__dict__ + filtered_old_hook_attr = {} + old_hook_init_signature = inspect.signature(old_hook_cls.__init__) + for k in old_hook_attr.keys(): + if k in old_hook_init_signature.parameters: + filtered_old_hook_attr[k] = old_hook_attr[k] + new_hook = old_hook_cls(**filtered_old_hook_attr) + return new_hook + + def _check_forward_args(self, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None or not args: + return + + x = args[0] + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + def _forward_wrapped(self, *args: Any, **kwargs: Any) -> torch.Tensor: + raise NotImplementedError + + def _forward_wrapped_mixed_batch( + self, x: torch.Tensor, active_adapter: str, *args: Any, **kwargs: Any + ) -> torch.Tensor: + raise NotImplementedError + + def _forward_wrapped_passthrough(self, *args: Any, **kwargs: Any) -> torch.Tensor: + """The forward call when no adapter is involved in the forward computation, only the base model""" + raise NotImplementedError + + def _mixed_batch_forward( + self, input: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + + SUPPORTED_MODULES = (torch.nn.Linear, torch.nn.Embedding, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d) + + module_names = ", ".join([module.__name__ for module in SUPPORTED_MODULES]) + + if not isinstance(self.original_module, SUPPORTED_MODULES): + raise TypeError(f"Mixed batching is only supported for the following modules: {module_names}.") + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + results = [0 for _ in range(len(input))] + + for i, active_adapter in enumerate(unique_adapters): + sub_batch = input[sub_batch_indices_list[i]] + + if active_adapter == "__base__": + output = self.original_module(sub_batch, *args, **kwargs) + else: + output = self._forward_wrapped_mixed_batch(sub_batch, active_adapter, *args, **kwargs) + + for index, j in enumerate(sub_batch_indices_list[i]): + results[j] = output[index] + + return torch.stack(results) + + def forward(self, *args, **kwargs): + self._check_forward_args(*args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters or any(adapter not in self._adapters for adapter in self.active_adapters): + return self._forward_wrapped_passthrough(*args, **kwargs) + + if adapter_names is None: + return self._forward_wrapped(*args, **kwargs) + return self._mixed_batch_forward(*args, adapter_names=adapter_names, **kwargs) + + def enable_adapters(self, enabled: bool): + """Toggle the enabling and disabling of adapters + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self._disable_adapters = False + else: + self._disable_adapters = True + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + raise NotImplementedError + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + """Set the active adapter + + Note: This only deals with active_adapters, not with requires_grad. If the latter needs changing, handle it via + the subclass. + + Args: + adapter_names (str or list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + self._active_adapter = adapter_names + else: + self._active_adapter = [] + for adapter_name in adapter_names: + if adapter_name not in self._adapters: + raise ValueError(f"Adapter {adapter_name} not found in {self._adapters}") + + self._active_adapter.append(adapter_name) + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """Delete an adapter from the layer, set a new active adapter if necessary""" + raise NotImplementedError + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if isinstance(adapter_names, str): + adapter_names_set = {adapter_names} + else: + adapter_names_set = set(adapter_names) + + for layer_name in self.adapter_layer_names: + # use attrgetter, as it resolves `.` in the attribute name + module_dict = attrgetter(layer_name)(self) + for key, layer in module_dict.items(): + if key in adapter_names_set: + _set_layer_requires_grad(layer, requires_grad) + + def adapter_state_dict(self, adapter_name): + """Return the state dict of this module for a given adapter.""" + raise NotImplementedError + + def adapter_state_dict_load_map(self, adapter_name): + """Return a mapping from the key present in disk-loaded state dict + and how it should be represented in the loaded model's state dict. + + The default should be a 1:1 mapping but it is important to define a mapping as it also serves as the + ground-truth for which keys are supposed to be loaded from a saved state dict. + """ + raise NotImplementedError + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Handles unloading when called from PEFT models. Returns the wrapped module + and handles merging onto the wrapped module if requested. + """ + raise NotImplementedError + + +class ModulesToSaveWrapper(AuxiliaryTrainingWrapper): + """Wraps a module that is supposed to be trained (i.e. `requires_grad_(True)`) and saved after training.""" + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = ("modules_to_save",) + + def __init__(self, module_to_save, adapter_name, tied_module=None): + super().__init__(module_to_save, adapter_name, tied_module=tied_module) + + def init_modules(self, adapter_name, **kwargs): + # we treat each adapter separately, so we have multiple adapters, same (copied) module for each + self.modules_to_save = torch.nn.ModuleDict({}) + + def _error_message_name(self): + return "modules_to_save" + + def _forward_wrapped(self, *args, **kwargs): + if not self.active_adapters: + return self._forward_wrapped_passthrough(*args, **kwargs) + return self.modules_to_save[self.active_adapters[0]](*args, **kwargs) + + def _forward_wrapped_mixed_batch(self, x, active_adapter, *args, **kwargs): + return self.modules_to_save[active_adapter](x, *args, **kwargs) + + def _forward_wrapped_passthrough(self, *args, **kwargs): + return self.original_module(*args, **kwargs) + + def _hasattr_wrapped(self, name, modules): + # this method is only called if there is at least one active adapter + return self.active_adapters[0] in modules["modules_to_save"] + + def _getattr_wrapped(self, name, modules): + return getattr(modules["modules_to_save"][self.active_adapters[0]], name) + + def update(self, adapter_name, tied_module=None, **kwargs): + super().update(adapter_name) + + context_manager = nullcontext() + for _, param in self.original_module.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + import deepspeed + + context_manager = deepspeed.zero.GatheredParameters(self.original_module.parameters(), modifier_rank=0) + break + + if adapter_name not in self.modules_to_save: + with context_manager: + if tied_module: + new_linear = torch.nn.Linear(*tied_module.weight.shape, bias=False) + new_linear.weight = tied_module.weight + + self.modules_to_save[adapter_name] = new_linear + else: + self.modules_to_save[adapter_name] = copy.deepcopy(self.original_module) + + if hasattr(self.modules_to_save[adapter_name], "_hf_hook"): + old_hook = self.modules_to_save[adapter_name]._hf_hook + new_hook = self._create_new_hook(old_hook) + remove_hook_from_module(self.modules_to_save[adapter_name]) + add_hook_to_module(self.modules_to_save[adapter_name], new_hook) + + self.original_module.requires_grad_(False) + + # note that there currently cannot be more than one active adapter for the same layer with modules to save + # since there would be no clear way to decide which adapter's weights are the correct ones. therefore we + # assume that there is only one active adapter. this precondition is enforced by _set_adapter. + if adapter_name == self.active_adapter: + _set_layer_requires_grad(self.modules_to_save[adapter_name], True) + + def enable_adapters(self, enabled: bool): + """Takes care of setting the required_grad flag on the modules_to_save. + If adapters are enabled, gradients for the modules_to_save are required as well. + """ + super().enable_adapters(enabled) + + if enabled: + for adapter_name in self.active_adapters: + _set_layer_requires_grad(self.modules_to_save[adapter_name], True) + else: + for module in self.modules_to_save.values(): + _set_layer_requires_grad(module, False) + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + if isinstance(adapter_name, str): + return adapter_name + + # adapter_name is a list of str + if len(adapter_name) == 0: + raise ValueError("Please specify at least one adapter to set") + + adapter_names_in_module = [n for n in adapter_name if n in self.modules_to_save] + + if len(adapter_names_in_module) > 1: + raise ValueError(f"Only one adapter can be set at a time for {self}, got {len(adapter_names_in_module)}") + + adapter_name_to_set: str | None + if not adapter_names_in_module: + adapter_name_to_set = None + else: + adapter_name_to_set = adapter_names_in_module[0] + + return adapter_name_to_set + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + """Set the active adapter + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_names (list[str], str): + The name(s) of the adapter(s) to set as active. + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + adapter_names = [adapter_names] + + if len(adapter_names) > 1: + raise ValueError(f"Attempted to set multiple ({adapter_names}) adapters at once for modules_to_save.") + + for currently_active_adapter_name in self.active_adapters: + _set_layer_requires_grad(self.modules_to_save[currently_active_adapter_name], False) + + if len(adapter_names) == 0: + # when calling model.add_adapter, the new adapter is not automatically active + self._active_adapter = [] + return + + adapter_name = adapter_names[0] + + if adapter_name not in self._adapters: + raise ValueError(f"Adapter {adapter_name} not found in {self._adapters}") + + _set_layer_requires_grad(self.modules_to_save[adapter_name], not inference_mode) + self._active_adapter = adapter_name + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """ + Delete the adapter if present. + + This method will also set a new active adapter if the deleted adapter was the active adapter. It is important + that the new adapter is chosen by the caller in a deterministic way, so that the same adapter is chosen on all + layers. + """ + if adapter_name not in self.modules_to_save: + return + + # set new active adapter, if necessary + # note: there can only ever be one active adapter, unlike for LoRA etc. + if isinstance(new_active_adapters, (list, tuple)) and len(new_active_adapters) > 1: + name = self.__class__.__name__ + raise ValueError( + f"Attempted to set multiple ({new_active_adapters}) adapters at once for {name}, which is not allowed." + ) + + if adapter_name in self._adapters: + self._adapters.remove(adapter_name) + + if not new_active_adapters: + # no active adapter now + del self.modules_to_save[adapter_name] + self._active_adapter = [] + return + + new_active_adapter = new_active_adapters[0] + if new_active_adapter not in self.modules_to_save: + # a new active adapter was chosen but it seems like it has no modules_to_save + del self.modules_to_save[adapter_name] + self._active_adapter = [] + return + + if new_active_adapter != self.active_adapters[0]: + self.set_adapter(new_active_adapter) + del self.modules_to_save[adapter_name] + + def adapter_state_dict_load_map(self, adapter_name): + # Maps the module keys as they are in the saved state dict to the in-memory state dict. + # Must contain all keys that are supposed to be loaded. + if adapter_name not in self._adapters: + # In caes of multiple adapters, each bringing their own modules to save, each + # ModulesToSaveWrapper will be queried but not every wrapper is obliged to serve the same adapters. + return {} + return {k: f"modules_to_save.{adapter_name}.{k}" for k in self.modules_to_save[adapter_name].state_dict()} + + def adapter_state_dict(self, adapter_name, state_dict): + if adapter_name not in self._adapters: + # In caes of multiple adapters, each bringing their own modules to save, each + # ModulesToSaveWrapper will be queried but not every wrapper is obliged to serve the same adapters. + return {} + + return { + k: state_dict[f"modules_to_save.{adapter_name}.{k}"] + for k in self.modules_to_save[adapter_name].state_dict() + } + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Unloading in case of `ModulesToSave` means to simply return the wrapped module. + + However, if the wrapped module is itself a tuner, we'll call merge on it before. + """ + new_module = self.modules_to_save[self.active_adapter] + + # TODO: not sure if this is still a sensible thing to do. We would basically have to + # do the same checks as `_unload_and_optionally_merge` to support MHA, for example. + if hasattr(new_module, "base_layer"): + # check if the module is itself a tuner layer + if merge: + new_module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + new_module = new_module.get_base_layer() + + return new_module + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + return set(self.modules_to_save.keys()) + + +class TrainableTokensWrapper(AuxiliaryTrainingWrapper): + """Wraps a module (typically an embedding layer) that is supposed to be re-trained selectively (i.e. + solely updating a few columns) using the `TrainableTokensLayer` PEFT method. + + Supports weight-tying to another adapter when passed a `tied_adapter` which is expected to be a + `TrainableTokensLayer`. + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = ("token_adapter.trainable_tokens_delta",) + other_param_names: tuple[str, ...] = ("token_adapter.token_indices", "token_adapter.trainable_tokens_original") + + def __init__( + self, + module_to_save: torch.nn.Module, + adapter_name: str, + token_indices: list[int], + tied_adapter=None, + ) -> None: + super().__init__(module_to_save, adapter_name, token_indices=token_indices, tied_adapter=tied_adapter) + + # unset the original_module attribute since we're using a property to remove this from the state dict. + self.original_module = None + + @property + def original_module(self): + # use a property instead of an attribute to exclude this pointer from the state dict + # to make sure that it will not be saved. + return self.token_adapter.base_layer + + def init_modules(self, adapter_name, token_indices, tied_adapter): + # use a local import to avoid potential circular imports + from peft.tuners.trainable_tokens import TrainableTokensLayer + + # since super().__init__() calls update before we have a chance to initialise the adapter we would + # need here, we do the initialization here. + self.token_adapter = TrainableTokensLayer(self.original_module, adapter_name, token_indices, tied_adapter) + + def _error_message_name(self): + return "trainable_token_indices" + + def _hasattr_wrapped(self, name, modules): + return name == "weight" + + def _getattr_wrapped(self, name, modules): + # some models query self.wte.weight.dtype, some may query the weights directly. for the first case it is not + # necessary to do anything special but we don't know if is going to be `.dtype`. so we need to get the merged + # weights from the adapter. + if name == "weight": + return modules["token_adapter"].get_merged_weights(self.token_adapter.active_adapters) + + raise RuntimeError( + f"This code should've never been reached, probably a bad check in `_hasattr_wrapped` for {name}. " + "Please file an issue under https://github.com/huggingface/peft/issues." + ) + + def _forward_wrapped(self, x, *args, **kwargs): + if not self.active_adapters: + return self._forward_wrapped_passthrough(x, *args, **kwargs) + return self.token_adapter(x) + + def _forward_wrapped_mixed_batch(self, x, active_adapter, *args, **kwargs): + return self.token_adapter.forward_adapters(x, [active_adapter]) + + def _forward_wrapped_passthrough(self, x, *args, **kwargs): + # the token adapter knows how to deal with disabled adapter / no active adapter, don't call original_module + # directly + return self.token_adapter(x, *args, **kwargs) + + def update(self, active_adapter, **kwargs): + # TODO this does not support deepspeed/fsdp since it is missing a context manager + # see ModulesToSaveWrapper implementation + if active_adapter not in self._adapters: + self.token_adapter.update_layer(active_adapter, **kwargs) + + super().update(active_adapter) + + def adapter_state_dict_load_map(self, adapter_name): + if self.token_adapter.tied_adapter: + return {} + return {"token_adapter.trainable_tokens_delta": f"token_adapter.trainable_tokens_delta.{adapter_name}"} + + def adapter_state_dict(self, adapter_name, state_dict): + if self.token_adapter.tied_adapter: + # storing of weight-tied layers is not up to us and will be handled by + # transformers. we're just here to keep those layers in sync during training. + # therefore we return an empty state dict. + return {} + + return { + f"token_adapter.{k}": state_dict[f"token_adapter.{k}.{adapter_name}"] for k in ["trainable_tokens_delta"] + } + + def enable_adapters(self, enabled: bool): + """Enables/disables the underlying `TrainableTokens` adapter. + Also handles the internal adapter disable flag. + """ + super().enable_adapters(enabled) + + self.token_adapter.enable_adapters(enabled) + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + if isinstance(adapter_name, str): + return adapter_name + + # adapter_name is a list of str + if len(adapter_name) == 0: + raise ValueError("Please specify at least one adapter to set") + + # TODO In theory, multiple active trainable tokens is fine when the indices don't overlap + adapter_names_in_module = [n for n in adapter_name if n in self.token_adapter.trainable_tokens_delta] + + if len(adapter_names_in_module) > 1: + raise ValueError(f"Only one adapter can be set at a time for {self}, got {len(adapter_names_in_module)}") + + adapter_name_to_set: str | None + if not adapter_names_in_module: + adapter_name_to_set = None + else: + adapter_name_to_set = adapter_names_in_module[0] + + return adapter_name_to_set + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + super().set_adapter(adapter_names, inference_mode=inference_mode) + self.token_adapter.set_adapter(adapter_names, inference_mode=inference_mode) + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """ + Delete the adapter if present. + + This method will also set a new active adapter if the deleted adapter was the active adapter. It is important + that the new adapter is chosen by the caller in a deterministic way, so that the same adapter is chosen on all + layers. + """ + self.token_adapter.delete_adapter(adapter_name) + + # set new active adapter, if necessary + # note: there can only ever be one active adapter, unlike for LoRA etc. + if isinstance(new_active_adapters, (list, tuple)) and len(new_active_adapters) > 1: + name = self.__class__.__name__ + raise ValueError( + f"Attempted to set multiple ({new_active_adapters}) adapters at once for {name}, which is not allowed." + ) + + if adapter_name in self._adapters: + self._adapters.remove(adapter_name) + + if not new_active_adapters: + self._active_adapter = [] + return + + if new_active_adapters[0] not in self.token_adapter.trainable_tokens_delta: + # a new active adapter was chosen but it seems like it has no trainable_tokens + self._active_adapter = [] + return + + new_active_adapter = new_active_adapters[0] + self.set_adapter(new_active_adapter) + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Unloading for `TrainableTokensWrapper` means to return the wrapped module, e.g. the embedding layer and, + if requested, merging the `TrainableTokens` adapter onto the wrapped module. + """ + if merge: + self.token_adapter.merge(safe_merge=safe_merge, adapter_names=adapter_names) + return self.token_adapter.get_base_layer() + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + return set(self.token_adapter.trainable_tokens_delta.keys()) + + +def _get_input_embeddings_name(model: torch.nn.Module, default: Optional[str] = None) -> Optional[str]: + if not hasattr(model, "get_input_embeddings"): + return default + + input_embeddings = model.get_input_embeddings() + for name, module in model.named_modules(): + if module is input_embeddings: + return name + + return default + + +def _get_submodules(model: torch.nn.Module, key: str) -> tuple[torch.nn.Module, torch.nn.Module, str]: + parent = model.get_submodule(".".join(key.split(".")[:-1])) + target_name = key.split(".")[-1] + target = model.get_submodule(key) + return parent, target, target_name + + +def _get_submodules_with_grandparent( + model: torch.nn.Module, key: str +) -> tuple[torch.nn.Module, Optional[torch.nn.Module], torch.nn.Module, str]: + parent = model.get_submodule(".".join(key.split(".")[:-1])) + try: + grandparent = model.get_submodule(".".join(key.split(".")[:-2])) + except AttributeError: + # no grand parent + grandparent = None + target_name = key.split(".")[-1] + target = model.get_submodule(key) + return parent, grandparent, target, target_name + + +def _freeze_adapter(model: torch.nn.Module, adapter_name: str) -> None: + for n, p in model.named_parameters(): + if adapter_name in n: + p.requires_grad = False + + +def _set_trainable( + model, + adapter_name, + module_names, + inference_mode: bool, + strict_module_check: bool = False, + wrapper_cls: Optional[AuxiliaryTrainingWrapper] = None, + activate_adapter: bool = True, + **wrapper_kwargs, +): + """Wraps modules that are supposed to be re-trained either normally, i.e. marking them to require gradients and + saving them alongside other modules, or with certain methods that go alongside PEFT methods, such as retraining + specific token indices using selective read/write. + + Note that you need to validate beforehand if there are layers targeted by multiple wrappers, e.g. if the + 'embedding' layer is configured for both `ModulesToSaveWrapper` and `TrainableTokensWrapper` there would be + conflicts down the line. + + The default is to wrap the module in a `ModulesToSaveWrapper` wrapper. + + If `strict_module_check` is set, this method raises an ValueError, similar to BaseTuner.inject_adapter when none of + the requested modules in `module_names` is not found in the model. + + The `active_adapter` flag indicates if this new adapter should be activated. + """ + from peft.tuners.tuners_utils import BaseTunerLayer + + if wrapper_cls is None: + wrapper_cls = ModulesToSaveWrapper + + if not module_names: + # This is useful for the case that the PEFT config does not have `modules_to_save`, e.g. + # in the case of prompt tuning and friends. + return + + trainable_modules = [] + found_modules = set() + # disable removal of duplicates to support targeting tied weights + key_list = [key for key, _ in model.named_modules(remove_duplicate=False)] + + for key in key_list: + target_module_found = any(key.endswith(target_key) for target_key in module_names) + if target_module_found: + parent, grandparent, target, target_name = _get_submodules_with_grandparent(model, key) + if isinstance(grandparent, BaseTunerLayer): + # This is an extreme edge case: Let's assume that there is a PEFT config with + # modules_to_save=["default"], which is the same name as the adapter name. The PEFT method's adapter + # (e.g. LoRA) is applied first. Then, when the modules_to_save matching is performed, the LoRA layer + # would be considered a valid target. Assuming that the name is "foo.bar.lora_A.default", it would + # match, with "default" being an nn.Linear and the parent, "lora_A", being an nn.ModuleDict. This by + # itself is not enough to prove that this is an unintended match. Thererfore, we also need to check the + # grandparent, "bar", that would be a lora.LoraLayer. When we see this, we should raise an error. + raise ValueError( + f"You are trying to target a module with {wrapper_cls} that is a child of {type(grandparent)}. " + "This is almost certainly not the intended behavior. Please ensure that the adapter name, " + f"'{adapter_name}', does not conflict with any of the targeted modules." + ) + + # For transformers >=5 we need to check the grandparent to detect already modified tied weights. The way + # the new `get_tied_weights_keys` works is that we resolve the current name of the module tied to the + # embeddings. If we replaced the tied weight (i.e. moved it to, say, `lm_head.token_adapter.base_layer`) + # we'll get the new name whereas the old way was that we got `lm_head` regardless of whether it was modified + # or not. We'll assume that we always have two levels of nesting and therefore do the same check as before + # but on the grandparent to accommodate for the new behavior. + if isinstance(grandparent, wrapper_cls): + grandparent.update(adapter_name, **wrapper_kwargs) + grandparent.set_adapter(grandparent.active_adapter, inference_mode=inference_mode) + elif isinstance(target, wrapper_cls): + target.update(adapter_name, **wrapper_kwargs) + target.set_adapter(target.active_adapter, inference_mode=inference_mode) + else: + new_module = wrapper_cls(target, adapter_name, **wrapper_kwargs) + if activate_adapter: + new_module.set_adapter(adapter_name, inference_mode=inference_mode) + else: + new_module.set_adapter([], inference_mode=inference_mode) + setattr(parent, target_name, new_module) + trainable_modules.append(new_module) + found_modules.add(target_name) + + not_found = set(module_names).difference(found_modules) + if strict_module_check and not found_modules: + raise ValueError( + f"Target modules {not_found} not found in the base model. Please check the target modules and try again." + ) + + return trainable_modules + + +def _set_adapter(model, adapter_name: str | list[str], inference_mode: bool = False) -> None: + """Call set_adapter on the AuxiliaryTrainingWrapper modules""" + for module in model.modules(): + if isinstance(module, AuxiliaryTrainingWrapper): + # only check the adapter_name if we actually encounter a AuxiliaryTrainingWrapper, otherwise we don't care + adapter_name_to_set = module.check_set_adapter(adapter_name) + + # if the adapter is found in this module, set it as the active adapter, else disable the adapters of this + # module + if adapter_name_to_set in module._adapters: + module.set_adapter(adapter_name_to_set, inference_mode=inference_mode) + else: + module.set_adapter([], inference_mode=inference_mode) + + +def _prepare_prompt_learning_config(peft_config, model_config): + orig_model_config = model_config + if hasattr(model_config, "to_dict"): + model_config = model_config.to_dict() + # In case of VLM we focus on the language model portion of the model. + if "text_config" in model_config: + model_config = model_config["text_config"] + + if peft_config.num_layers is None: + if hasattr(orig_model_config, "num_hidden_layers"): + # dict entry was removed in https://github.com/huggingface/transformers/pull/41250 + num_layers = orig_model_config.num_hidden_layers + elif "num_hidden_layers" in model_config: + num_layers = model_config["num_hidden_layers"] + elif "num_layers" in model_config: + num_layers = model_config["num_layers"] + elif "n_layer" in model_config: + num_layers = model_config["n_layer"] + else: + raise ValueError("Please specify `num_layers` in `peft_config`") + peft_config.num_layers = num_layers + + if peft_config.token_dim is None: + if "hidden_size" in model_config: + token_dim = model_config["hidden_size"] + elif "n_embd" in model_config: + token_dim = model_config["n_embd"] + elif "d_model" in model_config: + token_dim = model_config["d_model"] + else: + raise ValueError("Please specify `token_dim` in `peft_config`") + peft_config.token_dim = token_dim + + if peft_config.num_attention_heads is None: + if "num_attention_heads" in model_config: + num_attention_heads = model_config["num_attention_heads"] + elif "n_head" in model_config: + num_attention_heads = model_config["n_head"] + elif "num_heads" in model_config: + num_attention_heads = model_config["num_heads"] + elif "encoder_attention_heads" in model_config: + num_attention_heads = model_config["encoder_attention_heads"] + else: + raise ValueError("Please specify `num_attention_heads` in `peft_config`") + peft_config.num_attention_heads = num_attention_heads + + # For grouped-query attention, see #1901. + if (peft_config.peft_type in {"PREFIX_TUNING", "CARTRIDGE"}) and ("num_key_value_heads" in model_config): + # Models with heterogeneous attention (e.g. Gemma4) expose distinct shapes for global vs. sliding layers via + # `global_head_dim` / `num_global_key_value_heads`. Provision the prefix for the global-layer footprint; sliding + # layers whose KV shape doesn't match are skipped per-layer at injection time. Matches the default in + # google-deepmind/gemma#631. + if model_config.get("global_head_dim") is not None: + head_dim = model_config["global_head_dim"] + num_key_value_heads = model_config.get("num_global_key_value_heads") or model_config["num_key_value_heads"] + elif model_config.get("head_dim", None) is not None: + head_dim = model_config["head_dim"] + num_key_value_heads = model_config["num_key_value_heads"] + else: + head_dim = peft_config.token_dim // peft_config.num_attention_heads + num_key_value_heads = model_config["num_key_value_heads"] + peft_config.token_dim = head_dim * num_key_value_heads + peft_config.num_attention_heads = num_key_value_heads + + if getattr(peft_config, "encoder_hidden_size", None) is None: + peft_config.encoder_hidden_size = peft_config.token_dim + + return peft_config + + +def _get_no_split_modules(model) -> set[str]: + """ + Get the modules of the model that should not be split when using device_map. We iterate through the modules to get + the underlying `_no_split_modules`. + + Returns: + `List[str]`: List of modules that should not be split + """ + # After discussion in https://github.com/huggingface/transformers/pull/38141, based on: + # https://github.com/huggingface/transformers/blob/1e921a3a9cea92b383ca4b0484ee45596bbdadc3/src/transformers/modeling_utils.py#L2677-L2704 + _no_split_modules: set[str] = set() + if not hasattr(model, "_no_split_modules"): + return _no_split_modules + + if is_transformers_ge_v5_1_0: + # See https://github.com/huggingface/transformers/commit/36ec3bfa33ebf6c3b38a1d6808292aeea4aae84d + return model._no_split_modules + + # TODO remove once transformers <5.1.0 is not supported anymore + modules_to_check = [model] + while len(modules_to_check) > 0: + module = modules_to_check.pop(-1) + # if the module does not appear in _no_split_modules, we also check the children + if module.__class__.__name__ not in _no_split_modules: + if isinstance(module, PreTrainedModel): + if module._no_split_modules is not None: + _no_split_modules = _no_split_modules | set(module._no_split_modules) + modules_to_check += list(module.children()) + return _no_split_modules + + +def fsdp_auto_wrap_policy(model): + if hasattr(FullyShardedDataParallelPlugin, "get_module_class_from_name"): + get_module_class_from_name = FullyShardedDataParallelPlugin.get_module_class_from_name + else: + from accelerate.utils.dataclasses import get_module_class_from_name + from torch.distributed.fsdp.wrap import _or_policy, lambda_auto_wrap_policy, transformer_auto_wrap_policy + + from ..tuners import CartridgeEncoder, PrefixEncoder, PromptEmbedding, PromptEncoder + + default_transformer_cls_names_to_wrap = ",".join(_get_no_split_modules(model)) + transformer_cls_names_to_wrap = os.environ.get( + "FSDP_TRANSFORMER_CLS_TO_WRAP", default_transformer_cls_names_to_wrap + ).split(",") + transformer_cls_to_wrap = {CartridgeEncoder, PrefixEncoder, PromptEncoder, PromptEmbedding} + for layer_class in transformer_cls_names_to_wrap: + if len(layer_class) == 0: + continue + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise TypeError("Could not find the transformer layer class to wrap in the model.") + else: + transformer_cls_to_wrap.add(transformer_cls) + + def lambda_policy_fn(module): + return ( + len(list(module.named_children())) == 0 + and getattr(module, "weight", None) is not None + and module.weight.requires_grad + ) + + lambda_policy = functools.partial(lambda_auto_wrap_policy, lambda_fn=lambda_policy_fn) + transformer_wrap_policy = functools.partial( + transformer_auto_wrap_policy, + transformer_layer_cls=transformer_cls_to_wrap, + ) + + auto_wrap_policy = functools.partial(_or_policy, policies=[lambda_policy, transformer_wrap_policy]) + return auto_wrap_policy + + +def transpose(weight: torch.Tensor, fan_in_fan_out: bool) -> torch.Tensor: + if not fan_in_fan_out: + return weight + + if isinstance(weight, torch.nn.Parameter): + return torch.nn.Parameter(weight.T) + return weight.T + + +def _is_valid_match(key: str, target_key: str) -> bool: + """ + Helper function to match module names target_key and key. Makes sure that either the key is exactly the target_key + or the target_key is a submodule of key + """ + if key.endswith(target_key): + if len(key) > len(target_key): + return key.endswith("." + target_key) # must be a sub module + return True + return False + + +def _get_batch_size(input_ids: Optional[torch.Tensor], inputs_embeds: Optional[torch.Tensor]) -> int: + """Get the batch size based on either input_ids or input_embeds + + Raises an ValueError if both are None. + + """ + if (input_ids is None) and (inputs_embeds is None): + raise ValueError("You have to provide either input_ids or inputs_embeds") + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + return batch_size + + +def get_quantization_config(model: torch.nn.Module, method: str): + """ + Get the quantization config of the related quantization method + """ + if ( + hasattr(model, "config") + and hasattr(model.config, "quantization_config") + and (getattr(model, "quantization_method", None) == method) + ): + return model.config.quantization_config + return None + + +def is_gptqmodel_quant_linear(module: Optional[torch.nn.Module]) -> bool: + """ + Check if a module is a GPT-QModel quantized linear. + """ + if module is None or not is_gptqmodel_available(): + return False + + try: + from gptqmodel.nn_modules.qlinear import BaseQuantLinear + except ImportError: + return False + + return isinstance(module, BaseQuantLinear) + + +def is_gptqmodel_awq_layer(module: Optional[torch.nn.Module]) -> bool: + """ + Check if a module is a GPT-QModel quantized linear that supports the AWQ method. + """ + if not is_gptqmodel_quant_linear(module): + return False + + supported_methods = getattr(module, "SUPPORTS_METHODS", []) + return any(method.value == "awq" for method in supported_methods) + + +def get_gptqmodel_quant_linear(gptq_quantization_config, device_map=None): + """ + Get the right GPTQQuantLinear class based on the quantization config file + """ + if gptq_quantization_config is None: + return None + + if not is_gptqmodel_available(): + return None + + from gptqmodel import BACKEND + from gptqmodel.quantization import METHOD + from gptqmodel.utils.importer import hf_select_quant_linear_v2 + + desc_act = gptq_quantization_config.desc_act + group_size = gptq_quantization_config.group_size + bits = gptq_quantization_config.bits + checkpoint_format = ( + gptq_quantization_config.checkpoint_format + if hasattr(gptq_quantization_config, "checkpoint_format") + else "gptq" + ) + sym = gptq_quantization_config.sym + meta = gptq_quantization_config.meta if hasattr(gptq_quantization_config, "meta") else None + + QuantLinear = hf_select_quant_linear_v2( + bits=bits, + group_size=group_size, + desc_act=desc_act, + sym=sym, + device_map=device_map, + format=checkpoint_format, + quant_method=METHOD.GPTQ, + meta=meta, + backend=BACKEND.AUTO_TRAINABLE, + pack=False, + ) + + return QuantLinear + + +def id_tensor_storage(tensor: torch.Tensor) -> tuple[torch.device, int, int]: + """ + Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For + example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is + guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with + non-overlapping lifetimes may have the same id. + + This method is the exact same copy of + https://github.com/huggingface/transformers/blob/main/src/transformers/pytorch_utils.py#L282C1-L300C58 but we added + it here manually to avoid import issue with old versions of transformers. + """ + if tensor.device.type == "xla" and is_torch_tpu_available(): + # NOTE: xla tensors dont have storage + # use some other unique id to distinguish. + # this is a XLA tensor, it must be created using torch_xla's + # device. So the following import is safe: + import torch_xla + + unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor) + else: + unique_id = storage_ptr(tensor) + + return tensor.device, unique_id, storage_size(tensor) + + +def cast_mixed_precision_params(model: torch.nn.Module, dtype: torch.dtype) -> None: + """ + Cast all non-trainable parameters of the model to the given `dtype`. The `dtype` can be `torch.float16` or + `torch.bfloat16` as per the mixed-precision training you are performing. The trainable parameters are cast to full + precision. This is meant to reduce the GPU memory usage when using PEFT methods by using half-precision dtype for + non-trainable parameters. Having the trainable parameters in full-precision preserves training stability when using + automatic mixed-precision training. + + Args: + model (`torch.nn.Module`): + The model to cast the non-trainable parameters of. + dtype (`torch.dtype`): + The dtype to cast the non-trainable parameters to. The `dtype` can be `torch.float16` or + `torch.bfloat16` as per the mixed-precision training you are performing. + """ + for p in model.parameters(): + if not p.requires_grad: + p.data = p.to(dtype) + else: + p.data = p.to(torch.float32) + + +def str_to_bool(value: str) -> int: + """ + Converts a string representation of truth to `True` (1) or `False` (0). + + True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`; + """ + # same as function as in accelerate.utils, which replaces the deprecated distutils.util.strtobool + value = value.lower() + if value in ("y", "yes", "t", "true", "on", "1"): + return 1 + elif value in ("n", "no", "f", "false", "off", "0"): + return 0 + else: + raise ValueError(f"invalid truth value {value}") + + +def check_file_exists_on_hf_hub(repo_id: str, filename: str, **kwargs) -> Optional[bool]: + """Check if a file exists on HF Hub, if check was not successful returns None instead of erroring. + + Respect offline mode if set. + + """ + exists: Optional[bool] = None + if str_to_bool(os.environ.get("HF_HUB_OFFLINE", "0")): + # user set offline mode, cannot check + return exists + + try: + exists = file_exists(repo_id, filename, **kwargs) + except (HFValidationError, EntryNotFoundError): + # error, exists stays None + pass + except Exception as e: + warnings.warn( + f"Unable to fetch remote file due to the following error {e} - silently ignoring the lookup" + f" for the file {filename} in {repo_id}." + ) + + return exists + + +def match_target_against_key(target_pattern: str, key: str) -> Optional[re.Match[str]]: + """Backing function for `target_modules` config parameter. + + Having this as its own function ensures that target key matching can be implemented in the same way everywhere. + """ + return re.fullmatch(target_pattern, key) + + +def get_pattern_key(pattern_keys: Sequence[str], key_to_match: str) -> str: + """Match a substring of key_to_match in pattern keys""" + for key in pattern_keys: + match = re.match(rf"(.*\.)?({key})$", key_to_match) + if not match: + continue + return key + + return key_to_match + + +def set_additional_trainable_modules(model, peft_config, model_config, adapter_name, activate_adapter: bool = True): + """Handle the resolution of additional trainable modules (also called AuxiliaryTrainingWrapper) + by checking the config if such modules are requested and adding them to the model. + + Currently trainable tokens and modules to save are considered additional trainable modules. + + If `activate_adapter` is set to `False`, the adapter won't be activated. This is typically the case when + `model.add_adapter` or `model.load_adapter` are being called. + """ + if getattr(peft_config, "modules_to_save", None) is not None: + # this may add a new ModulesToSaveWrapper + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=getattr(peft_config, "modules_to_save", None), + activate_adapter=activate_adapter, + ) + + if getattr(peft_config, "modules_to_tie", None) is not None: + # Tie the modules if any tied layer is passed in `modules_to_save`. + # This should always be called after + # `_set_trainable` is called for `modules_to_save`. + tied_module = getattr(model.get_input_embeddings().modules_to_save, adapter_name) + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=getattr(peft_config, "modules_to_tie", None), + activate_adapter=activate_adapter, + tied_module=tied_module, + ) + + if getattr(peft_config, "trainable_token_indices", None) is not None: + if isinstance(peft_config.trainable_token_indices, dict): + target_layers = peft_config.trainable_token_indices + else: + layer_name = _get_input_embeddings_name(model, "embed_tokens") + target_layers = {layer_name: peft_config.trainable_token_indices} + + modules_to_save = getattr(peft_config, "modules_to_save", None) + if modules_to_save is not None: + for target_layer_name in target_layers: + if target_layer_name in modules_to_save: + raise ValueError( + "The embedding layer is already marked to be trained fully, either specify " + f'`modules_to_save=[..., "{target_layer_name}", ...]` or ' + f"`trainable_tokens={{'{target_layer_name}': x}}` but not both." + ) + + # Check weight tying configuration first to determine which layers to wrap + weights_tied = model_config.get("tie_word_embeddings", False) + ensure_weight_tying = getattr(peft_config, "ensure_weight_tying", False) + + # When multiple target layers are specified, check if they correspond to tied weights + indices_mismatch = False + layers_to_skip = set() + tied_layer_keys = [] + + if len(target_layers) > 1 and weights_tied: + # Get module names that are tied with the embedding + tied_module_names = set(_get_module_names_tied_with_embedding(model)) + + # Also get the input embedding layer name as it's the source of tied weights + embedding_module = model.get_input_embeddings() + # Get the full embedding name (not just the last part) to support nested structures + embedding_name = next(n for n, m in model.named_modules() if m is embedding_module) + + # Find which target layers are in the tied weights (including the embedding source) + for target_layer_name in target_layers: + # Check if this is the embedding layer (use endswith to allow flexible matching) + # This allows users to specify just "embed_tokens" OR "m1.encoder.embed_tokens" for precision + if embedding_name.endswith(target_layer_name): + tied_layer_keys.append(target_layer_name) + continue + # Check if this target layer matches any tied module (considering nested structures) + for tied_module in tied_module_names: + if tied_module.endswith(target_layer_name) or target_layer_name in tied_module.split("."): + tied_layer_keys.append(target_layer_name) + break + + # If we found multiple tied layers in our targets, check their indices + if len(tied_layer_keys) >= 2: + # Check if all tied layers have the same indices + first_indices = target_layers[tied_layer_keys[0]] + indices_mismatch = not all(target_layers[key] == first_indices for key in tied_layer_keys[1:]) + + # Raise error immediately if ensure_weight_tying=True and indices mismatch + if indices_mismatch and ensure_weight_tying: + tied_layers_info = ", ".join([f"{key}: {target_layers[key]}" for key in tied_layer_keys]) + raise ValueError( + f"Cannot ensure weight tying when different token indices are specified for tied layers. " + f"Conflicting layers: {tied_layers_info}. " + f"Please use the same indices for all tied layers or set ensure_weight_tying=False." + ) + + # If indices match, skip tied modules (except embedding) as they'll be handled by weight tying logic + if not indices_mismatch: + layers_to_skip = set(tied_layer_keys) & tied_module_names + + # Wrap target layers (skip those that will be handled by weight tying logic) + for target_layer_name, token_indices in target_layers.items(): + if target_layer_name in layers_to_skip: + continue + + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=[target_layer_name], + strict_module_check=True, + wrapper_cls=TrainableTokensWrapper, + token_indices=token_indices, + activate_adapter=activate_adapter, + ) + + # Warn if user expects weight tying but model doesn't have tied weights + if not weights_tied and ensure_weight_tying: + warnings.warn( + "ensure_weight_tying=True but the model does not have tied weights " + "(tie_word_embeddings=False). Weight tying will not be applied for trainable_token_indices." + ) + + # Apply weight tying when appropriate + should_apply_tying = ( + weights_tied + and isinstance(model.get_input_embeddings(), TrainableTokensWrapper) + and (ensure_weight_tying or not indices_mismatch) + ) + + if should_apply_tying: + # There might be the possibility that we have output weights that are tied to the input weights. + # In that case we will tie any module that wants tied weights to the token adapter to make sure that + # any modification is reflected in the tied layers as well. + tied_weights_module_names = _get_module_names_tied_with_embedding(model) + token_adapter = model.get_input_embeddings().token_adapter + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=tied_weights_module_names, + strict_module_check=True, + wrapper_cls=TrainableTokensWrapper, + token_indices=token_adapter.token_indices[adapter_name], + tied_adapter=model.get_input_embeddings().token_adapter, + ) + + +def create_attention_mask( + model, *, model_input, attention_mask, past_key_values, cache_position, batch_size, sequence_length, position_ids +): + # adapted from: + # https://github.com/huggingface/transformers/blob/cb4c56ce0dfa1350267ed28e57760986a58a9ba4/src/transformers/generation/utils.py#L644-L680 + # In PEFT, we sometimes need to re-create the attention mask. This is because some prompt learning methods insert + # new items into the sequence, which results in the attention mask needing an update. We re-use transformers code + # for this as much as possible. + transformers_ge_4_53_1 = version.parse(transformers.__version__) >= version.parse("4.53.1") + if transformers_ge_4_53_1: + # the function already exists in v4.53.0 but has a different signature, so we check for 4.53.1 + from transformers.masking_utils import create_masks_for_generate + else: + raise ImportError("Your transformers version is too old, please upgrade it to >= 4.53.1") + + # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create + # the 4D causal mask exists, it should be present in the base model (XXXModel class) or in its decoder. + base_model = getattr(model, model.base_model_prefix, model) + decoder = base_model.get_decoder() if hasattr(base_model, "get_decoder") else None + causal_mask_creation_function = getattr(base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None) + if causal_mask_creation_function is None and decoder is not None: # it may be in the decoder + causal_mask_creation_function = getattr(decoder, "_prepare_4d_causal_attention_mask_with_cache_position", None) + + # If it's not defined, it means the model uses the new general mask API + if causal_mask_creation_function is None: # can't be found + token_type_ids = getattr(model_input, "token_type_ids", None) + # Some models may overwrite the general one + causal_mask_creation_function = getattr(model, "create_masks_for_generate", create_masks_for_generate) + attention_mask = causal_mask_creation_function( + config=model.config, + # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings + input_embeds=torch.empty((batch_size, sequence_length), dtype=model.dtype), + attention_mask=attention_mask, + cache_position=cache_position, + past_key_values=past_key_values, + token_type_ids=token_type_ids, + position_ids=position_ids, + ) + else: + attention_mask = causal_mask_creation_function( + attention_mask, + sequence_length=sequence_length, + target_length=past_key_values.get_max_cache_shape(), + dtype=model.dtype, + cache_position=cache_position, + batch_size=batch_size, + config=model.config, + past_key_values=past_key_values, + position_ids=position_ids, + ) + return attention_mask + + +def _get_module_names_tied_with_embedding(model) -> list[str]: + """ + Get the list of the fully qualified names of the modules that are tied to the input embeddings. In case of a + source-target-mapping `_tied_weights_keys`, it will attempt to identify the input embedding weights from the + mapping and return the list of tied modules accordingly. This gives a unified interface to both transformers v4 + tied weights and v5 mapped tied weights. + + For example: For models which have `embed_tokens` and `lm_head` as the tied keys, this function will return + [`lm_head`]. The PEFT model is assumed to be transparent: returned names will be relative to the base model, so + even though `model.base_model.lm_head` is tied, the returned name is `lm_head` since such attributes are forwarded + to the base model anyway. Non-transformer models have to provide a `_tied_weights_keys` attribute for this function + to work. + + If the model's config has `tie_word_embeddings` set to `False`, this function returns an empty list, as weight + tying is explicitly disabled for that model checkpoint. + """ + tied_weights: list[str] = [] + + if hasattr(model, "get_base_model"): + # unpack PeftModel + model = model.get_base_model() + + if hasattr(model, "tuner_layer_cls"): + # unpack BaseTuner + model = model.model + + # `_tied_weights_keys` is architectural capability; `tie_word_embeddings=False` means tying is + # explicitly disabled for this checkpoint and must be respected. + model_config = getattr(model, "config", None) + if ( + model_config is not None + and hasattr(model_config, "tie_word_embeddings") + and model_config.tie_word_embeddings is False + ): + return [] + + if not hasattr(model, "_tied_weights_keys"): + return [] + + base_layer_pattern = re.compile(r"[^.]+\.base_layer\.") + + if isinstance(model._tied_weights_keys, dict): + if not hasattr(model, "get_input_embeddings"): + raise ValueError( + "The supplied model implements `_tied_weights_keys` as a dict but doesn't implement " + "'get_input_embeddings' so we can't determine which weights are tied to embeddings." + ) + + # collect all _tied_weights_keys, as sub-modules may have additional entries + tied_weights_keys: dict[str, str] = {} + for module_name, module in model.named_modules(): + module_tied_weights_keys = getattr(module, "_tied_weights_keys", None) + if module_tied_weights_keys and not module_name: + tied_weights_keys.update(module_tied_weights_keys) + elif module_tied_weights_keys: + tied_weights_keys.update( + {f"{module_name}.{k}": f"{module_name}.{v}" for k, v in module_tied_weights_keys.items()} + ) + + # technically it would be sufficient to just return candidates since that contains all the keys of + # all models that are tied (not just equal!) to the input embeddings. the only reason why we aren't + # doing that is because we need to filter out the original embedding name since we promise to just + # return the keys of the tying targets. + input_embedding_params = set(model.get_input_embeddings().parameters()) + candidates = [n for n, p in model.named_parameters(remove_duplicate=False) if p in input_embedding_params] + + # Consider the case that sources and targets are already wrapped by a PEFT method. In that case we won't + # find them by their old names. Therefore, we need to create a map of the new names to the old names so + # that we can translate back and forth. + peft_reverse_mapping = {base_layer_pattern.sub("", name): name for name in candidates} + + # AuxiliaryTrainingWrapper don't have an adapter suffix but still have a base_layer attribute, + # add those as a potential translation. + peft_reverse_mapping.update(**{name.replace("base_layer.", ""): name for name in candidates}) + + tied_weights.extend( + peft_reverse_mapping.get(k, k) + for k, v in tied_weights_keys.items() + if peft_reverse_mapping.get(v, v) in candidates + ) + + elif model._tied_weights_keys is not None: + # TODO remove this when transformers