2
0

python.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Execution = class {
  4. constructor(sources) {
  5. /* eslint-disable consistent-this */
  6. const self = this;
  7. /* eslint-enable consistent-this */
  8. const execution = self;
  9. this._sources = sources || new Map();
  10. this._events = new Map();
  11. this._utf8Decoder = new TextDecoder('utf-8');
  12. this._unresolved = new Map();
  13. this._operators = new Map();
  14. const dict = class extends Map {
  15. constructor(items) {
  16. super();
  17. if (items) {
  18. if (items instanceof Map) {
  19. items = Array.from(items);
  20. } else if (!Array.isArray(items)) {
  21. items = Object.entries(items);
  22. }
  23. for (const [name, value] of items) {
  24. this.__setitem__(name, value);
  25. }
  26. }
  27. }
  28. __contains__(key) {
  29. return this.has(key);
  30. }
  31. __setitem__(key, value) {
  32. this.set(key, value);
  33. }
  34. __getitem__(key) {
  35. return this.get(key);
  36. }
  37. __delitem__(key) {
  38. this.delete(key);
  39. }
  40. get(key, defaultValue) {
  41. return super.has(key) ? super.get(key) : defaultValue;
  42. }
  43. setdefault(key, defaultValue) {
  44. if (this.has(key)) {
  45. return this.get(key);
  46. }
  47. const value = defaultValue || null;
  48. this.set(key, value);
  49. return value;
  50. }
  51. pop(key) {
  52. if (this.__contains__(key)) {
  53. const v = this.__getitem__(key);
  54. this.__delitem__(key);
  55. return v;
  56. }
  57. return null;
  58. }
  59. items() {
  60. return Array.from(this);
  61. }
  62. update(other) {
  63. for (const [key, value] of other) {
  64. this.set(key, value);
  65. }
  66. }
  67. };
  68. this._modules = new dict();
  69. this._registry = new Map();
  70. const module = class {
  71. constructor(name) {
  72. this.__name__ = name;
  73. }
  74. };
  75. const builtins = this.register('builtins', new module('builtins'));
  76. this.builtins = builtins;
  77. this._registry.set('__builtin__', builtins);
  78. this.registerType('builtins.type', class {
  79. constructor(...args) {
  80. if (args.length === 1) {
  81. const [obj] = args;
  82. if (obj === null) {
  83. // eslint-disable-next-line no-constructor-return
  84. return builtins.NoneType;
  85. }
  86. if (obj && obj.__class__) {
  87. // eslint-disable-next-line no-constructor-return
  88. return obj.__class__;
  89. }
  90. throw new python.Error(`Unknown type '${obj}'`);
  91. }
  92. if (args.length === 3) {
  93. const [name, bases, body] = args;
  94. const cls = bases.length > 0 ? class extends bases[0] {} : class {};
  95. execution.registerType(name, cls);
  96. for (const [key, value] of body) {
  97. cls[key] = value;
  98. }
  99. // eslint-disable-next-line no-constructor-return
  100. return cls;
  101. }
  102. throw new python.Error(`Invalid 'builtins.dict' argument count.`);
  103. }
  104. }).__class__ = builtins.type;
  105. this.registerType('builtins.module', module);
  106. this.registerType('builtins.method', class {});
  107. this.registerType('builtins.function', class {
  108. constructor(code, globals, name) {
  109. this.__code__ = code;
  110. this.__globals__ = globals;
  111. this.__name__ = name;
  112. }
  113. });
  114. this.registerType('builtins.classmethod', class {});
  115. this.registerType('builtins.code', class {});
  116. this.import('builtins');
  117. this.registerType('builtins.builtin_function_or_method', class {});
  118. const typing = this.register('typing');
  119. this.typing = typing;
  120. const operator = this.register('operator');
  121. this.register('_codecs');
  122. this.register('argparse');
  123. this.enum = this.register('enum');
  124. const collections = this.register('collections');
  125. const copy = this.register('copy');
  126. this.register('copy_reg');
  127. const ast = this.register('ast');
  128. this.ast = ast;
  129. this.register('cuml');
  130. const cloudpickle = this.register('cloudpickle');
  131. const datetime = this.register('datetime');
  132. this.register('gensim');
  133. const io = this.register('io');
  134. const joblib = this.register('joblib');
  135. const jax = this.register('jax');
  136. this.register('jax.numpy');
  137. this.register('jax._src.array');
  138. this.register('jax._src.device_array');
  139. const functools = this.register('functools');
  140. this.registerType('functools.partial', class {});
  141. const keras = this.register('keras');
  142. const catboost = this.register('catboost');
  143. this.register('lightgbm');
  144. this.register('nolearn');
  145. const fastcore = this.register('fastcore');
  146. const fastai = this.register('fastai');
  147. const math = this.register('math');
  148. math.inf = Infinity;
  149. const numpy = this.register('numpy');
  150. this.register('numpy.core.multiarray');
  151. this.register('numpy.core._multiarray_umath');
  152. this.register('numpy.matrixlib.defmatrix');
  153. const pandas = this.register('pandas');
  154. this.register('pandas.indexes.base');
  155. this.register('pandas.indexes.range');
  156. this.register('pandas._libs.tslib');
  157. this.register('pandas._libs.internals');
  158. const pickle = this.register('pickle');
  159. const shap = this.register('shap');
  160. this.register('shap.explainers.linear');
  161. const sklearn = this.register('sklearn');
  162. this.register('sklearn.externals.joblib.numpy_pickle');
  163. const torch = this.register('torch');
  164. this.torch = torch;
  165. const torchvision = this.register('torchvision');
  166. const torchao = this.register('torchao');
  167. const sympy = this.register('sympy');
  168. this.register('torch.storage');
  169. this.register('torch.nn.parameter');
  170. this.register('torch.ops');
  171. this.register('torch._ops');
  172. this.register('torch.ops.higher_order');
  173. this.register('torch.ops.torchvision');
  174. this.register('torch.ops.torchaudio');
  175. this.register('torch.ops._caffe2');
  176. this.register('torchvision');
  177. this.register('__torch__');
  178. const sys = this.register('sys');
  179. sys.modules = this._modules;
  180. this.register('xgboost');
  181. this.registerType('ast.AST', class {});
  182. this.registerType('ast.mod', class extends ast.AST {});
  183. this.registerType('ast.expr', class extends ast.AST {});
  184. this.registerType('ast.unaryop', class extends ast.AST {});
  185. this.registerType('ast.binop', class extends ast.AST {});
  186. this.registerType('ast.operator', class extends ast.AST {});
  187. this.registerType('ast.boolop', class extends ast.AST {});
  188. this.registerType('ast.cmpop', class extends ast.AST {});
  189. this.registerType('ast.stmt', class extends ast.AST {});
  190. this.registerType('ast.excepthandler', class extends ast.AST {});
  191. this.registerType('ast.keyword', class extends ast.AST {
  192. constructor(arg, value) {
  193. super();
  194. this.arg = arg;
  195. this.value = value;
  196. }
  197. });
  198. this.registerType('ast.alias', class extends ast.AST {
  199. constructor(name, asname) {
  200. super();
  201. this.name = name;
  202. this.asname = asname;
  203. }
  204. });
  205. this.registerType('ast.Name', class extends ast.expr {
  206. constructor(id, ctx) {
  207. super();
  208. this.id = id;
  209. if (ctx) {
  210. this.ctx = ctx;
  211. }
  212. }
  213. });
  214. this.registerType('ast.Constant', class extends ast.expr {
  215. constructor(value, type) {
  216. super();
  217. this.value = value;
  218. this.type = type || null;
  219. }
  220. });
  221. this.registerType('ast.Ellipsis', class extends ast.Constant {
  222. constructor() {
  223. super(builtins.ellipsis);
  224. }
  225. });
  226. this.registerType('ast.Starred', class extends ast.expr {
  227. constructor(value, ctx) {
  228. super();
  229. this.value = value;
  230. if (ctx) {
  231. this.ctx = ctx;
  232. }
  233. }
  234. });
  235. this.registerType('ast.List', class extends ast.expr {
  236. constructor(elts, ctx) {
  237. super();
  238. this.elts = elts;
  239. if (ctx) {
  240. this.ctx = ctx;
  241. }
  242. }
  243. });
  244. this.registerType('ast.Set', class extends ast.expr {
  245. constructor(elts) {
  246. super();
  247. this.elts = elts;
  248. }
  249. });
  250. this.registerType('ast.Tuple', class extends ast.expr {
  251. constructor(elts, ctx) {
  252. super();
  253. this.elts = elts;
  254. if (ctx) {
  255. this.ctx = ctx;
  256. }
  257. }
  258. });
  259. this.registerType('ast.Dict', class extends ast.expr {
  260. constructor(keys, values) {
  261. super();
  262. this.keys = keys;
  263. this.values = values;
  264. }
  265. });
  266. this.registerType('ast.ListComp', class extends ast.expr {
  267. constructor(elt, generators) {
  268. super();
  269. this.elt = elt;
  270. this.generators = generators;
  271. }
  272. });
  273. this.registerType('ast.SetComp', class extends ast.expr {
  274. constructor(elt, generators) {
  275. super();
  276. this.elt = elt;
  277. this.generators = generators;
  278. }
  279. });
  280. this.registerType('ast.GeneratorExp', class extends ast.expr {
  281. constructor(elt, generators) {
  282. super();
  283. this.elt = elt;
  284. this.generators = generators;
  285. }
  286. });
  287. this.registerType('ast.DictComp', class extends ast.expr {
  288. constructor(key, value, generators) {
  289. super();
  290. this.key = key;
  291. this.value = value;
  292. this.generators = generators;
  293. }
  294. });
  295. this.registerType('ast.comprehension', class extends ast.AST {
  296. constructor(target, iter, ifs, is_async) {
  297. super();
  298. this.target = target;
  299. this.iter = iter;
  300. this.ifs = ifs;
  301. this.is_async = is_async;
  302. }
  303. });
  304. this.registerType('ast.Subscript', class extends ast.expr {
  305. constructor(value, slice, ctx) {
  306. super();
  307. this.value = value;
  308. this.slice = slice;
  309. if (ctx) {
  310. this.ctx = ctx;
  311. }
  312. }
  313. });
  314. this.registerType('ast.Slice', class extends ast.expr {
  315. constructor(lower, upper, step) {
  316. super();
  317. this.lower = lower;
  318. this.upper = upper;
  319. this.step = step;
  320. }
  321. });
  322. this.registerType('ast.UnaryOp', class extends ast.expr {
  323. constructor(op, operand) {
  324. super();
  325. this.op = op;
  326. this.operand = operand;
  327. }
  328. });
  329. this.registerType('ast.UAdd', class extends ast.unaryop {});
  330. this.registerType('ast.USub', class extends ast.unaryop {});
  331. this.registerType('ast.Not', class extends ast.unaryop {});
  332. this.registerType('ast.Invert', class extends ast.unaryop {});
  333. this.registerType('ast.BinOp', class extends ast.expr {
  334. constructor(left, op, right) {
  335. super();
  336. this.left = left;
  337. this.op = op;
  338. this.right = right;
  339. }
  340. });
  341. this.registerType('ast.Add', class extends ast.operator {});
  342. this.registerType('ast.Sub', class extends ast.operator {});
  343. this.registerType('ast.Mult', class extends ast.operator {});
  344. this.registerType('ast.Div', class extends ast.operator {});
  345. this.registerType('ast.FloorDiv', class extends ast.operator {});
  346. this.registerType('ast.Mod', class extends ast.operator {});
  347. this.registerType('ast.Pow', class extends ast.operator {});
  348. this.registerType('ast.LShift', class extends ast.operator {});
  349. this.registerType('ast.RShift', class extends ast.operator {});
  350. this.registerType('ast.BitOr', class extends ast.operator {});
  351. this.registerType('ast.BitXor', class extends ast.operator {});
  352. this.registerType('ast.BitAnd', class extends ast.operator {});
  353. this.registerType('ast.MatMult', class extends ast.operator {});
  354. this.registerType('ast.BoolOp', class extends ast.expr {
  355. constructor(op, values) {
  356. super();
  357. this.op = op;
  358. this.values = values;
  359. }
  360. });
  361. this.registerType('ast.And', class extends ast.boolop {});
  362. this.registerType('ast.Or', class extends ast.boolop {});
  363. this.registerType('ast.Compare', class extends ast.expr {
  364. constructor(left, ops, comparators) {
  365. super();
  366. this.left = left;
  367. this.ops = ops;
  368. this.comparators = comparators;
  369. }
  370. });
  371. this.registerType('ast.Eq', class extends ast.cmpop {});
  372. this.registerType('ast.NotEq', class extends ast.cmpop {});
  373. this.registerType('ast.Lt', class extends ast.cmpop {});
  374. this.registerType('ast.LtE', class extends ast.cmpop {});
  375. this.registerType('ast.Gt', class extends ast.cmpop {});
  376. this.registerType('ast.GtE', class extends ast.cmpop {});
  377. this.registerType('ast.Is', class extends ast.cmpop {});
  378. this.registerType('ast.IsNot', class extends ast.cmpop {});
  379. this.registerType('ast.In', class extends ast.cmpop {});
  380. this.registerType('ast.NotIn', class extends ast.cmpop {});
  381. this.registerType('ast.Call', class extends ast.expr {
  382. constructor(func, args, keywords) {
  383. super();
  384. this.func = func;
  385. this.args = args;
  386. this.keywords = keywords || [];
  387. }
  388. });
  389. this.registerType('ast.Attribute', class extends ast.expr {
  390. constructor(value, attr, ctx) {
  391. super();
  392. this.value = value;
  393. this.attr = attr;
  394. if (ctx) {
  395. this.ctx = ctx;
  396. }
  397. }
  398. });
  399. this.registerType('ast.Lambda', class extends ast.expr {
  400. constructor(args, body) {
  401. super();
  402. this.args = args;
  403. this.body = body;
  404. }
  405. });
  406. this.registerType('ast.IfExp', class extends ast.expr {
  407. constructor(test, body, orelse) {
  408. super();
  409. this.test = test;
  410. this.body = body;
  411. this.orelse = orelse;
  412. }
  413. });
  414. this.registerType('ast.NamedExpr', class extends ast.expr {
  415. constructor(target, value) {
  416. super();
  417. this.target = target;
  418. this.value = value;
  419. }
  420. });
  421. this.registerType('ast.Yield', class extends ast.expr {
  422. constructor(value) {
  423. super();
  424. this.value = value;
  425. }
  426. });
  427. this.registerType('ast.YieldFrom', class extends ast.expr {
  428. constructor(value) {
  429. super();
  430. this.value = value;
  431. }
  432. });
  433. this.registerType('ast.Expr', class extends ast.stmt {
  434. constructor(value) {
  435. super();
  436. this.value = value;
  437. }
  438. });
  439. this.registerType('ast.Assign', class extends ast.stmt {
  440. constructor(targets, value, ctx) {
  441. super();
  442. this.targets = targets;
  443. this.value = value;
  444. if (ctx) {
  445. this.ctx = ctx;
  446. }
  447. }
  448. });
  449. this.registerType('ast.AnnAssign', class extends ast.stmt {
  450. constructor(target, annotation, value, simple) {
  451. super();
  452. this.target = target;
  453. this.annotation = annotation;
  454. this.value = value;
  455. this.simple = simple;
  456. }
  457. });
  458. this.registerType('ast.AugAssign', class extends ast.stmt {
  459. constructor(target, op, value) {
  460. super();
  461. this.target = target;
  462. this.op = op;
  463. this.value = value;
  464. }
  465. });
  466. this.registerType('ast.If', class extends ast.stmt {
  467. constructor(test, body, orelse) {
  468. super();
  469. this.test = test;
  470. this.body = body;
  471. this.orelse = orelse;
  472. }
  473. });
  474. this.registerType('ast.For', class extends ast.stmt {
  475. constructor(target, iter, body, orelse /*, type_comment */) {
  476. super();
  477. this.target = target;
  478. this.iter = iter;
  479. this.body = body;
  480. this.orelse = orelse;
  481. }
  482. });
  483. this.registerType('ast.While', class extends ast.stmt {
  484. constructor(test, body, orelse /*, type_comment */) {
  485. super();
  486. this.test = test;
  487. this.body = body;
  488. this.orelse = orelse;
  489. }
  490. });
  491. this.registerType('ast.Del', class extends ast.stmt {
  492. constructor(targets) {
  493. super();
  494. this.targets = targets;
  495. }
  496. });
  497. this.registerType('ast.Return', class extends ast.stmt {
  498. constructor(value) {
  499. super();
  500. this.value = value;
  501. }
  502. });
  503. this.registerType('ast.Try', class extends ast.stmt {
  504. constructor(body, handlers, orelse, finalbody) {
  505. super();
  506. this.body = body;
  507. this.handlers = handlers;
  508. this.orelse = orelse;
  509. this.finalbody = finalbody;
  510. }
  511. });
  512. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  513. constructor(type, name, body) {
  514. super();
  515. this.type_ = type;
  516. this.name = name;
  517. this.body = body;
  518. }
  519. });
  520. this.registerType('ast.ClassDef', class extends ast.stmt {
  521. constructor(name, bases, keywords, body, decorator_list, type_params) {
  522. super();
  523. this.name = name;
  524. this.bases = bases;
  525. this.keywords = keywords;
  526. this.body = body;
  527. this.decorator_list = decorator_list;
  528. this.type_params = type_params;
  529. }
  530. });
  531. this.registerType('ast.FunctionDef', class extends ast.stmt {
  532. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  533. super();
  534. this.name = name;
  535. this.args = args;
  536. this.body = body;
  537. this.decorator_list = decorator_list;
  538. this.returns = returns;
  539. this.type_comment = type_comment;
  540. this.type_params = type_params;
  541. }
  542. });
  543. this.registerType('ast.arguments', class extends ast.AST {
  544. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  545. super();
  546. this.posonlyargs = posonlyargs;
  547. this.args = args;
  548. this.vararg = vararg;
  549. this.kwonlyargs = kwonlyargs;
  550. this.kw_defaults = kw_defaults;
  551. this.kwarg = kwarg;
  552. this.defaults = defaults;
  553. }
  554. });
  555. this.registerType('ast.arg', class extends ast.AST {
  556. constructor(arg, annotation, type_comment) {
  557. super();
  558. this.arg = arg;
  559. this.annotation = annotation;
  560. this.type_comment = type_comment;
  561. }
  562. });
  563. this.registerType('ast.Import', class extends ast.stmt {
  564. constructor(names) {
  565. super();
  566. this.names = names;
  567. }
  568. });
  569. this.registerType('ast.ImportFrom', class extends ast.stmt {
  570. constructor(module, names, level) {
  571. super();
  572. this.module = module;
  573. this.names = names;
  574. this.level = level;
  575. }
  576. });
  577. this.registerType('ast.Assert', class extends ast.stmt {
  578. constructor(test, msg) {
  579. super();
  580. this.test = test;
  581. this.msg = msg;
  582. }
  583. });
  584. this.registerType('ast.Raise', class extends ast.stmt {
  585. constructor(exc, cause) {
  586. super();
  587. this.exc = exc;
  588. this.cause = cause;
  589. }
  590. });
  591. this.registerType('ast.With', class extends ast.stmt {
  592. constructor(items, body, type_comment) {
  593. super();
  594. this.items = items;
  595. this.body = body;
  596. this.type_comment = type_comment;
  597. }
  598. });
  599. this.registerType('ast.withitem', class extends ast.AST {
  600. constructor(context_expr, optional_vars) {
  601. super();
  602. this.context_expr = context_expr;
  603. this.optional_vars = optional_vars;
  604. }
  605. });
  606. this.registerType('ast.Global', class extends ast.stmt {
  607. constructor(names) {
  608. super();
  609. this.names = names;
  610. }
  611. });
  612. this.registerType('ast.Nonlocal', class extends ast.stmt {
  613. constructor(names) {
  614. super();
  615. this.names = names;
  616. }
  617. });
  618. this.registerType('ast.Continue', class extends ast.stmt {});
  619. this.registerType('ast.Break', class extends ast.stmt {});
  620. this.registerType('ast.Pass', class extends ast.stmt {});
  621. this.registerType('ast.Await', class extends ast.stmt {
  622. constructor(value) {
  623. super();
  624. this.value = value;
  625. }
  626. });
  627. this.registerType('ast.Module', class extends ast.mod {
  628. constructor(body, type_ignores) {
  629. super();
  630. this.body = body;
  631. this.type_ignores = type_ignores;
  632. }
  633. });
  634. this.registerFunction('ast.parse', (source, filename, mode, debug) => {
  635. const parser = new ast._Parser();
  636. const module = parser.parse(source, filename, debug, mode);
  637. return module;
  638. });
  639. this.registerFunction('ast._convert_literal', (node) => {
  640. if (node instanceof ast.Constant) {
  641. return node.value;
  642. }
  643. if (node instanceof ast.Dict && node.keys.length === node.values.length) {
  644. const keys = node.keys.map((k) => ast._convert_literal(k));
  645. const values = node.values.map((v) => ast._convert_literal(v));
  646. return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  647. }
  648. if (node instanceof ast.Tuple) {
  649. return new builtins.tuple(node.elts.map((e) => ast._convert_literal(e)));
  650. }
  651. if (node instanceof ast.List) {
  652. return new builtins.list(node.elts.map((e) => ast._convert_literal(e)));
  653. }
  654. throw new python.Error(`'${node.__class__.__name__}' not implemented.`);
  655. });
  656. this.registerFunction('ast.literal_eval', (node_or_string) => {
  657. if (typeof node_or_string === 'string') {
  658. node_or_string = ast.parse(node_or_string, '', 'eval').body;
  659. } else {
  660. throw new python.Error(`'ast.literal_eval' node eval not implemented.`);
  661. }
  662. return ast._convert_literal(node_or_string);
  663. });
  664. this.registerType('ast._Parser', class {
  665. constructor() {
  666. ast._Parser._precedence = ast._Parser._precedence || {
  667. 'or': 2, 'and': 3, 'not' : 4,
  668. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  669. '|': 6, '^' : 7, '&' : 8,
  670. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  671. // '+': 12, '-': 12,
  672. '~': 13, '**': 14
  673. };
  674. }
  675. parse(text, file, debug, mode) {
  676. this._tokenizer = new ast._Tokenizer(text, file);
  677. this._debug = debug;
  678. const position = this._position();
  679. let body = [];
  680. while (!this._tokenizer.match('eof')) {
  681. const statement = this._parseStatement();
  682. if (statement) {
  683. body.push(statement);
  684. continue;
  685. }
  686. if (this._tokenizer.accept('\n') || this._tokenizer.accept(';') || this._tokenizer.peek().type === 'eof') {
  687. continue;
  688. }
  689. if (this._tokenizer.accept('indent') && this._tokenizer.peek().type === 'eof') {
  690. continue;
  691. }
  692. throw new python.Error(`Unsupported statement ${this._location()}`);
  693. }
  694. if (mode === 'eval') {
  695. if (body.length !== 1 || body[0] instanceof ast.Expr === false) {
  696. throw new python.Error('Expected expression.');
  697. }
  698. body = body[0].value;
  699. }
  700. const module = new ast.Module(body);
  701. this._mark(module, position);
  702. return module;
  703. }
  704. _parseSuite() {
  705. const body = [];
  706. let statement = null;
  707. if (this._tokenizer.accept('\n')) {
  708. if (this._tokenizer.accept('indent')) {
  709. while (!this._tokenizer.accept('eof') && !this._tokenizer.accept('dedent')) {
  710. if (this._tokenizer.accept(';')) {
  711. continue;
  712. }
  713. statement = this._parseStatement();
  714. if (statement) {
  715. body.push(statement);
  716. continue;
  717. }
  718. if (this._tokenizer.accept('\n')) {
  719. continue;
  720. }
  721. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  722. continue;
  723. }
  724. throw new python.Error(`Empty statement ${this._location()}`);
  725. }
  726. }
  727. } else if (!this._tokenizer.accept('eof')) {
  728. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  729. if (this._tokenizer.accept(';')) {
  730. continue;
  731. }
  732. statement = this._parseStatement();
  733. if (statement) {
  734. body.push(statement);
  735. continue;
  736. }
  737. throw new python.Error(`Empty statement ${this._location()}`);
  738. }
  739. this._tokenizer.accept('\n');
  740. }
  741. return body;
  742. }
  743. _parseStatement() {
  744. let node = null;
  745. let position = this._position();
  746. if (this._eat('id', 'break')) {
  747. const node = new ast.Break();
  748. return this._mark(node, position);
  749. }
  750. if (this._eat('id', 'continue')) {
  751. const node = new ast.Continue();
  752. return this._mark(node, position);
  753. }
  754. if (this._eat('id', 'return')) {
  755. const value = this._parseExpression(-1, [], true);
  756. const node = new ast.Return(value);
  757. return this._mark(node, position);
  758. }
  759. if (this._eat('id', 'raise')) {
  760. let exc = this._parseExpression(-1, ['from']);
  761. let cause = null;
  762. if (this._tokenizer.accept('id', 'from')) {
  763. cause = this._parseExpression();
  764. } else if (this._tokenizer.accept(',')) {
  765. exc = [exc];
  766. exc.push(this._parseExpression());
  767. if (this._tokenizer.accept(',')) {
  768. exc.push(this._parseExpression());
  769. }
  770. }
  771. node = new ast.Raise(exc, cause);
  772. return this._mark(node, position);
  773. }
  774. if (this._eat('id', 'assert')) {
  775. const test = this._parseExpression(-1, [',']);
  776. let msg = null;
  777. if (this._tokenizer.accept(',')) {
  778. msg = this._parseExpression();
  779. }
  780. node = new ast.Assert(test, msg);
  781. return this._mark(node, position);
  782. }
  783. if (this._eat('id', 'global')) {
  784. const names = [];
  785. do {
  786. const name = this._parseName(true);
  787. names.push(name.id);
  788. }
  789. while (this._tokenizer.accept(','));
  790. const node = new ast.Global(names);
  791. return this._mark(node, position);
  792. }
  793. if (this._eat('id', 'nonlocal')) {
  794. const names = [];
  795. do {
  796. const name = this._parseName(true);
  797. names.push(name.id);
  798. }
  799. while (this._tokenizer.accept(','));
  800. const node = new ast.Nonlocal(names);
  801. return this._mark(node, position);
  802. }
  803. if (this._eat('id', 'import')) {
  804. const names = [];
  805. do {
  806. const name = this._parseDottedName();
  807. let asname = null;
  808. if (this._tokenizer.accept('id', 'as')) {
  809. asname = this._parseName(true).id;
  810. }
  811. const node = new ast.alias(name, asname);
  812. names.push(node);
  813. }
  814. while (this._tokenizer.accept(','));
  815. const node = new ast.Import(names);
  816. return this._mark(node, position);
  817. }
  818. if (this._eat('id', 'from')) {
  819. let level = 0;
  820. const dots = this._tokenizer.peek();
  821. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  822. this._eat(dots.type);
  823. level = Array.from(dots.type).length;
  824. }
  825. const module = this._parseDottedName();
  826. this._tokenizer.expect('id', 'import');
  827. const names = [];
  828. const close = this._tokenizer.accept('(');
  829. do {
  830. const name = this._parseName(true).id;
  831. let asname = null;
  832. if (this._tokenizer.accept('id', 'as')) {
  833. asname = this._parseName(true).id;
  834. }
  835. const node = new ast.alias(name, asname);
  836. names.push(node);
  837. }
  838. while (this._tokenizer.accept(','));
  839. if (close) {
  840. this._tokenizer.expect(')');
  841. }
  842. const node = new ast.ImportFrom(module, names, level);
  843. return this._mark(node, position);
  844. }
  845. const decorator_list = this._decorator();
  846. position = this._position();
  847. if (this._eat('id', 'class')) {
  848. const name = this._parseName(true);
  849. const bases = [];
  850. if (this._tokenizer.accept('(')) {
  851. while (!this._tokenizer.accept(')')) {
  852. if (this._tokenizer.accept('\n')) {
  853. continue;
  854. }
  855. const expression = this._parseExpression(-1, [], false);
  856. if (expression === null) {
  857. throw new python.Error(`Expected expression ${this._location()}`);
  858. }
  859. bases.push(expression);
  860. if (!this._tokenizer.accept(',')) {
  861. this._tokenizer.accept('\n');
  862. this._tokenizer.expect(')');
  863. break;
  864. }
  865. }
  866. }
  867. this._tokenizer.expect(':');
  868. const body = this._parseSuite();
  869. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  870. return this._mark(node, position);
  871. }
  872. const async = this._eat('id', 'async') !== null;
  873. if (async &&
  874. !this._tokenizer.match('id', 'def') &&
  875. !this._tokenizer.match('id', 'with') &&
  876. !this._tokenizer.match('id', 'for')) {
  877. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  878. }
  879. if (this._eat('id', 'def')) {
  880. const name = this._parseName(true);
  881. this._tokenizer.expect('(');
  882. const args = this._parseArguments(')');
  883. let returns = null;
  884. if (this._tokenizer.accept('->')) {
  885. returns = this._parseType();
  886. }
  887. this._tokenizer.expect(':');
  888. const body = this._parseSuite();
  889. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  890. if (async) {
  891. node.async = async;
  892. }
  893. return this._mark(node, position);
  894. }
  895. if (decorator_list && decorator_list.length > 0) {
  896. throw new python.Error('Unexpected decorator.');
  897. }
  898. if (this._eat('id', 'del')) {
  899. const targets = this._parseExpression(-1, [], true);
  900. node = new ast.Del(targets);
  901. return this._mark(node, position);
  902. }
  903. if (this._eat('id', 'if')) {
  904. const test = this._parseExpression();
  905. this._tokenizer.expect(':');
  906. const body = this._parseSuite();
  907. const node = new ast.If(test, body);
  908. let current = node;
  909. this._tokenizer.accept('\n');
  910. while (this._tokenizer.accept('id', 'elif')) {
  911. const test = this._parseExpression();
  912. this._tokenizer.expect(':');
  913. const body = this._parseSuite();
  914. current.orelse = new ast.If(test, body);
  915. current = current.orelse;
  916. this._tokenizer.accept('\n');
  917. }
  918. if (this._tokenizer.accept('id', 'else')) {
  919. this._tokenizer.expect(':');
  920. current.orelse = this._parseSuite();
  921. }
  922. return this._mark(node, position);
  923. }
  924. if (this._eat('id', 'while')) {
  925. const test = this._parseExpression();
  926. this._tokenizer.expect(':');
  927. const body = this._parseSuite();
  928. let orelse = null;
  929. if (this._tokenizer.accept('id', 'else')) {
  930. this._tokenizer.expect(':');
  931. orelse = this._parseSuite();
  932. }
  933. const node = new ast.While(test, body, orelse);
  934. return this._mark(node, position);
  935. }
  936. if (this._eat('id', 'pass')) {
  937. const node = new ast.Pass();
  938. return this._mark(node, position);
  939. }
  940. if (this._eat('id', 'for')) {
  941. let target = this._parseExpression(-1, ['in']);
  942. while (this._tokenizer.accept(',')) {
  943. if (target instanceof ast.Tuple === false) {
  944. target = new ast.Tuple([target]);
  945. }
  946. if (this._tokenizer.match('id', 'in')) {
  947. target.elts.push({});
  948. break;
  949. }
  950. target.elts.push(this._parseExpression(-1, ['in']));
  951. }
  952. this._tokenizer.expect('id', 'in');
  953. let iter = this._parseExpression();
  954. while (this._tokenizer.accept(',')) {
  955. if (iter.type !== 'tuple') {
  956. iter = new ast.Tuple([iter]);
  957. }
  958. if (this._tokenizer.match(':')) {
  959. iter.elts.push({});
  960. break;
  961. }
  962. iter.elts.push(this._parseExpression(-1, ['in']));
  963. }
  964. this._tokenizer.expect(':');
  965. const body = this._parseSuite();
  966. let orelse = null;
  967. if (this._tokenizer.accept('id', 'else')) {
  968. this._tokenizer.expect(':');
  969. orelse = this._parseSuite();
  970. }
  971. const node = new ast.For(target, iter, body, orelse);
  972. return this._mark(node, position);
  973. }
  974. if (this._eat('id', 'with')) {
  975. const items = [];
  976. do {
  977. const context_expr = this._parseExpression();
  978. let optional_vars = null;
  979. if (this._tokenizer.accept('id', 'as')) {
  980. optional_vars = this._parseExpression();
  981. }
  982. const node = new ast.withitem(context_expr, optional_vars);
  983. items.push(node);
  984. }
  985. while (this._tokenizer.accept(','));
  986. this._tokenizer.expect(':');
  987. const body = this._parseSuite();
  988. const node = new ast.With(items, body, null);
  989. if (async) {
  990. node.async = async;
  991. }
  992. return this._mark(node, position);
  993. }
  994. if (this._eat('id', 'try')) {
  995. this._tokenizer.expect(':');
  996. const body = this._parseSuite();
  997. const handlers = [];
  998. let orelse = null;
  999. let finalbody = null;
  1000. while (this._tokenizer.match('id', 'except')) {
  1001. this._tokenizer.expect('id', 'except');
  1002. const type = this._parseExpression();
  1003. const name = this._tokenizer.accept('id', 'as') ? this._parseExpression() : null;
  1004. this._tokenizer.expect(':');
  1005. const body = this._parseSuite();
  1006. const except = new ast.ExceptHandler(type, name, body);
  1007. handlers.push(except);
  1008. }
  1009. if (this._tokenizer.match('id', 'else')) {
  1010. this._tokenizer.expect('id', 'else');
  1011. this._tokenizer.expect(':');
  1012. orelse = this._parseSuite();
  1013. }
  1014. if (this._tokenizer.match('id', 'finally')) {
  1015. this._tokenizer.expect('id', 'finally');
  1016. this._tokenizer.expect(':');
  1017. finalbody = this._parseSuite();
  1018. }
  1019. const node = new ast.Try(body, handlers, orelse, finalbody);
  1020. return this._mark(node, position);
  1021. }
  1022. const expr = this._parseExpression(-1, [], true);
  1023. if (expr) {
  1024. if (expr instanceof ast.Name && this._tokenizer.accept(':')) {
  1025. const position = this._position();
  1026. const annotation = this._parseExpression(-1, ['=']);
  1027. let value = null;
  1028. if (this._tokenizer.accept('=')) {
  1029. value = this._parseExpression();
  1030. }
  1031. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  1032. return this._mark(node, position);
  1033. }
  1034. if (expr instanceof ast.stmt) {
  1035. return expr;
  1036. }
  1037. switch (expr.__class__.__name__) {
  1038. case 'AnnAssign':
  1039. case 'Assert':
  1040. case 'Assign':
  1041. case 'Attribute':
  1042. case 'AugAssign':
  1043. case 'Await':
  1044. case 'BinOp':
  1045. case 'Call':
  1046. case 'Compare':
  1047. case 'Constant':
  1048. case 'Dict':
  1049. case 'Ellipsis':
  1050. case 'For':
  1051. case 'If':
  1052. case 'Lambda':
  1053. case 'List':
  1054. case 'Name':
  1055. case 'NamedExpr':
  1056. case 'Raise':
  1057. case 'Subscript':
  1058. case 'Tuple':
  1059. case 'Yield':
  1060. // return expr;
  1061. return new ast.Expr(expr);
  1062. default:
  1063. throw new python.Error(`Unhandled expression ${this._location()}`);
  1064. }
  1065. }
  1066. return null;
  1067. }
  1068. _parseExpression(minPrecedence, terminal, tuple) {
  1069. minPrecedence = minPrecedence || -1;
  1070. const terminalSet = new Set(terminal);
  1071. const stack = [];
  1072. for (;;) {
  1073. let position = this._position();
  1074. let node = null;
  1075. const token = this._tokenizer.peek();
  1076. if (stack.length === 1 && terminalSet.has(token.value)) {
  1077. break;
  1078. }
  1079. const precedence = ast._Parser._precedence[token.value];
  1080. if (precedence) {
  1081. if (precedence >= minPrecedence) {
  1082. this._tokenizer.read();
  1083. if (token.value === 'not' && this._tokenizer.accept('id', 'in')) {
  1084. token.value = 'not in';
  1085. } else if (token.value === 'is' && this._tokenizer.accept('id', 'not')) {
  1086. token.value = 'is not';
  1087. }
  1088. if (stack.length > 0) {
  1089. let op = null;
  1090. switch (token.value) {
  1091. case '+': op = new ast.Add(); break;
  1092. case '-': op = new ast.Sub(); break;
  1093. case '*': op = new ast.Mult(); break;
  1094. case '/': op = new ast.Div(); break;
  1095. case '//': op = new ast.FloorDiv(); break;
  1096. case '**': op = new ast.Pow(); break;
  1097. case '@': op = new ast.MatMult(); break;
  1098. case '&': op = new ast.BitAnd(); break;
  1099. case '^': op = new ast.BitXor(); break;
  1100. case '|': op = new ast.BitOr(); break;
  1101. case '%': op = new ast.Mod(); break;
  1102. case '>>': op = new ast.RShift(); break;
  1103. case '<<': op = new ast.LShift(); break;
  1104. default: break;
  1105. }
  1106. if (op) {
  1107. const left = stack.pop();
  1108. const right = this._parseExpression(precedence, terminal, tuple === true);
  1109. node = new ast.BinOp(left, op, right);
  1110. } else {
  1111. switch (token.value) {
  1112. case '==': op = new ast.Eq(); break;
  1113. case '!=': op = new ast.NotEq(); break;
  1114. case '>=': op = new ast.GtE(); break;
  1115. case '<=': op = new ast.LtE(); break;
  1116. case '<': op = new ast.Lt(); break;
  1117. case '>': op = new ast.Gt(); break;
  1118. case 'is': op = new ast.Is(); break;
  1119. case 'is not': op = new ast.IsNot(); break;
  1120. case 'in': op = new ast.In(); break;
  1121. case 'not in': op = new ast.NotIn(); break;
  1122. default: break;
  1123. }
  1124. const left = stack.pop();
  1125. const comparator = this._parseExpression(precedence, ['for', 'if'], tuple === true);
  1126. node = new ast.Compare(left, [op], [comparator]);
  1127. }
  1128. } else if (token.value === '*') {
  1129. const value = this._parseExpression(precedence, terminal, tuple === true);
  1130. node = new ast.Starred(value);
  1131. } else if (token.value === '**') {
  1132. const value = this._parseExpression(precedence, terminal, tuple === true);
  1133. node = new ast.keyword(null, value);
  1134. } else {
  1135. let op = null;
  1136. switch (token.value) {
  1137. case '-': op = new ast.USub(); break;
  1138. case '+': op = new ast.UAdd(); break;
  1139. case '~': op = new ast.Invert(); break;
  1140. case 'not': op = new ast.Not(); break;
  1141. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1142. }
  1143. const operand = this._parseExpression(precedence, terminal, tuple === true);
  1144. node = new ast.UnaryOp(op, operand);
  1145. node = this._mark(node, position);
  1146. }
  1147. stack.push(node);
  1148. continue;
  1149. }
  1150. }
  1151. if (this._tokenizer.accept(':=')) {
  1152. const target = stack.pop();
  1153. const value = this._parseExpression(-1, terminal, tuple !== false);
  1154. const node = new ast.NamedExpr(target, value);
  1155. this._mark(node, position);
  1156. stack.push(node);
  1157. continue;
  1158. }
  1159. if (this._tokenizer.accept('=')) {
  1160. const position = this._position();
  1161. const targets = stack.pop();
  1162. const value = this._parseExpression(-1, terminal, tuple !== false);
  1163. const node = new ast.Assign([targets], value);
  1164. this._mark(node, position);
  1165. stack.push(node);
  1166. continue;
  1167. }
  1168. let op = null;
  1169. switch (token.type) {
  1170. case '+=': op = new ast.Add(); break;
  1171. case '-=': op = new ast.Sub(); break;
  1172. case '**=': op = new ast.Pow(); break;
  1173. case '*=': op = new ast.Mult(); break;
  1174. case '//=': op = new ast.FloorDiv(); break;
  1175. case '/=': op = new ast.Div(); break;
  1176. case '&=': op = new ast.BitAnd(); break;
  1177. case '%=': op = new ast.Mod(); break;
  1178. case '^=': op = new ast.BitXor(); break;
  1179. case '<<=': op = new ast.LShift(); break;
  1180. case '>>=': op = new ast.RShift(); break;
  1181. case '|=': op = new ast.BitOr(); break;
  1182. case '@=': op = new ast.MatMul(); break;
  1183. default: break;
  1184. }
  1185. if (op) {
  1186. this._tokenizer.expect(token.type);
  1187. const target = stack.pop();
  1188. const value = this._parseExpression(-1, terminal, true);
  1189. const node = new ast.AugAssign(target, op, value);
  1190. stack.push(node);
  1191. continue;
  1192. }
  1193. position = this._position();
  1194. if (this._eat('id', 'if')) {
  1195. const body = stack.pop();
  1196. const test = this._parseExpression();
  1197. this._tokenizer.expect('id', 'else');
  1198. const orelse = this._parseExpression();
  1199. const node = new ast.IfExp(test, body, orelse);
  1200. this._mark(node, position);
  1201. stack.push(node);
  1202. continue;
  1203. }
  1204. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1205. const position = this._position();
  1206. const elt = stack.pop();
  1207. const generators = this._parseGenerators();
  1208. let node = null;
  1209. if (elt instanceof ast.Dict) {
  1210. if (elt.keys.length !== 1 || elt.values.length !== 1) {
  1211. throw new python.Error(`Invalid dict comprehension ${this._location()}`);
  1212. }
  1213. node = new ast.DictComp(elt.keys[0], elt.values[0], generators);
  1214. } else if (elt instanceof ast.Set) {
  1215. if (elt.elts.length !== 1) {
  1216. throw new python.Error(`Invalid set comprehension ${this._location()}`);
  1217. }
  1218. node = new ast.SetComp(elt.elts[0], generators);
  1219. } else {
  1220. node = new ast.GeneratorExp(elt, generators);
  1221. }
  1222. this._mark(node, position);
  1223. stack.push(node);
  1224. continue;
  1225. }
  1226. if (this._eat('id', 'lambda')) {
  1227. const args = this._parseArguments(':');
  1228. const body = this._parseExpression(-1, terminal, false);
  1229. const node = new ast.Lambda(args, body);
  1230. this._mark(node, position);
  1231. stack.push(node);
  1232. continue;
  1233. }
  1234. if (this._eat('id', 'yield')) {
  1235. if (this._tokenizer.accept('id', 'from')) {
  1236. const value = this._parseExpression(-1, [], true);
  1237. node = new ast.YieldFrom(value);
  1238. stack.push(node);
  1239. } else {
  1240. const value = [];
  1241. do {
  1242. value.push(this._parseExpression(-1, [], false));
  1243. }
  1244. while (this._tokenizer.accept(','));
  1245. node = new ast.Yield(value);
  1246. stack.push(node);
  1247. }
  1248. continue;
  1249. }
  1250. if (this._eat('id', 'await')) {
  1251. const value = this._parseExpression(minPrecedence, terminal, tuple);
  1252. const node = new ast.Await(value);
  1253. this._mark(node, position);
  1254. stack.push(node);
  1255. continue;
  1256. }
  1257. if (this._eat('.')) {
  1258. const value = stack.pop();
  1259. const attr = this._parseName().id;
  1260. const node = new ast.Attribute(value, attr);
  1261. this._mark(node, position);
  1262. stack.push(node);
  1263. continue;
  1264. }
  1265. if (this._tokenizer.peek().type === '(') {
  1266. const position = this._position();
  1267. const args = [];
  1268. const keywords = [];
  1269. this._tokenizer.expect('(');
  1270. let tuple = false;
  1271. while (!this._tokenizer.accept(')')) {
  1272. if (this._tokenizer.accept('\n')) {
  1273. continue;
  1274. }
  1275. const position = this._position();
  1276. const expr = this._parseExpression(-1, [], false);
  1277. if (expr === null) {
  1278. throw new python.Error(`Expected expression ${this._location()}`);
  1279. }
  1280. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1281. const [target] = expr.targets;
  1282. if (target instanceof ast.Name === false) {
  1283. throw new python.Error(`Expected name ${this._location()}`);
  1284. }
  1285. const node = new ast.keyword(target.id, expr.value);
  1286. this._mark(node, position);
  1287. keywords.push(node);
  1288. } else {
  1289. args.push(expr);
  1290. }
  1291. if (this._tokenizer.accept(',')) {
  1292. tuple = true;
  1293. } else {
  1294. this._tokenizer.accept('\n');
  1295. this._tokenizer.expect(')');
  1296. break;
  1297. }
  1298. }
  1299. if (stack.length === 0 && keywords.length === 0) {
  1300. node = args.length === 1 && !tuple ? args[0] : new ast.Tuple(args);
  1301. this._mark(node, position);
  1302. } else {
  1303. const func = stack.pop();
  1304. node = new ast.Call(func, args, keywords);
  1305. let start = func;
  1306. while (start instanceof ast.Attribute) {
  1307. start = start.value;
  1308. }
  1309. position.lineno = start.lineno;
  1310. position.col_offset = start.col_offset;
  1311. this._mark(node, position);
  1312. }
  1313. stack.push(node);
  1314. continue;
  1315. }
  1316. if (this._tokenizer.peek().type === '[') {
  1317. if (stack.length === 0) {
  1318. stack.push(this._parseList());
  1319. } else {
  1320. const value = stack.pop();
  1321. const position = this._position();
  1322. const slice = this._parseSlice();
  1323. node = new ast.Subscript(value, slice);
  1324. this._mark(node, position);
  1325. stack.push(node);
  1326. }
  1327. continue;
  1328. }
  1329. if (this._tokenizer.peek().type === '{') {
  1330. const elts = [];
  1331. const keys = [];
  1332. const values = [];
  1333. this._tokenizer.expect('{');
  1334. let dict = true;
  1335. while (!this._tokenizer.accept('}')) {
  1336. const item = this._parseExpression(-1, [], false);
  1337. if (item === null) {
  1338. throw new python.Error(`Expected expression ${this._location()}`);
  1339. }
  1340. if (!this._tokenizer.accept(':')) {
  1341. dict = false;
  1342. }
  1343. if (dict) {
  1344. const value = this._parseExpression(-1, ['for'], false);
  1345. if (value === null) {
  1346. throw new python.Error(`Expected expression ${this._location()}`);
  1347. }
  1348. if (this._eat('id', 'for')) {
  1349. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1350. throw new python.Error(`Invalid list expression ${this._location()}`);
  1351. }
  1352. const target = this._parseExpression(-1, ['in'], true);
  1353. this._tokenizer.expect('id', 'in');
  1354. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1355. const ifs = [];
  1356. while (this._tokenizer.accept('id', 'if')) {
  1357. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1358. }
  1359. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1360. const generators = [comprehension];
  1361. this._tokenizer.expect('}');
  1362. return new ast.DictComp(item, value, generators);
  1363. }
  1364. keys.push(item);
  1365. values.push(value);
  1366. } else {
  1367. elts.push(item);
  1368. }
  1369. this._tokenizer.accept(',');
  1370. this._tokenizer.accept('\n');
  1371. if (this._tokenizer.accept('}')) {
  1372. break;
  1373. }
  1374. }
  1375. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1376. throw new python.Error(`Invalid set expression ${this._location()}`);
  1377. }
  1378. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1379. stack.push(node);
  1380. continue;
  1381. }
  1382. const literal = this._parseLiteral();
  1383. if (literal) {
  1384. if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1385. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1386. } else {
  1387. let value = literal.value;
  1388. switch (literal.type) {
  1389. case 'int':
  1390. case 'float':
  1391. value = value === 'inf' ? Infinity : Number(value);
  1392. break;
  1393. case 'complex':
  1394. value = new builtins.complex(0, Number(value.slice(0, -1)));
  1395. break;
  1396. case 'str':
  1397. value = value.substring(1, value.length - 1);
  1398. break;
  1399. default:
  1400. throw new python.Error(`Invalid literal type '${literal.type}' ${this._location()}`);
  1401. }
  1402. const node = new ast.Constant(value, literal.type);
  1403. this._mark(node, position);
  1404. stack.push(node);
  1405. }
  1406. continue;
  1407. }
  1408. if (this._eat('id', 'False')) {
  1409. const node = new ast.Constant(false, 'bool');
  1410. this._mark(node, position);
  1411. stack.push(node);
  1412. continue;
  1413. }
  1414. if (this._eat('id', 'True')) {
  1415. const node = new ast.Constant(true, 'bool');
  1416. this._mark(node, position);
  1417. stack.push(node);
  1418. continue;
  1419. }
  1420. if (this._eat('id', 'None')) {
  1421. const node = new ast.Constant(null);
  1422. this._mark(node, position);
  1423. stack.push(node);
  1424. continue;
  1425. }
  1426. if (this._tokenizer.peek().keyword) {
  1427. break;
  1428. }
  1429. if (this._eat('...')) {
  1430. const node = new ast.Ellipsis();
  1431. this._mark(node, position);
  1432. stack.push(node);
  1433. continue;
  1434. }
  1435. const name = this._parseName();
  1436. if (name) {
  1437. stack.push(name);
  1438. continue;
  1439. }
  1440. if (tuple === true && stack.length === 1 && this._tokenizer.accept(',')) {
  1441. if (stack[0] instanceof ast.Tuple) {
  1442. [node] = stack;
  1443. } else {
  1444. const position = this._position();
  1445. const elts = [stack.pop()];
  1446. node = new ast.Tuple(elts);
  1447. this._mark(node, position);
  1448. stack.push(node);
  1449. }
  1450. // for, bar, = <expr>
  1451. if (this._tokenizer.peek().type === '=') {
  1452. continue;
  1453. }
  1454. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1455. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1456. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1457. if (expression) {
  1458. node.elts.push(expression);
  1459. continue;
  1460. }
  1461. }
  1462. break;
  1463. }
  1464. break;
  1465. }
  1466. if (stack.length === 1) {
  1467. return stack.pop();
  1468. }
  1469. if (stack.length !== 0) {
  1470. throw new python.Error(`Unexpected expression ${this._location()}`);
  1471. }
  1472. return null;
  1473. }
  1474. _decorator() {
  1475. const list = [];
  1476. while (this._tokenizer.accept('@')) {
  1477. const value = this._parseExpression();
  1478. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1479. throw new python.Error(`Invalid decorator ${this._location()}`);
  1480. }
  1481. this._tokenizer.accept('\n');
  1482. list.push(value);
  1483. }
  1484. return list;
  1485. }
  1486. _parseGenerators() {
  1487. const generators = [];
  1488. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1489. const is_async = this._eat('id', 'async') ? 1 : 0;
  1490. this._tokenizer.expect('id', 'for');
  1491. const target = this._parseExpression(-1, ['in'], true);
  1492. this._tokenizer.expect('id', 'in');
  1493. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1494. const ifs = [];
  1495. while (this._tokenizer.accept('id', 'if')) {
  1496. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1497. }
  1498. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1499. generators.push(comprehension);
  1500. }
  1501. return generators;
  1502. }
  1503. _parseList() {
  1504. const elts = [];
  1505. this._tokenizer.expect('[');
  1506. if (!this._tokenizer.match(']')) {
  1507. const position = this._position();
  1508. const expr = this._parseExpression(-1, ['for']);
  1509. if (this._tokenizer.match('id', 'for')) {
  1510. const generators = this._parseGenerators();
  1511. this._tokenizer.expect(']');
  1512. const node = new ast.ListComp(expr, generators);
  1513. this._mark(node, position);
  1514. return node;
  1515. }
  1516. if (expr === null) {
  1517. throw new python.Error(`Expected expression ${this._location()}`);
  1518. }
  1519. elts.push(expr);
  1520. while (this._tokenizer.accept(',')) {
  1521. if (this._tokenizer.match(']')) {
  1522. break;
  1523. }
  1524. const expr = this._parseExpression(-1, ['for']);
  1525. if (!expr) {
  1526. throw new python.Error(`Expected expression ${this._location()}`);
  1527. }
  1528. elts.push(expr);
  1529. }
  1530. }
  1531. this._tokenizer.expect(']');
  1532. return new ast.List(elts);
  1533. }
  1534. _parseSlice() {
  1535. const elts = [];
  1536. let slice = [null, null, null];
  1537. let index = 0;
  1538. let valid = false;
  1539. this._tokenizer.expect('[');
  1540. while (true) {
  1541. if (this._tokenizer.accept(':')) {
  1542. index++;
  1543. valid = true;
  1544. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1545. if (!valid || index > 2) {
  1546. throw new python.Error(`Invalid slice at ${this._location()}`);
  1547. }
  1548. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1549. slice = [null, null, null];
  1550. index = 0;
  1551. if (this._tokenizer.accept(']')) {
  1552. break;
  1553. }
  1554. this._tokenizer.expect(',');
  1555. } else {
  1556. const expression = this._parseExpression();
  1557. if (expression === null) {
  1558. throw new python.Error(`Expected expression ${this._location()}`);
  1559. }
  1560. slice[index] = expression;
  1561. valid = true;
  1562. }
  1563. }
  1564. if (elts.length > 1) {
  1565. return new ast.Tuple(elts);
  1566. }
  1567. return elts[0];
  1568. }
  1569. _parseName(required) {
  1570. const token = this._tokenizer.peek();
  1571. if (token.type === 'id' && !token.keyword) {
  1572. const position = this._position();
  1573. this._tokenizer.read();
  1574. const node = new ast.Name(token.value);
  1575. return this._mark(node, position);
  1576. }
  1577. if (required) {
  1578. throw new python.Error(`Invalid syntax ${this._location()}`);
  1579. }
  1580. return null;
  1581. }
  1582. _parseDottedName() {
  1583. const list = [];
  1584. do {
  1585. const name = this._parseName(true);
  1586. list.push(name.id);
  1587. }
  1588. while (this._tokenizer.accept('.'));
  1589. return list.join('.');
  1590. }
  1591. _parseLiteral() {
  1592. const token = this._tokenizer.peek();
  1593. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1594. this._tokenizer.read();
  1595. return token;
  1596. }
  1597. return null;
  1598. }
  1599. _parseTypeArguments() {
  1600. const list = [];
  1601. this._tokenizer.expect('[');
  1602. while (!this._tokenizer.accept(']')) {
  1603. const type = this._parseType();
  1604. if (type === null) {
  1605. throw new python.Error(`Expected type ${this._location()}`);
  1606. }
  1607. list.push(type);
  1608. if (!this._tokenizer.accept(',')) {
  1609. this._tokenizer.expect(']');
  1610. break;
  1611. }
  1612. }
  1613. return list;
  1614. }
  1615. _parseType() {
  1616. const target = this._parseExpression(-1, ['[', '=']);
  1617. if (target) {
  1618. if (this._tokenizer.peek().value === '[') {
  1619. const list = this._parseList();
  1620. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1621. return new ast.Subscript(target, slice);
  1622. }
  1623. return target;
  1624. }
  1625. return null;
  1626. }
  1627. _parseArguments(terminal) {
  1628. let posonlyargs = [];
  1629. let args = [];
  1630. let vararg = null;
  1631. const kwonlyargs = [];
  1632. const kw_defaults = [];
  1633. let kwarg = null;
  1634. const defaults = [];
  1635. let is_slash = false;
  1636. let is_vararg = false; // '*'
  1637. let is_kwarg = false; // '**'
  1638. const read = (required) => {
  1639. const name = this._parseName(required);
  1640. if (name) {
  1641. const annotation = terminal !== ':' && this._tokenizer.accept(':') ? this._parseType() : null;
  1642. return new ast.arg(name.id, annotation, null);
  1643. }
  1644. return null;
  1645. };
  1646. while (!this._tokenizer.accept(terminal)) {
  1647. this._tokenizer.accept('\n');
  1648. if (this._tokenizer.accept('/')) {
  1649. if (is_slash || is_vararg || is_kwarg) {
  1650. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1651. }
  1652. is_slash = true;
  1653. } else if (this._tokenizer.accept('*')) {
  1654. if (is_vararg) {
  1655. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1656. }
  1657. is_vararg = true;
  1658. const arg = read(false);
  1659. vararg = arg ? arg : vararg;
  1660. } else if (this._tokenizer.accept('**')) {
  1661. if (is_kwarg) {
  1662. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1663. }
  1664. is_kwarg = true;
  1665. kwarg = read(true);
  1666. } else {
  1667. const arg = read(false);
  1668. if (!arg) {
  1669. this._tokenizer.expect(terminal);
  1670. break;
  1671. }
  1672. const default_value = this._tokenizer.accept('=') ? this._parseExpression() : null;
  1673. if (!is_vararg && !is_kwarg) {
  1674. if (is_slash) {
  1675. args.push(arg);
  1676. } else {
  1677. posonlyargs.push(arg);
  1678. }
  1679. if (default_value !== null) {
  1680. defaults.push(default_value);
  1681. }
  1682. } else if (is_vararg && !is_kwarg) {
  1683. kwonlyargs.push(arg);
  1684. kw_defaults.push(default_value);
  1685. } else {
  1686. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1687. }
  1688. }
  1689. this._tokenizer.accept('\n');
  1690. if (!this._tokenizer.accept(',')) {
  1691. this._tokenizer.expect(terminal);
  1692. break;
  1693. }
  1694. }
  1695. if (!is_slash) {
  1696. args = posonlyargs.concat(args);
  1697. posonlyargs = [];
  1698. }
  1699. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1700. }
  1701. _eat(type, value) {
  1702. if (this._tokenizer.match(type, value)) {
  1703. const position = this._position();
  1704. this._tokenizer.expect(type, value);
  1705. return position;
  1706. }
  1707. return null;
  1708. }
  1709. _mark(node, position) {
  1710. node.filename = position.filename;
  1711. node.lineno = position.lineno;
  1712. node.col_offset = position.col_offset;
  1713. node.end_lineno = this._tokenizer.lineno;
  1714. node.end_col_offset = this._tokenizer.col_offset;
  1715. return node;
  1716. }
  1717. _position() {
  1718. return {
  1719. filename: this._tokenizer.filename,
  1720. lineno: this._tokenizer.lineno,
  1721. col_offset: this._tokenizer.col_offset
  1722. };
  1723. }
  1724. _location() {
  1725. return this._tokenizer.location();
  1726. }
  1727. });
  1728. this.registerType('ast._Tokenizer', class {
  1729. constructor(text, file) {
  1730. this._text = text;
  1731. this.filename = file;
  1732. this.linepos = 0;
  1733. this.lineno = 1;
  1734. this._position = 0;
  1735. this._token = { type: '', value: '' };
  1736. this._brackets = 0;
  1737. this._indentation = [];
  1738. this._outdent = 0;
  1739. if (!ast._Tokenizer._whitespace) {
  1740. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1741. const identifierStartChars = '\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc';
  1742. const identifierChars = '\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f';
  1743. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1744. /* eslint-disable no-misleading-character-class */
  1745. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1746. /* eslint-enable no-misleading-character-class */
  1747. }
  1748. }
  1749. peek() {
  1750. if (!this._cache) {
  1751. this._tokenize();
  1752. this._cache = true;
  1753. }
  1754. return this._token;
  1755. }
  1756. read() {
  1757. if (!this._cache) {
  1758. this._tokenize();
  1759. }
  1760. const next = this._position + this._token.value.length;
  1761. while (this._position < next) {
  1762. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1763. this._position = this._newLine(this._position);
  1764. this.linepos = this._position;
  1765. this.lineno++;
  1766. } else {
  1767. this._position++;
  1768. }
  1769. }
  1770. this._cache = false;
  1771. return this._token;
  1772. }
  1773. match(type, value) {
  1774. const token = this.peek();
  1775. if (token.type === type && (!value || token.value === value)) {
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. accept(type, value) {
  1781. const token = this.peek();
  1782. if (token.type === type && (!value || token.value === value)) {
  1783. this.read();
  1784. return true;
  1785. }
  1786. return false;
  1787. }
  1788. expect(type, value) {
  1789. const token = this.peek();
  1790. if (token.type !== type) {
  1791. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1792. }
  1793. if (value && token.value !== value) {
  1794. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1795. }
  1796. this.read();
  1797. }
  1798. location() {
  1799. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1800. }
  1801. get col_offset() {
  1802. return this._position - this.linepos + 1;
  1803. }
  1804. static _isSpace(c) {
  1805. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1806. return true;
  1807. }
  1808. if (c.charCodeAt(0) >= 0x1680) {
  1809. return ast._Tokenizer._whitespace.test(c);
  1810. }
  1811. return false;
  1812. }
  1813. static _isNewline(c) {
  1814. switch (c) {
  1815. case '\n':
  1816. case '\r':
  1817. case '\u2028': // 8232
  1818. case '\u2029': // 8233
  1819. return true;
  1820. default:
  1821. return false;
  1822. }
  1823. }
  1824. static _isIdentifierStartChar(c) {
  1825. if (c < 'A') {
  1826. return c === '$';
  1827. }
  1828. if (c <= 'Z') {
  1829. return true;
  1830. }
  1831. if (c < 'a') {
  1832. return c === '_';
  1833. }
  1834. if (c <= 'z') {
  1835. return true;
  1836. }
  1837. const code = c.charCodeAt(0);
  1838. if (code >= 0xAA) {
  1839. return ast._Tokenizer._identifierStart.test(c);
  1840. }
  1841. return false;
  1842. }
  1843. static _isIdentifierChar(c) {
  1844. if (c < '0') {
  1845. return c === '$';
  1846. }
  1847. if (c <= '9') {
  1848. return true;
  1849. }
  1850. if (c < 'A') {
  1851. return false;
  1852. }
  1853. if (c <= 'Z') {
  1854. return true;
  1855. }
  1856. if (c < 'a') {
  1857. return c === '_';
  1858. }
  1859. if (c <= 'z') {
  1860. return true;
  1861. }
  1862. const code = c.charCodeAt(0);
  1863. if (code >= 0xAA) {
  1864. return ast._Tokenizer._identifierChar.test(c);
  1865. }
  1866. return false;
  1867. }
  1868. _get(position) {
  1869. return position >= this._text.length ? '\0' : this._text[position];
  1870. }
  1871. _skipLine() {
  1872. while (this._position < this._text.length) {
  1873. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1874. break;
  1875. }
  1876. this._position++;
  1877. }
  1878. }
  1879. _skipWhitespace() {
  1880. while (this._position < this._text.length) {
  1881. const c = this._text[this._position];
  1882. if (c === '#') {
  1883. this._skipLine();
  1884. } else if (ast._Tokenizer._isSpace(c)) {
  1885. this._position++;
  1886. } else if (c === '\\') {
  1887. // Explicit Line Continuation
  1888. this._position++;
  1889. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1890. this._position = this._newLine(this._position);
  1891. this.linepos = this._position;
  1892. this.lineno += 1;
  1893. } else {
  1894. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1895. }
  1896. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1897. // Implicit Line Continuation
  1898. this._position = this._newLine(this._position);
  1899. this.linepos = this._position;
  1900. this.lineno += 1;
  1901. } else {
  1902. break;
  1903. }
  1904. }
  1905. }
  1906. _newLine(position) {
  1907. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1908. return position + 2;
  1909. }
  1910. return position + 1;
  1911. }
  1912. _tokenize() {
  1913. if (this._token.type !== '\n') {
  1914. this._skipWhitespace();
  1915. }
  1916. if (this._token.type === 'dedent') {
  1917. this._indentation.pop();
  1918. this._outdent--;
  1919. if (this._outdent > 0) {
  1920. this._token = { type: 'dedent', value: '' };
  1921. return;
  1922. }
  1923. }
  1924. if (this._token.type === '\n') {
  1925. let indent = '';
  1926. let i = this._position;
  1927. while (i < this._text.length) {
  1928. const c = this._text[i];
  1929. if (ast._Tokenizer._isSpace(c)) {
  1930. indent += c;
  1931. i++;
  1932. } else if (ast._Tokenizer._isNewline(c)) {
  1933. indent = '';
  1934. i = this._newLine(i);
  1935. this._position = i;
  1936. this.linepos = i;
  1937. this.lineno += 1;
  1938. } else if (c === '#') {
  1939. indent = '';
  1940. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1941. i++;
  1942. }
  1943. continue;
  1944. } else {
  1945. break;
  1946. }
  1947. }
  1948. let type = null;
  1949. if (indent.length > 0) {
  1950. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1951. if (indent.length > current.length) {
  1952. type = 'indent';
  1953. this._indentation.push(indent);
  1954. } else if (indent.length > 0 && indent.length < current.length) {
  1955. type = 'dedent';
  1956. this._outdent = 0;
  1957. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1958. this._outdent++;
  1959. }
  1960. } else {
  1961. this._position += indent.length;
  1962. }
  1963. } else if (i >= this._text.length) {
  1964. this._token = { type: 'eof', value: '' };
  1965. return;
  1966. } else if (this._indentation.length > 0) {
  1967. type = 'dedent';
  1968. this._outdent = this._indentation.length;
  1969. }
  1970. if (type === 'indent' || type === 'dedent') {
  1971. this._token = { type, value: indent };
  1972. return;
  1973. }
  1974. }
  1975. if (this._position >= this._text.length) {
  1976. this._token = { type: 'eof', value: '' };
  1977. return;
  1978. }
  1979. const c = this._get(this._position);
  1980. const string = this._string();
  1981. if (string) {
  1982. this._token = string;
  1983. return;
  1984. }
  1985. switch (c) {
  1986. case '(':
  1987. case '[':
  1988. case '{':
  1989. this._brackets++;
  1990. this._token = { type: c, value: c };
  1991. return;
  1992. case ')':
  1993. case ']':
  1994. case '}':
  1995. if (this._brackets === 0) {
  1996. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  1997. }
  1998. this._brackets--;
  1999. this._token = { type: c, value: c };
  2000. return;
  2001. case ',':
  2002. case ';':
  2003. case '?':
  2004. this._token = { type: c, value: c };
  2005. return;
  2006. default: {
  2007. const number = this._number();
  2008. if (number) {
  2009. this._token = number;
  2010. return;
  2011. }
  2012. if (c === '.') {
  2013. let end = this._position + 1;
  2014. while (this._get(end) === '.') {
  2015. end++;
  2016. }
  2017. const text = this._text.substring(this._position, end);
  2018. this._token = { type: text, value: text };
  2019. return;
  2020. }
  2021. const identifier = this._identifier();
  2022. if (identifier) {
  2023. this._token = identifier;
  2024. return;
  2025. }
  2026. const operator = this._operator();
  2027. if (operator) {
  2028. this._token = operator;
  2029. return;
  2030. }
  2031. break;
  2032. }
  2033. }
  2034. if (c === '.') {
  2035. this._token = { type: c, value: c };
  2036. return;
  2037. }
  2038. if (c === '\\') {
  2039. this._token = { type: '\\', value: c };
  2040. return;
  2041. }
  2042. if (ast._Tokenizer._isNewline(c)) {
  2043. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2044. return;
  2045. }
  2046. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2047. }
  2048. _number() {
  2049. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2050. const binary = (c) => c === '0' || c === '1' || c === '_';
  2051. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2052. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2053. let c = this._get(this._position);
  2054. let i = this._position;
  2055. c = this._get(i);
  2056. if (c === '0') {
  2057. let radix = 0;
  2058. const n = this._get(i + 1);
  2059. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2060. i += 2;
  2061. while (hex(this._get(i))) {
  2062. i += 1;
  2063. }
  2064. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2065. i += 1;
  2066. }
  2067. radix = 16;
  2068. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2069. i += 2;
  2070. while (binary(this._get(i))) {
  2071. i++;
  2072. }
  2073. radix = 2;
  2074. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2075. i += 2;
  2076. while (octal(this._get(i))) {
  2077. i++;
  2078. }
  2079. radix = 8;
  2080. } else if (n >= '0' && n <= '7') {
  2081. i++;
  2082. while (octal(this._get(i))) {
  2083. i += 1;
  2084. }
  2085. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2086. i += 1;
  2087. }
  2088. radix = 8;
  2089. }
  2090. if (radix > 0 && this._get(i) !== '.') {
  2091. const radixText = this._text.substring(this._position, i);
  2092. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2093. if (!isNaN(parseInt(radixParseText, radix))) {
  2094. return { type: 'int', value: radixText };
  2095. }
  2096. }
  2097. }
  2098. i = this._position;
  2099. let isDecimal = false;
  2100. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2101. while (decimal(this._get(i))) {
  2102. i++;
  2103. }
  2104. c = this._get(i).toLowerCase();
  2105. isDecimal = c !== '.' && c !== 'e';
  2106. }
  2107. if (this._get(i) === '0') {
  2108. i++;
  2109. c = this._get(i).toLowerCase();
  2110. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2111. }
  2112. if (isDecimal) {
  2113. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2114. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2115. }
  2116. // if (this._get(i) === 'l' || this._get(i) === 'L') {
  2117. // Python 2 long integer
  2118. // }
  2119. const intText = this._text.substring(this._position, i);
  2120. if (!isNaN(parseInt(intText, 10))) {
  2121. return { type: 'int', value: intText };
  2122. }
  2123. }
  2124. i = this._position;
  2125. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2126. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2127. while (decimal(this._get(i))) {
  2128. i++;
  2129. }
  2130. if (this._get(i) === '.') {
  2131. i++;
  2132. }
  2133. while (decimal(this._get(i))) {
  2134. i++;
  2135. }
  2136. if (i > this._position) {
  2137. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2138. i++;
  2139. if (this._get(i) === '-' || this._get(i) === '+') {
  2140. i++;
  2141. }
  2142. if (decimal(this._get(i))) {
  2143. while (decimal(this._get(i))) {
  2144. i++;
  2145. }
  2146. } else {
  2147. i = this._position;
  2148. }
  2149. } else {
  2150. while (decimal(this._get(i))) {
  2151. i++;
  2152. }
  2153. }
  2154. }
  2155. if (i > this._position) {
  2156. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2157. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2158. }
  2159. const floatText = this._text.substring(this._position, i);
  2160. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2161. if (!isNaN(parseFloat(floatParseText))) {
  2162. return { type: 'float', value: floatText };
  2163. }
  2164. }
  2165. }
  2166. return null;
  2167. }
  2168. _identifier() {
  2169. let i = this._position;
  2170. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2171. i++;
  2172. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2173. i++;
  2174. }
  2175. }
  2176. if (i > this._position) {
  2177. const text = this._text.substring(this._position, i);
  2178. let keyword = false;
  2179. switch (text) {
  2180. case 'and':
  2181. case 'as':
  2182. case 'else':
  2183. case 'For':
  2184. case 'If':
  2185. case 'Import':
  2186. case 'in':
  2187. case 'is':
  2188. case 'not':
  2189. case 'or':
  2190. keyword = true;
  2191. break;
  2192. default:
  2193. break;
  2194. }
  2195. return { type: 'id', value: text, keyword };
  2196. }
  2197. return null;
  2198. }
  2199. _operator() {
  2200. let length = 0;
  2201. const c0 = this._get(this._position);
  2202. const c1 = this._get(this._position + 1);
  2203. const c2 = this._get(this._position + 2);
  2204. switch (c0) {
  2205. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2206. length = c1 === '=' ? 2 : 1;
  2207. break;
  2208. case '-':
  2209. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2210. break;
  2211. case '*':
  2212. switch (c1) {
  2213. case '*': length = c2 === '=' ? 3 : 2; break;
  2214. case '=': length = 2; break;
  2215. default: length = 1; break;
  2216. }
  2217. break;
  2218. case '/':
  2219. switch (c1) {
  2220. case '/': length = c2 === '=' ? 3 : 2; break;
  2221. case '=': length = 2; break;
  2222. default: length = 1; break;
  2223. }
  2224. break;
  2225. case '<':
  2226. switch (c1) {
  2227. case '>': length = 2; break;
  2228. case '<': length = c2 === '=' ? 3 : 2; break;
  2229. case '=': length = 2; break;
  2230. default: length = 1; break;
  2231. }
  2232. break;
  2233. case '>':
  2234. switch (c1) {
  2235. case '>': length = c2 === '=' ? 3 : 2; break;
  2236. case '=': length = 2; break;
  2237. default: length = 1; break;
  2238. }
  2239. break;
  2240. case '@':
  2241. length = c1 === '=' ? 2 : 1;
  2242. break;
  2243. case ':':
  2244. length = c1 === '=' ? 2 : 1;
  2245. break;
  2246. default:
  2247. return null;
  2248. }
  2249. const text = this._text.substring(this._position, this._position + length);
  2250. return { type: text, value: text };
  2251. }
  2252. _string() {
  2253. let i = this._position;
  2254. let prefix = -1;
  2255. if (this._get(i) === "'" || this._get(i) === '"') {
  2256. prefix = '';
  2257. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2258. const c = this._get(i);
  2259. const cc = c.toLowerCase();
  2260. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2261. prefix = c;
  2262. }
  2263. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2264. const c = this._text.substring(this._position, this._position + 2);
  2265. const cc = c.toLowerCase();
  2266. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2267. prefix = c;
  2268. }
  2269. }
  2270. if (prefix.length >= 0) {
  2271. i += prefix.length;
  2272. let quote = '';
  2273. let count = 0;
  2274. const q0 = this._get(i);
  2275. const q1 = this._get(i + 1);
  2276. const q2 = this._get(i + 2);
  2277. switch (q0) {
  2278. case "'":
  2279. quote = q0;
  2280. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2281. break;
  2282. case '"':
  2283. quote = q0;
  2284. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2285. break;
  2286. default:
  2287. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2288. }
  2289. i += count;
  2290. if (count === 1) {
  2291. while (i < this._text.length) {
  2292. if (this._text[i] === quote) {
  2293. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2294. } else if (this._text[i] === '\\' &&
  2295. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2296. i += 2;
  2297. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2298. break;
  2299. } else {
  2300. i++;
  2301. }
  2302. }
  2303. } else if (count === 3) {
  2304. while (i < this._text.length) {
  2305. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2306. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2307. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2308. i += 2;
  2309. continue;
  2310. }
  2311. i++;
  2312. }
  2313. }
  2314. }
  2315. i = this._position;
  2316. if (this._get(i) === '`') {
  2317. i++;
  2318. while (i < this._text.length) {
  2319. if (this._text[i] === '`') {
  2320. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2321. }
  2322. i++;
  2323. }
  2324. }
  2325. return null;
  2326. }
  2327. });
  2328. this.registerType('builtins.dict', dict);
  2329. this.registerType('builtins.ellipsis', class {});
  2330. this.registerType('builtins.cell', class {});
  2331. this.registerType('builtins.list', class extends Array {
  2332. constructor(iterable) {
  2333. super();
  2334. if (Array.isArray(iterable)) {
  2335. this.push(...iterable);
  2336. }
  2337. }
  2338. });
  2339. this.registerType('builtins.number', class {});
  2340. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2341. return execution.__import__(name, globals, locals, fromlist, level);
  2342. });
  2343. this.registerType('builtins.bool', class extends Boolean {
  2344. constructor(value) {
  2345. if (value && value.__bool__) {
  2346. value = value.__bool__();
  2347. } else if (value && value.__len__) {
  2348. value = value.__len__() > 0;
  2349. } else {
  2350. value = value ? true : false;
  2351. }
  2352. super(value);
  2353. }
  2354. });
  2355. this.registerType('builtins.int', class extends Number {
  2356. constructor(value) {
  2357. if (value && value.__int__) {
  2358. value = value.__int__();
  2359. } else if (!Number.isInteger(value)) {
  2360. value = NaN;
  2361. }
  2362. super(value);
  2363. }
  2364. });
  2365. this.registerType('builtins.float', class extends Number {
  2366. constructor(value) {
  2367. if (value && value.__float__) {
  2368. value = value.__float__();
  2369. } else if (Number(value) !== value) {
  2370. value = NaN;
  2371. }
  2372. super(value);
  2373. }
  2374. });
  2375. this.registerType('builtins.long', class extends Number {
  2376. constructor(value) {
  2377. if (value && value.__int__) {
  2378. value = value.__int__();
  2379. } else if (!Number.isInteger(value)) {
  2380. value = NaN;
  2381. }
  2382. super(value);
  2383. }
  2384. });
  2385. this.registerType('builtins.str', class extends String {
  2386. constructor(value) {
  2387. if (value && value.__str__) {
  2388. value = value.__str__();
  2389. } else if (typeof value !== 'string') {
  2390. value = JSON.stringify(value);
  2391. }
  2392. super(value);
  2393. }
  2394. });
  2395. this.registerType('builtins.complex', class {
  2396. constructor(real, imaginary) {
  2397. this.real = real;
  2398. this.imag = imaginary;
  2399. }
  2400. toString() {
  2401. return `${this.real}${this.imag < 0 ? '' : '+'}${this.imag}j`;
  2402. }
  2403. });
  2404. this.registerType('builtins.NoneType', class {});
  2405. this.registerType('builtins.object', class {
  2406. static __new__(cls, ...args) {
  2407. return execution.invoke(cls, args);
  2408. }
  2409. static __setattr__(obj, name, value) {
  2410. builtins.setattr(obj, name, value);
  2411. }
  2412. });
  2413. this.registerType('builtins.tuple', class extends Array {
  2414. constructor(items) {
  2415. super(items ? items.length : 0);
  2416. if (items) {
  2417. for (let i = 0; i < items.length; i++) {
  2418. this[i] = items[i];
  2419. }
  2420. }
  2421. }
  2422. });
  2423. this.registerType('builtins.staticmethod', class {});
  2424. this.registerType('builtins.Warning', class {});
  2425. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2426. this.registerType('builtins.BaseException', class {});
  2427. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2428. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2429. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2430. this.registerFunction('builtins.print', () => {});
  2431. this.registerFunction('builtins.unicode');
  2432. builtins.Ellipsis = new builtins.ellipsis();
  2433. this.registerType('typing._Final', class {});
  2434. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2435. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2436. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2437. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2438. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2439. this.registerType('typing._CallableType', class {});
  2440. this.registerFunction('typing.cast');
  2441. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2442. typing.Callable = Reflect.construct(typing._CallableType, []);
  2443. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2444. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2445. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2446. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2447. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2448. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2449. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2450. this.registerType('enum.Enum', class {
  2451. // __reduce_ex__(proto) {
  2452. // return self.__class__, (self._value_, )
  2453. // }
  2454. });
  2455. this.registerFunction('operator.add');
  2456. this.registerFunction('operator.and_');
  2457. this.registerFunction('operator.and_');
  2458. this.registerFunction('operator.eq');
  2459. this.registerFunction('operator.floordiv');
  2460. this.registerFunction('operator.ge');
  2461. this.registerFunction('operator.getitem');
  2462. this.registerFunction('operator.gt');
  2463. this.registerFunction('operator.le');
  2464. this.registerFunction('operator.lt');
  2465. this.registerFunction('operator.mod');
  2466. this.registerFunction('operator.mul');
  2467. this.registerFunction('operator.ne');
  2468. this.registerFunction('operator.neg');
  2469. this.registerFunction('operator.or_');
  2470. this.registerFunction('operator.pos');
  2471. this.registerFunction('operator.pow');
  2472. this.registerFunction('operator.sub');
  2473. this.registerFunction('operator.truediv');
  2474. this.registerFunction('sys.path.append', () => {});
  2475. this.registerFunction('sys.path.insert', () => {});
  2476. this.registerType('argparse.Namespace', class {
  2477. constructor(args) {
  2478. this.args = args;
  2479. }
  2480. });
  2481. this.registerType('catboost._catboost._CatBoost', class {
  2482. _deserialize_model(/* serialized_model_str */) {
  2483. }
  2484. });
  2485. this.registerType('catboost.core._CatBoostBase', class {
  2486. constructor() {
  2487. this._object = new catboost._catboost._CatBoost();
  2488. }
  2489. __setstate__(state) {
  2490. for (const [key, value] of state) {
  2491. if (key === '__model') {
  2492. this._load_from_string(value);
  2493. continue;
  2494. }
  2495. this[key] = value;
  2496. }
  2497. }
  2498. _load_from_string(dump_model_str) {
  2499. this._deserialize_model(dump_model_str);
  2500. }
  2501. _deserialize_model(dump_model_str) {
  2502. this._object._deserialize_model(dump_model_str);
  2503. }
  2504. });
  2505. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2506. load_model(/* blob */) {
  2507. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2508. // this._load_from_string(blob);
  2509. }
  2510. });
  2511. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2512. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2513. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2514. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2515. catboost.CatBoost = catboost.core.CatBoost;
  2516. this.registerType('collections.deque', class extends Array {
  2517. constructor(iterable) {
  2518. super();
  2519. if (Array.isArray(iterable)) {
  2520. for (const value of iterable) {
  2521. this.push(value);
  2522. }
  2523. }
  2524. }
  2525. });
  2526. this.registerType('collections.OrderedDict', class extends dict {});
  2527. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2528. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2529. this.registerType('cuml.internals.array.CumlArray', class {});
  2530. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2531. this.registerType('cuml.raft.common.handle.Handle', class {
  2532. __setstate__(state) {
  2533. this._handle = state;
  2534. }
  2535. });
  2536. this.registerType('cuml.svm.svr.SVR', class {});
  2537. this.registerType('datetime.date', class {});
  2538. this.registerType('datetime.datetime', class extends datetime.date {});
  2539. this.registerType('datetime.timedelta', class {});
  2540. this.registerType('datetime.tzinfo', class {});
  2541. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2542. this.registerType('dnnlib.tflib.network.Network', class {});
  2543. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2544. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2545. constructor(dict) {
  2546. Object.assign(this, dict);
  2547. }
  2548. });
  2549. this.registerType('haiku._src.data_structures.frozendict', class {
  2550. constructor(obj) {
  2551. Object.assign(this, obj);
  2552. }
  2553. });
  2554. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2555. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2556. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2557. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2558. this.registerType('io.BytesIO', class {
  2559. constructor(buf, mode) {
  2560. this.mode = mode || 'r';
  2561. this._buf = this.mode === 'w' ? null : buf;
  2562. this._point = 0;
  2563. }
  2564. seek(offset) {
  2565. if (this._buf.seek) {
  2566. this._buf.seek(offset);
  2567. }
  2568. this._point = offset;
  2569. }
  2570. read(size, stream) {
  2571. if (this._buf.stream && stream) {
  2572. return this._buf.stream(size);
  2573. }
  2574. if (this._buf.peek) {
  2575. return this._buf.read(size);
  2576. }
  2577. if (this._buf instanceof Uint8Array) {
  2578. const start = this._point;
  2579. this._point = size === undefined ? this._buf.length : start + size;
  2580. return this._buf.subarray(start, this._point);
  2581. }
  2582. throw new python.Error('Unsupported buffer type.');
  2583. }
  2584. write(data) {
  2585. const src = this._buf || new Uint8Array();
  2586. const end = this._point + data.length;
  2587. const size = Math.max(src.length, end);
  2588. this._buf = new Uint8Array(size);
  2589. this._buf.set(src, 0);
  2590. this._buf.set(data, this._point);
  2591. this._point = end;
  2592. }
  2593. getbuffer() {
  2594. return new builtins.memoryview(this._buf);
  2595. }
  2596. });
  2597. this.registerType('io.StringIO', class {
  2598. constructor() {
  2599. this._buf = [];
  2600. }
  2601. write(text) {
  2602. this._buf.push(text);
  2603. }
  2604. toString() {
  2605. return this._buf.join('');
  2606. }
  2607. });
  2608. this.registerType('numpy.dtype', class {
  2609. constructor(obj, align, copy) {
  2610. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2611. this.kind = 'V';
  2612. this.byteorder = '|';
  2613. this.itemsize = obj.itemsize;
  2614. this.names = obj.names;
  2615. this.fields = new Map();
  2616. for (let i = 0; i < obj.names.length; i++) {
  2617. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2618. }
  2619. return;
  2620. }
  2621. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2622. this.byteorder = obj.substring(0, 1);
  2623. obj = obj.substring(1);
  2624. } else {
  2625. this.byteorder = '=';
  2626. }
  2627. switch (obj) {
  2628. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2629. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2630. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2631. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2632. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2633. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2634. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2635. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2636. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2637. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2638. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2639. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2640. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2641. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2642. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2643. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2644. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2645. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2646. default:
  2647. if (obj.startsWith('V')) {
  2648. this.itemsize = parseInt(obj.substring(1), 10);
  2649. this.kind = 'V';
  2650. } else if (obj.startsWith('O')) {
  2651. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2652. this.kind = 'O';
  2653. } else if (obj.startsWith('S')) {
  2654. this.itemsize = parseInt(obj.substring(1), 10);
  2655. this.kind = 'S';
  2656. } else if (obj.startsWith('U')) { // Unicode string
  2657. this.kind = 'U';
  2658. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2659. } else if (obj.startsWith('T')) {
  2660. this.kind = 'T';
  2661. this.itemsize = parseInt(obj.substring(1), 10);
  2662. } else {
  2663. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2664. }
  2665. break;
  2666. }
  2667. if (align) {
  2668. this.align = align;
  2669. }
  2670. if (copy) {
  2671. this.copy = copy;
  2672. }
  2673. }
  2674. get str() {
  2675. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2676. }
  2677. get name() {
  2678. switch (this.kind) {
  2679. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2680. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2681. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2682. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2683. case 'M': return 'datetime64';
  2684. case 'm': return 'timedelta64';
  2685. case 'b': return 'bool';
  2686. default: return this.__name__;
  2687. }
  2688. }
  2689. __setstate__(state) {
  2690. switch (state.length) {
  2691. case 8:
  2692. [
  2693. this.version, this.byteorder, this.subarray, this.names,
  2694. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2695. ] = state;
  2696. break;
  2697. case 9:
  2698. [
  2699. this.version, this.byteorder, this.subarray, this.names,
  2700. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2701. this.metadata
  2702. ] = state;
  2703. break;
  2704. default:
  2705. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2706. }
  2707. }
  2708. get __name__() {
  2709. switch (this.kind) {
  2710. case 'b':
  2711. switch (this.itemsize) {
  2712. case 1: return 'boolean';
  2713. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2714. }
  2715. case 'i':
  2716. switch (this.itemsize) {
  2717. case 1: return 'int8';
  2718. case 2: return 'int16';
  2719. case 4: return 'int32';
  2720. case 8: return 'int64';
  2721. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2722. }
  2723. case 'u':
  2724. switch (this.itemsize) {
  2725. case 1: return 'uint8';
  2726. case 2: return 'uint16';
  2727. case 4: return 'uint32';
  2728. case 8: return 'uint64';
  2729. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2730. }
  2731. case 'f':
  2732. switch (this.itemsize) {
  2733. case 1: return 'float8e5m2';
  2734. case 2: return 'float16';
  2735. case 4: return 'float32';
  2736. case 8: return 'float64';
  2737. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2738. }
  2739. case 'c':
  2740. switch (this.itemsize) {
  2741. case 8: return 'complex<float32>';
  2742. case 16: return 'complex<float64>';
  2743. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2744. }
  2745. case 'S':
  2746. case 'T':
  2747. return 'string';
  2748. case 'U':
  2749. return 'string';
  2750. case 'M':
  2751. return 'datetime';
  2752. case 'm':
  2753. return 'timedelta';
  2754. case 'O':
  2755. return 'object';
  2756. case 'V':
  2757. return 'void';
  2758. default:
  2759. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2760. }
  2761. }
  2762. });
  2763. this.registerType('numpy.generic', class {});
  2764. this.registerType('numpy.inexact', class {});
  2765. this.registerType('numpy.flexible', class extends numpy.generic {});
  2766. this.registerType('numpy.void', class extends numpy.flexible {});
  2767. this.registerType('numpy.bool_', class extends numpy.generic {});
  2768. this.registerType('numpy.number', class extends numpy.generic {});
  2769. this.registerType('numpy.integer', class extends numpy.number {});
  2770. this.registerType('numpy.floating', class extends numpy.inexact {});
  2771. this.registerType('numpy.float16', class extends numpy.floating {});
  2772. this.registerType('numpy.float32', class extends numpy.floating {});
  2773. this.registerType('numpy.float64', class extends numpy.floating {});
  2774. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2775. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2776. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2777. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2778. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2779. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2780. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2781. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2782. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2783. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2784. this.registerType('numpy.datetime64', class extends numpy.generic {
  2785. constructor(...args) {
  2786. super();
  2787. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2788. [this.buffer] = args;
  2789. }
  2790. }
  2791. toString() {
  2792. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2793. const value = view.getBigInt64(0, true);
  2794. if (value === -9223372036854775808n) {
  2795. return 'NaT';
  2796. }
  2797. const date = new Date(Number(value / 1000000n));
  2798. return date.toISOString().slice(0, -1);
  2799. }
  2800. });
  2801. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2802. constructor() {
  2803. super('|T16');
  2804. }
  2805. });
  2806. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2807. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2808. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2809. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2810. this.registerType('gensim.models.fasttext.FastText', class {});
  2811. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2812. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2813. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2814. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2815. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2816. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2817. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2818. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2819. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2820. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2821. this.registerFunction('gensim.models.phrases.original_scorer');
  2822. this.registerType('gensim.models.phrases.Phraser', class {});
  2823. this.registerType('gensim.models.phrases.Phrases', class {});
  2824. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2825. this.registerType('gensim.models.word2vec.Vocab', class {});
  2826. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2827. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2828. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2829. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2830. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2831. throw new builtins.AttributeError('This method should be called on a class object.');
  2832. });
  2833. this.registerFunction('gensim.utils.identity');
  2834. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2835. constructor(obj) {
  2836. Object.assign(this, obj);
  2837. }
  2838. });
  2839. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2840. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2841. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2842. __read__(unpickler) {
  2843. if (this.dtype.__name__ === 'object') {
  2844. return unpickler.load();
  2845. }
  2846. if (this.numpy_array_alignment_bytes) {
  2847. const [size] = unpickler.read(1);
  2848. unpickler.read(size);
  2849. }
  2850. if (this.order === 'F') {
  2851. throw new python.Error('Fortran order not implemented.');
  2852. }
  2853. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2854. this.data = unpickler.read(size);
  2855. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2856. }
  2857. });
  2858. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2859. __setstate__(state) {
  2860. this.subclass = state.get('subclass');
  2861. this.filename = state.get('state');
  2862. this.allow_mmap = state.get('allow_mmap');
  2863. }
  2864. __read__(/* unpickler */) {
  2865. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2866. }
  2867. });
  2868. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2869. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2870. this.registerType('keras.engine.sequential.Sequential', class {});
  2871. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2872. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2873. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2874. this.registerType('lasagne.layers.input.InputLayer', class {});
  2875. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2876. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2877. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2878. this.registerType('lightgbm.basic.Booster', class {
  2879. constructor() {
  2880. this.average_output = false;
  2881. this.models = [];
  2882. this.loaded_parameter = '';
  2883. }
  2884. __setstate__(state) {
  2885. const model_str = state.get('_handle', state.get('handle', null));
  2886. if (model_str) {
  2887. this.LoadModelFromString(model_str);
  2888. return;
  2889. }
  2890. for (const [key, value] of state) {
  2891. this[key] = value;
  2892. }
  2893. }
  2894. LoadModelFromString(model_str) {
  2895. const lines = model_str.split('\n');
  2896. const signature = lines.shift() || '?';
  2897. if (signature.trim() !== 'tree') {
  2898. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2899. }
  2900. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2901. const key_vals = new Map();
  2902. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2903. const cur_line = lines.shift().trim();
  2904. if (cur_line.length > 0) {
  2905. const strs = cur_line.split('=');
  2906. if (strs.length === 1) {
  2907. key_vals.set(strs[0], '');
  2908. } else if (strs.length === 2) {
  2909. key_vals.set(strs[0], strs[1]);
  2910. } else if (strs.length > 2) {
  2911. if (strs[0] === "feature_names") {
  2912. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2913. } else if (strs[0] === 'monotone_constraints') {
  2914. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2915. } else {
  2916. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2917. }
  2918. }
  2919. }
  2920. }
  2921. const atoi = (key, value) => {
  2922. if (key_vals.has(key)) {
  2923. return parseInt(key_vals.get(key), 10);
  2924. }
  2925. if (value !== undefined) {
  2926. return value;
  2927. }
  2928. throw new python.Error(`Model file does not specify ${key}.`);
  2929. };
  2930. const list = (key, size) => {
  2931. if (key_vals.has(key)) {
  2932. const value = key_vals.get(key).split(' ');
  2933. if (value.length !== size) {
  2934. throw new python.Error(`Wrong size of ${key}.`);
  2935. }
  2936. return value;
  2937. }
  2938. throw new python.Error(`Model file does not contain ${key}.`);
  2939. };
  2940. this.version = key_vals.get('version') || '';
  2941. this.num_class = atoi('num_class');
  2942. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2943. this.label_index = atoi('label_index');
  2944. this.max_feature_idx = atoi('max_feature_idx');
  2945. if (key_vals.has('average_output')) {
  2946. this.average_output = true;
  2947. }
  2948. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2949. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2950. if (key_vals.has('monotone_constraints')) {
  2951. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2952. }
  2953. if (key_vals.has('objective')) {
  2954. this.objective = key_vals.get('objective');
  2955. }
  2956. let tree = null;
  2957. while (lines.length > 0) {
  2958. const text = lines.shift();
  2959. const line = text.trim();
  2960. if (line.length === 0) {
  2961. continue;
  2962. }
  2963. if (line.startsWith('Tree=')) {
  2964. tree = { index: parseInt(line.split('=').pop(), 10) };
  2965. this.models.push(tree);
  2966. continue;
  2967. }
  2968. if (line === 'end of trees') {
  2969. break;
  2970. }
  2971. const param = line.split('=');
  2972. if (param.length !== 2) {
  2973. throw new python.Error(`Invalid property '${line}'.`);
  2974. }
  2975. const name = param[0].trim();
  2976. const value = param[1].trim();
  2977. tree[name] = value;
  2978. }
  2979. const ss = [];
  2980. let is_inparameter = false;
  2981. while (lines.length > 0) {
  2982. const text = lines.shift();
  2983. const line = text.trim();
  2984. if (line === 'parameters:') {
  2985. is_inparameter = true;
  2986. continue;
  2987. } else if (line === 'end of parameters') {
  2988. break;
  2989. } else if (is_inparameter) {
  2990. ss.push(line);
  2991. }
  2992. }
  2993. if (ss.length > 0) {
  2994. this.loaded_parameter = ss.join('\n');
  2995. }
  2996. }
  2997. });
  2998. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2999. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  3000. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  3001. this.registerFunction('megengine.functional.nn.relu', () => {});
  3002. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3003. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3004. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3005. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3006. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3007. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3008. this.registerFunction('megengine.functional.tensor.full', () => {});
  3009. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3010. this.registerFunction('megengine.functional.tensor.split', () => {});
  3011. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3012. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3013. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3014. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3015. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3016. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3017. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3018. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3019. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3020. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3021. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3022. this.registerType('megengine.distributed.group.Group', class {});
  3023. this.registerType('megengine.module.activation.ReLU', class {});
  3024. this.registerType('megengine.module.activation.Softmax', class {});
  3025. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3026. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3027. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3028. this.registerType('megengine.module.conv.Conv2d', class {});
  3029. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3030. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3031. this.registerType('megengine.module.dropout.Dropout', class {});
  3032. this.registerType('megengine.module.identity.Identity', class {});
  3033. this.registerType('megengine.module.linear.Linear', class {});
  3034. this.registerType('megengine.module.module.Module', class {});
  3035. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3036. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3037. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3038. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3039. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3040. this.registerType('megengine.module.qat.concat.Concat', class {});
  3041. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3042. this.registerType('megengine.module.sequential.Sequential', class {});
  3043. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3044. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3045. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3046. this.registerType('megengine.quantization.utils.QParams', class {});
  3047. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3048. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3049. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3050. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3051. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3052. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3053. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3054. this.registerType('megengine.traced_module.expr.Apply', class {});
  3055. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3056. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3057. this.registerType('megengine.traced_module.expr.Constant', class {});
  3058. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3059. this.registerType('megengine.traced_module.expr.Input', class {});
  3060. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3061. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3062. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3063. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3064. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3065. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3066. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3067. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3068. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3069. this.registerType('megengine.tensor.Parameter', class {
  3070. constructor(data, dtype, device) {
  3071. this.data = data;
  3072. this.dtype = dtype;
  3073. this.device = device;
  3074. }
  3075. });
  3076. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3077. toString() {
  3078. let content = '';
  3079. for (const child of this.children_defs) {
  3080. content += `${child},`;
  3081. }
  3082. if (typeof this.type === "string") {
  3083. return `${this.type.split(".").slice(-1)}(${content})`;
  3084. }
  3085. return `${this.type.__name__}(${content})`;
  3086. }
  3087. });
  3088. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3089. toString() {
  3090. let content = '';
  3091. if (this.const_val === null) {
  3092. content += '[';
  3093. } else {
  3094. content += this.const_val;
  3095. }
  3096. for (const t of Object.values(this.type)) {
  3097. content += t.__name__;
  3098. }
  3099. content += ']';
  3100. return content;
  3101. }
  3102. });
  3103. this.registerType('megengine.tensor.Tensor', class {
  3104. constructor(data, dtype, device) {
  3105. this.data = data;
  3106. this.dtype = dtype;
  3107. this.device = device;
  3108. }
  3109. });
  3110. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3111. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3112. this.name = name;
  3113. this.cname = cname;
  3114. this.np_dtype = np_dtype;
  3115. this.qmin = qmin;
  3116. this.qmax = qmax;
  3117. this.is_signed = is_signed;
  3118. }
  3119. });
  3120. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3121. this.registerType('nolearn.lasagne.base.Layers', class {});
  3122. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3123. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3124. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3125. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3126. this.registerType('numpy.ndarray', class {
  3127. constructor(shape, dtype, buffer, offset, strides, order) {
  3128. this.shape = shape;
  3129. this.dtype = dtype;
  3130. this.data = buffer === undefined ? null : buffer;
  3131. this.offset = offset === undefined ? 0 : offset;
  3132. this._strides = strides === undefined ? null : strides;
  3133. this.order = order === undefined ? null : order;
  3134. this.flags = {};
  3135. this._read();
  3136. }
  3137. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3138. return new cls(shape, dtype, buffer, offset, strides, order);
  3139. }
  3140. __setstate__(state) {
  3141. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3142. this._read();
  3143. }
  3144. flatten() {
  3145. const size = this.shape.reduce((a, b) => a * b, 1);
  3146. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3147. value.flags = this.flags;
  3148. return value;
  3149. }
  3150. reshape(shape, order) {
  3151. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3152. }
  3153. tobytes() {
  3154. return this.data;
  3155. }
  3156. tolist() {
  3157. if (this.shape.length < 0 || this.shape.length > 1) {
  3158. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3159. }
  3160. const size = this.shape.reduce((a, b) => a * b, 1);
  3161. const list = new Array(size);
  3162. switch (this.dtype.kind) {
  3163. case 'U': {
  3164. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3165. const itemsize = this.dtype.itemsize >> 2;
  3166. let offset = 0;
  3167. for (let i = 0; i < size; i++) {
  3168. const buffer = data.subarray(offset, offset + itemsize);
  3169. const index = buffer.indexOf(0);
  3170. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3171. offset += itemsize;
  3172. }
  3173. return list;
  3174. }
  3175. case 'S': {
  3176. const data = this.data;
  3177. const itemsize = this.dtype.itemsize;
  3178. const decoder = new TextDecoder('utf-8');
  3179. let offset = 0;
  3180. for (let i = 0; i < size; i++) {
  3181. const buffer = data.subarray(offset, offset + itemsize);
  3182. const index = buffer.indexOf(0);
  3183. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3184. offset += itemsize;
  3185. }
  3186. return list;
  3187. }
  3188. case 'V': {
  3189. const itemsize = this.dtype.itemsize;
  3190. let offset = 0;
  3191. for (let i = 0; i < size; i++) {
  3192. list[i] = this.data.slice(offset, offset + itemsize);
  3193. offset += itemsize;
  3194. }
  3195. return list;
  3196. }
  3197. case 'M': {
  3198. const itemsize = this.dtype.itemsize;
  3199. let offset = 0;
  3200. for (let i = 0; i < size; i++) {
  3201. const buffer = this.data.slice(offset, offset + itemsize);
  3202. list[i] = new numpy.datetime64(buffer);
  3203. offset += itemsize;
  3204. }
  3205. return list;
  3206. }
  3207. case 'T': {
  3208. return this.data;
  3209. }
  3210. case 'O': {
  3211. return this.data;
  3212. }
  3213. default: {
  3214. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3215. }
  3216. }
  3217. }
  3218. get itemsize() {
  3219. return this.dtype.itemsize;
  3220. }
  3221. get size() {
  3222. return (this.shape || []).reduce((a, b) => a * b, 1);
  3223. }
  3224. get strides() {
  3225. if (!this._strides) {
  3226. const shape = this.shape;
  3227. const strides = new Array(shape.length);
  3228. let stride = this.itemsize;
  3229. for (let i = shape.length - 1; i >= 0; i--) {
  3230. strides[i] = stride;
  3231. stride *= shape[i];
  3232. }
  3233. return strides;
  3234. }
  3235. return this._strides;
  3236. }
  3237. _read() {
  3238. if (this.data) {
  3239. const length = this.dtype.itemsize * this.size;
  3240. if (typeof this.data === 'string') {
  3241. this.data = this._unescape(this.data, length);
  3242. if (this.data.length !== length) {
  3243. throw new python.Error('Invalid string array data size.');
  3244. }
  3245. } else if (this.data.length !== length) {
  3246. // throw new python.Error('Invalid array data size.');
  3247. }
  3248. }
  3249. }
  3250. _unescape(token, size) {
  3251. const length = token.length;
  3252. const a = new Uint8Array(length);
  3253. if (size && size === length) {
  3254. for (let p = 0; p < size; p++) {
  3255. a[p] = token.charCodeAt(p);
  3256. }
  3257. return a;
  3258. }
  3259. let i = 0;
  3260. let o = 0;
  3261. while (i < length) {
  3262. let c = token.charCodeAt(i++);
  3263. if (c !== 0x5C || i >= length) {
  3264. a[o++] = c;
  3265. } else {
  3266. c = token.charCodeAt(i++);
  3267. switch (c) {
  3268. case 0x27: a[o++] = 0x27; break; // '
  3269. case 0x5C: a[o++] = 0x5C; break; // \\
  3270. case 0x22: a[o++] = 0x22; break; // "
  3271. case 0x72: a[o++] = 0x0D; break; // \r
  3272. case 0x6E: a[o++] = 0x0A; break; // \n
  3273. case 0x74: a[o++] = 0x09; break; // \t
  3274. case 0x62: a[o++] = 0x08; break; // \b
  3275. case 0x58: // x
  3276. case 0x78: { // X
  3277. const xsi = i - 1;
  3278. const xso = o;
  3279. for (let xi = 0; xi < 2; xi++) {
  3280. if (i >= length) {
  3281. i = xsi;
  3282. o = xso;
  3283. a[o] = 0x5c;
  3284. break;
  3285. }
  3286. let c = token.charCodeAt(i++);
  3287. if (c >= 65 && c <= 70) {
  3288. c -= 55;
  3289. } else if (c >= 97 && c <= 102) {
  3290. c -= 87;
  3291. } else if (c >= 48 && c <= 57) {
  3292. c -= 48;
  3293. } else {
  3294. c = -1;
  3295. }
  3296. if (c === -1) {
  3297. i = xsi;
  3298. o = xso;
  3299. a[o] = 0x5c;
  3300. break;
  3301. }
  3302. a[o] = a[o] << 4 | c;
  3303. }
  3304. o++;
  3305. break;
  3306. }
  3307. default:
  3308. if (c < 48 || c > 57) { // 0-9
  3309. a[o++] = 0x5c;
  3310. a[o++] = c;
  3311. } else {
  3312. i--;
  3313. const osi = i;
  3314. const oso = o;
  3315. for (let oi = 0; oi < 3; oi++) {
  3316. if (i >= length) {
  3317. i = osi;
  3318. o = oso;
  3319. a[o] = 0x5c;
  3320. break;
  3321. }
  3322. const od = token.charCodeAt(i++);
  3323. if (od < 48 || od > 57) {
  3324. i = osi;
  3325. o = oso;
  3326. a[o] = 0x5c;
  3327. break;
  3328. }
  3329. a[o] = a[o] << 3 | od - 48;
  3330. }
  3331. o++;
  3332. }
  3333. break;
  3334. }
  3335. }
  3336. }
  3337. return a.slice(0, o);
  3338. }
  3339. });
  3340. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3341. static __new__(/* subtype, data, dtype, copy */) {
  3342. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3343. }
  3344. });
  3345. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3346. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3347. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3348. super(data.shape, data.dtype, data.data);
  3349. }
  3350. });
  3351. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3352. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3353. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3354. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3355. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3356. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3357. __setstate__(state) {
  3358. [this._dtype, this._ndarray] = state;
  3359. Object.assign(this, Object.fromEntries(state[2]));
  3360. }
  3361. });
  3362. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3363. __setstate__(state) {
  3364. [this._dtype, this._ndarray] = state;
  3365. Object.assign(this, Object.fromEntries(state[2]));
  3366. }
  3367. });
  3368. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3369. __setstate__(state) {
  3370. [this._dtype, this._ndarray] = state;
  3371. Object.assign(this, Object.fromEntries(state[2]));
  3372. }
  3373. });
  3374. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3375. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3376. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3377. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3378. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3379. this.registerType('pandas.core.generic.Flags', class {});
  3380. this.registerType('pandas.core.generic.NDFrame', class {
  3381. constructor(data) {
  3382. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3383. this._metadata = [];
  3384. builtins.object.__setattr__(self, "_mgr", data);
  3385. builtins.object.__setattr__(self, "_attrs", {});
  3386. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3387. }
  3388. __setstate__(state) {
  3389. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3390. this._mgr = state;
  3391. } else if (state instanceof builtins.dict) {
  3392. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3393. state.__setitem__('_mgr', state.pop('_data'));
  3394. }
  3395. const typ = state.get('_typ');
  3396. if (typ) {
  3397. let attrs = state.get('_attrs', new builtins.dict());
  3398. if (!attrs) {
  3399. attrs = new builtins.dict();
  3400. }
  3401. builtins.object.__setattr__(this, '_attrs', attrs);
  3402. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3403. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3404. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3405. for (const k of meta) {
  3406. if (state.__contains__(k) && k !== '_flags') {
  3407. const v = state.__getitem__(k);
  3408. builtins.object.__setattr__(this, k, v);
  3409. }
  3410. }
  3411. for (const [k, v] of state) {
  3412. if (!meta.has(k)) {
  3413. builtins.object.__setattr__(this, k, v);
  3414. }
  3415. }
  3416. } else {
  3417. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3418. }
  3419. } else if (state.size === 2) {
  3420. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3421. }
  3422. }
  3423. });
  3424. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3425. });
  3426. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3427. return new cls(d);
  3428. });
  3429. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3430. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3431. this.registerType('pandas.core.indexes.base.Index', class {});
  3432. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3433. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3434. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3435. this.registerType('pandas.core.index.Int64Index', class {});
  3436. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3437. });
  3438. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3439. });
  3440. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3441. return pandas.core.internals.blocks.NumpyBlock;
  3442. });
  3443. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3444. return values;
  3445. });
  3446. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3447. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3448. return new klass(values, ndim, placement, refs);
  3449. });
  3450. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3451. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3452. this.registerType('pandas.core.series.Series', class {});
  3453. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3454. const obj = new cls();
  3455. if (state && obj.__setstate__) {
  3456. obj.__setstate__(state);
  3457. }
  3458. return obj;
  3459. });
  3460. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3461. const obj = new cls();
  3462. if (state && obj.__setstate__) {
  3463. obj.__setstate__(state);
  3464. }
  3465. return obj;
  3466. });
  3467. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3468. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3469. // if not isinstance(placement, BlockPlacement):
  3470. // placement = BlockPlacement(placement)
  3471. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3472. });
  3473. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3474. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3475. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3476. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3477. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3478. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3479. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3480. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3481. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3482. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3483. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3484. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3485. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3486. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3487. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3488. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3489. this.registerType('pathlib.Path', class {});
  3490. this.registerType('pathlib._local.PosixPath', class {});
  3491. this.registerType('pathlib._local.WindowsPath', class {});
  3492. const pathlib = this.register('pathlib');
  3493. pathlib.PosixPath = pathlib._local.PosixPath;
  3494. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3495. this.registerType('shap._serializable.Serializable', class {});
  3496. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3497. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3498. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3499. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3500. this.registerType('sklearn._loss.link.BaseLink', class {});
  3501. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3502. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3503. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3504. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3505. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3506. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3507. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3508. this.registerType('sklearn._loss.link.Interval', class {});
  3509. this.registerType('sklearn._loss.link.LogitLink', class {});
  3510. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3511. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3512. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3513. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3514. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3515. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3516. this.registerType('sklearn.base.BaseEstimator', class {});
  3517. this.registerType('sklearn.base.TransformerMixin', class {});
  3518. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3519. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3520. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3521. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3522. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3523. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3524. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3525. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3526. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3527. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3528. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3529. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3530. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3531. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3532. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3533. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3534. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3535. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3536. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3537. this.registerType('sklearn.decomposition.PCA', class {});
  3538. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3539. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3540. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3541. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3542. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3543. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3544. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3545. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3546. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3547. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3548. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3549. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3550. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3551. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3552. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3553. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3554. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3555. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3556. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3557. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3558. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3559. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3560. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3561. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3562. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3563. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3564. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3565. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3566. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3567. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3568. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3569. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3570. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3571. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3572. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3573. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3574. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3575. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3576. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3577. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3578. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3579. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3580. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3581. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3582. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3583. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3584. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3585. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3586. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3587. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3588. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3589. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3590. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3591. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3592. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3593. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3594. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3595. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3596. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3597. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3598. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3599. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3600. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3601. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3602. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3603. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3604. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3605. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3606. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3607. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3608. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3609. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3610. this.registerType('sklearn.impute.SimpleImputer', class {});
  3611. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3612. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3613. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3614. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3615. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3616. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3617. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3618. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3619. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3620. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3621. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3622. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3623. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3624. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3625. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3626. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3627. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3628. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3629. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3630. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3631. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3632. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3633. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3634. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3635. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3636. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3637. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3638. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3639. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3640. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3641. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3642. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3643. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3644. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3645. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3646. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3647. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3648. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3649. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3650. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3651. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3652. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3653. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3654. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3655. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3656. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3657. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3658. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3659. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3660. this.registerType('sklearn.model_selection._split.KFold', class {});
  3661. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3662. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3663. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3664. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3665. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3666. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3667. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3668. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3669. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3670. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3671. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3672. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3673. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3674. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3675. return obj.__new__(obj);
  3676. });
  3677. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3678. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3679. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3680. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3681. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3682. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3683. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3684. return obj.__new__(obj);
  3685. });
  3686. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3687. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3688. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3689. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3690. return obj.__new__(obj);
  3691. });
  3692. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3693. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3694. return obj.__new__(obj);
  3695. });
  3696. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3697. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3698. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3699. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3700. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3701. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3702. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3703. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3704. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3705. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3706. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3707. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3708. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3709. this.registerType('sklearn.pipeline.Pipeline', class {});
  3710. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3711. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3712. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3713. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3714. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3715. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3716. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3717. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3718. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3719. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3720. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3721. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3722. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3723. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3724. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3725. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3726. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3727. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3728. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3729. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3730. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3731. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3732. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3733. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3734. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3735. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3736. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3737. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3738. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3739. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3740. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3741. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3742. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3743. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3744. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3745. this.registerType('sklearn.svm._classes.SVC', class {});
  3746. this.registerType('sklearn.svm._classes.SVR', class {});
  3747. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3748. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3749. this.registerType('sklearn.svm.classes.SVC', class {});
  3750. this.registerType('sklearn.svm.classes.SVR', class {});
  3751. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3752. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3753. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3754. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3755. this.registerType('sklearn.tree._tree.Tree', class {
  3756. constructor(n_features, n_classes, n_outputs) {
  3757. this.n_features = n_features;
  3758. this.n_classes = n_classes;
  3759. this.n_outputs = n_outputs;
  3760. }
  3761. __setstate__(state) {
  3762. this.max_depth = state.get('max_depth');
  3763. this.node_count = state.get('node_count');
  3764. this.nodes = state.get('nodes');
  3765. this.values = state.get('values');
  3766. }
  3767. });
  3768. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3769. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3770. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3771. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3772. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3773. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3774. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3775. this.registerType('pickle.Unpickler', class {
  3776. constructor(data) {
  3777. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3778. this.persistent_load = () => {
  3779. throw new python.Error('Unsupported persistent id.');
  3780. };
  3781. }
  3782. load() {
  3783. const reader = this._reader;
  3784. const marker = [];
  3785. let stack = [];
  3786. const memo = {};
  3787. let size = 0;
  3788. while (reader.position < reader.length) {
  3789. const opcode = reader.byte();
  3790. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3791. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3792. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3793. switch (opcode) {
  3794. case 128: { // PROTO
  3795. const version = reader.byte();
  3796. if (version > 5) {
  3797. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3798. }
  3799. break;
  3800. }
  3801. case 99: { // GLOBAL 'c'
  3802. const module = reader.line();
  3803. const name = reader.line();
  3804. stack.push(this.find_class(module, name));
  3805. break;
  3806. }
  3807. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3808. const name = stack.pop();
  3809. const module = stack.pop();
  3810. stack.push(this.find_class(module, name));
  3811. break;
  3812. }
  3813. case 111: { // OBJ 'o'
  3814. const args = stack;
  3815. const cls = args.pop();
  3816. stack = marker.pop();
  3817. const obj = this._instantiate(cls, args);
  3818. stack.push(obj);
  3819. break;
  3820. }
  3821. case 112 : { // PUT 'p'
  3822. const index = parseInt(reader.line(), 10);
  3823. if (stack.length === 0) {
  3824. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3825. }
  3826. memo[index] = stack[stack.length - 1];
  3827. size++;
  3828. break;
  3829. }
  3830. case 103: { // GET 'g'
  3831. const index = parseInt(reader.line(), 10);
  3832. if (index in memo === false) {
  3833. throw new python.Error(`Memo value not found at index '${index}'.`);
  3834. }
  3835. stack.push(memo[index]);
  3836. break;
  3837. }
  3838. case 48: // POP '0'
  3839. stack.pop();
  3840. break;
  3841. case 49: // POP_MARK '1'
  3842. stack = marker.pop();
  3843. break;
  3844. case 50: // DUP '2'
  3845. if (stack.length === 0) {
  3846. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3847. }
  3848. stack.push(stack[stack.length - 1]);
  3849. break;
  3850. case 80: // PERSID 'P'
  3851. stack.push(this.persistent_load(reader.line()));
  3852. break;
  3853. case 81: // BINPERSID 'Q'
  3854. stack.push(this.persistent_load(stack.pop()));
  3855. break;
  3856. case 82: { // REDUCE 'R'
  3857. const args = stack.pop();
  3858. const func = stack.pop();
  3859. stack.push(this._reduce(func, args));
  3860. break;
  3861. }
  3862. case 129: { // NEWOBJ
  3863. const args = stack.pop();
  3864. const cls = stack.pop();
  3865. const obj = this._newobj(cls, args);
  3866. stack.push(obj);
  3867. break;
  3868. }
  3869. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3870. const kwargs = stack.pop();
  3871. const args = stack.pop();
  3872. const cls = stack.pop();
  3873. if (Object.entries(kwargs).length > 0) {
  3874. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3875. }
  3876. const obj = this._newobj(cls, args);
  3877. stack.push(obj);
  3878. break;
  3879. }
  3880. case 104: { // BINGET 'h'
  3881. const index = reader.byte();
  3882. if (index in memo === false) {
  3883. throw new python.Error(`Memo value not found at index '${index}'.`);
  3884. }
  3885. stack.push(memo[index]);
  3886. break;
  3887. }
  3888. case 105: { // INST 'i'
  3889. const module = reader.line();
  3890. const name = reader.line();
  3891. const args = stack;
  3892. const cls = `${module}.${name}`;
  3893. stack = marker.pop();
  3894. // cls = this.find_class(module, name)
  3895. const obj = this._instantiate(cls, args);
  3896. stack.push(obj);
  3897. break;
  3898. }
  3899. case 106: { // LONG_BINGET 'j'
  3900. const index = reader.uint32();
  3901. if (index in memo === false) {
  3902. throw new python.Error(`Memo value not found at index '${index}'.`);
  3903. }
  3904. stack.push(memo[index]);
  3905. break;
  3906. }
  3907. case 113: // BINPUT 'q'
  3908. if (stack.length === 0) {
  3909. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3910. }
  3911. memo[reader.byte()] = stack[stack.length - 1];
  3912. size++;
  3913. break;
  3914. case 114: // LONG_BINPUT 'r'
  3915. if (stack.length === 0) {
  3916. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3917. }
  3918. memo[reader.uint32()] = stack[stack.length - 1];
  3919. size++;
  3920. break;
  3921. case 74: // BININT 'J'
  3922. stack.push(reader.int32());
  3923. break;
  3924. case 75: // BININT1 'K'
  3925. stack.push(reader.byte());
  3926. break;
  3927. case 76: // LONG 'L'
  3928. stack.push(parseInt(reader.line(), 10));
  3929. break;
  3930. case 77: // BININT2 'M'
  3931. stack.push(reader.uint16());
  3932. break;
  3933. case 66: // BINBYTES 'B' (Protocol 3)
  3934. stack.push(reader.read(reader.int32()));
  3935. break;
  3936. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3937. stack.push(reader.read(reader.byte()));
  3938. break;
  3939. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3940. stack.push(reader.read(reader.int64().toNumber()));
  3941. break;
  3942. case 70: // FLOAT 'F'
  3943. stack.push(parseFloat(reader.line()));
  3944. break;
  3945. case 71: // BINFLOAT 'G'
  3946. stack.push(reader.float64());
  3947. break;
  3948. case 73: { // INT 'I'
  3949. const value = reader.line();
  3950. if (value === '01') {
  3951. stack.push(true);
  3952. } else if (value === '00') {
  3953. stack.push(false);
  3954. } else {
  3955. stack.push(parseInt(value, 10));
  3956. }
  3957. break;
  3958. }
  3959. case 93: // EMPTY_LIST ']'
  3960. stack.push(new builtins.list());
  3961. break;
  3962. case 41: // EMPTY_TUPLE ')'
  3963. stack.push([]);
  3964. break;
  3965. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3966. stack.push([]);
  3967. break;
  3968. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3969. const items = stack;
  3970. stack = marker.pop();
  3971. const obj = stack[stack.length - 1];
  3972. for (let i = 0; i < items.length; i++) {
  3973. obj.push(items[i]);
  3974. }
  3975. break;
  3976. }
  3977. case 145: { // FROZENSET '\x91' (Protocol 4)
  3978. const items = stack;
  3979. stack = marker.pop();
  3980. stack.push(items);
  3981. break;
  3982. }
  3983. case 100: { // DICT 'd'
  3984. const items = stack;
  3985. stack = marker.pop();
  3986. const dict = new builtins.dict();
  3987. for (let i = 0; i < items.length; i += 2) {
  3988. dict.__setitem__(items[i], items[i + 1]);
  3989. }
  3990. stack.push(dict);
  3991. break;
  3992. }
  3993. case 108: { // LIST 'l'
  3994. const items = stack;
  3995. stack = marker.pop();
  3996. stack.push(items);
  3997. break;
  3998. }
  3999. case 116: { // TUPLE 't'
  4000. const items = stack;
  4001. stack = marker.pop();
  4002. stack.push(items);
  4003. break;
  4004. }
  4005. case 133: { // TUPLE1 // '\x85'
  4006. stack.push([stack.pop()]);
  4007. break;
  4008. }
  4009. case 134: { // TUPLE2 '\x86'
  4010. const b = stack.pop();
  4011. const a = stack.pop();
  4012. stack.push([a, b]);
  4013. break;
  4014. }
  4015. case 135: { // TUPLE3 '\x87'
  4016. const c = stack.pop();
  4017. const b = stack.pop();
  4018. const a = stack.pop();
  4019. stack.push([a, b, c]);
  4020. break;
  4021. }
  4022. case 115: { // SETITEM 's'
  4023. const value = stack.pop();
  4024. const key = stack.pop();
  4025. const obj = stack[stack.length - 1];
  4026. if (obj.__setitem__) {
  4027. obj.__setitem__(key, value);
  4028. } else {
  4029. obj[key] = value;
  4030. }
  4031. break;
  4032. }
  4033. case 117: { // SETITEMS 'u'
  4034. const items = stack;
  4035. stack = marker.pop();
  4036. const obj = stack[stack.length - 1];
  4037. if (obj.__setitem__) {
  4038. for (let i = 0; i < items.length; i += 2) {
  4039. obj.__setitem__(items[i], items[i + 1]);
  4040. }
  4041. } else {
  4042. for (let i = 0; i < items.length; i += 2) {
  4043. obj[items[i]] = items[i + 1];
  4044. }
  4045. }
  4046. break;
  4047. }
  4048. case 125: // EMPTY_DICT '}'
  4049. stack.push(new builtins.dict());
  4050. break;
  4051. case 97: { // APPEND 'a'
  4052. const append = stack.pop();
  4053. stack[stack.length - 1].push(append);
  4054. break;
  4055. }
  4056. case 101: { // APPENDS 'e'
  4057. const appends = stack;
  4058. stack = marker.pop();
  4059. const list = stack[stack.length - 1];
  4060. list.push(...appends);
  4061. break;
  4062. }
  4063. case 83: { // STRING 'S'
  4064. const str = reader.line();
  4065. stack.push(str.substring(1, str.length - 1));
  4066. break;
  4067. }
  4068. case 84: // BINSTRING 'T'
  4069. stack.push(reader.string(reader.uint32()));
  4070. break;
  4071. case 85 : // SHORT_BINSTRING 'U'
  4072. stack.push(reader.string(reader.byte()));
  4073. break;
  4074. case 86: // UNICODE 'V'
  4075. stack.push(reader.line());
  4076. break;
  4077. case 88: // BINUNICODE 'X
  4078. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4079. break;
  4080. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4081. stack.push(reader.string(reader.byte(), 'utf-8'));
  4082. break;
  4083. case 98: { // BUILD 'b'
  4084. const state = stack.pop();
  4085. let obj = stack.pop();
  4086. if (obj.__setstate__) {
  4087. if (obj.__setstate__.__call__) {
  4088. obj.__setstate__.__call__([obj, state]);
  4089. } else {
  4090. obj.__setstate__(state);
  4091. }
  4092. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4093. obj.__state__ = state;
  4094. } else if (obj instanceof Map && state instanceof Map) {
  4095. for (const [key, value] of state) {
  4096. obj.set(key, value);
  4097. }
  4098. } else if (obj instanceof Map) {
  4099. /* eslint-disable guard-for-in */
  4100. for (const key in state) {
  4101. obj.set(key, state[key]);
  4102. }
  4103. /* eslint-enable guard-for-in */
  4104. } else if (state instanceof Map) {
  4105. for (const [key, value] of state) {
  4106. obj[key] = value;
  4107. }
  4108. } else {
  4109. Object.assign(obj, state);
  4110. }
  4111. if (obj.__read__) {
  4112. obj = obj.__read__(this);
  4113. }
  4114. stack.push(obj);
  4115. break;
  4116. }
  4117. case 40: // MARK '('
  4118. marker.push(stack);
  4119. stack = [];
  4120. break;
  4121. case 136: // NEWTRUE '\x88'
  4122. stack.push(true);
  4123. break;
  4124. case 137: // NEWFALSE '\x89'
  4125. stack.push(false);
  4126. break;
  4127. case 138: { // LONG1 '\x8a'
  4128. const data = reader.read(reader.byte());
  4129. let number = 0;
  4130. switch (data.length) {
  4131. case 0: number = 0; break;
  4132. case 1: [number] = data; break;
  4133. case 2: number = data[1] << 8 | data[0]; break;
  4134. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4135. case 4: number = (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0; break;
  4136. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4137. default: number = Array.prototype.slice.call(data, 0); break;
  4138. }
  4139. stack.push(number);
  4140. break;
  4141. }
  4142. case 139: // LONG4 '\x8b'
  4143. // decode LONG4
  4144. stack.push(reader.read(reader.uint32()));
  4145. break;
  4146. case 148: // MEMOIZE '\x94' (Protocol 4)
  4147. memo[size++] = stack[stack.length - 1];
  4148. break;
  4149. case 149: // FRAME '\x95' (Protocol 4)
  4150. reader.read(8);
  4151. break;
  4152. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4153. stack.push(reader.read(reader.int64().toNumber()));
  4154. break;
  4155. }
  4156. case 78: // NONE 'N'
  4157. stack.push(null);
  4158. break;
  4159. case 46: // STOP '.'
  4160. return stack.pop();
  4161. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4162. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4163. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4164. default:
  4165. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4166. }
  4167. }
  4168. throw new python.Error('Unexpected end of file.');
  4169. }
  4170. find_class(module, name) {
  4171. execution.__import__(module);
  4172. return execution.resolve(`${module}.${name}`);
  4173. }
  4174. _instantiate(cls, args) {
  4175. return execution.invoke(cls, args);
  4176. }
  4177. _newobj(cls, args) {
  4178. // cls.__new__(cls, args)
  4179. return execution.invoke(cls, args);
  4180. }
  4181. _reduce(func, args) {
  4182. return execution.invoke(func, args);
  4183. }
  4184. read(size) {
  4185. return this._reader.read(size);
  4186. }
  4187. stream(size) {
  4188. return this._reader.stream(size);
  4189. }
  4190. });
  4191. this.registerType('random.Random', class {});
  4192. this.registerType('re.Pattern', class {
  4193. constructor(pattern, flags) {
  4194. this.pattern = pattern;
  4195. this.flags = flags;
  4196. }
  4197. });
  4198. this.registerType('spacy._ml.PrecomputableAffine', class {
  4199. __setstate__(state) {
  4200. Object.assign(this, new pickle.Unpickler(state).load());
  4201. }
  4202. });
  4203. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4204. __setstate__(state) {
  4205. Object.assign(this, new pickle.Unpickler(state).load());
  4206. }
  4207. });
  4208. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4209. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4210. this.registerType('theano.compile.function_module.Function', class {});
  4211. this.registerType('theano.compile.function_module.Supervisor', class {});
  4212. this.registerType('theano.compile.io.In', class {});
  4213. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4214. this.registerType('theano.compile.mode.Mode', class {});
  4215. this.registerType('theano.compile.ops.OutputGuard', class {});
  4216. this.registerType('theano.compile.ops.Shape', class {});
  4217. this.registerType('theano.compile.ops.Shape_i', class {});
  4218. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4219. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4220. this.registerType('theano.gof.graph.Apply', class {});
  4221. this.registerType('theano.gof.link.Container', class {});
  4222. this.registerType('theano.gof.opt._metadict', class {});
  4223. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4224. this.registerType('theano.gof.opt.MergeFeature', class {});
  4225. this.registerType('theano.gof.optdb.Query', class {});
  4226. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4227. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4228. this.registerType('theano.gof.utils.scratchpad', class {});
  4229. this.registerType('theano.misc.ordered_set.Link', class {});
  4230. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4231. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4232. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4233. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4234. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4235. this.registerType('theano.scalar.basic.Abs', class {});
  4236. this.registerType('theano.scalar.basic.Add', class {});
  4237. this.registerType('theano.scalar.basic.Cast', class {});
  4238. this.registerType('theano.scalar.basic.Composite', class {});
  4239. this.registerType('theano.scalar.basic.EQ', class {});
  4240. this.registerType('theano.scalar.basic.GE', class {});
  4241. this.registerType('theano.scalar.basic.Identity', class {});
  4242. this.registerType('theano.scalar.basic.IntDiv', class {});
  4243. this.registerType('theano.scalar.basic.Inv', class {});
  4244. this.registerType('theano.scalar.basic.LE', class {});
  4245. this.registerType('theano.scalar.basic.LT', class {});
  4246. this.registerType('theano.scalar.basic.Mul', class {});
  4247. this.registerType('theano.scalar.basic.Neg', class {});
  4248. this.registerType('theano.scalar.basic.Pow', class {});
  4249. this.registerType('theano.scalar.basic.Scalar', class {});
  4250. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4251. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4252. this.registerType('theano.scalar.basic.Second', class {});
  4253. this.registerType('theano.scalar.basic.Sgn', class {});
  4254. this.registerType('theano.scalar.basic.specific_out', class {});
  4255. this.registerType('theano.scalar.basic.Sub', class {});
  4256. this.registerType('theano.scalar.basic.Switch', class {});
  4257. this.registerType('theano.scalar.basic.Tanh', class {});
  4258. this.registerType('theano.scalar.basic.transfer_type', class {});
  4259. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4260. this.registerType('theano.tensor.basic.Alloc', class {});
  4261. this.registerType('theano.tensor.basic.Dot', class {});
  4262. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4263. this.registerType('theano.tensor.basic.Reshape', class {});
  4264. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4265. this.registerType('theano.tensor.blas.Dot22', class {});
  4266. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4267. this.registerType('theano.tensor.blas.Gemm', class {});
  4268. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4269. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4270. this.registerType('theano.tensor.elemwise.Sum', class {});
  4271. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4272. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4273. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4274. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4275. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4276. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4277. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4278. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4279. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4280. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4281. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4282. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4283. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4284. this.registerType('theano.tensor.opt.MakeVector', class {});
  4285. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4286. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4287. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4288. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4289. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4290. this.registerType('theano.tensor.type.TensorType', class {});
  4291. this.registerType('theano.tensor.var.TensorConstant', class {});
  4292. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4293. this.registerType('theano.tensor.var.TensorVariable', class {});
  4294. this.registerType('thinc.describe.Biases', class {});
  4295. this.registerType('thinc.describe.Dimension', class {});
  4296. this.registerType('thinc.describe.Gradient', class {});
  4297. this.registerType('thinc.describe.Weights', class {});
  4298. this.registerType('thinc.describe.Synapses', class {});
  4299. this.registerType('thinc.neural._classes.affine.Affine', class {
  4300. __setstate__(state) {
  4301. Object.assign(this, new pickle.Unpickler(state).load());
  4302. }
  4303. });
  4304. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4305. __setstate__(state) {
  4306. Object.assign(this, new pickle.Unpickler(state).load());
  4307. }
  4308. });
  4309. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4310. __setstate__(state) {
  4311. Object.assign(this, new pickle.Unpickler(state).load());
  4312. }
  4313. });
  4314. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4315. __setstate__(state) {
  4316. Object.assign(this, new pickle.Unpickler(state).load());
  4317. }
  4318. });
  4319. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4320. __setstate__(state) {
  4321. Object.assign(this, new pickle.Unpickler(state).load());
  4322. }
  4323. });
  4324. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4325. __setstate__(state) {
  4326. Object.assign(this, new pickle.Unpickler(state).load());
  4327. }
  4328. });
  4329. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4330. __setstate__(state) {
  4331. Object.assign(this, new pickle.Unpickler(state).load());
  4332. }
  4333. });
  4334. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4335. __setstate__(state) {
  4336. Object.assign(this, new pickle.Unpickler(state).load());
  4337. }
  4338. });
  4339. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4340. __setstate__(state) {
  4341. Object.assign(this, new pickle.Unpickler(state).load());
  4342. }
  4343. });
  4344. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4345. __setstate__(state) {
  4346. Object.assign(this, new pickle.Unpickler(state).load());
  4347. }
  4348. });
  4349. this.registerType('thinc.neural.mem.Memory', class {
  4350. });
  4351. this.registerType('thinc.neural.ops.NumpyOps', class {
  4352. });
  4353. this.registerType('__main__.BYOLState', class {
  4354. constructor(dict) {
  4355. Object.assign(this, dict);
  4356. }
  4357. });
  4358. const types = this.register('types');
  4359. this.registerType('types.GenericAlias', class {});
  4360. this.registerType('types.SimpleNamespace', class {});
  4361. this.registerType('types.BuiltinFunctionType', class {});
  4362. this.registerType('types.BuiltinMethodType', class {});
  4363. this.registerFunction('types.resolve_bases', (bases) => {
  4364. return bases;
  4365. });
  4366. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4367. if (kwds) {
  4368. kwds = new builtins.dict(kwds);
  4369. } else {
  4370. kwds = new builtins.dict();
  4371. }
  4372. let meta = null;
  4373. if (kwds.__contains__('metaclass')) {
  4374. meta = kwds.pop('metaclass');
  4375. } else if (bases && bases.length > 0) {
  4376. meta = builtins.type(bases[0]);
  4377. } else {
  4378. meta = builtins.type;
  4379. }
  4380. if (meta instanceof builtins.type) {
  4381. meta = types._calculate_meta(meta, bases);
  4382. }
  4383. let ns = null;
  4384. if (builtins.hasattr(meta, '__prepare__')) {
  4385. // ns = meta.__prepare__(name, bases, **kwds)
  4386. } else {
  4387. ns = new builtins.dict();
  4388. }
  4389. return [meta, ns, kwds];
  4390. });
  4391. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4392. const winner = meta;
  4393. return winner;
  4394. });
  4395. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4396. const resolved_bases = types.resolve_bases(bases);
  4397. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4398. if (exec_body) {
  4399. exec_body(ns);
  4400. }
  4401. return new meta(name, resolved_bases, ns);
  4402. });
  4403. types.ObjectType = builtins.object;
  4404. types.ModuleType = builtins.module;
  4405. types.MethodType = builtins.method;
  4406. types.FunctionType = builtins.function;
  4407. types.TypeType = builtins.type;
  4408. types.CodeType = builtins.code;
  4409. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4410. this.registerType('xgboost.core.Booster', class {
  4411. load_model(fname) {
  4412. if (fname instanceof Uint8Array) {
  4413. // XGBoosterLoadModel()
  4414. } else {
  4415. // XGBoosterUnserializeFromBuffer(handle) {
  4416. }
  4417. }
  4418. __setstate__(state) {
  4419. const handle = state.get('handle');
  4420. if (handle) {
  4421. this.handle = handle;
  4422. // XGBoosterLoadModelFromBuffer()
  4423. }
  4424. }
  4425. });
  4426. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4427. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4428. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4429. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4430. return new builtins.bytearray(obj, encoding);
  4431. });
  4432. this.registerType('builtins.bytearray', class extends Uint8Array {
  4433. constructor(source, encoding /*, errors */) {
  4434. source = builtins.bytes.__encode__(source, encoding);
  4435. super(Number.isInteger(source) ? source : source.length);
  4436. if (Array.isArray(source)) {
  4437. for (let i = 0; i < source.length; i++) {
  4438. this[i] = source;
  4439. }
  4440. } else if (source instanceof Uint8Array) {
  4441. this.set(source, 0);
  4442. } else if (typeof source === 'string') {
  4443. for (let i = 0; i < source.length; i++) {
  4444. this[i] = source.charCodeAt(i);
  4445. }
  4446. }
  4447. }
  4448. static __encode__(source, encoding) {
  4449. if (source === undefined) {
  4450. return 0;
  4451. }
  4452. if (Number.isInteger(source)) {
  4453. return source;
  4454. }
  4455. if (Array.isArray(source) || source instanceof Uint8Array) {
  4456. return source;
  4457. }
  4458. if (typeof source === 'string') {
  4459. switch (encoding) {
  4460. case 'latin1':
  4461. case 'latin-1':
  4462. return source;
  4463. case 'utf8':
  4464. case 'utf-8':
  4465. return new TextEncoder('utf-8').encode(source);
  4466. case undefined:
  4467. throw new python.Error('Unsupported string argument without an encoding.');
  4468. default:
  4469. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4470. }
  4471. }
  4472. throw new python.Error('Unsupported source.');
  4473. }
  4474. });
  4475. this.registerType('builtins.bytes', class extends Uint8Array {
  4476. constructor(source, encoding /*, errors */) {
  4477. source = builtins.bytes.__encode__(source, encoding);
  4478. super(Number.isInteger(source) ? source : source.length);
  4479. if (Array.isArray(source)) {
  4480. for (let i = 0; i < source.length; i++) {
  4481. this[i] = source;
  4482. }
  4483. } else if (source instanceof Uint8Array) {
  4484. this.set(source, 0);
  4485. } else if (typeof source === 'string') {
  4486. for (let i = 0; i < source.length; i++) {
  4487. this[i] = source.charCodeAt(i);
  4488. }
  4489. }
  4490. }
  4491. static __encode__(source, encoding) {
  4492. if (source === undefined) {
  4493. return 0;
  4494. }
  4495. if (Number.isInteger(source)) {
  4496. return source;
  4497. }
  4498. if (Array.isArray(source) || source instanceof Uint8Array) {
  4499. return source;
  4500. }
  4501. if (typeof source === 'string') {
  4502. switch (encoding) {
  4503. case 'latin1':
  4504. case 'latin-1':
  4505. return source;
  4506. case 'utf8':
  4507. case 'utf-8':
  4508. return new TextEncoder('utf-8').encode(source);
  4509. case undefined:
  4510. throw new python.Error('Unsupported string argument without an encoding.');
  4511. default:
  4512. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4513. }
  4514. }
  4515. throw new python.Error('Unsupported source.');
  4516. }
  4517. });
  4518. this.registerType('builtins.memoryview', class {
  4519. constructor(buf) {
  4520. this._buf = buf;
  4521. }
  4522. get nbytes() {
  4523. return this._buf.length;
  4524. }
  4525. });
  4526. this.registerType('builtins.frozenset', class extends Set {
  4527. constructor(iterable) {
  4528. super();
  4529. if (iterable) {
  4530. for (const item of iterable) {
  4531. this.add(item);
  4532. }
  4533. }
  4534. }
  4535. });
  4536. this.registerFunction('builtins.exec');
  4537. this.registerFunction('builtins.issubclass', (obj, type) => {
  4538. const name = `${type.__module__}.${type.__name__}`;
  4539. if (obj.__module__ && obj.__name__) {
  4540. if (name === `${obj.__module__}.${obj.__name__}`) {
  4541. return true;
  4542. }
  4543. }
  4544. if (obj.__bases__) {
  4545. for (const base of obj.__bases__) {
  4546. if (builtins.issubclass(base, type)) {
  4547. return true;
  4548. }
  4549. }
  4550. }
  4551. return false;
  4552. });
  4553. this.registerFunction('builtins.isinstance', (obj, type) => {
  4554. if (obj && type && obj instanceof type) {
  4555. return true;
  4556. }
  4557. if (obj && obj.__class__) {
  4558. return builtins.issubclass(obj.__class__, type);
  4559. }
  4560. return false;
  4561. });
  4562. this.registerFunction('builtins.hasattr', (obj, name) => {
  4563. if (obj instanceof Map && obj.__contains__) {
  4564. return obj.__contains__(name);
  4565. }
  4566. return Object.prototype.hasOwnProperty.call(obj, name);
  4567. });
  4568. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4569. if (obj && obj.__getattr__) {
  4570. return obj.__getattr__(name);
  4571. }
  4572. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4573. return obj[name];
  4574. }
  4575. return defaultValue;
  4576. });
  4577. this.registerFunction('builtins.len', (obj) => {
  4578. return obj.length;
  4579. });
  4580. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4581. if (obj && obj.__setattr__) {
  4582. obj.__setattr__(name, value);
  4583. } else {
  4584. obj[name] = value;
  4585. }
  4586. });
  4587. this.registerType('builtins.set', class extends Set {
  4588. __contains__(item) {
  4589. return this.has(item);
  4590. }
  4591. update(iterable) {
  4592. for (const item of iterable) {
  4593. this.add(item);
  4594. }
  4595. }
  4596. });
  4597. this.registerType('builtins.slice', class {
  4598. constructor(start, stop, step) {
  4599. this.start = start;
  4600. this.stop = stop;
  4601. this.step = step;
  4602. }
  4603. });
  4604. this.registerFunction('builtins.hash');
  4605. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4606. return name;
  4607. });
  4608. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4609. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4610. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4611. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4612. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4613. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4614. cell.cell_contents = value;
  4615. }
  4616. return cell;
  4617. });
  4618. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4619. // globals["__builtins__"] = __builtins__
  4620. return new types.FunctionType(code, globals, name, argdefs, closure);
  4621. });
  4622. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4623. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4624. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4625. if (class_tracker_id) {
  4626. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4627. }
  4628. return class_def;
  4629. });
  4630. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4631. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4632. const kwds = { 'metaclass': type_constructor };
  4633. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4634. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4635. });
  4636. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4637. return new builtins.cell();
  4638. });
  4639. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4640. [state] = state;
  4641. let registry = null;
  4642. for (const [attrname, attr] of state.items()) {
  4643. if (attrname === '_abc_impl') {
  4644. registry = attr;
  4645. } else {
  4646. builtins.setattr(obj, attrname, attr);
  4647. }
  4648. }
  4649. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4650. obj.__firstlineno__ = state.get('__firstlineno__');
  4651. }
  4652. if (registry) {
  4653. for (const subclass of registry) {
  4654. obj.register(subclass);
  4655. }
  4656. }
  4657. return obj;
  4658. });
  4659. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4660. const [, slotstate] = state;
  4661. [state] = state;
  4662. // obj.__dict__.update(state)
  4663. /* const obj_globals = */ slotstate.pop('__globals__');
  4664. const obj_closure = slotstate.pop('__closure__');
  4665. slotstate.pop('_cloudpickle_submodules');
  4666. if (obj.__globals__) {
  4667. // obj.__globals__.update(obj_globals);
  4668. // obj.__globals__.__builtins__ = __builtins__;
  4669. }
  4670. if (obj_closure) {
  4671. // let value = null;
  4672. for (let i = 0; i < obj_closure.length; i++) {
  4673. // const cell = obj_closure[i];
  4674. try {
  4675. // value = cell.cell_contents;
  4676. } catch {
  4677. // cell is empty
  4678. }
  4679. // obj.__closure__[i].cell_contents = value;
  4680. }
  4681. }
  4682. for (const [k, v] of slotstate.items()) {
  4683. builtins.setattr(obj, k, v);
  4684. }
  4685. });
  4686. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4687. execution.__import__(name);
  4688. return sys.modules.get(name);
  4689. });
  4690. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4691. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4692. const ray = this.register('ray');
  4693. this.register('ray.cloudpickle.cloudpickle');
  4694. this.register('ray.cloudpickle.cloudpickle_fast');
  4695. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4696. ray.cloudpickle.cloudpickle._fill_function = cloudpickle.cloudpickle._fill_function;
  4697. ray.cloudpickle.cloudpickle._make_cell = cloudpickle.cloudpickle._make_cell;
  4698. ray.cloudpickle.cloudpickle._make_function = cloudpickle.cloudpickle._make_function;
  4699. ray.cloudpickle.cloudpickle._make_skel_func = cloudpickle.cloudpickle._make_skel_func;
  4700. ray.cloudpickle.cloudpickle._make_skeleton_class = cloudpickle.cloudpickle._make_skeleton_class;
  4701. ray.cloudpickle.cloudpickle._make_empty_cell = cloudpickle.cloudpickle._make_empty_cell;
  4702. ray.cloudpickle.cloudpickle._empty_cell_value = cloudpickle.cloudpickle._empty_cell_value;
  4703. ray.cloudpickle.cloudpickle._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4704. ray.cloudpickle.cloudpickle._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4705. ray.cloudpickle.cloudpickle._lookup_class_or_track = cloudpickle.cloudpickle._lookup_class_or_track;
  4706. ray.cloudpickle.cloudpickle_fast._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4707. ray.cloudpickle.cloudpickle_fast._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4708. this.registerType('ray.rllib.algorithms.ppo.ppo.PPO', class {});
  4709. this.registerType('ray.rllib.algorithms.ppo.ppo.PPOConfig', class {});
  4710. this.registerType('ray.rllib.algorithms.algorithm_config.AlgorithmConfig', class {});
  4711. this.registerFunction('ray.rllib.algorithms.algorithm_config.AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN');
  4712. this.registerType('ray.rllib.algorithms.algorithm_config.TorchCompileWhatToCompile', class {});
  4713. this.registerType('ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector', class {});
  4714. this.registerType('ray.rllib.callbacks.callbacks.RLlibCallback', class {});
  4715. this.registerType('ray.rllib.core.learner.learner.TorchCompileWhatToCompile', class {});
  4716. this.registerType('ray.rllib.policy.policy.PolicySpec', class {});
  4717. this.registerType('ray.rllib.policy.sample_batch.SampleBatch', class {});
  4718. this.registerType('ray.rllib.utils.metrics.stats.mean.MeanStats', class {});
  4719. this.registerType('ray.rllib.utils.metrics.stats.ema.EmaStats', class {});
  4720. this.registerType('ray.rllib.utils.metrics.stats.min.MinStats', class {});
  4721. this.registerType('ray.rllib.utils.metrics.stats.max.MaxStats', class {});
  4722. this.registerType('ray.rllib.utils.metrics.stats.sum.SumStats', class {});
  4723. this.registerType('ray.rllib.utils.metrics.stats.lifetime_sum.LifetimeSumStats', class {});
  4724. this.registerType('ray.rllib.utils.metrics.stats.percentiles.PercentilesStats', class {});
  4725. this.registerType('ray.rllib.utils.metrics.stats.item.ItemStats', class {});
  4726. this.registerType('ray.rllib.utils.metrics.stats.item_series.ItemSeriesStats', class {});
  4727. this.registerType('collections.Counter', class {});
  4728. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4729. return {};
  4730. });
  4731. this.registerFunction('copy.deepcopy');
  4732. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4733. // copyreg._reconstructor in Python 3
  4734. if (base === '__builtin__.object' || base === builtins.object) {
  4735. return self.invoke(cls, []);
  4736. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4737. const obj = self.invoke(cls, []);
  4738. for (let i = 0; i < state.length; i++) {
  4739. obj[i] = state[i];
  4740. }
  4741. return obj;
  4742. }
  4743. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4744. });
  4745. this.registerFunction('copy.deepcopy', (/* x */) => {
  4746. throw new python.Error('Unsupported copy.deepcopy().');
  4747. });
  4748. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4749. const array = f(...args);
  4750. if (array.__setstate__) {
  4751. array.__setstate__(state);
  4752. }
  4753. if (npdict) {
  4754. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4755. }
  4756. return array;
  4757. });
  4758. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4759. return function() {
  4760. };
  4761. });
  4762. this.registerFunction('dill._dill._create_code', (args) => {
  4763. return self.invoke('types.CodeType', [args]);
  4764. });
  4765. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4766. return function() {
  4767. };
  4768. });
  4769. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4770. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4771. if (obj) {
  4772. return obj;
  4773. }
  4774. return undefined;
  4775. });
  4776. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4777. const [name, bases, dict] = args;
  4778. const type = class extends bases[0] {};
  4779. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4780. return self.registerType(identifier, Object.assign(type, dict));
  4781. });
  4782. this.registerFunction('dill._dill._eval_repr');
  4783. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4784. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4785. return self[name];
  4786. }
  4787. return undefined;
  4788. });
  4789. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4790. try {
  4791. if (import_name.startsWith('__runtime__.')) {
  4792. return execution.module(import_name);
  4793. } else if (import_name.indexOf('.') === -1) {
  4794. return execution.__import__(import_name);
  4795. }
  4796. return execution.resolve(import_name);
  4797. } catch (error) {
  4798. if (safe) {
  4799. return null;
  4800. }
  4801. throw error;
  4802. }
  4803. });
  4804. this.registerFunction('dill._dill._load_type', (name) => {
  4805. const _dill = self.register('dill._dill');
  4806. if (!_dill._reverse_typemap) {
  4807. _dill._reverse_typemap = new Map();
  4808. for (const name of ['__builtin__', 'types']) {
  4809. const module = self.register(name);
  4810. for (const [name, obj] of Object.entries(module)) {
  4811. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4812. _dill._reverse_typemap.set(name, obj);
  4813. }
  4814. }
  4815. }
  4816. _dill._reverse_typemap.set('PartialType', functools.partial);
  4817. _dill._reverse_typemap.set('CellType', builtins.cell);
  4818. }
  4819. if (!_dill._reverse_typemap.has(name)) {
  4820. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4821. }
  4822. return _dill._reverse_typemap.get(name);
  4823. });
  4824. this.registerFunction('dill._dill.loads');
  4825. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4826. const np_value = fun(...args);
  4827. np_value.__setstate__(arr_state);
  4828. const jnp_value = jax.device_put(np_value);
  4829. jnp_value.aval = jnp_value.aval.update(aval_state);
  4830. return jnp_value;
  4831. });
  4832. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4833. this.registerFunction('jax.device_put', (x) => {
  4834. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4835. return new jax.Array(aval, x.data);
  4836. });
  4837. this.registerType('jax._src.core.AbstractValue', class {});
  4838. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4839. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4840. constructor(shape, dtype, weak_type) {
  4841. super();
  4842. this.shape = shape;
  4843. this.dtype = dtype;
  4844. this.weak_type = weak_type || false;
  4845. }
  4846. update(dict) {
  4847. const shape = dict.get('shape') || this.shape;
  4848. const dtype = dict.get('dtype') || this.dtype;
  4849. const weak_type = dict.get('weak_type') || this.weak_type;
  4850. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4851. }
  4852. });
  4853. this.registerType('jax.Array', class {
  4854. constructor(aval, data) {
  4855. this.aval = aval;
  4856. this.data = data;
  4857. }
  4858. get dtype() {
  4859. return this.aval.dtype;
  4860. }
  4861. get shape() {
  4862. return this.aval.shape;
  4863. }
  4864. tobytes() {
  4865. return this.data;
  4866. }
  4867. });
  4868. jax.numpy.ndarray = jax.Array;
  4869. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4870. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4871. });
  4872. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4873. this.registerFunction('lasagne.nonlinearities.rectify');
  4874. this.registerFunction('lasagne.nonlinearities.softmax');
  4875. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4876. this.registerFunction('lasagne.updates.nesterov_momentum');
  4877. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4878. const BinaryReader = class {
  4879. constructor(buffer, ext_hook) {
  4880. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4881. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4882. this._buffer = buffer;
  4883. this._position = 0;
  4884. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4885. this._ext_hook = ext_hook;
  4886. }
  4887. value() {
  4888. const c = this._view.getUint8(this.skip(1));
  4889. if (c >= 0xe0) {
  4890. return c - 0x100;
  4891. }
  4892. if (c < 0xC0) {
  4893. if (c < 0x80) {
  4894. return c;
  4895. }
  4896. if (c < 0x90) {
  4897. return this.map(c - 0x80);
  4898. }
  4899. if (c < 0xa0) {
  4900. return this.array(c - 0x90);
  4901. }
  4902. return this.string(c - 0xa0);
  4903. }
  4904. switch (c) {
  4905. case 0xC0: return null;
  4906. case 0xC2: return false;
  4907. case 0xC3: return true;
  4908. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4909. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4910. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4911. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4912. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4913. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4914. case 0xCA: return this._view.getFloat32(this.skip(4));
  4915. case 0xCB: return this._view.getFloat64(this.skip(8));
  4916. case 0xCC: return this._view.getUint8(this.skip(1));
  4917. case 0xCD: return this._view.getUint16(this.skip(2));
  4918. case 0xCE: return this._view.getUint32(this.skip(4));
  4919. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4920. case 0xD0: return this._view.getInt8(this.skip(1));
  4921. case 0xD1: return this._view.getInt16(this.skip(2));
  4922. case 0xD2: return this._view.getInt32(this.skip(4));
  4923. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4924. case 0xD4: return this.extension(1);
  4925. case 0xD5: return this.extension(2);
  4926. case 0xD6: return this.extension(4);
  4927. case 0xD7: return this.extension(8);
  4928. case 0xD8: return this.extension(16);
  4929. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4930. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4931. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4932. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4933. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4934. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4935. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4936. default: throw new python.Error(`Invalid code '${c}'.`);
  4937. }
  4938. }
  4939. map(size) {
  4940. const map = {};
  4941. for (let i = 0; i < size; i++) {
  4942. const key = this.value();
  4943. const value = this.value();
  4944. map[key] = value;
  4945. }
  4946. return map;
  4947. }
  4948. array(size) {
  4949. const array = new Array(size);
  4950. for (let i = 0; i < size; i++) {
  4951. array[i] = this.value();
  4952. }
  4953. return array;
  4954. }
  4955. extension(size) {
  4956. const code = this._view.getUint8(this.skip(1));
  4957. const data = this.read(size);
  4958. return this._ext_hook(code, data);
  4959. }
  4960. skip(offset) {
  4961. const position = this._position;
  4962. this._position += offset;
  4963. if (this._position > this._buffer.length) {
  4964. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4965. }
  4966. return position;
  4967. }
  4968. read(size) {
  4969. const data = this._buffer.subarray(this._position, this._position + size);
  4970. this._position += size;
  4971. return data;
  4972. }
  4973. string(size) {
  4974. const buffer = this.read(size);
  4975. this._decoder = this._decoder || new TextDecoder('utf8');
  4976. return this._decoder.decode(buffer);
  4977. }
  4978. };
  4979. return new BinaryReader(packed, ext_hook).value();
  4980. });
  4981. this.registerFunction('nolearn.lasagne.base.objective');
  4982. this.registerFunction('numpy.core._DType_reconstruct');
  4983. this.registerFunction('numpy.core._ufunc_reconstruct');
  4984. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4985. return numpy.ndarray.__new__(subtype, shape, dtype);
  4986. });
  4987. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4988. const shape = [buf.length / dtype.itemsize];
  4989. return new numpy.ndarray(shape, dtype, buf);
  4990. });
  4991. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  4992. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  4993. });
  4994. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4995. return new numpy.dtypes.StringDType();
  4996. });
  4997. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4998. let data = rawData;
  4999. if (typeof rawData === 'string' || rawData instanceof String) {
  5000. data = new Uint8Array(rawData.length);
  5001. for (let i = 0; i < rawData.length; i++) {
  5002. data[i] = rawData.charCodeAt(i);
  5003. }
  5004. }
  5005. switch (dtype.kind) {
  5006. case 'b': {
  5007. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5008. switch (dtype.itemsize) {
  5009. case 1: return view.getInt8(0) ? true : false;
  5010. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  5011. }
  5012. }
  5013. case 'f': {
  5014. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5015. switch (dtype.itemsize) {
  5016. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  5017. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  5018. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  5019. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  5020. }
  5021. }
  5022. case 'i': {
  5023. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5024. switch (dtype.itemsize) {
  5025. case 1: return view.getInt8(0);
  5026. case 2: return view.getInt16(0, dtype.byteorder === '<');
  5027. case 4: return view.getInt32(0, dtype.byteorder === '<');
  5028. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  5029. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  5030. }
  5031. }
  5032. case 'u': {
  5033. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5034. switch (dtype.itemsize) {
  5035. case 1: return view.getUint8(0);
  5036. case 2: return view.getUint16(0, dtype.byteorder === '<');
  5037. case 4: return view.getUint32(0, dtype.byteorder === '<');
  5038. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5039. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5040. }
  5041. }
  5042. case 'U': {
  5043. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5044. const list = [];
  5045. for (let i = 0; i < dtype.itemsize; i += 4) {
  5046. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5047. }
  5048. return list.join('');
  5049. }
  5050. default: {
  5051. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5052. }
  5053. }
  5054. });
  5055. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5056. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5057. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5058. this.registerFunction('numpy.core._multiarray_umath.greater');
  5059. this.registerFunction('numpy.core._multiarray_umath.less');
  5060. this.registerFunction('numpy.core._multiarray_umath.log');
  5061. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5062. let data = rawData;
  5063. if (typeof rawData === 'string') {
  5064. data = new Uint8Array(rawData.length);
  5065. for (let i = 0; i < rawData.length; i++) {
  5066. data[i] = rawData.charCodeAt(i);
  5067. }
  5068. }
  5069. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5070. switch (dtype.__name__) {
  5071. case 'uint8':
  5072. return dataView.getUint8(0);
  5073. case 'float32':
  5074. return dataView.getFloat32(0, true);
  5075. case 'float64':
  5076. return dataView.getFloat64(0, true);
  5077. case 'int8':
  5078. return dataView.getInt8(0, true);
  5079. case 'int16':
  5080. return dataView.getInt16(0, true);
  5081. case 'int32':
  5082. return dataView.getInt32(0, true);
  5083. case 'int64':
  5084. return dataView.getBigInt64(0, true);
  5085. default:
  5086. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5087. }
  5088. });
  5089. this.registerFunction('numpy.core._multiarray_umath.sin');
  5090. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5091. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5092. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5093. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5094. this.register('numpy.core.numeric', numpy._core.numeric);
  5095. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5096. this.registerFunction('numpy.load', (file) => {
  5097. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5098. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5099. if (!file.read(6).every((v, i) => v === signature[i])) {
  5100. throw new python.Error('Invalid signature.');
  5101. }
  5102. const version = file.read(2);
  5103. const [major, minor] = version;
  5104. if (major > 3) {
  5105. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5106. }
  5107. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5108. let data = null;
  5109. switch (dtype.byteorder) {
  5110. case '|': {
  5111. data = file.read();
  5112. if (dtype.kind === 'O') {
  5113. const unpickler = new pickle.Unpickler(data);
  5114. return unpickler.load();
  5115. }
  5116. break;
  5117. }
  5118. case '>':
  5119. case '<': {
  5120. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5121. const stream = file.getbuffer().nbytes > 0x1000000;
  5122. data = file.read(dtype.itemsize * count, stream);
  5123. break;
  5124. }
  5125. default: {
  5126. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5127. }
  5128. }
  5129. if (fortran_order) {
  5130. data = null;
  5131. }
  5132. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5133. });
  5134. this.registerFunction('numpy.save', (file, arr) => {
  5135. const descr = arr.dtype.str;
  5136. if (descr[0] !== '<' && descr[0] !== '>') {
  5137. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5138. }
  5139. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5140. throw new python.Error(`Unsupported data type '${descr}'.`);
  5141. }
  5142. let shape = '';
  5143. switch (arr.shape.length) {
  5144. case 0: shape = '()'; break;
  5145. case 1: shape = `(${arr.shape[0]},)`; break;
  5146. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5147. }
  5148. const properties = [
  5149. `'descr': '${descr}'`,
  5150. "'fortran_order': False",
  5151. `'shape': ${shape}`
  5152. ];
  5153. let header = `{ ${properties.join(', ')} }`;
  5154. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5155. const encoder = new TextEncoder('ascii');
  5156. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5157. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5158. file.write(encoder.encode(header));
  5159. file.write(arr.tobytes());
  5160. });
  5161. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5162. const buffer = new Uint8Array([0, 0, 0, 0]);
  5163. const [major] = version;
  5164. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5165. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5166. let header = file.read(header_length);
  5167. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5168. header = decoder.decode(header).trim();
  5169. try {
  5170. header = ast.literal_eval(header);
  5171. } catch {
  5172. if (major <= 2) {
  5173. header = numpy.lib._format_impl._filter_header(header);
  5174. header = ast.literal_eval(header);
  5175. }
  5176. }
  5177. if (header.descr === undefined) {
  5178. throw new python.Error("Invalid 'descr'.");
  5179. }
  5180. if (!Array.isArray(header.shape)) {
  5181. throw new python.Error("Invalid 'shape'.");
  5182. }
  5183. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5184. return [header.shape, header.fortran_order, dtype];
  5185. });
  5186. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5187. if (typeof descr === 'string') {
  5188. return new numpy.dtype(descr);
  5189. } else if (descr instanceof builtins.tuple) {
  5190. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5191. return new numpy.dtype([dt, descr[1]]);
  5192. }
  5193. const titles = [];
  5194. const names = [];
  5195. const formats = [];
  5196. const offsets = [];
  5197. let offset = 0;
  5198. for (const field of descr) {
  5199. let name = null;
  5200. let dt = null;
  5201. let descr_str = null;
  5202. let shape = null;
  5203. let title = null;
  5204. if (field.length === 2) {
  5205. [name, descr_str] = field;
  5206. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5207. } else {
  5208. [name, descr_str, shape] = field;
  5209. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5210. }
  5211. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5212. if (!is_pad) {
  5213. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5214. titles.push(title);
  5215. names.push(name);
  5216. formats.push(dt);
  5217. offsets.push(offset);
  5218. }
  5219. offset += dt.itemsize;
  5220. }
  5221. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5222. });
  5223. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5224. const tokens = [];
  5225. const tokenizer = new ast._Tokenizer(s, '');
  5226. while (!tokenizer.match('eof')) {
  5227. const token = tokenizer.read();
  5228. if (token.type === 'int') {
  5229. const next = tokenizer.peek();
  5230. if (next.type === 'id' && next.value === 'L') {
  5231. tokenizer.read();
  5232. }
  5233. }
  5234. tokens.push(token.value);
  5235. }
  5236. return tokens.join('');
  5237. });
  5238. this.registerFunction('numpy.amin');
  5239. this.registerFunction('numpy.amax');
  5240. this.registerFunction('numpy.std');
  5241. this.registerFunction('numpy.asarray', (a, dtype) => {
  5242. const encode = (context, data, dim) => {
  5243. const size = context.shape[dim];
  5244. const littleendian = context.littleendian;
  5245. if (dim === context.shape.length - 1) {
  5246. for (let i = 0; i < size; i++) {
  5247. switch (context.dtype) {
  5248. case 'f2':
  5249. context.view.setFloat16(context.position, data[i], littleendian);
  5250. break;
  5251. case 'f4':
  5252. context.view.setFloat32(context.position, data[i], littleendian);
  5253. break;
  5254. case 'f8':
  5255. context.view.setFloat64(context.position, data[i], littleendian);
  5256. break;
  5257. case 'i1':
  5258. context.view.setInt8(context.position, data[i], littleendian);
  5259. break;
  5260. case 'i2':
  5261. context.view.setInt16(context.position, data[i], littleendian);
  5262. break;
  5263. case 'i4':
  5264. context.view.setInt32(context.position, data[i], littleendian);
  5265. break;
  5266. case 'i8':
  5267. context.view.setBigInt64(context.position, typeof data[i] === 'number' ? BigInt(data[i]) : data[i], littleendian);
  5268. break;
  5269. case 'u1':
  5270. context.view.setUint8(context.position, data[i], littleendian);
  5271. break;
  5272. case 'u2':
  5273. context.view.setUint16(context.position, data[i], littleendian);
  5274. break;
  5275. case 'u4':
  5276. context.view.setUint32(context.position, data[i], littleendian);
  5277. break;
  5278. case 'u8':
  5279. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5280. break;
  5281. case 'c8':
  5282. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5283. break;
  5284. case 'c16':
  5285. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5286. break;
  5287. case 'b1':
  5288. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5289. break;
  5290. default:
  5291. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5292. }
  5293. context.position += context.itemsize;
  5294. }
  5295. } else {
  5296. for (let j = 0; j < size; j++) {
  5297. encode(context, data[j], dim + 1);
  5298. }
  5299. }
  5300. };
  5301. const array_size = (value) => {
  5302. if (value.every((item) => Array.isArray(item))) {
  5303. const dims = value.map((item) => array_size(item));
  5304. const [dim] = dims;
  5305. for (let i = 1; i < dims.length; i++) {
  5306. if (dim.length === dims[i].length) {
  5307. if (!dims[i].every((value, i) => value === dim[i])) {
  5308. throw new python.Error('Invalid array shape.');
  5309. }
  5310. }
  5311. }
  5312. return [value.length].concat(dim);
  5313. }
  5314. return [value.length];
  5315. };
  5316. const shape = Array.isArray(a) ? array_size(a) : [];
  5317. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5318. const context = {
  5319. position: 0,
  5320. itemsize: dtype.itemsize,
  5321. dtype: dtype.str.substring(1),
  5322. littleendian: dtype.str[0],
  5323. shape,
  5324. data: new Uint8Array(size)
  5325. };
  5326. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5327. encode(context, a, 0);
  5328. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5329. });
  5330. this.registerFunction('numpy.max');
  5331. this.registerFunction('numpy.mean');
  5332. this.registerFunction('numpy.min');
  5333. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5334. const data = self.invoke(baseclass, [baseshape, basetype]);
  5335. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5336. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5337. return self.invoke(subtype, [data, mask, basetype]);
  5338. });
  5339. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5340. return {};
  5341. });
  5342. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5343. return {};
  5344. });
  5345. this.registerType('numpy.random.bit_generator.BitGenerator', class {
  5346. __setstate__(state) {
  5347. if (state instanceof Map || !Array.isArray(state)) {
  5348. this.state = state;
  5349. } else {
  5350. [this.state, this._seed_seq] = state;
  5351. }
  5352. }
  5353. });
  5354. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5355. __setstate__(state) {
  5356. [this.entropy, this.n_children_spawned, this.pool, this.pool_size, this.spawn_key] = state;
  5357. }
  5358. });
  5359. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5360. const obj = new cls();
  5361. if (state) {
  5362. obj.__setstate__(state);
  5363. }
  5364. return obj;
  5365. });
  5366. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5367. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5368. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5369. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5370. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5371. numpy.random._pickle.BitGenerators = {
  5372. 'MT19937': numpy.random._mt19937.MT19937,
  5373. 'PCG64': numpy.random._pcg64.PCG64,
  5374. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5375. 'Philox': numpy.random._philox.Philox,
  5376. 'SFC64': numpy.random._sfc64.SFC64,
  5377. };
  5378. this.registerType('numpy.random._generator.Generator', class {
  5379. constructor(bit_generator) {
  5380. this.bit_generator = bit_generator;
  5381. }
  5382. });
  5383. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5384. bit_generator = bit_generator || 'MT19937';
  5385. let bit_gen_class = null;
  5386. if (builtins.isinstance(bit_generator, builtins.type)) {
  5387. bit_gen_class = bit_generator;
  5388. } else {
  5389. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5390. }
  5391. if (bit_gen_class) {
  5392. return new bit_gen_class();
  5393. }
  5394. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5395. });
  5396. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5397. if (bit_generator_name instanceof numpy.random.bit_generator.BitGenerator) {
  5398. return new numpy.random._generator.Generator(bit_generator_name);
  5399. }
  5400. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5401. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5402. });
  5403. this.registerFunction('numpy.reshape');
  5404. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5405. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5406. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5407. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5408. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5409. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5410. this.registerFunction('sklearn.metrics._classification.f1_score');
  5411. this.registerFunction('sklearn.metrics._classification.log_loss');
  5412. this.registerFunction('sklearn.metrics._classification.precision_score');
  5413. this.registerFunction('sklearn.metrics._classification.recall_score');
  5414. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5415. return obj.__new__(obj);
  5416. });
  5417. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5418. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5419. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5420. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5421. this.registerFunction('sklearn.metrics._regression.r2_score');
  5422. sklearn.metrics.regression = sklearn.metrics._regression;
  5423. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5424. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5425. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5426. this.registerFunction('re._compile', (pattern, flags) => {
  5427. return self.invoke('re.Pattern', [pattern, flags]);
  5428. });
  5429. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5430. return function() {
  5431. return self.invoke(`types.${args[0]}`, args);
  5432. };
  5433. });
  5434. this.registerType('sympy.printing.defaults.Printable', class {});
  5435. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5436. constructor(...args) {
  5437. super();
  5438. this._args = args;
  5439. }
  5440. get args() {
  5441. return this._args;
  5442. }
  5443. });
  5444. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5445. });
  5446. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5447. });
  5448. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5449. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5450. __str__() {
  5451. return this._args.map((a) => a.__str__()).join('**');
  5452. }
  5453. });
  5454. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5455. __str__() {
  5456. return this._args.map((a) => a.__str__()).join(' + ');
  5457. }
  5458. });
  5459. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5460. __str__() {
  5461. return this._args.map((a) => a.__str__()).join('*');
  5462. }
  5463. });
  5464. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5465. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5466. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5467. constructor(value) {
  5468. super();
  5469. this.value = value;
  5470. this.is_Integer = true;
  5471. }
  5472. __int__() {
  5473. return this.value;
  5474. }
  5475. __str__() {
  5476. return this.value.toString();
  5477. }
  5478. });
  5479. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5480. constructor(name) {
  5481. super();
  5482. this.name = name;
  5483. }
  5484. __int__() {
  5485. throw new python.Error('Cannot convert symbols to int.');
  5486. }
  5487. __str__() {
  5488. return this.name;
  5489. }
  5490. });
  5491. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5492. constructor(lhs, rhs, op) {
  5493. super();
  5494. this._args = [lhs, rhs];
  5495. this._op = op;
  5496. }
  5497. __str__() {
  5498. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5499. }
  5500. });
  5501. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5502. });
  5503. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5504. });
  5505. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5506. constructor(lhs, rhs) {
  5507. super(lhs, rhs, '>=');
  5508. }
  5509. });
  5510. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5511. });
  5512. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5513. constructor(lhs, rhs) {
  5514. super(lhs, rhs, '<=');
  5515. }
  5516. });
  5517. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5518. constructor(lhs, rhs) {
  5519. super(lhs, rhs, '<');
  5520. }
  5521. });
  5522. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5523. constructor(lhs, rhs) {
  5524. super(lhs, rhs, '>');
  5525. }
  5526. });
  5527. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5528. constructor(lhs, rhs) {
  5529. super(lhs, rhs, '==');
  5530. }
  5531. });
  5532. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5533. });
  5534. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5535. __str__() {
  5536. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5537. }
  5538. });
  5539. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5540. if (a instanceof sympy.core.expr.Expr) {
  5541. return a;
  5542. }
  5543. const p = ast.parse(a);
  5544. const sympify = (node) => {
  5545. if (node instanceof ast.Call) {
  5546. switch (node.func.id) {
  5547. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5548. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5549. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5550. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5551. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5552. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5553. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5554. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5555. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5556. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5557. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5558. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5559. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5560. }
  5561. }
  5562. if (node instanceof ast.Name) {
  5563. return new sympy.core.symbol.Symbol(node.id);
  5564. }
  5565. if (node instanceof ast.Constant) {
  5566. if (node.type === 'int') {
  5567. return new sympy.core.numbers.Integer(node.value);
  5568. }
  5569. }
  5570. if (node instanceof ast.BinOp) {
  5571. if (node.op instanceof ast.Mult) {
  5572. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5573. }
  5574. if (node.op instanceof ast.Pow) {
  5575. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5576. }
  5577. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5578. }
  5579. if (node instanceof ast.Compare) {
  5580. const left = sympify(node.left);
  5581. const right = sympify(node.comparators[0]);
  5582. const [op] = node.ops;
  5583. if (op instanceof ast.Gt) {
  5584. return new sympy.core.relational.StrictGreaterThan(left, right);
  5585. }
  5586. if (op instanceof ast.GtE) {
  5587. return new sympy.core.relational.GreaterThan(left, right);
  5588. }
  5589. if (op instanceof ast.Lt) {
  5590. return new sympy.core.relational.StrictLessThan(left, right);
  5591. }
  5592. if (op instanceof ast.LtE) {
  5593. return new sympy.core.relational.LessThan(left, right);
  5594. }
  5595. if (op instanceof ast.Eq) {
  5596. return new sympy.core.relational.Equality(left, right);
  5597. }
  5598. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5599. }
  5600. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5601. };
  5602. return sympify(p.body[0].value);
  5603. });
  5604. this.registerFunction('theano.scalar.basic.same_out');
  5605. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5606. this.registerFunction('theano.scalar.basic.upcast_out');
  5607. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5608. this.registerFunction('theano.tensor.nnet.conv2d');
  5609. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5610. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5611. this.registerType('torch.nn.modules.module.Module', class {
  5612. constructor() {
  5613. this._modules = new collections.OrderedDict();
  5614. this._parameters = new collections.OrderedDict();
  5615. this._buffers = new collections.OrderedDict();
  5616. }
  5617. __setattr__(name, value) {
  5618. if (value instanceof torch.nn.modules.module.Module) {
  5619. this._modules.set(name, value);
  5620. } else {
  5621. this[name] = value;
  5622. }
  5623. }
  5624. __getattr__(name) {
  5625. if (this._modules.has(name)) {
  5626. return this._modules.get(name);
  5627. }
  5628. return this[name];
  5629. }
  5630. __delattr__(name) {
  5631. if (this._modules.has(name)) {
  5632. this._modules.delete(name);
  5633. }
  5634. }
  5635. children() {
  5636. return this._modules.values();
  5637. }
  5638. named_modules(memo, prefix, remove_duplicate) {
  5639. memo = memo || new Set();
  5640. prefix = prefix || '';
  5641. const modules = new builtins.dict();
  5642. if (!memo.has(this)) {
  5643. if (remove_duplicate) {
  5644. memo.add(this);
  5645. }
  5646. modules.set(prefix, this);
  5647. for (const [name, module] of this._modules.items()) {
  5648. if (module && module.named_modules) {
  5649. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5650. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5651. modules.set(k, v);
  5652. }
  5653. }
  5654. }
  5655. }
  5656. return modules;
  5657. }
  5658. named_children() {
  5659. return this._modules;
  5660. }
  5661. parameters() {
  5662. return this._parameters.values();
  5663. }
  5664. named_parameters(recurse) {
  5665. if (recurse) {
  5666. throw new python.Error('Named parameters with recurse not implemented.');
  5667. }
  5668. return this._parameters;
  5669. }
  5670. buffers() {
  5671. return this._buffers.values();
  5672. }
  5673. named_buffers(recurse) {
  5674. if (recurse) {
  5675. throw new python.Error('Named parameters with recurse not implemented.');
  5676. }
  5677. return this._buffers;
  5678. }
  5679. _get_name() {
  5680. return this.__class__.__name__;
  5681. }
  5682. add_module(name, module) {
  5683. this._modules.set(name, module);
  5684. }
  5685. register_module(name, module) {
  5686. this.add_module(name, module);
  5687. }
  5688. });
  5689. torch.nn.Module = torch.nn.modules.module.Module;
  5690. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5691. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5692. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5693. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5694. this.registerType('torch._C.SchemaParser', class {
  5695. constructor(str, allow_typevars) {
  5696. this.L = new torch._C.Lexer(str);
  5697. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5698. }
  5699. parseName() {
  5700. const L = this.L;
  5701. let name = L.expect('id').text();
  5702. if (L.nextIf(':')) {
  5703. L.expect(':');
  5704. name = `${name}::${L.expect('ident').text()}`;
  5705. }
  5706. let overload_name = '';
  5707. if (L.nextIf('.')) {
  5708. overload_name = L.expect('ident').text();
  5709. }
  5710. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5711. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5712. return new torch._C.OperatorName(name, overload_name);
  5713. }
  5714. parseDeclaration() {
  5715. const L = this.L;
  5716. const name = this.parseName();
  5717. if (L.cur().kind !== '(') {
  5718. return name;
  5719. }
  5720. throw new python.Error('Not implemented.');
  5721. }
  5722. parseExactlyOneDeclaration() {
  5723. // const L = this.L;
  5724. const result = this.parseDeclaration();
  5725. // L.nextIf(TK_NEWLINE);
  5726. // L.expect(TK_EOF);
  5727. return result;
  5728. }
  5729. parseArgument(idx, is_return, kwarg_only) {
  5730. const L = this.L;
  5731. const type_parser = this.type_parser;
  5732. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5733. let N = null;
  5734. if (L.nextIf('[')) {
  5735. fake_type = torch.ListType.create(fake_type);
  5736. real_type = torch.ListType.create(real_type);
  5737. if (L.cur().kind === '#') {
  5738. N = Number(L.cur().text());
  5739. L.next();
  5740. }
  5741. L.expect(']');
  5742. let container = type_parser.parseAliasAnnotation();
  5743. if (alias_info) {
  5744. if (!container) {
  5745. container = new torch._C.AliasInfo();
  5746. container.is_write = alias_info.is_write;
  5747. }
  5748. container.addContainedType(alias_info);
  5749. }
  5750. alias_info = container;
  5751. if (L.nextIf('?')) {
  5752. fake_type = torch.OptionalType.create(fake_type);
  5753. real_type = torch.OptionalType.create(real_type);
  5754. }
  5755. }
  5756. let name = null;
  5757. /* eslint-disable no-undef-init */
  5758. let default_value = undefined;
  5759. /* eslint-enable no-undef-init */
  5760. if (is_return) {
  5761. kwarg_only = false;
  5762. if (L.cur().kind === 'id') {
  5763. name = L.next().text();
  5764. } else {
  5765. name = '';
  5766. }
  5767. } else {
  5768. name = L.expect('id').text();
  5769. if (L.nextIf('=')) {
  5770. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5771. }
  5772. }
  5773. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5774. }
  5775. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5776. // auto range = L.cur().range;
  5777. const L = this.L;
  5778. const range = null;
  5779. switch (kind) {
  5780. case torch._C.TypeKind.StringType:
  5781. case torch._C.TypeKind.OptionalType:
  5782. case torch._C.TypeKind.NumberType:
  5783. case torch._C.TypeKind.IntType:
  5784. case torch._C.TypeKind.BoolType:
  5785. case torch._C.TypeKind.FloatType:
  5786. case torch._C.TypeKind.ComplexType:
  5787. return this.parseSingleConstant(arg_type, kind, real_type);
  5788. case torch._C.TypeKind.ListType: {
  5789. const elem_type = arg_type.containedType(0);
  5790. const real_elem_type = real_type.containedType(0);
  5791. if (L.cur().kind === 'id') {
  5792. return this.parseTensorDefault(range);
  5793. } else if (arg_N && L.cur().kind !== '[') {
  5794. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5795. const repeated = Array(arg_N).fill(v);
  5796. // std::vector<IValue> repeated(arg_N, v);
  5797. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5798. }
  5799. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5800. }
  5801. case torch._C.TypeKind.DynamicType:
  5802. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5803. default:
  5804. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5805. }
  5806. }
  5807. parseSingleConstant(type, kind, real_type) {
  5808. const L = this.L;
  5809. if (kind === torch._C.TypeKind.DynamicType) {
  5810. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5811. }
  5812. // const auto& str2dtype = c10::getStringToDtypeMap();
  5813. if (L.cur().kind === 'id') {
  5814. if (L.cur().text() === 'True') {
  5815. L.next();
  5816. return new torch._C.IValue(true);
  5817. }
  5818. if (L.cur().text() === 'False') {
  5819. L.next();
  5820. return new torch._C.IValue(false);
  5821. }
  5822. if (L.cur().text() === 'None') {
  5823. L.next();
  5824. return new torch._C.IValue();
  5825. }
  5826. } else if (L.cur().kind === 'string') {
  5827. const token = L.next();
  5828. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5829. } else if (L.cur().kind === '#') {
  5830. let n = '';
  5831. if (L.nextIf('-')) {
  5832. n = `-${L.expect('#').text()}`; // # .text();
  5833. } else {
  5834. n = L.expect('#').text(); // # .text();
  5835. }
  5836. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5837. throw new Error("Complex type not implemented.");
  5838. /*
  5839. const imag = std::stod(n.substr(0, n.size() - 1));
  5840. return c10::complex<double>(0, imag);
  5841. */
  5842. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5843. const v = parseFloat(n);
  5844. return new torch._C.IValue(v, 'Double');
  5845. } else {
  5846. const v = parseInt(n, 10);
  5847. return new torch._C.IValue(v, 'Int');
  5848. }
  5849. }
  5850. throw new python.Error('Not implemented.');
  5851. /*
  5852. switch (L.cur().kind) {
  5853. case TK_TRUE:
  5854. L.next();
  5855. return true;
  5856. case TK_FALSE:
  5857. L.next();
  5858. return false;
  5859. case TK_NONE:
  5860. L.next();
  5861. return IValue();
  5862. case TK_STRINGLITERAL: {
  5863. const token = L.next();
  5864. return parseStringLiteral(token.range, token.text());
  5865. }
  5866. case TK_IDENT: {
  5867. const tok = L.next();
  5868. const text_view = tok.text_view();
  5869. // NB: float/complex/long are here for BC purposes. Other dtypes
  5870. // are handled via str2dtype.
  5871. // Please don't add more cases to this if-else block.
  5872. if ("float" == text_view) {
  5873. return static_cast<int64_t>("at::kFloat");
  5874. } else if ("complex" == text_view) {
  5875. return static_cast<int64_t>("at::kComplexFloat");
  5876. } else if ("long" == text_view) {
  5877. return static_cast<int64_t>("at::kLong");
  5878. } else if ("strided" == text_view) {
  5879. return static_cast<int64_t>("at::kStrided");
  5880. } else if ("Mean" == text_view) {
  5881. return static_cast<int64_t>("at::Reduction::Mean");
  5882. } else if ("contiguous_format" == text_view) {
  5883. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5884. } else {
  5885. const text = tok.text();
  5886. if (isPossiblyOptionalScalarType(real_type) &&
  5887. str2dtype.count(text) > 0) {
  5888. return static_cast<int64_t>(str2dtype.at(text));
  5889. } else {
  5890. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5891. }
  5892. }
  5893. }
  5894. default: {
  5895. let n;
  5896. if (L.nextIf('-')) {
  5897. n = "-" + L.expect(TK_NUMBER).text();
  5898. }
  5899. else {
  5900. n = L.expect(TK_NUMBER).text();
  5901. }
  5902. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5903. throw new python.Error('Complex type not implemented.');
  5904. const imag = std::stod(n.substr(0, n.size() - 1));
  5905. return c10::complex<double>(0, imag);
  5906. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5907. throw new python.Error('Float type not implemented.');
  5908. return std::stod(n);
  5909. } else {
  5910. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5911. int64_t v = std::stoll(n);
  5912. return v;
  5913. }
  5914. }
  5915. }
  5916. */
  5917. }
  5918. parseConstantList(type, kind, real_type) {
  5919. const L = this.L;
  5920. const tok = L.expect('[');
  5921. const vs = [];
  5922. if (L.cur().kind !== ']') {
  5923. do {
  5924. vs.push(this.parseSingleConstant(type, kind, real_type));
  5925. } while (L.nextIf(','));
  5926. }
  5927. L.expect(']');
  5928. return this.convertToList(type, kind, tok.range, vs);
  5929. }
  5930. convertToList(type, kind, range, vs) {
  5931. switch (kind) {
  5932. case torch._C.TypeKind.ComplexType:
  5933. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5934. case torch._C.TypeKind.FloatType:
  5935. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5936. case torch._C.TypeKind.IntType:
  5937. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5938. case torch._C.TypeKind.BoolType:
  5939. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5940. case torch._C.TypeKindDynamicType:
  5941. return this.convertToList(type.dynamicKind(), range, vs);
  5942. default:
  5943. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5944. throw new python.Error('lists are only supported for float, int and complex types');
  5945. }
  5946. }
  5947. });
  5948. this.registerType('torch.FunctionSchema', class {
  5949. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5950. const index = name.indexOf('(');
  5951. if (index === -1) {
  5952. this._name = name;
  5953. this._overload_name = overload_name || '';
  5954. this._arguments = args || [];
  5955. this._returns = returns || [];
  5956. this._is_vararg = is_vararg || false;
  5957. this._is_varret = is_varret || false;
  5958. } else {
  5959. const value = name.substring(0, index).trim();
  5960. const dot = value.indexOf('.');
  5961. if (dot === -1) {
  5962. this._name = value;
  5963. this._overload_name = '';
  5964. } else {
  5965. this._name = value.substring(0, dot);
  5966. this._overload_name = value.substring(dot + 1, value.length);
  5967. }
  5968. this._buffer = name.substring(index, name.length);
  5969. }
  5970. }
  5971. static parse(schema) {
  5972. return new torch.FunctionSchema(schema);
  5973. }
  5974. get name() {
  5975. return this._name;
  5976. }
  5977. get overload_name() {
  5978. return this._overload_name;
  5979. }
  5980. get arguments() {
  5981. this._parse();
  5982. return this._arguments;
  5983. }
  5984. get returns() {
  5985. this._parse();
  5986. return this._returns;
  5987. }
  5988. get is_vararg() {
  5989. this._parse();
  5990. return this._is_vararg;
  5991. }
  5992. get is_varret() {
  5993. this._parse();
  5994. return this._is_varret;
  5995. }
  5996. argumentIndexWithName(name) {
  5997. const index = this.arguments.findIndex((arg) => arg.name === name);
  5998. return index === -1 ? null : index;
  5999. }
  6000. _parse() {
  6001. if (this._buffer) {
  6002. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  6003. const L = parser.L;
  6004. this._arguments = [];
  6005. this._is_vararg = false;
  6006. this._kwarg_only = false;
  6007. let idx = 0;
  6008. L.expect('(');
  6009. if (!L.nextIf(')')) {
  6010. while (true) {
  6011. if (this._is_vararg) {
  6012. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  6013. }
  6014. if (L.nextIf('*')) {
  6015. this._kwarg_only = true;
  6016. } else if (L.nextIf('...')) {
  6017. this._is_vararg = true;
  6018. } else {
  6019. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  6020. this._arguments.push(argument);
  6021. }
  6022. if (!L.nextIf(',')) {
  6023. break;
  6024. }
  6025. }
  6026. L.expect(')');
  6027. }
  6028. L.expect('->');
  6029. this._returns = [];
  6030. this._is_varret = false;
  6031. if (L.nextIf('...')) {
  6032. this._is_varret = true;
  6033. } else if (L.nextIf('(')) {
  6034. if (!L.nextIf(')')) {
  6035. while (true) {
  6036. if (this._is_varret) {
  6037. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6038. }
  6039. if (L.nextIf('...')) {
  6040. this._is_varret = true;
  6041. } else {
  6042. const argument = parser.parseArgument(idx++, true, false);
  6043. this._returns.push(argument);
  6044. }
  6045. if (!L.nextIf(',')) {
  6046. break;
  6047. }
  6048. }
  6049. L.expect(')');
  6050. }
  6051. } else {
  6052. this._returns.push(parser.parseArgument(0, true, false));
  6053. }
  6054. delete this._buffer;
  6055. }
  6056. }
  6057. __str__() {
  6058. const list = [this.name];
  6059. const overload_name = this.overload_name;
  6060. if (overload_name !== '' && overload_name !== 'default') {
  6061. list.push(`.${this.overload_name}`);
  6062. }
  6063. list.push('(');
  6064. let first = true;
  6065. let kwarg_only = false;
  6066. for (const argument of this.arguments) {
  6067. if (!first) {
  6068. list.push(', ');
  6069. }
  6070. if (argument.kwarg_only && !kwarg_only) {
  6071. list.push('*, ');
  6072. kwarg_only = true;
  6073. }
  6074. first = false;
  6075. list.push(argument.str());
  6076. }
  6077. if (this.is_vararg) {
  6078. if (!first) {
  6079. list.push(', ');
  6080. }
  6081. first = true;
  6082. list.push('...');
  6083. }
  6084. list.push(') -> ');
  6085. const returns = this.returns;
  6086. const braces = !this.is_varret &&
  6087. (returns.length !== 1 ||
  6088. returns[0].name ||
  6089. returns[0].real_type instanceof torch.TupleType ||
  6090. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6091. if (braces) {
  6092. list.push('(');
  6093. }
  6094. first = true;
  6095. for (const argument of this.returns) {
  6096. if (!first) {
  6097. list.push(', ');
  6098. }
  6099. first = false;
  6100. list.push(argument.str());
  6101. }
  6102. if (this.is_varret) {
  6103. if (!first) {
  6104. list.push(', ');
  6105. }
  6106. first = true;
  6107. list.push('...');
  6108. }
  6109. if (braces) {
  6110. list.push(')');
  6111. }
  6112. return list.join('');
  6113. }
  6114. aliasAnalysis() {
  6115. return this._alias_kind || 'CONSERVATIVE';
  6116. }
  6117. setAliasAnalysis(v) {
  6118. this._alias_kind = v;
  6119. }
  6120. hasAnyAliasInfo() {
  6121. for (const arg of this.arguments) {
  6122. if (arg.alias_info !== null) {
  6123. return true;
  6124. }
  6125. }
  6126. for (const ret of this.returns) {
  6127. if (ret.alias_info !== null) {
  6128. return true;
  6129. }
  6130. }
  6131. return false;
  6132. }
  6133. is_mutable() {
  6134. return this.arguments.some((arg) => {
  6135. const aliasInfo = arg.alias_info;
  6136. return aliasInfo && aliasInfo.is_write;
  6137. });
  6138. }
  6139. });
  6140. this.registerType('torch._C.SchemaInfo', class {
  6141. constructor(schema) {
  6142. this._schema = schema;
  6143. this._alias_maps_current = false;
  6144. this._has_init = false;
  6145. }
  6146. is_nondeterministic() {
  6147. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6148. //
  6149. }
  6150. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6151. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6152. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6153. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6154. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6155. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6156. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6157. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6158. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6159. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6160. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6161. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6162. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6163. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6164. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6165. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6166. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6167. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6168. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6169. 'aten::randint_like(Tensor self, int high, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6170. 'aten::randint_like(Tensor self, int low, int high, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6171. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6172. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6173. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6174. ]);
  6175. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6176. return true;
  6177. }
  6178. /*
  6179. const auto& op = c10::Dispatcher::singleton().findOp(
  6180. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6181. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6182. */
  6183. return false;
  6184. }
  6185. });
  6186. this.registerType('torch._C.OperatorRegistry', class {
  6187. constructor() {
  6188. this.to_register = [];
  6189. this.operators = new Map();
  6190. }
  6191. registerPendingOperators() {
  6192. for (const op of this.to_register) {
  6193. const sym = op.schema().name;
  6194. if (!this.operators.has(sym)) {
  6195. this.operators.set(sym, []);
  6196. }
  6197. this.operators.get(sym).push(op);
  6198. }
  6199. this.to_register = [];
  6200. }
  6201. registerOperator(op) {
  6202. this.to_register.push(op);
  6203. }
  6204. getOperators(name) {
  6205. this.registerPendingOperators();
  6206. if (this.operators.has(name)) {
  6207. return this.operators.get(name);
  6208. }
  6209. return [];
  6210. }
  6211. });
  6212. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6213. return torch._C.getRegistry().getOperators(name);
  6214. });
  6215. this.registerType('torch._C.Operator', class {
  6216. constructor(schema) {
  6217. this._schema = schema;
  6218. }
  6219. schema() {
  6220. return this._schema;
  6221. }
  6222. getOperation(/* node */) {
  6223. return null;
  6224. }
  6225. aliasAnalysisKind() {
  6226. const schemaRef = this.schema();
  6227. const alias_analysis = schemaRef.aliasAnalysis();
  6228. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6229. return alias_analysis;
  6230. }
  6231. });
  6232. this.registerFunction('torch._C.getRegistry', () => {
  6233. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6234. return torch._C.r;
  6235. });
  6236. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6237. const operations = torch._C.getAllOperatorsFor(op_name);
  6238. for (const op of operations) {
  6239. if (op.schema().overload_name === overload_name) {
  6240. return op.schema();
  6241. }
  6242. }
  6243. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6244. });
  6245. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6246. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6247. });
  6248. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6249. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6250. if (sortedOps.length === 0) {
  6251. return [null, null];
  6252. }
  6253. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6254. return [{}, overload_names];
  6255. });
  6256. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6257. const operations = torch._C.getAllOperatorsFor(op_name);
  6258. for (const op of operations) {
  6259. if (op.schema().overload_name === overload_name) {
  6260. return [{}, {}, null];
  6261. }
  6262. }
  6263. return null;
  6264. });
  6265. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6266. return null;
  6267. });
  6268. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6269. });
  6270. this.registerType('torch._C.MatchedSchema', class {
  6271. constructor(inputs, return_types, return_field_names, schema_name) {
  6272. this.inputs = inputs;
  6273. this.return_types = return_types;
  6274. this.register_field_names = return_field_names;
  6275. this.schema_name = schema_name;
  6276. }
  6277. });
  6278. this.registerType('torch._C.Self', class {
  6279. });
  6280. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6281. return nvs.map((v) => v.value(g));
  6282. });
  6283. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6284. constructor(classType) {
  6285. super();
  6286. this._classType = classType;
  6287. }
  6288. makeSugared(v) {
  6289. v.setType(this._classType);
  6290. return new torch._C.SimpleValue(v);
  6291. }
  6292. getClassType() {
  6293. return this._classType;
  6294. }
  6295. });
  6296. this.registerType('torch._C.Function', class {
  6297. isGraphFunction() {
  6298. return false;
  6299. }
  6300. name() {
  6301. return this.qualname().name();
  6302. }
  6303. });
  6304. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6305. constructor(qualname, schema) {
  6306. super();
  6307. this._name = qualname;
  6308. this._schema = schema;
  6309. }
  6310. qualname() {
  6311. return this._name;
  6312. }
  6313. getSchema() {
  6314. return this._schema;
  6315. }
  6316. ensure_defined() {
  6317. }
  6318. });
  6319. this.registerType('torch._C.DeadCodeEliminator', class {
  6320. constructor(...args) {
  6321. this._aliasDb = null;
  6322. this._useAliasDb = false;
  6323. this._memo = new Map();
  6324. this._marked = new Set();
  6325. this._liveValues = new Set();
  6326. this._deleteCallback = () => {};
  6327. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6328. [this._graph, this._sideEffectPolicy] = args;
  6329. this._useAliasDb = true;
  6330. } else {
  6331. [this._sideEffectPolicy] = args;
  6332. }
  6333. }
  6334. run(block, recurse) {
  6335. this.eliminateDeadForkInputs(block, recurse);
  6336. this.mark(block.return_node());
  6337. this.mark(block);
  6338. this._deleteCallback(this._liveValues);
  6339. this.sweep(block, recurse);
  6340. }
  6341. setDeleteCallback(deleteCallback) {
  6342. this._deleteCallback = deleteCallback;
  6343. }
  6344. eliminateDeadForkInputs(block, recurse) {
  6345. for (const node of block.nodes()) {
  6346. if (recurse) {
  6347. for (const sb of node.blocks()) {
  6348. this.eliminateDeadForkInputs(sb, recurse);
  6349. }
  6350. }
  6351. if (node.kind() !== 'prim::fork') {
  6352. continue;
  6353. }
  6354. const g = node.g("Subgraph");
  6355. for (let i = 0; i < g.inputs().length; i++) {
  6356. if (!g.inputs()[i].hasUses()) {
  6357. g.eraseInput(i);
  6358. node.removeInput(i);
  6359. }
  6360. }
  6361. }
  6362. }
  6363. markReturnNode(node) {
  6364. if (this._marked.has(node)) {
  6365. return false;
  6366. }
  6367. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6368. const outerNode = node.owningBlock().owningNode();
  6369. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6370. return this.mark(node);
  6371. }
  6372. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6373. const loop = new torch._C.LoopView(outerNode);
  6374. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6375. if (outerNode.kind() === 'onnx::Loop') {
  6376. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6377. continue;
  6378. }
  6379. const innerInput = loop.bodyCarriedInputs()[i];
  6380. const innerOutput = loop.bodyCarriedOutputs()[i];
  6381. const outerOutput = loop.carriedOutputs()[i];
  6382. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6383. this._liveValues.add(innerOutput);
  6384. }
  6385. }
  6386. this._liveValues.add(loop.nextCond());
  6387. } else {
  6388. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6389. for (let i = 0; i < outerNode.outputs().length; i++) {
  6390. const innerOutput = node.inputs()[i];
  6391. const outerOutput = outerNode.outputs()[i];
  6392. if (!this._liveValues.has(outerOutput)) {
  6393. this._liveValues.add(innerOutput);
  6394. }
  6395. }
  6396. }
  6397. this._marked.add(node);
  6398. return true;
  6399. }
  6400. markLoop(node) {
  6401. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6402. let marked = false;
  6403. let anyMarked = false;
  6404. do {
  6405. marked = this.mark(node.blocks().at(0));
  6406. anyMarked = anyMarked || marked;
  6407. } while (marked);
  6408. return anyMarked;
  6409. }
  6410. mark(...args) {
  6411. if (args.length === 1 && args[0] instanceof torch.Block) {
  6412. const [block] = args;
  6413. let anyMarked = false;
  6414. for (const node of block.nodes()) {
  6415. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6416. const marked = this.mark(node);
  6417. anyMarked = anyMarked || marked;
  6418. }
  6419. }
  6420. const marked = this.markReturnNode(block.return_node());
  6421. anyMarked = anyMarked || marked;
  6422. for (const node of block.nodes()) {
  6423. if (node.kind() === 'prim::Loop') {
  6424. const marked = this.markLoop(node);
  6425. anyMarked = anyMarked || marked;
  6426. } else {
  6427. for (const subBlock of node.blocks()) {
  6428. const marked = this.mark(subBlock);
  6429. anyMarked = anyMarked || marked;
  6430. }
  6431. }
  6432. const marked = this.markIfLive(node);
  6433. anyMarked = anyMarked || marked;
  6434. }
  6435. return anyMarked;
  6436. }
  6437. if (args.length === 1 && args[0] instanceof torch.Node) {
  6438. const [node] = args;
  6439. if (this._marked.has(node)) {
  6440. return false;
  6441. }
  6442. this._marked.add(node);
  6443. let curNode = node;
  6444. while (curNode && curNode.owningBlock()) {
  6445. this.mark(curNode);
  6446. curNode = curNode.owningBlock().owningNode();
  6447. }
  6448. for (const input of node.inputs()) {
  6449. if (!this._liveValues.has(input)) {
  6450. this._liveValues.add(input);
  6451. }
  6452. }
  6453. return true;
  6454. }
  6455. throw new python.Error('Not implemented.');
  6456. }
  6457. markIfLive(node) {
  6458. for (const output of node.outputs()) {
  6459. if (this._liveValues.has(output)) {
  6460. return this.mark(node);
  6461. }
  6462. }
  6463. if (this._useAliasDb) {
  6464. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6465. return this.mark(node);
  6466. }
  6467. }
  6468. return false;
  6469. }
  6470. sweep(block, recurse) {
  6471. const nodes = Array.from(block.nodes()).reverse();
  6472. for (const node of nodes) {
  6473. this.removeDeadBlockOutputs(node);
  6474. this.removeDeadLoopOutputs(node);
  6475. if (recurse) {
  6476. for (const block of node.blocks()) {
  6477. this.sweep(block, true);
  6478. }
  6479. }
  6480. if (!this._marked.has(node) && !node.hasUses()) {
  6481. node.destroy();
  6482. }
  6483. }
  6484. }
  6485. hasUntrackedMutation(node) {
  6486. if (!this._useAliasDb) {
  6487. if (node.kind() === 'prim::SetAttr') {
  6488. return true;
  6489. }
  6490. const schema = node.maybeSchema();
  6491. return schema && schema.is_mutable();
  6492. }
  6493. return this.getOrCreateAliasDb().writesToWildcard(node);
  6494. }
  6495. hasSideEffects(node) {
  6496. const it = this._memo.get(node);
  6497. if (it) {
  6498. return it;
  6499. }
  6500. const has_side_effects = node.hasSideEffects() ||
  6501. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6502. this.hasUntrackedMutation(node);
  6503. this._memo.set(node, has_side_effects);
  6504. return has_side_effects;
  6505. }
  6506. removeDeadBlockOutputs(node) {
  6507. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6508. return;
  6509. }
  6510. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6511. const i = i_1 - 1;
  6512. if (!node.outputs()[i].hasUses()) {
  6513. node.eraseOutput(i);
  6514. for (const b of node.blocks()) {
  6515. b.eraseOutput(i);
  6516. }
  6517. }
  6518. }
  6519. }
  6520. removeDeadLoopOutputs() {
  6521. }
  6522. getOrCreateAliasDb() {
  6523. if (!this._aliasDb) {
  6524. this._aliasDb = new torch._C.AliasDb(this._graph);
  6525. }
  6526. return this._aliasDb;
  6527. }
  6528. });
  6529. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6530. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6531. const [graph] = args;
  6532. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6533. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6534. worker.run(graph.block(), /*recurse=*/true);
  6535. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6536. const [block] = args;
  6537. const recurse = false;
  6538. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6539. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6540. worker.run(block, recurse);
  6541. } else {
  6542. throw new python.Error('Not implemented.');
  6543. }
  6544. });
  6545. this.registerFunction('torch._C.removeTupleNodes', () => {
  6546. });
  6547. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6548. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6549. const [graph] = args;
  6550. torch._C.LowerSimpleTuples(graph.block());
  6551. torch._C.EliminateDeadCode(graph);
  6552. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6553. const [block] = args;
  6554. for (const n of block.nodes()) {
  6555. torch._C.removeTupleNodes(n, false);
  6556. for (const b of n.blocks()) {
  6557. torch._C.LowerSimpleTuples(b);
  6558. }
  6559. }
  6560. } else {
  6561. throw new python.Error('Not implemented.');
  6562. }
  6563. });
  6564. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6565. torch._C.AT_ASSERT(lhs !== null);
  6566. torch._C.AT_ASSERT(rhs !== null);
  6567. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6568. return false;
  6569. }
  6570. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6571. return true;
  6572. }
  6573. const lnames = lhs.attributeNames();
  6574. const rnames = rhs.attributeNames();
  6575. lnames.sort();
  6576. rnames.sort();
  6577. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6578. return false;
  6579. }
  6580. for (const name of lnames) {
  6581. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6582. return false;
  6583. }
  6584. const kind = lhs.kindOf(name);
  6585. switch (kind) {
  6586. case 'i':
  6587. case 'f':
  6588. case 's':
  6589. case 't': {
  6590. if (lhs[kind](name) !== rhs[kind](name)) {
  6591. return false;
  6592. }
  6593. break;
  6594. }
  6595. case 'c': {
  6596. const lc = lhs.c(name);
  6597. const rc = rhs.c(name);
  6598. if (lc.real !== rc.real || lc.imag !== rc.imag) {
  6599. return false;
  6600. }
  6601. break;
  6602. }
  6603. case 'ival': {
  6604. if (lhs[kind](name) !== rhs[kind](name)) {
  6605. return false;
  6606. }
  6607. break;
  6608. }
  6609. default: {
  6610. throw new python.Error('Not implemented.');
  6611. }
  6612. }
  6613. }
  6614. return true;
  6615. });
  6616. this.registerFunction('torch._C.get_hash', (...args) => {
  6617. let hash = 0;
  6618. for (const value of args) {
  6619. if (typeof value === 'number') {
  6620. hash += (value | 0);
  6621. } else if (typeof value === 'string') {
  6622. hash += (value.length | 0);
  6623. } else if (Array.isArray(value)) {
  6624. for (const item of value) {
  6625. hash += torch._C.get_hash(item);
  6626. }
  6627. } else if (value instanceof builtins.complex) {
  6628. hash += (value.real | 0) + (value.imag | 0);
  6629. }
  6630. }
  6631. return hash;
  6632. });
  6633. this.registerFunction('torch._C.HashNode', (k) => {
  6634. torch._C.AT_ASSERT(k !== null);
  6635. let constant_hash = 0;
  6636. if (k.kind() === 'prim::Constant') {
  6637. const type = k.output().type();
  6638. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6639. constant_hash = k.i('value');
  6640. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6641. constant_hash = k.f('value');
  6642. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6643. constant_hash = k.c('value');
  6644. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6645. constant_hash = k.i('value');
  6646. }
  6647. }
  6648. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6649. });
  6650. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6651. if (lhs === null && rhs === null) {
  6652. return true;
  6653. }
  6654. if (lhs === null || rhs === null) {
  6655. return false;
  6656. }
  6657. if (lhs.kind() !== rhs.kind()) {
  6658. return false;
  6659. }
  6660. const lhs_outputs = lhs.outputs();
  6661. const rhs_outputs = rhs.outputs();
  6662. if (lhs_outputs.length !== rhs_outputs.length) {
  6663. return false;
  6664. }
  6665. for (let i = 0; i < lhs_outputs.length; i++) {
  6666. const lt = lhs_outputs[i].type();
  6667. const rt = rhs_outputs[i].type();
  6668. if (!lt.equals(rt)) {
  6669. return false;
  6670. }
  6671. }
  6672. const lhs_inputs = lhs.inputs();
  6673. const rhs_inputs = rhs.inputs();
  6674. if (lhs_inputs.length !== rhs_inputs.length) {
  6675. return false;
  6676. }
  6677. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6678. return false;
  6679. }
  6680. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6681. return false;
  6682. }
  6683. if (lhs.blocks().length !== rhs.blocks().length) {
  6684. return false;
  6685. }
  6686. for (let i = 0; i < lhs.blocks().length; i++) {
  6687. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6688. return false;
  6689. }
  6690. }
  6691. return true;
  6692. });
  6693. this.registerType('torch._C.NodeSet', class {
  6694. constructor() {
  6695. this._nodes = new Map();
  6696. }
  6697. insert(n) {
  6698. const key = torch._C.HashNode(n);
  6699. if (this._nodes.has(key)) {
  6700. this._nodes.get(key).push(n);
  6701. } else {
  6702. this._nodes.set(key, [n]);
  6703. }
  6704. }
  6705. get(n) {
  6706. const key = torch._C.HashNode(n);
  6707. if (this._nodes.has(key)) {
  6708. const nodes = this._nodes.get(key);
  6709. for (const node of nodes) {
  6710. if (torch._C.EqualNode(node, n)) {
  6711. return node;
  6712. }
  6713. }
  6714. }
  6715. return null;
  6716. }
  6717. has(n) {
  6718. return this.get(n) !== null;
  6719. }
  6720. });
  6721. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6722. const ty = stack.pop().type();
  6723. for (const candidate of types) {
  6724. if (ty.isSubtypeOf(candidate)) {
  6725. stack.push(new torch._C.IValue(true, 'Bool'));
  6726. stack.push(true);
  6727. return;
  6728. }
  6729. }
  6730. stack.push(new torch._C.IValue(false, 'Bool'));
  6731. });
  6732. this.registerType('torch._C.Tuple', class {
  6733. constructor(elements) {
  6734. this._elements = elements;
  6735. }
  6736. static create(elements) {
  6737. return new torch._C.Tuple(elements);
  6738. }
  6739. elements() {
  6740. return this._elements;
  6741. }
  6742. });
  6743. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6744. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6745. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6746. const tuple = torch._C.Tuple.create(elems.reverse());
  6747. stack.push(new torch._C.IValue(tuple));
  6748. });
  6749. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6750. let stack = [];
  6751. for (const input of n.inputs()) {
  6752. const ival = torch._C.toIValue(input);
  6753. if (ival) {
  6754. stack.push(ival);
  6755. } else {
  6756. return null;
  6757. }
  6758. }
  6759. switch (n.kind()) {
  6760. case 'prim::ListUnpack': {
  6761. if (stack.back().toList().size() !== n.outputs().length) {
  6762. return null;
  6763. }
  6764. torch._C.listUnpack(stack, n.outputs().length);
  6765. break;
  6766. }
  6767. case 'prim::TupleConstruct': {
  6768. const tt = n.output().type().expect(torch.TupleType);
  6769. if (tt.name()) {
  6770. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6771. } else {
  6772. torch._C.tupleConstruct(stack, n.inputs().length);
  6773. }
  6774. break;
  6775. }
  6776. case 'prim::ListConstruct': {
  6777. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6778. break;
  6779. }
  6780. case 'prim::DictConstruct': {
  6781. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6782. break;
  6783. }
  6784. case 'prim::CreateObject': {
  6785. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6786. break;
  6787. }
  6788. case 'prim::GetAttr': {
  6789. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6790. torch._C.push(stack, attr);
  6791. break;
  6792. }
  6793. case 'prim::isinstance': {
  6794. torch._C.isinstance(stack, n.tys('types'));
  6795. break;
  6796. }
  6797. default: {
  6798. const maybe_schema = n.maybeSchema();
  6799. if (maybe_schema && maybe_schema.is_vararg) {
  6800. return null;
  6801. }
  6802. // try
  6803. // {
  6804. // const op = n.getOperation();
  6805. // op(stack);
  6806. const [module, name] = n.kind().split('::');
  6807. const obj = torch.ops[module];
  6808. if (!obj) {
  6809. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6810. }
  6811. const fn = torch.ops[module].__getattr__(name);
  6812. if (!fn || !fn.__call__) {
  6813. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6814. }
  6815. const args = stack.map((v) => v.value);
  6816. const result = fn.__call__(...args);
  6817. if (result === undefined) {
  6818. stack = [];
  6819. } else if (result instanceof torch._C.IValue) {
  6820. stack = [result];
  6821. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6822. stack = result;
  6823. } else {
  6824. stack = [new torch._C.IValue(result)];
  6825. }
  6826. // } catch {
  6827. // stack = [];
  6828. // return null;
  6829. // }
  6830. break;
  6831. }
  6832. }
  6833. for (const v of stack) {
  6834. if (v.isTensor()) {
  6835. const t = v.toTensor();
  6836. if (t.defined() && t.requires_grad()) {
  6837. return null;
  6838. }
  6839. }
  6840. if (ignore_custom_classes) {
  6841. if (v.isCustomClass()) {
  6842. return null;
  6843. }
  6844. }
  6845. if (v.isCustomClass()) {
  6846. if (v.toObject().is_weak_compilation_ref()) {
  6847. continue;
  6848. }
  6849. if (!db) {
  6850. continue;
  6851. }
  6852. const n_non_const = n;
  6853. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6854. continue;
  6855. }
  6856. const obj = v.toObject();
  6857. obj.unsafe_make_weak_compilation_ref();
  6858. }
  6859. if (v.isObject()) {
  6860. if (!v.toObject().is_weak_compilation_ref()) {
  6861. return null;
  6862. }
  6863. }
  6864. }
  6865. return stack;
  6866. });
  6867. this.registerType('torch._C.ConstantPropagator', class {
  6868. constructor(graph, aliasing_types, ignore_custom_classes) {
  6869. this._made_change = false;
  6870. this._graph = graph;
  6871. this._aliasing_types = aliasing_types;
  6872. this._ignore_custom_classes = ignore_custom_classes;
  6873. }
  6874. static NoAliasDb(graph) {
  6875. return new torch._C.ConstantPropagator(graph, false, false);
  6876. }
  6877. run() {
  6878. this.ConstantPropagation(this._graph.block());
  6879. return this._made_change;
  6880. }
  6881. propagateNode(n) {
  6882. let outputs = [];
  6883. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6884. if (outputs_opt) {
  6885. outputs = outputs_opt;
  6886. const graph = n.owningGraph();
  6887. const guard = new torch._C.WithInsertPoint(n);
  6888. for (let i = 0; i < outputs.length; i++) {
  6889. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6890. if (new_output) {
  6891. this._made_change = true;
  6892. if (outputs[i].isNone()) {
  6893. new_output.setType(n.outputs()[i].type());
  6894. }
  6895. n.outputs()[i].replaceAllUsesWith(new_output);
  6896. }
  6897. }
  6898. guard.dispose();
  6899. }
  6900. }
  6901. removeLoopNode(n) {
  6902. const loop_input_offset = 2;
  6903. for (let i = 0; i < n.outputs().length; i++) {
  6904. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6905. }
  6906. this._made_change = true;
  6907. n.destroy();
  6908. }
  6909. loopWillNotRun(node) {
  6910. const [trip_count, start_cond] = node.inputs();
  6911. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6912. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6913. const loop_might_run = cond_val && iter_len > 0;
  6914. return !loop_might_run;
  6915. }
  6916. inlineIfBody(body) {
  6917. const n = body.owningNode();
  6918. for (const body_node of body.nodes()) {
  6919. body_node.moveBefore(n);
  6920. }
  6921. for (let i = 0; i < n.outputs().length; i++) {
  6922. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6923. }
  6924. n.destroy();
  6925. }
  6926. inlineIf(n) {
  6927. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6928. torch._C.AT_ASSERT(input_bool !== null);
  6929. const block_index = input_bool ? 0 : 1;
  6930. this.ConstantPropagation(n.blocks().at(block_index));
  6931. this.inlineIfBody(n.blocks().at(block_index));
  6932. this._made_change = true;
  6933. }
  6934. replaceAndRemoveIfOutput(n, i, replacement) {
  6935. n.outputs()[i].replaceAllUsesWith(replacement);
  6936. n.eraseOutput(i);
  6937. n.blocks().at(0).eraseOutput(i);
  6938. n.blocks().at(1).eraseOutput(i);
  6939. }
  6940. removeExtraIfOutputs(n) {
  6941. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6942. const [true_block, false_block] = n.blocks();
  6943. const graph = n.owningGraph();
  6944. const initial_outputs = true_block.outputs().length;
  6945. const guard = new torch._C.WithInsertPoint(n);
  6946. for (let i = 0; i < true_block.outputs().length;) {
  6947. const t_out = true_block.outputs()[i];
  6948. const f_out = false_block.outputs()[i];
  6949. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6950. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6951. continue;
  6952. }
  6953. const maybe_const = torch._C.toIValue(t_out);
  6954. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6955. const new_const = graph.insertConstant(maybe_const);
  6956. this.replaceAndRemoveIfOutput(n, i, new_const);
  6957. continue;
  6958. }
  6959. i++;
  6960. }
  6961. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6962. guard.dispose();
  6963. }
  6964. removeExtraLoopOutputs(node) {
  6965. const initial_outputs = node.outputs().length;
  6966. const [loop_body] = node.blocks();
  6967. const loop_input_offset = 2;
  6968. const loop_body_offset = 1;
  6969. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6970. const i = i_1 - 1;
  6971. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6972. const node_input = node.inputs()[loop_input_offset + i];
  6973. node.outputs().at(i).replaceAllUsesWith(node_input);
  6974. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6975. node.eraseOutput(i);
  6976. node.removeInput(loop_input_offset + i);
  6977. loop_body.eraseInput(loop_body_offset + i);
  6978. loop_body.eraseOutput(loop_body_offset + i);
  6979. }
  6980. }
  6981. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6982. }
  6983. noMutableValues(values) {
  6984. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6985. }
  6986. getOrCreateAliasDb() {
  6987. if (!this._aliasDb) {
  6988. this._aliasDb = new torch._C.AliasDb(this._graph);
  6989. }
  6990. return this._aliasDb;
  6991. }
  6992. supportedNode(n) {
  6993. torch._C.skip_list = torch._C.skip_list || new Set([
  6994. 'prim::If',
  6995. 'prim::Loop',
  6996. 'prim::Closure',
  6997. 'prim::Constant',
  6998. 'prim::AutogradZero',
  6999. 'prim::Uninitialized',
  7000. 'prim::Guard',
  7001. 'prim::profile',
  7002. 'prim::profile_ivalue',
  7003. 'prim::unchecked_unwrap_optional',
  7004. 'prim::awaitable',
  7005. 'aten::dequantize'
  7006. ]);
  7007. let no_mutation = false;
  7008. if (this._aliasing_types) {
  7009. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  7010. } else {
  7011. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  7012. }
  7013. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  7014. }
  7015. ConstantPropagation(...args) {
  7016. if (args[0] instanceof torch.Graph) {
  7017. throw new python.Error('Not implemented.');
  7018. } else if (args[0] instanceof torch.Block) {
  7019. const [block] = args;
  7020. for (const n of block.nodes()) {
  7021. this.ConstantPropagation(n);
  7022. }
  7023. } else if (args[0] instanceof torch.Node) {
  7024. const [n] = args;
  7025. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  7026. if (n.kind() === 'prim::If') {
  7027. if (constant_inputs) {
  7028. this.inlineIf(n);
  7029. } else {
  7030. this.ConstantPropagation(n.blocks());
  7031. this.removeExtraIfOutputs(n);
  7032. }
  7033. } else if (n.kind() === 'prim::Loop') {
  7034. if (this.loopWillNotRun(n)) {
  7035. this.removeLoopNode(n);
  7036. } else {
  7037. this.ConstantPropagation(n.blocks());
  7038. this.removeExtraLoopOutputs(n);
  7039. }
  7040. } else if (constant_inputs && this.supportedNode(n)) {
  7041. this.propagateNode(n);
  7042. } else {
  7043. this.ConstantPropagation(n.blocks()); // not implemented
  7044. }
  7045. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7046. const [blocks] = args;
  7047. for (const block of blocks) {
  7048. this.ConstantPropagation(block);
  7049. }
  7050. } else {
  7051. throw new python.Error('Not implemented.');
  7052. }
  7053. }
  7054. });
  7055. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7056. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7057. const made_change = cp.run();
  7058. if (made_change) {
  7059. torch._C.EliminateDeadCode(graph);
  7060. }
  7061. return made_change;
  7062. });
  7063. this.registerType('torch._C.MutableTypePtrHelper', class {
  7064. constructor(mutable_type_cache) {
  7065. this._mutable_type_cache = mutable_type_cache;
  7066. }
  7067. mapTypeToAliasTypeSet(type) {
  7068. if (this._mutable_type_cache) {
  7069. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7070. if (result) {
  7071. return result;
  7072. }
  7073. }
  7074. return this.mapTypeToAliasTypeSetImpl(type);
  7075. }
  7076. mapTypeToAliasTypeSetImpl(type) {
  7077. if (type instanceof torch.ListType ||
  7078. type instanceof torch.DictType ||
  7079. type instanceof torch.ClassType ||
  7080. type instanceof torch.TensorType) {
  7081. return [torch._C.unshapedType(type)];
  7082. }
  7083. if (type instanceof torch.UnionType) {
  7084. const mutable_types = [];
  7085. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7086. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7087. if (maybe_inner_types) {
  7088. mutable_types.push(...maybe_inner_types);
  7089. }
  7090. }
  7091. if (mutable_types.length === 0) {
  7092. return null;
  7093. }
  7094. return mutable_types;
  7095. }
  7096. if (type instanceof torch.OptionalType) {
  7097. const inner = type.getElementType();
  7098. return this.mapTypeToAliasTypeSet(inner);
  7099. }
  7100. if (type instanceof torch.AnyType) {
  7101. return [torch._C.AliasTypeSet([type])];
  7102. }
  7103. if (type instanceof torch.FutureType) {
  7104. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7105. if (maybe_mut_types) {
  7106. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7107. }
  7108. return null;
  7109. }
  7110. if (type instanceof torch.AwaitType) {
  7111. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7112. if (maybe_mut_types) {
  7113. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7114. }
  7115. return null;
  7116. }
  7117. if (type instanceof torch.TupleType) {
  7118. const mutable_types = [];
  7119. for (const inner of type.elements()) {
  7120. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7121. if (maybe_inner_types) {
  7122. mutable_types.push(...maybe_inner_types);
  7123. }
  7124. }
  7125. if (mutable_types.length === 0) {
  7126. return null;
  7127. }
  7128. return [[torch.TupleType.create(mutable_types)]];
  7129. }
  7130. return null;
  7131. }
  7132. });
  7133. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7134. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7135. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7136. return true;
  7137. }
  7138. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7139. if (mutable_type_cache) {
  7140. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7141. }
  7142. return helper.mapTypeToAliasTypeSet(type) !== null;
  7143. });
  7144. this.registerType('torch._C.AliasDb', class {
  7145. constructor() {
  7146. this._writeIndex = new Map();
  7147. }
  7148. static isMutableType(...args) {
  7149. if (args[0] instanceof torch.Type) {
  7150. const [type] = args;
  7151. return torch._C.isMutableTypeImpl(type, null);
  7152. }
  7153. if (args[0] instanceof torch.Value) {
  7154. const [value] = args;
  7155. return torch._C.AliasDb.isMutableType(value.type());
  7156. }
  7157. throw new python.Error('Not implemented.');
  7158. }
  7159. writesToAlias(/* n, vs */) {
  7160. /*
  7161. const writtenTo = this.getWrites(n);
  7162. if (writtenTo.length === 0) {
  7163. return false;
  7164. }
  7165. MemoryLocations locs;
  7166. for (const v of vs) {
  7167. const it = elementMap_.find(v);
  7168. if (it != elementMap_.end()) {
  7169. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7170. if (writtenTo.intersects(vlocs)) {
  7171. return true;
  7172. }
  7173. }
  7174. }
  7175. */
  7176. return false;
  7177. }
  7178. writesToWildcard(n) {
  7179. if (!this._writeIndex.has(n)) {
  7180. return false;
  7181. }
  7182. const writes = this._writeIndex.get(n);
  7183. for (const pr of this._wildcardIndex) {
  7184. const [, wildcardElement] = pr;
  7185. if (writes.test(wildcardElement.index)) {
  7186. return true;
  7187. }
  7188. }
  7189. return false;
  7190. }
  7191. safeToChangeAliasingRelationship(a, b) {
  7192. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7193. return false;
  7194. }
  7195. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7196. }
  7197. });
  7198. this.registerFunction('torch._C.hasWriters', () => {
  7199. });
  7200. this.registerFunction('torch._C.escapesScope', () => {
  7201. });
  7202. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7203. constructor(graph) {
  7204. this._current = graph.block().nodes().front();
  7205. }
  7206. next() {
  7207. return null;
  7208. }
  7209. });
  7210. this.registerType('torch._C.ConcatCombiner', class {
  7211. constructor(graph) {
  7212. this._graph = graph;
  7213. this._aliasDb = new torch._C.AliasDb(graph);
  7214. this._combinable_concats = [];
  7215. }
  7216. collectOptimizableConcats() {
  7217. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7218. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7219. if (node.kind() === 'aten::cat') {
  7220. this.handleConcat(node);
  7221. }
  7222. }
  7223. }
  7224. combineConcats() {
  7225. if (this._combinable_concats.length === 0) {
  7226. return false;
  7227. }
  7228. const list_construct_inputs = this.getListConstructInputs();
  7229. for (const node_and_new_list of list_construct_inputs) {
  7230. const [node, inputs] = node_and_new_list;
  7231. const new_list_construct = this.createListConstruct(inputs);
  7232. const old_list_construct = node.input(0).node();
  7233. new_list_construct.output().setType(old_list_construct.output().type());
  7234. new_list_construct.insertBefore(node);
  7235. old_list_construct.replaceAllUsesWith(new_list_construct);
  7236. }
  7237. return true;
  7238. }
  7239. run() {
  7240. this.collectOptimizableConcats();
  7241. const changed = this.combineConcats();
  7242. if (changed) {
  7243. torch._C.EliminateDeadCode(this._graph);
  7244. }
  7245. return changed;
  7246. }
  7247. });
  7248. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7249. const changed = new torch._C.ConcatCombiner(graph).run();
  7250. return changed;
  7251. });
  7252. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7253. constructor(graph, disable_shape_peepholes) {
  7254. this._graph = graph;
  7255. this._shape_peepholes = !disable_shape_peepholes;
  7256. }
  7257. run() {
  7258. let changed = this.optimizeBlock(this._graph.block());
  7259. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7260. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7261. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7262. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7263. changed = changed || torch._C.CombineConcats(this._graph);
  7264. return changed;
  7265. }
  7266. optimizeBlock(block) {
  7267. let changed = false;
  7268. for (const node of block.nodes()) {
  7269. for (const sub_block of node.blocks()) {
  7270. changed = changed || this.optimizeBlock(sub_block);
  7271. }
  7272. if (node.kind() !== 'prim::Constant') {
  7273. const guard = new torch._C.WithInsertPoint(node);
  7274. for (const output of node.outputs()) {
  7275. if (output.type() instanceof torch.NoneType) {
  7276. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7277. changed = true;
  7278. }
  7279. }
  7280. guard.dispose();
  7281. }
  7282. if (node.kind() === 'prim::If') {
  7283. // throw new python.Error('Not implemented.');
  7284. /*
  7285. const n = new torch._C.IfView(node);
  7286. // this handles redundant short circuits like "x and True" or "x or
  7287. // False"
  7288. for (const auto i : c10::irange(n.outputs().length)) {
  7289. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7290. continue;
  7291. }
  7292. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7293. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7294. if (true_val && !false_val) {
  7295. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7296. changed = true;
  7297. }
  7298. }
  7299. for (let i = 0; i < n.outputs().length; ++i) {
  7300. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7301. const output_optional = n.outputs()[i].type();
  7302. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7303. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7304. if (unif) {
  7305. n.outputs()[i].setType(unif);
  7306. changed = true;
  7307. }
  7308. }
  7309. }
  7310. */
  7311. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7312. torch._C.AT_ASSERT(node.inputs().length === 2);
  7313. for (const check_none_index of [0, 1]) {
  7314. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7315. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7316. if (input_must_be_none && other_must_not_be_none) {
  7317. const guard = new torch._C.WithInsertPoint(node);
  7318. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7319. node.output().replaceAllUsesWith(output);
  7320. changed = true;
  7321. guard.dispose();
  7322. }
  7323. }
  7324. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7325. throw new python.Error('Not implemented.');
  7326. /*
  7327. // we are unwrapping an input that can't be None, remove the unwrap
  7328. const input = node.input();
  7329. if (input.mustNotBeNone()) {
  7330. node.output().replaceAllUsesWith(node.input());
  7331. changed = true;
  7332. }
  7333. */
  7334. } else if (node.kind() === 'prim::unchecked_cast') {
  7335. const input_type = torch._C.unshapedType(node.input().type());
  7336. const output_type = torch._C.unshapedType(node.output().type());
  7337. if (input_type.isSubtypeOf(output_type)) {
  7338. node.output().replaceAllUsesWith(node.input());
  7339. changed = true;
  7340. }
  7341. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7342. node.output().replaceAllUsesWith(node.input());
  7343. changed = true;
  7344. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7345. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7346. continue;
  7347. }
  7348. const inp_type = node.inputs()[0].type();
  7349. const immut_type = (type) => {
  7350. const kind = type.kind();
  7351. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7352. return handled_immutable_types.has(kind);
  7353. };
  7354. let non_throwing_type = false;
  7355. if (inp_type instanceof torch.ListType) {
  7356. non_throwing_type = immut_type(inp_type.getElementType());
  7357. } else if (inp_type instanceof torch.DictType) {
  7358. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7359. } else {
  7360. non_throwing_type = immut_type(inp_type);
  7361. }
  7362. if (non_throwing_type) {
  7363. const guard = new torch._C.WithInsertPoint(node);
  7364. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7365. changed = true;
  7366. guard.dispose();
  7367. }
  7368. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7369. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7370. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7371. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7372. }
  7373. }
  7374. return changed;
  7375. }
  7376. });
  7377. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7378. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7379. const changed = peephole.run();
  7380. if (changed) {
  7381. torch._C.EliminateDeadCode(graph.block());
  7382. }
  7383. return changed;
  7384. });
  7385. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7386. if (!cond) {
  7387. throw new python.Error('Assertion failed.');
  7388. }
  7389. });
  7390. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7391. if (!cond) {
  7392. throw new python.Error('Assertion failed.');
  7393. }
  7394. });
  7395. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7396. if (!cond) {
  7397. throw new python.Error('Assertion failed.');
  7398. }
  7399. });
  7400. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7401. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7402. for (let next_node = it.next(); next_node !== null;) {
  7403. const node = next_node;
  7404. next_node = it.next();
  7405. if (node.kind() === 'prim::EmptyListLiteral') {
  7406. if (node.hasUses()) {
  7407. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7408. }
  7409. const li = graph.createList(torch.TensorType.get(), []);
  7410. li.insertBefore(node);
  7411. node.replaceAllUsesWith(li);
  7412. }
  7413. node.destroy();
  7414. }
  7415. });
  7416. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7417. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7418. const [graph] = args;
  7419. const aliasDb = new torch._C.AliasDb(graph);
  7420. const constants = new torch._C.NodeSet();
  7421. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7422. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7423. const [block, constants, aliasDb] = args;
  7424. for (const node of block.nodes()) {
  7425. if (node.blocks().length > 0) {
  7426. for (const block of node.blocks()) {
  7427. torch._C.ConstantPooling(block, constants, aliasDb);
  7428. }
  7429. continue;
  7430. }
  7431. if (node.kind() !== 'prim::Constant') {
  7432. continue;
  7433. }
  7434. if (constants.has(node)) {
  7435. const existing = constants.get(node);
  7436. const old_ivalue = torch._C.toIValue(existing.output());
  7437. const new_ivalue = torch._C.toIValue(node.output());
  7438. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7439. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7440. continue;
  7441. }
  7442. node.replaceAllUsesWith(existing);
  7443. node.destroy();
  7444. continue;
  7445. } else {
  7446. constants.insert(node);
  7447. }
  7448. const [first_node] = node.owningGraph().block().nodes();
  7449. if (node !== first_node) {
  7450. node.moveBefore(first_node);
  7451. }
  7452. }
  7453. } else {
  7454. throw new python.Error('Not implemented.');
  7455. }
  7456. });
  7457. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7458. /*
  7459. const autocast_stack = [];
  7460. let incompatible_amp = null;
  7461. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7462. for (const node of block.nodes()) {
  7463. switch (node.kind()) {
  7464. case 'prim::CallFunction':
  7465. if (current_state() === initial_state) {
  7466. if (current_state()) {
  7467. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7468. }
  7469. break;
  7470. }
  7471. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7472. incompatible_amp = true;
  7473. break;
  7474. case 'prim::CallMethod':
  7475. if (current_state() === initial_state) {
  7476. if (current_state()) {
  7477. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7478. }
  7479. break;
  7480. }
  7481. if (node.input(0).type() instanceof torch.ClassType) {
  7482. const class_type = node.input(0).type();
  7483. const name = node.s('name');
  7484. const fn = class_type.getMethod(name);
  7485. if (!fn.isGraphFunction()) {
  7486. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7487. incompatible_amp = true;
  7488. }
  7489. } else {
  7490. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7491. incompatible_amp = true;
  7492. }
  7493. break;
  7494. case 'prim::Enter': {
  7495. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7496. if (autocast_scope) {
  7497. if (node.hasUses()) {
  7498. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7499. }
  7500. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7501. incompatible_amp = false;
  7502. autocast_stack.push(autocast_scope);
  7503. }
  7504. break;
  7505. }
  7506. case 'prim::Exit': {
  7507. if (torch._C.isAutocastNode(node.input(0))) {
  7508. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7509. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7510. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7511. incompatible_amp = false;
  7512. autocast_stack.pop();
  7513. }
  7514. break;
  7515. }
  7516. case 'aten::is_autocast_enabled': {
  7517. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7518. break;
  7519. }
  7520. case 'aten::is_autocast_cpu_enabled': {
  7521. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7522. break;
  7523. }
  7524. case 'aten::_convolution':
  7525. case 'aten::conv1d':
  7526. case 'aten::conv2d':
  7527. case 'aten::conv3d':
  7528. case 'aten::conv_tbc':
  7529. case 'aten::conv_transpose1d':
  7530. case 'aten::convolution':
  7531. case 'aten::cudnn_convolution':
  7532. case 'aten::cudnn_convolution_transpose':
  7533. case 'aten::prelu':
  7534. case 'aten::addmm':
  7535. case 'aten::addmv':
  7536. case 'aten::addr':
  7537. case 'aten::matmul':
  7538. case 'aten::mm':
  7539. case 'aten::mv':
  7540. case 'aten::linear':
  7541. case 'aten::addbmm':
  7542. case 'aten::baddbmm':
  7543. case 'aten::bmm':
  7544. case 'aten::chain_matmul':
  7545. case 'aten::_thnn_fused_lstm_cell':
  7546. case 'aten::_thnn_fused_gru_cell':
  7547. case 'aten::lstm_cell':
  7548. case 'aten::gru_cell':
  7549. case 'aten::rnn_tanh_cell':
  7550. case 'aten::rnn_relu_cell': {
  7551. if (!node.schema().is_mutable()) {
  7552. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7553. }
  7554. break;
  7555. }
  7556. case 'aten::native_layer_norm':
  7557. case 'aten::acos':
  7558. case 'aten::asin':
  7559. case 'aten::cosh':
  7560. case 'aten::erfinv':
  7561. case 'aten::exp':
  7562. case 'aten::expm1':
  7563. case 'aten::log':
  7564. case 'aten::log10':
  7565. case 'aten::log2':
  7566. case 'aten::log1p':
  7567. case 'aten::reciprocal':
  7568. case 'aten::rsqrt':
  7569. case 'aten::sinh':
  7570. case 'aten::tan':
  7571. case 'aten::pow':
  7572. case 'aten::softplus':
  7573. case 'aten::gelu':
  7574. case 'aten::layer_norm':
  7575. case 'aten::group_norm':
  7576. case 'aten::frobenius_norm':
  7577. case 'aten::nuclear_norm':
  7578. case 'aten::cosine_similarity':
  7579. case 'aten::cosine_embedding_loss':
  7580. case 'aten::nll_loss':
  7581. case 'aten::nll_loss2d':
  7582. case 'aten::hinge_embedding_loss':
  7583. case 'aten::kl_div':
  7584. case 'aten::l1_loss':
  7585. case 'aten::smooth_l1_loss':
  7586. case 'aten::mse_loss':
  7587. case 'aten::margin_ranking_loss':
  7588. case 'aten::multilabel_margin_loss':
  7589. case 'aten::soft_margin_loss':
  7590. case 'aten::triplet_margin_loss':
  7591. case 'aten::multi_margin_loss':
  7592. case 'aten::binary_cross_entropy_with_logits':
  7593. case 'aten::dist':
  7594. case 'aten::pdist':
  7595. case 'aten::cdist':
  7596. case 'aten::renorm':
  7597. case 'aten::logsumexp': {
  7598. if (!node.schema().is_mutable()) {
  7599. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7600. }
  7601. break;
  7602. }
  7603. case 'aten::prod':
  7604. case 'aten::log_softmax':
  7605. case 'aten::cumprod':
  7606. case 'aten::cumsum':
  7607. case 'aten::sum': {
  7608. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7609. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7610. }
  7611. break;
  7612. }
  7613. case 'aten::softmax': {
  7614. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7615. const context = current_state();
  7616. context.cpu_enabled = false;
  7617. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7618. }
  7619. break;
  7620. }
  7621. case 'aten::addcdiv':
  7622. case 'aten::addcmul':
  7623. case 'aten::atan2':
  7624. case 'aten::bilinear':
  7625. case 'aten::cat':
  7626. case 'aten::cross':
  7627. case 'aten::dot':
  7628. case 'aten::equal':
  7629. case 'aten::index_put':
  7630. case 'aten::stack':
  7631. case 'aten::tensordot':
  7632. case 'aten::add':
  7633. case 'aten::sub':
  7634. case 'aten::mul':
  7635. case 'aten::div': {
  7636. if (!node.schema().is_mutable()) {
  7637. torch._C.castInputsToWidestType(node, current_state());
  7638. }
  7639. break;
  7640. }
  7641. case 'aten::binary_cross_entropy': {
  7642. if (current_state()) {
  7643. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7644. }
  7645. break;
  7646. }
  7647. default: {
  7648. break;
  7649. }
  7650. }
  7651. for (const sub_block of node.blocks()) {
  7652. torch._C.handleBlock(sub_block, current_state());
  7653. }
  7654. }
  7655. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7656. */
  7657. });
  7658. this.registerFunction('torch._C.autocastEnabled', () => {
  7659. return true;
  7660. });
  7661. this.registerFunction('torch._C.Autocast', (graph) => {
  7662. if (torch._C.autocastEnabled()) {
  7663. const init = null;
  7664. /* AutocastContext init = {
  7665. at::autocast::is_autocast_enabled(at::kCUDA),
  7666. at::autocast::is_autocast_enabled(at::kCPU),
  7667. at::autocast::get_autocast_dtype(at::kCUDA),
  7668. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7669. torch._C.handleBlock(graph.block(), init);
  7670. }
  7671. });
  7672. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7673. disable_autocast = disable_autocast || false;
  7674. torch._C.Inline(graph);
  7675. torch._C.PeepholeOptimize(graph, true);
  7676. torch._C.ConstantPropagationImmutableTypes(graph);
  7677. if (!disable_autocast) {
  7678. torch._C.Autocast(graph);
  7679. }
  7680. torch._C.ConstantPooling(graph);
  7681. });
  7682. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7683. constructor(name, graph, function_creator, executor_execution_mode) {
  7684. super();
  7685. this._name = name;
  7686. this._graph = graph;
  7687. this._executor_execution_mode = executor_execution_mode || null;
  7688. this._function_creator = function_creator;
  7689. this._force_no_amp = false;
  7690. }
  7691. isGraphFunction() {
  7692. return true;
  7693. }
  7694. qualname() {
  7695. return this._name;
  7696. }
  7697. graph() {
  7698. return this._graph;
  7699. }
  7700. optimized_graph() {
  7701. const graph_ref = this._graph.copy();
  7702. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7703. return graph_ref;
  7704. }
  7705. ensure_defined() {
  7706. if (this._function_creator) {
  7707. const creator = this._function_creator;
  7708. this._function_creator = () => {
  7709. throw new python.Error('Recursive method call.');
  7710. };
  7711. creator(this);
  7712. this._function_creator = null;
  7713. }
  7714. this.check_single_output();
  7715. }
  7716. check_single_output() {
  7717. if (this.graph().outputs().length !== 1) {
  7718. throw new python.Error('Graph must have a single output.');
  7719. }
  7720. }
  7721. getSchema() {
  7722. this._schema = this._schema || this.defaultSchemaFor(this);
  7723. return this._schema;
  7724. }
  7725. setSchema(schema) {
  7726. this._schema = schema;
  7727. }
  7728. num_inputs() {
  7729. return this.graph().inputs().length;
  7730. }
  7731. unshapedType(type) {
  7732. if (type.isSubtypeOf(torch.TensorType.get())) {
  7733. return torch.TensorType.get();
  7734. }
  7735. const contained = type.containedTypes();
  7736. if (contained.length === 0) {
  7737. return type;
  7738. }
  7739. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7740. }
  7741. defaultSchemaFor(fn) {
  7742. const args = [];
  7743. const returns = [];
  7744. const g = fn.graph();
  7745. const num_inputs = fn.num_inputs();
  7746. for (let i = 0; i < num_inputs; i++) {
  7747. const v = g.inputs()[i];
  7748. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7749. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7750. args.push(argument);
  7751. }
  7752. const num_outputs = g.outputs().length;
  7753. for (let i = 0; i < num_outputs; i++) {
  7754. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7755. returns.push(argument);
  7756. }
  7757. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7758. }
  7759. });
  7760. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7761. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7762. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7763. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7764. __str__() {
  7765. return this._args.map((a) => a.__str__()).join('//');
  7766. }
  7767. });
  7768. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7769. this.registerType('torch.utils._sympy.functions.Where', class {});
  7770. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7771. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7772. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7773. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7774. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7775. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7776. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7777. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7778. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7779. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7780. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7781. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7782. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7783. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7784. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7785. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7786. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7787. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7788. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7789. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7790. static extract() {
  7791. }
  7792. });
  7793. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7794. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7795. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7796. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7797. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7798. this.registerType('torch.utils.data.dataset.Subset', class {});
  7799. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7800. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7801. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7802. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7803. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7804. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7805. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7806. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7807. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7808. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7809. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7810. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7811. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7812. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7813. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7814. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7815. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7816. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7817. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7818. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7819. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7820. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7821. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7822. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7823. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7824. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7825. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7826. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7827. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7828. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7829. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7830. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7831. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7832. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7833. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7834. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7835. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7836. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7837. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7838. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7839. this.registerType('torch._C._LegacyVariableBase', class {});
  7840. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7841. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7842. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7843. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7844. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7845. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7846. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7847. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7848. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7849. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7850. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7851. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7852. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7853. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7854. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7855. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7856. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7857. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7858. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7859. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7860. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7861. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7862. this.registerType('torch.distributions.beta.Beta', class {});
  7863. this.registerType('torch.distributions.binomial.Binomial', class {});
  7864. this.registerType('torch.distributions.categorical.Categorical', class {});
  7865. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7866. this.registerType('torch.distributions.constraints._Interval', class {});
  7867. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7868. this.registerType('torch.distributions.constraints._Real', class {});
  7869. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7870. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7871. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7872. this.registerType('torch.distributions.normal.Normal', class {});
  7873. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7874. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7875. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7876. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7877. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7878. this.registerType('torch.distributions.uniform.Uniform', class {});
  7879. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7880. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7881. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7882. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7883. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7884. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7885. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7886. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7887. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7888. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7889. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7890. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7891. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7892. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7893. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7894. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7895. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7896. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7897. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7898. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7899. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7900. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7901. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7902. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7903. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7904. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7905. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7906. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7907. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7908. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7913. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7915. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7916. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7917. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7918. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7920. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7921. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7922. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7923. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7924. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7925. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7926. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7927. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7928. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7929. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7930. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7931. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7932. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7933. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7934. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7935. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7936. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7937. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7938. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7939. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7940. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7941. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7942. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7943. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7944. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7945. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7946. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7947. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7948. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7949. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7950. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7951. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7952. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7953. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7954. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7955. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7956. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7957. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7958. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7959. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7960. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7961. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7962. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7963. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7964. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7965. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7966. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7967. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7968. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7969. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7970. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7971. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7972. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7973. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7974. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7975. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7976. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7977. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7978. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7979. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7980. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7981. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7982. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7983. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7984. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7985. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7986. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7987. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7988. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7989. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7990. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  7991. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7992. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  7993. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  7994. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  7995. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  7996. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  7997. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  7998. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  7999. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  8000. this.registerType('torch.nn.modules.module.PatchForward', class {});
  8001. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  8002. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  8003. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  8004. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  8005. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  8006. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  8007. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8008. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8009. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8010. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  8011. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8012. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8013. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8014. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  8015. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  8016. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  8017. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  8018. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  8019. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  8020. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  8021. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  8022. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  8023. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  8024. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8025. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8026. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8027. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  8028. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  8029. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  8030. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  8031. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8032. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8033. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8034. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8035. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8036. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8037. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8038. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8039. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8040. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8041. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8042. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8043. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8044. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8045. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8046. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8047. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8048. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8049. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8050. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8051. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8052. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8053. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8054. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8055. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8056. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8057. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8058. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8059. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8060. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8061. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8062. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8063. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8064. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8065. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8066. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8067. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8068. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8069. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8070. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8071. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8072. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8073. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8074. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8075. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8076. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8077. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8078. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8079. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8080. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8081. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8082. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8083. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8084. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8085. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8086. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8087. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8088. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8089. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8090. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8091. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8092. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8093. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8094. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8095. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8096. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8097. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8098. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8099. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8100. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8101. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8102. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8103. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8104. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8105. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8106. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8107. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8108. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8109. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8110. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8111. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8112. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8113. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8114. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8115. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8116. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8117. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8118. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8119. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8120. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8121. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8122. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8123. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8124. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8125. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8126. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8127. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8128. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8129. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8130. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8131. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8132. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8133. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8134. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8135. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8136. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8137. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8138. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8139. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8140. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8141. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8142. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8143. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8144. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8145. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8146. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8147. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8148. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8149. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8150. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8151. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8152. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8153. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8154. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8155. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8156. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8157. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8158. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8159. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8160. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8161. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8162. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8163. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8164. this.registerType('torch.optim.adamw.AdamW', class {});
  8165. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8166. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8167. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8168. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8169. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8170. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8171. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8172. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8173. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8174. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8175. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8176. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8177. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8178. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8179. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8180. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8181. this.registerType('torch.optim.sgd.SGD', class {});
  8182. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8183. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8184. torch.optim.RAdam = torch.optim.radam.RAdam;
  8185. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8186. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8187. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8188. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8189. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8190. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8191. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8192. this.registerFunction('torch.quantization.observer._with_args');
  8193. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8194. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8195. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8196. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8197. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8198. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8199. __enter__() {
  8200. return this;
  8201. }
  8202. __exit__(/* exc_type, exc_value, traceback */) {
  8203. }
  8204. });
  8205. this.registerFunction('torch.utils._pytree.tree_map');
  8206. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8207. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8208. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8209. this._expr = expr;
  8210. this.shape_env = shape_env;
  8211. this.pytype = pytype;
  8212. this._optimized_summation = optimized_summation;
  8213. this._hint = hint;
  8214. this.constant = constant;
  8215. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8216. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8217. }
  8218. __str__() {
  8219. return this._expr.__str__();
  8220. }
  8221. });
  8222. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8223. constructor() {
  8224. this.var_to_val = new Map();
  8225. this.var_to_stack = new Map();
  8226. }
  8227. add_var_to_val(expr, val) {
  8228. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8229. }
  8230. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8231. }
  8232. create_symintnode(sym, hint, source) {
  8233. let out = null;
  8234. let fx_node = null;
  8235. if (this._translation_validation_enabled && source !== null) {
  8236. throw new python.Error('Not implemented.');
  8237. } else {
  8238. fx_node = null;
  8239. }
  8240. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8241. out = builtins.int(sym);
  8242. if (hint !== null && out !== hint) {
  8243. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8244. }
  8245. } else {
  8246. // if free_unbacked_symbols(sym):
  8247. // hint = None
  8248. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8249. }
  8250. return out;
  8251. }
  8252. create_symboolnode(sym) {
  8253. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8254. }
  8255. });
  8256. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8257. /*
  8258. assert isinstance(sym, sympy.Symbol)
  8259. const name_str = sym.name.toLowerCase();
  8260. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8261. return name_str.startsWith(prefix_str[prefix])
  8262. }
  8263. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8264. */
  8265. return false;
  8266. });
  8267. this.registerType('torch.fx.proxy.TracerBase', class {
  8268. constructor() {
  8269. this.traced_func_name = 'forward';
  8270. }
  8271. });
  8272. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8273. trace(root /*, concrete_args */) {
  8274. let fn = null;
  8275. if (root instanceof torch.nn.Module) {
  8276. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8277. this.root = root;
  8278. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8279. this.root_module_name = root._get_name();
  8280. this.submodule_paths = new builtins.dict(root.named_modules());
  8281. } else {
  8282. this.root = new torch.nn.Module();
  8283. fn = root;
  8284. }
  8285. const tracer_cls = builtins.getattr(this, '__class__', null);
  8286. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8287. if (builtins.hasattr(this, '__code__')) {
  8288. const code = fn.__code__;
  8289. this.graph._co_fields = {
  8290. co_name: code.co_name,
  8291. co_filename: code.co_filename,
  8292. co_firstlineno: code.co_firstlineno,
  8293. };
  8294. }
  8295. return this.graph;
  8296. }
  8297. is_leaf_module(m /*, module_qualified_name */) {
  8298. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8299. }
  8300. });
  8301. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8302. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8303. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8304. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8305. return new graph_module_cls(...args);
  8306. });
  8307. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8308. let tracer_cls = body.get('_tracer_cls');
  8309. if (!tracer_cls) {
  8310. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8311. }
  8312. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8313. const cls_tracer = tracer_cls;
  8314. const KeepModules = class extends cls_tracer {
  8315. is_leaf_module() {
  8316. return true;
  8317. }
  8318. };
  8319. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8320. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8321. const graph = new KeepModules().trace(com, tracer_extras);
  8322. graph._tracer_cls = tracer_cls;
  8323. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8324. for (const [k, v] of body.items()) {
  8325. if (!builtins.hasattr(gm, k)) {
  8326. builtins.setattr(gm, k, v);
  8327. }
  8328. }
  8329. return gm;
  8330. });
  8331. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8332. globals = { ...globals };
  8333. const context = new python.Execution.Context(globals, null);
  8334. execution.exec(src, context);
  8335. const forward_fn = globals.forward;
  8336. delete globals.forward;
  8337. return forward_fn;
  8338. });
  8339. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8340. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8341. let fn_src = null;
  8342. if (body.has('_code')) {
  8343. fn_src = body.get('_code');
  8344. } else if (body.has('code')) {
  8345. fn_src = body.get('code');
  8346. } else {
  8347. fn_src = body._code || body.code;
  8348. }
  8349. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8350. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8351. });
  8352. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8353. const forward = importer.import_module(generated_module_name).forward;
  8354. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8355. });
  8356. this.registerType('torch.fx.graph.CodeGen', class {});
  8357. this.registerType('torch.fx.graph._Namespace', class {
  8358. constructor() {
  8359. this._obj_to_name = new Map();
  8360. this._unassociated_names = new Set();
  8361. this._used_names = new Set();
  8362. this._base_count = {};
  8363. }
  8364. create_name(candidate, obj) {
  8365. if (obj && this._obj_to_name.has(obj)) {
  8366. return self._obj_to_name.get(obj);
  8367. }
  8368. candidate = candidate || '_unnamed';
  8369. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8370. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8371. const match = candidate.match(/(.*)_(\d+)$"/);
  8372. let base = candidate;
  8373. let num = null;
  8374. if (match) {
  8375. [, base] = match;
  8376. num = parseInt(match[2], 10);
  8377. }
  8378. candidate = num ? `${base}_${num}` : base;
  8379. if (!num) {
  8380. num = this._base_count[base] || 0;
  8381. }
  8382. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8383. num += 1;
  8384. candidate = `${base}_${num}`;
  8385. }
  8386. this._used_names.add(candidate);
  8387. this._base_count[base] = num;
  8388. if (obj) {
  8389. this._obj_to_name[obj] = candidate;
  8390. } else {
  8391. this._unassociated_names.add(candidate);
  8392. }
  8393. return candidate;
  8394. }
  8395. _is_illegal_name(/* name, obj */) {
  8396. /*
  8397. if name in keyword.kwlist:
  8398. return True
  8399. if name in builtins.__dict__:
  8400. return obj is not builtins.__dict__[name]
  8401. if name in _custom_builtins:
  8402. return obj is not _custom_builtins[name].obj
  8403. */
  8404. return false;
  8405. }
  8406. associate_name_with_obj() {
  8407. }
  8408. });
  8409. this.registerType('torch.fx.node.Node', class {
  8410. constructor(graph, name, op, target, args, kwargs, return_type) {
  8411. this.graph = graph;
  8412. this.name = name;
  8413. this.op = op;
  8414. this.target = target;
  8415. this._input_nodes = new builtins.dict();
  8416. this.__update_args_kwargs(args, kwargs);
  8417. this.users = new builtins.dict();
  8418. this.type = return_type;
  8419. this._prev = this;
  8420. this._next = this;
  8421. this._erased = false;
  8422. this._repr_fn = null;
  8423. this.meta = new builtins.dict();
  8424. }
  8425. get args() {
  8426. return this._args;
  8427. }
  8428. get kwargs() {
  8429. return this._kwargs;
  8430. }
  8431. get next() {
  8432. return this._next;
  8433. }
  8434. prepend(x) {
  8435. x._remove_from_list();
  8436. const p = this._prev;
  8437. [p._next, x._prev] = [x, p];
  8438. [x._next, this._prev] = [this, x];
  8439. }
  8440. _remove_from_list() {
  8441. const [p, n] = [this._prev, this._next];
  8442. [p._next, n._prev] = [n, p];
  8443. }
  8444. __update_args_kwargs(new_args, new_kwargs) {
  8445. const update_users_and_input_nodes = (n) => {
  8446. if (n instanceof torch.fx.node.Node) {
  8447. this._input_nodes.setdefault(n);
  8448. n.users.setdefault(this);
  8449. }
  8450. return n;
  8451. };
  8452. const map_aggregate = (a, fn) => {
  8453. if (a instanceof builtins.tuple) {
  8454. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8455. if (!builtins.hasattr(a, '_fields')) {
  8456. return t;
  8457. }
  8458. throw new python.Error('Not implemented.');
  8459. // return type(a)(*t);
  8460. } else if (Array.isArray(a)) {
  8461. return a.map((elem) => map_aggregate(elem, fn));
  8462. } else if (a instanceof builtins.dict) {
  8463. const rv = new builtins.dict();
  8464. for (const [k, v] of a) {
  8465. rv.__setitem__(k, map_aggregate(v, fn));
  8466. }
  8467. return rv;
  8468. } else if (a instanceof builtins.slice) {
  8469. throw new python.Error('Not implemented.');
  8470. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8471. }
  8472. return fn(a);
  8473. };
  8474. for (const old_use of this._input_nodes.keys()) {
  8475. old_use.users.pop(this);
  8476. }
  8477. // object.__setattr__(self, "_input_nodes", {})
  8478. this._input_nodes = new builtins.dict();
  8479. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8480. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8481. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8482. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8483. }
  8484. });
  8485. torch.fx.Node = torch.fx.node.Node;
  8486. torch.fx.graph.Node = torch.fx.node.Node;
  8487. this.registerType('torch.fx.graph.Graph', class {
  8488. constructor(owning_module, tracer_cls, tracer_extras) {
  8489. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8490. this._used_names = new Map();
  8491. this._len = 0;
  8492. this._graph_namespace = new torch.fx.graph._Namespace();
  8493. this._owning_module = owning_module;
  8494. this._tracer_cls = tracer_cls;
  8495. this._tracer_extras = tracer_extras;
  8496. // this._codegen = CodeGen()
  8497. // this._co_fields = {}
  8498. }
  8499. get nodes() {
  8500. const array = new Array(this._len);
  8501. let node = this._root.next;
  8502. for (let i = 0; node !== this._root; i++) {
  8503. array[i] = node;
  8504. node = node.next;
  8505. }
  8506. return array;
  8507. }
  8508. placeholder(name, type_expr /*, default_value */) {
  8509. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8510. const kwargs = new builtins.dict();
  8511. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8512. }
  8513. create_node(op, target, args, kwargs, name, type_expr) {
  8514. args = args || new builtins.tuple();
  8515. kwargs = kwargs || new builtins.dict();
  8516. const candidate = name || this._target_to_str(target);
  8517. name = this._graph_namespace.create_name(candidate, null);
  8518. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8519. this._graph_namespace.associate_name_with_obj(name, n);
  8520. this._insert(n);
  8521. this._len += 1;
  8522. return n;
  8523. }
  8524. _insert(n) {
  8525. this._root.prepend(n);
  8526. }
  8527. output(result, type_expr) {
  8528. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8529. }
  8530. _target_to_str(target) {
  8531. if (typeof target === 'string') {
  8532. if (target.startsWith('__') && target.endsWith('__')) {
  8533. target = target.substring(2, target.length - 2);
  8534. }
  8535. } else {
  8536. target = target.__name__;
  8537. }
  8538. return this._snake_case(target);
  8539. }
  8540. _snake_case(s) {
  8541. const chars = [];
  8542. let prev_lower = false;
  8543. for (const c of s) {
  8544. const x = c.toLowerCase();
  8545. if (prev_lower && x !== c) {
  8546. chars.push('_');
  8547. } else {
  8548. prev_lower = true;
  8549. }
  8550. chars.push(x);
  8551. }
  8552. return chars.join('');
  8553. }
  8554. });
  8555. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8556. constructor(body) {
  8557. super();
  8558. for (const [k, v] of body.items()) {
  8559. builtins.setattr(this, k, v);
  8560. }
  8561. }
  8562. });
  8563. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8564. const parts = target.split('.');
  8565. const field = parts.pop();
  8566. for (const item of parts) {
  8567. const f = builtins.getattr(from_module, item);
  8568. let t = builtins.getattr(to_module, item, null);
  8569. if (f === t) {
  8570. return;
  8571. }
  8572. if (t === null) {
  8573. t = new torch.nn.modules.module.Module();
  8574. builtins.setattr(to_module, item, t);
  8575. }
  8576. from_module = f;
  8577. to_module = t;
  8578. }
  8579. const orig = builtins.getattr(from_module, field);
  8580. builtins.setattr(to_module, field, orig);
  8581. });
  8582. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8583. constructor(root, graph, class_name) {
  8584. super();
  8585. this.__class__.__name__ = class_name || 'GraphModule';
  8586. this.graph = graph;
  8587. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8588. for (const node of graph.nodes) {
  8589. if (node.op === 'get_attr' || node.op === 'call_module') {
  8590. torch.fx.graph_module._copy_attr(root, this, node.target);
  8591. }
  8592. }
  8593. }
  8594. }
  8595. });
  8596. torch.fx.Graph = torch.fx.graph.Graph;
  8597. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8598. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8599. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8600. return fn_or_name;
  8601. });
  8602. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8603. this.registerFunction('torchvision.datasets.folder.default_loader');
  8604. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8605. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8606. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8607. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8608. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8609. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8610. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8611. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8612. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8613. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8614. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8615. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8616. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8617. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8618. this.registerType('torchvision.ops.misc.Permute', class {});
  8619. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8620. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8621. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8622. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8623. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8624. this.registerType('torchvision.models._api.Weights', class {});
  8625. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8626. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8627. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8628. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8629. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8630. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8631. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8632. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8633. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8634. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8635. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8636. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8637. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8638. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8639. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8640. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8641. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8642. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8643. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8644. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8645. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8646. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8647. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8648. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8649. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8650. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8651. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8652. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8653. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8654. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8655. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8656. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8657. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8658. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8659. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8660. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8661. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8662. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8663. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8664. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8665. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8666. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8667. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8668. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8669. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8670. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8671. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8672. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8673. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8674. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8675. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8676. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8677. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8678. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8679. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8680. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8681. this.registerType('torchvision.models.googlenet.Inception', class {});
  8682. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8683. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8684. this.registerType('torchvision.models.inception.Inception3', class {});
  8685. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8686. this.registerType('torchvision.models.inception.InceptionA', class {});
  8687. this.registerType('torchvision.models.inception.InceptionB', class {});
  8688. this.registerType('torchvision.models.inception.InceptionC', class {});
  8689. this.registerType('torchvision.models.inception.InceptionD', class {});
  8690. this.registerType('torchvision.models.inception.InceptionE', class {});
  8691. this.registerFunction('torchvision.models.inception.inception_v3');
  8692. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8693. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8694. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8695. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8696. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8697. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8698. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8699. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8700. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8701. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8702. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8703. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8704. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8705. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8706. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8707. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8708. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8709. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8710. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8711. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8712. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8713. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8714. this.registerType('torchvision.models.regnet.RegNet', class {});
  8715. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8716. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8717. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8718. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8719. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8720. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8721. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8722. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8723. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8724. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8725. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8726. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8727. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8728. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8729. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8730. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8731. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8732. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8733. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8734. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8735. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8736. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8737. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8738. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8739. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8740. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8741. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8742. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8743. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8744. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8745. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8746. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8747. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8748. this.registerType('torchvision.models.resnet.ResNet', class {});
  8749. this.registerType('torchvision.models.vgg.VGG', class {});
  8750. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8751. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8752. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8753. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8754. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8755. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8756. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8757. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8758. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8759. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8760. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8761. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8762. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8763. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8764. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8765. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8766. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8767. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8768. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8769. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8770. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8771. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8772. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8773. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8774. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8775. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8776. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8777. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8778. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8779. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8780. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8781. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8782. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8783. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8784. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8785. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8786. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8787. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8788. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8789. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8790. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8791. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8792. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8793. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8794. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8795. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8796. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8797. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8798. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8799. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8800. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8801. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8802. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8803. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8804. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8805. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8806. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8807. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8808. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8809. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8810. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8811. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8812. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8813. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8814. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8815. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8816. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8817. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8818. this.registerFunction('torchvision.ops.boxes.box_iou');
  8819. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8820. this.registerFunction('builtins.annotate', (type, value) => {
  8821. if (type === builtins.int) {
  8822. return Number.isInteger(value) ? value : NaN;
  8823. }
  8824. if (type === builtins.float) {
  8825. return typeof value === 'number' ? value : NaN;
  8826. }
  8827. if (type === builtins.number) {
  8828. // if (pytorch.Utility.isTensor(value)) {
  8829. // value.resize_([]);
  8830. // }
  8831. }
  8832. return value;
  8833. });
  8834. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8835. return undefined;
  8836. });
  8837. this.registerFunction('builtins.range', (start, stop, step) => {
  8838. if (stop === undefined && step === undefined) {
  8839. if (Number.isInteger(start)) {
  8840. return Array(start).keys();
  8841. }
  8842. if (isNaN(start)) {
  8843. return [];
  8844. }
  8845. }
  8846. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8847. });
  8848. this.registerFunction('math.trunc');
  8849. builtins.xrange = builtins.range;
  8850. this.registerFunction('torch._C._nn.gelu');
  8851. this.registerFunction('torch._C._nn.avg_pool2d');
  8852. this.registerFunction('torch._C._nn.avg_pool3d');
  8853. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8854. this.registerFunction('torch._C._nn.softplus');
  8855. this.registerFunction('torch._native_multi_head_attention');
  8856. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8857. if (layout === torch.sparse_coo) {
  8858. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8859. }
  8860. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8861. });
  8862. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8863. return device;
  8864. });
  8865. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8866. device = torch._utils._get_restore_location(device);
  8867. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8868. });
  8869. this.registerFunction('torch.from_numpy', (obj) => {
  8870. const dtypes = new Map([
  8871. ['<f2', torch.float16],
  8872. ['<f4', torch.float32],
  8873. ['<f8', torch.float64],
  8874. ['<i2', torch.int16],
  8875. ['<i4', torch.int32],
  8876. ['<i8', torch.int64],
  8877. ]);
  8878. if (!dtypes.has(obj.dtype.str)) {
  8879. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8880. }
  8881. const dtype = dtypes.get(obj.dtype.str);
  8882. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8883. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8884. storage._set_cdata(obj.data);
  8885. const tensor = new torch.Tensor();
  8886. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8887. return tensor;
  8888. });
  8889. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8890. const tensor = torch.from_numpy(data);
  8891. // tensor = tensor.to(dtype, device)
  8892. tensor.requires_grad = requires_grad;
  8893. return tensor;
  8894. });
  8895. this.registerFunction('torch._utils._rebuild_device_tensor_from_cpu_tensor', (data, dtype, device, requires_grad) => {
  8896. data = data.clone();
  8897. data.requires_grad = requires_grad;
  8898. return data;
  8899. });
  8900. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  8901. const tensor = self.invoke('torch.Tensor', []);
  8902. tensor._layout = torch.sparse_coo;
  8903. tensor._indices = indices;
  8904. tensor._values = values;
  8905. tensor._shape = size;
  8906. return tensor;
  8907. });
  8908. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  8909. torch._C._set_tensor_metadata(tensor, metadata);
  8910. });
  8911. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  8912. return tensor;
  8913. });
  8914. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  8915. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  8916. });
  8917. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  8918. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  8919. const [, storage_type, , ,size] = storage;
  8920. storage = new storage_type(size);
  8921. }
  8922. const tensor = new torch.Tensor();
  8923. tensor.__setstate__([storage, storage_offset, size, stride]);
  8924. return tensor;
  8925. });
  8926. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  8927. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  8928. tensor.requires_grad = requires_grad;
  8929. if (metadata) {
  8930. torch._utils.set_tensor_metadata(tensor, metadata);
  8931. }
  8932. tensor.backward_hooks = backward_hooks;
  8933. return tensor;
  8934. });
  8935. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  8936. const t = new torch.Tensor(null, null, dtype);
  8937. t.set_(storage, storage_offset, size, stride);
  8938. if (metadata) {
  8939. torch._utils.set_tensor_metadata(t, metadata);
  8940. }
  8941. t._backward_hooks = backward_hooks;
  8942. return torch._utils._restore_device_fake_mode(t);
  8943. });
  8944. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  8945. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8946. param.backward_hooks = backward_hooks;
  8947. return param;
  8948. });
  8949. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  8950. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8951. param.backward_hooks = backward_hooks;
  8952. torch._utils._set_obj_state(param, state);
  8953. return param;
  8954. });
  8955. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  8956. const _set_obj_state = (obj, state) => {
  8957. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  8958. if (dict_state) {
  8959. for (const [k, v] of Object.entries(dict_state)) {
  8960. builtins.setattr(obj, k, v);
  8961. }
  8962. }
  8963. if (slots_state) {
  8964. for (const [k, v] of Object.entries(slots_state)) {
  8965. builtins.setattr(obj, k, v);
  8966. }
  8967. }
  8968. };
  8969. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8970. param._backward_hooks = backward_hooks;
  8971. _set_obj_state(param, state);
  8972. return param;
  8973. });
  8974. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  8975. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  8976. tensor.quantizer_params = quantizer_params;
  8977. return tensor;
  8978. });
  8979. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  8980. let dict_state = state;
  8981. let slots_state = null;
  8982. if (state instanceof self.builtins.tuple) {
  8983. if (state.length !== 2) {
  8984. throw new python.Error(`Invalid serialized state: '${state}'.`);
  8985. }
  8986. [dict_state, slots_state] = state;
  8987. }
  8988. if (dict_state) {
  8989. for (const [name, value] of Object.entries(dict_state)) {
  8990. builtins.setattr(obj, name, value);
  8991. }
  8992. }
  8993. if (slots_state) {
  8994. for (const [name, value] of Object.entries(slots_state)) {
  8995. builtins.setattr(obj, name, value);
  8996. }
  8997. }
  8998. return obj;
  8999. });
  9000. this.registerFunction('torch._set_item', (dict, key, value) => {
  9001. dict[key] = value;
  9002. });
  9003. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  9004. let ret = func(...args);
  9005. if (ret.__class__ !== new_type) {
  9006. // ret = ret.as_subclass(new_type);
  9007. }
  9008. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  9009. if (setstate === torch.Tensor.__setstate__) {
  9010. ret = torch._utils._set_obj_state(ret, state);
  9011. } else {
  9012. ret.__setstate__(state);
  9013. }
  9014. return ret;
  9015. });
  9016. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  9017. if (step === 0) {
  9018. throw new python.Error('range() arg 3 must not be zero');
  9019. }
  9020. if (step > 0 && lo < hi) {
  9021. return 1 + (hi - 1 - lo) / step;
  9022. } else if (step < 0 && lo > hi) {
  9023. return 1 + (lo - 1 - hi) / (0 - step);
  9024. }
  9025. return 0;
  9026. });
  9027. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  9028. this.registerOperator('aten::_unwrap_optional', (value) => {
  9029. return value;
  9030. });
  9031. this.registerFunction('torch.get_default_dtype', () => {
  9032. torch._default_type = torch._default_type || torch.float32;
  9033. return torch._default_type;
  9034. });
  9035. this.registerFunction('torch.set_default_dtype', (value) => {
  9036. torch._default_type = value;
  9037. });
  9038. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9039. return value || torch.get_default_dtype();
  9040. });
  9041. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9042. const shape = size;
  9043. dtype = torch._prims_common.dtype_or_default(dtype);
  9044. let storage = null;
  9045. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9046. const size = shape.reduce((a, b) => a * b, 1);
  9047. storage = new torch.storage.TypedStorage(size, dtype);
  9048. }
  9049. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9050. tensor.__setstate__([storage, 0, shape, stride]);
  9051. return tensor;
  9052. });
  9053. this.registerFunction('torch.all', (input) => {
  9054. if (Array.isArray(input) && input.length === 0) {
  9055. return true;
  9056. }
  9057. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9058. });
  9059. this.registerFunction('torch.append', (list, value) => {
  9060. list.push(value);
  9061. return value;
  9062. });
  9063. this.registerFunction('torch.clear', (value) => {
  9064. if (value instanceof torch.Value) {
  9065. throw new python.Error('Invalid value.');
  9066. }
  9067. if (Object(value) === value) {
  9068. for (const key of Object.keys(value)) {
  9069. delete value[key];
  9070. }
  9071. }
  9072. });
  9073. this.registerFunction('torch.dict', (args) => {
  9074. const obj = {};
  9075. if (args) {
  9076. if (Array.isArray(args)) {
  9077. for (const [key, value] of args) {
  9078. obj[key] = value;
  9079. }
  9080. } else {
  9081. throw new python.Error("'torch.dict' arguments not supported.");
  9082. }
  9083. }
  9084. return obj;
  9085. });
  9086. this.registerOperator('aten::cosine_similarity', () => {
  9087. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9088. });
  9089. this.registerOperator('aten::extend', (list, value) => {
  9090. list.push(...value);
  9091. });
  9092. this.registerOperator('aten::insert', (list, index, value) => {
  9093. list.splice(index, 0, value);
  9094. return value;
  9095. });
  9096. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9097. return value.replace(oldvalue, newvalue);
  9098. });
  9099. this.registerOperator('aten::add', (a, b) => {
  9100. if ((typeof a === 'number' || a instanceof Number) && (typeof b === 'number' || b instanceof Number)) {
  9101. return a + b;
  9102. }
  9103. if (typeof a === 'number' && b instanceof builtins.complex) {
  9104. return new builtins.complex(a + b.real, b.imag);
  9105. }
  9106. if (a instanceof builtins.complex && typeof b === 'number') {
  9107. return new builtins.complex(a.real + b, a.imag);
  9108. }
  9109. if (a instanceof builtins.complex && b instanceof builtins.complex) {
  9110. return new builtins.complex(a.real + b.real, a.imag + b.imag);
  9111. }
  9112. if (Array.isArray(a) && Array.isArray(b)) {
  9113. return a.concat(b);
  9114. }
  9115. if (typeof a === 'string' && typeof b === 'string') {
  9116. return a + b;
  9117. }
  9118. throw new python.Error('Unsupported aten::add expression type.');
  9119. });
  9120. this.registerOperator('aten::log', (x) => {
  9121. if (typeof x === 'number' || x instanceof Number) {
  9122. return Math.log(x);
  9123. }
  9124. throw new python.Error('Unsupported aten::log expression type.');
  9125. });
  9126. this.registerOperator('aten::dim', (tensor) => {
  9127. if (tensor && tensor.size) {
  9128. const size = tensor.size();
  9129. if (size) {
  9130. return size.length;
  9131. }
  9132. }
  9133. return NaN;
  9134. });
  9135. this.registerOperator('aten::numel', (tensor) => {
  9136. if (tensor && tensor.size) {
  9137. const size = tensor.size();
  9138. if (size) {
  9139. return size.reduce((a, b) => a * b, 1);
  9140. }
  9141. }
  9142. return NaN;
  9143. });
  9144. this.registerOperator('aten::eq', (left, right) => {
  9145. if (typeof left === 'string' && typeof right === 'string') {
  9146. return left === right;
  9147. }
  9148. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9149. if (isNaN(left) && isNaN(right)) {
  9150. return true;
  9151. }
  9152. return left === right;
  9153. }
  9154. if (left === undefined || right === undefined) {
  9155. return true;
  9156. }
  9157. if (Array.isArray(left) && Array.isArray(right)) {
  9158. return left.length === right.length && left.every((item, index) => item === right[index]);
  9159. }
  9160. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9161. });
  9162. this.registerOperator('aten::floor', (value) => {
  9163. return Math.floor(value);
  9164. });
  9165. this.registerOperator('aten::ceil', (value) => {
  9166. return Math.ceil(value);
  9167. });
  9168. this.registerOperator('aten::floordiv', (left, right) => {
  9169. return Math.floor(left / right);
  9170. });
  9171. this.registerOperator('aten::format', (...args) => {
  9172. const list = args.shift().split(/({}D?)/);
  9173. return list.map((text) => {
  9174. if (text === '{}' || text === '{}D') {
  9175. const arg = args.shift();
  9176. if (Array.isArray(arg)) {
  9177. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9178. }
  9179. return arg ? arg.toString() : '?';
  9180. }
  9181. return text;
  9182. }).join('');
  9183. });
  9184. this.registerOperator('aten::strip', (self, chars) => {
  9185. chars = chars || '\\n\\t\\f\\v';
  9186. const regex = new RegExp(`[${chars}]`, 'g');
  9187. return self.replace(regex, '');
  9188. });
  9189. this.registerOperator('aten::gt', (left, right) => {
  9190. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9191. if (!isNaN(left) && !isNaN(right)) {
  9192. return left > right;
  9193. }
  9194. }
  9195. if (isNaN(left) && !isNaN(right)) {
  9196. return true;
  9197. }
  9198. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9199. });
  9200. this.registerOperator('aten::ge', (left, right) => {
  9201. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9202. if (!isNaN(left) && !isNaN(right)) {
  9203. return left > right;
  9204. }
  9205. }
  9206. if (isNaN(left) && !isNaN(right)) {
  9207. return true;
  9208. }
  9209. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9210. });
  9211. this.registerOperator('aten::is_floating_point', (tensor) => {
  9212. const type = tensor.dtype.scalar_type();
  9213. return (type === 5 || type === 6 || type === 7);
  9214. });
  9215. this.registerOperator('aten::is_grad_enabled', () => {
  9216. return false;
  9217. });
  9218. this.registerOperator('aten::is_autocast_enabled', () => {
  9219. return false;
  9220. });
  9221. this.registerOperator('aten::isfinite');
  9222. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9223. });
  9224. this.registerFunction('torch.serialization._get_layout', (name) => {
  9225. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9226. return value instanceof torch.layout ? value : null;
  9227. });
  9228. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9229. return torch.load(b);
  9230. });
  9231. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9232. return data;
  9233. });
  9234. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9235. return data;
  9236. });
  9237. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9238. return data;
  9239. });
  9240. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9241. return data;
  9242. });
  9243. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9244. return self.builtins.CONSTANTS[`c${data}`];
  9245. });
  9246. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9247. return value;
  9248. });
  9249. this.registerOperator('aten::keys', (dict) => {
  9250. return Object.keys(dict);
  9251. });
  9252. this.registerOperator('aten::len', (value) => {
  9253. if (Array.isArray(value)) {
  9254. return value.length;
  9255. }
  9256. if (value && value.shape && value.__len__) {
  9257. return value.__len__();
  9258. }
  9259. return NaN;
  9260. });
  9261. this.registerOperator('aten::le', (left, right) => {
  9262. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9263. if (isNaN(left) || isNaN(right)) {
  9264. return false;
  9265. }
  9266. return left <= right;
  9267. }
  9268. if (left === undefined || right === undefined) {
  9269. return true;
  9270. }
  9271. throw new python.Error("Unsupported 'torch.le' expression type.");
  9272. });
  9273. this.registerOperator('aten::list', (args) => {
  9274. return args;
  9275. });
  9276. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9277. return size;
  9278. });
  9279. this.registerType('torch.PyTorchFileReader', class {
  9280. constructor(entries) {
  9281. let prefix = 0;
  9282. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9283. for (let set = new Set(); set && paths.length > 0;) {
  9284. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9285. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9286. prefix += set ? set.keys().next().value.length + 1 : 0;
  9287. }
  9288. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9289. this._version = 0;
  9290. this.init();
  9291. }
  9292. init() {
  9293. let stream = null;
  9294. if (this.has_record('.data/version')) {
  9295. stream = this.get_record('.data/version');
  9296. } else if (this.has_record('version')) {
  9297. stream = this.get_record('version');
  9298. }
  9299. if (stream) {
  9300. const decoder = new TextDecoder('utf-8');
  9301. const buffer = stream.peek();
  9302. const text = decoder.decode(buffer);
  9303. this._version = Number(text.split('\n').shift().trim());
  9304. }
  9305. }
  9306. has_record(name) {
  9307. return this._records.has(name);
  9308. }
  9309. get_record(name) {
  9310. if (!this.has_record(name)) {
  9311. throw new python.Error(`Record '${name}' not found.`);
  9312. }
  9313. return this._records.get(name);
  9314. }
  9315. get_all_records() {
  9316. return Array.from(this._records.keys());
  9317. }
  9318. version() {
  9319. return this._version;
  9320. }
  9321. });
  9322. this.registerFunction('torch.load', (f) => {
  9323. const legacy_load = (entries) => {
  9324. const deserialized_objects = {};
  9325. if (entries.has('storages')) {
  9326. const data = entries.get('storages');
  9327. const unpickler = new pickle.Unpickler(data);
  9328. const num_storages = unpickler.load();
  9329. for (let i = 0; i < num_storages; i++) {
  9330. const args = unpickler.load();
  9331. const [key, , storage_type] = args;
  9332. const obj = storage_type._new_with_file(unpickler);
  9333. deserialized_objects[key] = obj;
  9334. }
  9335. /*
  9336. let storage_views = unpickler.load();
  9337. for target_cdata, root_cdata, offset, size in storage_views:
  9338. root = deserialized_objects[root_cdata]
  9339. deserialized_objects[target_cdata] = root[offset:offset + size]
  9340. */
  9341. }
  9342. if (entries.has('tensors')) {
  9343. const data = entries.get('tensors');
  9344. const unpickler = new pickle.Unpickler(data);
  9345. const num_tensors = unpickler.load();
  9346. const int32 = (unpickler) => {
  9347. const buffer = unpickler.read(4);
  9348. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9349. };
  9350. const int64 = (unpickler) => {
  9351. const buffer = unpickler.read(8);
  9352. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9353. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9354. }
  9355. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9356. };
  9357. for (let i = 0; i < num_tensors; i++) {
  9358. const args = unpickler.load();
  9359. const [key, storage_id] = args;
  9360. const storage = deserialized_objects[storage_id];
  9361. const ndim = int32(unpickler);
  9362. unpickler.read(4);
  9363. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9364. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9365. const storage_offset = int64(unpickler);
  9366. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9367. deserialized_objects[key] = tensor;
  9368. }
  9369. }
  9370. const data = entries.get('pickle');
  9371. const unpickler = new pickle.Unpickler(data);
  9372. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9373. return unpickler.load();
  9374. };
  9375. const _legacy_load = () => {
  9376. const unpickler = new pickle.Unpickler(f);
  9377. unpickler.load(); // magic_number
  9378. const protocol_version = unpickler.load();
  9379. if (protocol_version !== 1001) {
  9380. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9381. }
  9382. const sys_info = unpickler.load();
  9383. if (sys_info.get('protocol_version') !== 1001) {
  9384. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9385. }
  9386. if (sys_info.get('little_endian') === false) {
  9387. throw new python.Error("Unsupported big-endian storage data.");
  9388. }
  9389. const module_source_map = new Map();
  9390. const deserialized_objects = new Map();
  9391. unpickler.persistent_load = (saved_id) => {
  9392. switch (saved_id[0]) {
  9393. case 'module': {
  9394. const [, module, ,source] = saved_id;
  9395. module_source_map.set(module, source);
  9396. return saved_id[1];
  9397. }
  9398. case 'storage': {
  9399. const [, storage_type, key, , size, view_metadata] = saved_id;
  9400. if (!deserialized_objects.has(key)) {
  9401. const obj = new storage_type(size);
  9402. deserialized_objects.set(key, obj);
  9403. }
  9404. if (view_metadata) {
  9405. const view_key = view_metadata.shift();
  9406. view_metadata.shift(); // view_offset
  9407. view_metadata.shift(); // view_size
  9408. if (!deserialized_objects.has(view_key)) {
  9409. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9410. deserialized_objects.set(view_key, view);
  9411. }
  9412. return deserialized_objects.get(view_key);
  9413. }
  9414. return deserialized_objects.get(key);
  9415. }
  9416. default: {
  9417. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9418. }
  9419. }
  9420. };
  9421. const obj = unpickler.load();
  9422. const deserialized_storage_keys = unpickler.load();
  9423. for (const deserialized_storage_key of deserialized_storage_keys) {
  9424. const storage = deserialized_objects.get(deserialized_storage_key);
  9425. storage._set_from_file(unpickler);
  9426. }
  9427. if (!obj) {
  9428. throw new python.Error('File format is not PyTorch.');
  9429. }
  9430. if (obj === 'None') {
  9431. throw new python.Error("File contains 'None' root object.");
  9432. }
  9433. return obj;
  9434. };
  9435. const _load = (entries) => {
  9436. if (f.has('constant.pkl')) {
  9437. throw python.Error("TorchScript 'torch.load' not supported.");
  9438. }
  9439. const loaded_storages = new Map();
  9440. const persistent_load = (saved_id) => {
  9441. switch (saved_id[0]) {
  9442. case 'storage': {
  9443. const [, storage_type, key, , numel] = saved_id;
  9444. if (!loaded_storages.has(key)) {
  9445. const storage = new storage_type(numel);
  9446. if (!storage._set_cdata) {
  9447. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9448. }
  9449. const name = `data/${key}`;
  9450. const stream = entries.get(name);
  9451. if (!stream) {
  9452. throw new python.Error(`Record '${name}' not found.`);
  9453. }
  9454. storage._set_cdata(stream);
  9455. loaded_storages.set(key, storage);
  9456. }
  9457. return loaded_storages.get(key);
  9458. }
  9459. default: {
  9460. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9461. }
  9462. }
  9463. };
  9464. const data_file = entries.get('data.pkl');
  9465. const unpickler = new pickle.Unpickler(data_file);
  9466. unpickler.persistent_load = persistent_load;
  9467. const result = unpickler.load();
  9468. return result;
  9469. };
  9470. if (f instanceof Map) {
  9471. const reader = new torch.PyTorchFileReader(f);
  9472. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9473. f = new Map(records);
  9474. if (f.has('pickle')) {
  9475. return legacy_load(f);
  9476. }
  9477. if (f.has('data.pkl')) {
  9478. return _load(f);
  9479. }
  9480. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9481. }
  9482. return _legacy_load(f);
  9483. });
  9484. this.registerOperator('prim::abs', (a) => {
  9485. if (typeof a === 'number' || a instanceof Number) {
  9486. return Math.abs(a);
  9487. }
  9488. if (a instanceof builtins.complex) {
  9489. return Math.hypot(a.real, a.imag);
  9490. }
  9491. throw new python.Error('Unsupported prim::abs expression type.');
  9492. });
  9493. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9494. return value;
  9495. });
  9496. this.registerOperator('prim::data', (tensor) => {
  9497. return tensor;
  9498. });
  9499. this.registerOperator('prim::device', (tensor) => {
  9500. return tensor.device;
  9501. });
  9502. this.registerOperator('prim::dtype', (tensor) => {
  9503. return tensor.dtype.scalar_type();
  9504. });
  9505. this.registerOperator('prim::is_quantized', (tensor) => {
  9506. return tensor.is_quantized;
  9507. });
  9508. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9509. return false;
  9510. });
  9511. this.registerOperator('prim::is_nested', (tensor) => {
  9512. return tensor.is_nested;
  9513. });
  9514. this.registerOperator('prim::is_sparse', (tensor) => {
  9515. return tensor.is_sparse;
  9516. });
  9517. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9518. return value;
  9519. });
  9520. this.registerOperator('prim::NumToTensor', (value) => {
  9521. const tensor = self.invoke('torch.Tensor', []);
  9522. tensor.value = value;
  9523. return tensor;
  9524. });
  9525. this.registerOperator('prim::min', (...args) => {
  9526. if (Array.isArray(args[0])) {
  9527. return Math.min.apply(null, args[0]);
  9528. }
  9529. return Math.min.apply(null, args);
  9530. });
  9531. this.registerOperator('prim::max', (...args) => {
  9532. if (Array.isArray(args[0])) {
  9533. return Math.max.apply(null, args[0]);
  9534. }
  9535. return Math.max.apply(null, args);
  9536. });
  9537. this.registerOperator('prim::shape', (tensor) => {
  9538. return tensor && tensor.size ? tensor.size() : undefined;
  9539. });
  9540. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9541. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9542. params.weight = weight;
  9543. params.bias = bias;
  9544. params.stride = stride;
  9545. params.padding = padding;
  9546. params.dilation = dilation;
  9547. params.groups = groups;
  9548. return params;
  9549. });
  9550. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9551. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9552. params.weight = weight;
  9553. params.bias = bias;
  9554. params.stride = stride;
  9555. params.padding = padding;
  9556. params.dilation = dilation;
  9557. params.groups = groups;
  9558. return params;
  9559. });
  9560. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9561. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9562. params.weight = weight;
  9563. params.bias = bias;
  9564. params.stride = stride;
  9565. params.padding = padding;
  9566. params.dilation = dilation;
  9567. params.groups = groups;
  9568. return params;
  9569. });
  9570. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9571. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9572. params.weight = weight;
  9573. params.bias = bias;
  9574. params.stride = stride;
  9575. params.padding = padding;
  9576. params.dilation = dilation;
  9577. params.groups = groups;
  9578. return params;
  9579. });
  9580. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9581. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9582. params.weight = weight;
  9583. params.bias = bias;
  9584. params.stride = stride;
  9585. params.padding = padding;
  9586. params.output_padding = output_padding;
  9587. params.dilation = dilation;
  9588. params.groups = groups;
  9589. return params;
  9590. });
  9591. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9592. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9593. params.weight = weight;
  9594. params.bias = bias;
  9595. params.stride = stride;
  9596. params.padding = padding;
  9597. params.output_padding = output_padding;
  9598. params.dilation = dilation;
  9599. params.groups = groups;
  9600. return params;
  9601. });
  9602. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9603. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9604. params.weight = weight;
  9605. params.bias = bias;
  9606. return params;
  9607. });
  9608. this.registerOperator('prim::RaiseException', (message) => {
  9609. throw new python.Error(message);
  9610. });
  9611. this.registerOperator('prim::TupleIndex', (t, i) => {
  9612. return t.elements()[i];
  9613. });
  9614. this.registerOperator('prim::TupleUnpack', (t) => {
  9615. return t.elements();
  9616. });
  9617. this.registerOperator('aten::is_scripting', () => {
  9618. return true;
  9619. });
  9620. this.registerOperator('aten::__and__', (left, right) => {
  9621. return left && right;
  9622. });
  9623. this.registerOperator('aten::__contains__', (dict, key) => {
  9624. return builtins.hasattr(dict, key);
  9625. });
  9626. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9627. return start + index * step;
  9628. });
  9629. this.registerOperator('aten::__is__', (left, right) => {
  9630. return left === right;
  9631. });
  9632. this.registerOperator('aten::__isnot__', (left, right) => {
  9633. return left !== right;
  9634. });
  9635. this.registerOperator('aten::__not__', (value) => {
  9636. if (Number.isInteger(value)) {
  9637. value = Boolean(value);
  9638. }
  9639. if (typeof value === 'boolean') {
  9640. return !value;
  9641. }
  9642. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9643. });
  9644. this.registerOperator('aten::log10', (value) => {
  9645. return Math.log10(value);
  9646. });
  9647. this.registerOperator('aten::device', (type, index) => {
  9648. return new torch.device(type, index);
  9649. });
  9650. this.registerOperator('aten::lt', (left, right) => {
  9651. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9652. return left < right;
  9653. }
  9654. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9655. });
  9656. this.registerOperator('aten::mul', (left, right) => {
  9657. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9658. return left * right;
  9659. }
  9660. if (isNaN(left) || isNaN(right)) {
  9661. return NaN;
  9662. }
  9663. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9664. return left.map((value) => value * right);
  9665. }
  9666. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9667. });
  9668. this.registerOperator('aten::div', (left, right) => {
  9669. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9670. return left / right;
  9671. }
  9672. if (isNaN(left) || isNaN(right)) {
  9673. return NaN;
  9674. }
  9675. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9676. });
  9677. this.registerFunction('torch.round', (value) => {
  9678. if (typeof value === 'number' || value instanceof Number) {
  9679. return Math.round(value);
  9680. }
  9681. if (isNaN(value)) {
  9682. return value;
  9683. }
  9684. throw new python.Error("Unsupported 'torch.round' expression type.");
  9685. });
  9686. this.registerOperator('aten::remainder', (left, right) => {
  9687. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9688. return left % right;
  9689. }
  9690. if (isNaN(left) || isNaN(right)) {
  9691. return NaN;
  9692. }
  9693. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9694. });
  9695. this.registerOperator('aten::ne', (left, right) => {
  9696. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9697. return left !== right;
  9698. }
  9699. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9700. if (isNaN(left) || isNaN(right)) {
  9701. return false;
  9702. }
  9703. return left !== right;
  9704. }
  9705. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9706. return false;
  9707. }
  9708. if (typeof left === 'string' && typeof right === 'string') {
  9709. return left !== right;
  9710. }
  9711. if (left === undefined || right === undefined) {
  9712. return true;
  9713. }
  9714. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9715. });
  9716. this.registerOperator('aten::neg', (value) => {
  9717. if (typeof value === 'number') {
  9718. return -value;
  9719. }
  9720. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9721. });
  9722. this.registerOperator('aten::pow', (left, right) => {
  9723. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9724. return Math.pow(left, right);
  9725. }
  9726. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9727. });
  9728. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9729. return -1;
  9730. });
  9731. this.registerFunction('torch.t', (tensor) => {
  9732. return tensor;
  9733. });
  9734. this.registerOperator('aten::size', (tensor, dim) => {
  9735. if (tensor && tensor.size) {
  9736. const size = tensor.size();
  9737. if (Array.isArray(size)) {
  9738. if (dim === undefined) {
  9739. return size;
  9740. }
  9741. if (Number.isInteger(dim)) {
  9742. if (dim >= 0 && dim < size.length) {
  9743. return size[dim];
  9744. }
  9745. if (dim < 0 && -dim < size.length) {
  9746. return size[size.length + dim];
  9747. }
  9748. }
  9749. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9750. }
  9751. }
  9752. if (Number.isInteger(dim)) {
  9753. return NaN;
  9754. }
  9755. return [];
  9756. });
  9757. this.registerFunction('aten::sqrt', (x) => {
  9758. return Math.sqrt(x);
  9759. });
  9760. this.registerOperator('aten::slice', (l, start, end, step) => {
  9761. if (!Array.isArray(l)) {
  9762. throw new python.Error('Slicing expected array');
  9763. }
  9764. step = step || 1;
  9765. if (step !== 1) {
  9766. throw new python.Error('Slicing only supports step=1');
  9767. }
  9768. start = Math.max(0, start >= 0 ? start : l.length + start);
  9769. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9770. return l.slice(start, end);
  9771. });
  9772. this.registerOperator('aten::sub', (left, right) => {
  9773. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9774. return left - right;
  9775. }
  9776. if (typeof left === 'number' && right instanceof builtins.complex) {
  9777. return new builtins.complex(left - right.real, right.imag);
  9778. }
  9779. if (left instanceof builtins.complex && typeof right === 'number') {
  9780. return new builtins.complex(left.real - right, left.imag);
  9781. }
  9782. if (left instanceof builtins.complex && right instanceof builtins.complex) {
  9783. return new builtins.complex(left.real - right.real, left.imag - right.imag);
  9784. }
  9785. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9786. });
  9787. this.registerFunction('torch.sym_int');
  9788. this.registerFunction('torch.sym_float');
  9789. this.registerFunction('torch.sym_ite');
  9790. this.registerFunction('torch.sym_max');
  9791. this.registerFunction('torch.sym_min');
  9792. this.registerFunction('torch.sym_not');
  9793. this.registerFunction('torch.sym_sqrt');
  9794. this.registerFunction('torch.sym_sqrt');
  9795. this.registerFunction('torch.functional.einsum');
  9796. this.registerFunction('torch.functional.norm');
  9797. this.registerFunction('torch.functional.split');
  9798. this.registerFunction('torch.nn.init.constant_');
  9799. this.registerFunction('torch.nn.init.normal_');
  9800. this.registerFunction('torch.nn.init.xavier_uniform_');
  9801. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9802. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9803. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9804. this.registerFunction('torch.nn.functional.cross_entropy');
  9805. this.registerFunction('torch.nn.functional.elu');
  9806. this.registerFunction('torch.nn.functional.gelu');
  9807. this.registerFunction('torch.nn.functional.hardsigmoid');
  9808. this.registerFunction('torch.nn.functional.hardswish');
  9809. this.registerFunction('torch.nn.functional.hardtanh');
  9810. this.registerFunction('torch.nn.functional.interpolate');
  9811. this.registerFunction('torch.nn.functional.leaky_relu');
  9812. this.registerFunction('torch.nn.functional.l1_loss');
  9813. this.registerFunction('torch.nn.functional.linear');
  9814. this.registerFunction('torch.nn.functional.log_softmax');
  9815. this.registerFunction('torch.nn.functional._max_pool2d');
  9816. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9817. this.registerFunction('torch.nn.functional.mse_loss');
  9818. this.registerFunction('torch.nn.functional.pad');
  9819. this.registerFunction('torch.nn.functional.relu');
  9820. this.registerFunction('torch.nn.functional.relu6');
  9821. this.registerFunction('torch.nn.functional.sigmoid');
  9822. this.registerFunction('torch.nn.functional.silu');
  9823. this.registerFunction('torch.nn.functional.softmax');
  9824. this.registerFunction('torch.nn.functional.tanh');
  9825. this.registerFunction('torch.values', (dict) => {
  9826. return Object.values(dict);
  9827. });
  9828. this.registerFunction('torch.warn', () => {
  9829. });
  9830. this.registerType('torch._ops.OperatorBase', class {
  9831. constructor() {
  9832. this.functorch_table = {};
  9833. }
  9834. });
  9835. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9836. constructor(name, cacheable) {
  9837. super();
  9838. this._name = name;
  9839. this.__name__ = name;
  9840. this._ns = 'higher_order';
  9841. this.__module__ = 'torch.ops.higher_order';
  9842. this._cacheable = cacheable;
  9843. }
  9844. get namespace() {
  9845. return this._ns;
  9846. }
  9847. get name() {
  9848. return this._name;
  9849. }
  9850. });
  9851. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9852. constructor(name) {
  9853. super(name, false);
  9854. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9855. }
  9856. });
  9857. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9858. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9859. constructor(name) {
  9860. super(name, false);
  9861. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9862. }
  9863. });
  9864. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9865. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9866. constructor(name) {
  9867. super(name, false);
  9868. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9869. }
  9870. });
  9871. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  9872. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9873. constructor(name) {
  9874. super(name, false);
  9875. }
  9876. });
  9877. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  9878. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9879. constructor(name) {
  9880. super(name, false);
  9881. }
  9882. });
  9883. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  9884. this.registerType('torch.Type', class {
  9885. constructor(kind, annotation_str) {
  9886. this._kind = kind;
  9887. if (annotation_str) {
  9888. this._annotation_str = annotation_str;
  9889. }
  9890. }
  9891. static get(kind, annotation_str) {
  9892. torch.Type.cache = torch.Type.cache || new Map();
  9893. if (!annotation_str) {
  9894. if (!torch.Type.cache.has(kind)) {
  9895. torch.Type.cache.set(kind, new torch.Type(kind));
  9896. }
  9897. return torch.Type.cache.get(kind);
  9898. }
  9899. return new torch.Type(kind, annotation_str);
  9900. }
  9901. kind() {
  9902. return this._kind;
  9903. }
  9904. get annotation_str() {
  9905. return this._annotation_str;
  9906. }
  9907. equals(rhs) {
  9908. return this.kind() === rhs.kind();
  9909. }
  9910. isSubtypeOf(rhs) {
  9911. if (rhs.kind() === 'AnyType' || this === rhs) {
  9912. return true;
  9913. }
  9914. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  9915. return this.isSubtypeOf(rhs.getElementType());
  9916. }
  9917. if (rhs instanceof torch.UnionType) {
  9918. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  9919. }
  9920. if (rhs instanceof torch._C.DynamicType) {
  9921. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  9922. }
  9923. return this.equals(rhs);
  9924. }
  9925. containedTypes() {
  9926. return [];
  9927. }
  9928. containedType(i) {
  9929. return this.containedTypes()[i];
  9930. }
  9931. withContained(contained_types) {
  9932. const current_contained = this.containedTypes();
  9933. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  9934. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  9935. return this;
  9936. }
  9937. return this.createWithContained(contained_types);
  9938. }
  9939. createWithContained(/* createWithContained */) {
  9940. throw new python.Error('Not implemented.');
  9941. }
  9942. isUnionType() {
  9943. return false;
  9944. }
  9945. hasFreeVariables() {
  9946. return false;
  9947. }
  9948. is_module() {
  9949. return false;
  9950. }
  9951. expect(type) {
  9952. torch._C.AT_ASSERT(this instanceof type);
  9953. return this;
  9954. }
  9955. str() {
  9956. if (this instanceof torch._C.VarType && this._annotation_str) {
  9957. return this._annotation_str;
  9958. } else if (this._kind === 'ScalarTypeType') {
  9959. return 'ScalarType';
  9960. } else if (this._kind === 'QSchemeType') {
  9961. return 'QScheme';
  9962. } else if (this._kind) {
  9963. return this._kind;
  9964. }
  9965. throw new python.Error(`Not implemented '${this.kind()}'.`);
  9966. }
  9967. __str__() {
  9968. return this.str();
  9969. }
  9970. toString() {
  9971. return this.__str__();
  9972. }
  9973. });
  9974. this.registerType('torch.ClassType', class extends torch.Type {
  9975. constructor(qualified_name, cu, is_module) {
  9976. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  9977. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  9978. this._is_module = is_module;
  9979. this._attributes = [];
  9980. this._attributeTypes = [];
  9981. this._methods = [];
  9982. this._staticmethods = new Map();
  9983. this._forward_hooks = [];
  9984. this._forward_pre_hooks = [];
  9985. this._properties = [];
  9986. this._constants = new Map();
  9987. }
  9988. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  9989. return new torch.ClassType(qualifiedName, cu, is_module);
  9990. }
  9991. qualified_name() {
  9992. return this.annotation_str;
  9993. }
  9994. name() {
  9995. return this._name;
  9996. }
  9997. is_module() {
  9998. return this._is_module;
  9999. }
  10000. is_parameter(slot) {
  10001. return this._attributes[slot].is_parameter === true;
  10002. }
  10003. is_buffer(slot) {
  10004. return this._attributes[slot].is_buffer === true;
  10005. }
  10006. addMethod(method) {
  10007. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  10008. this._methods.push(method);
  10009. }
  10010. findMethod(name) {
  10011. for (const method of this._methods) {
  10012. if (name === method.name()) {
  10013. return method;
  10014. }
  10015. }
  10016. return null;
  10017. }
  10018. getMethod(name) {
  10019. const method = this.findMethod(name);
  10020. if (!method) {
  10021. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  10022. }
  10023. return method;
  10024. }
  10025. methods() {
  10026. return this._methods;
  10027. }
  10028. addStaticMethod(func) {
  10029. this._staticmethods.set(func.name, func);
  10030. }
  10031. findStaticMethod(name) {
  10032. return this._staticmethods.get(name);
  10033. }
  10034. findHook(name) {
  10035. let hook = this.findForwardHook(name);
  10036. if (hook === null) {
  10037. hook = this.findForwardPreHook(name);
  10038. }
  10039. return hook;
  10040. }
  10041. findForwardHook(name) {
  10042. for (const hook of this._forward_hooks) {
  10043. if (name === hook.name()) {
  10044. return hook;
  10045. }
  10046. }
  10047. return null;
  10048. }
  10049. findForwardPreHook(name) {
  10050. for (const pre_hook of this._forward_pre_hooks) {
  10051. if (name === pre_hook.name()) {
  10052. return pre_hook;
  10053. }
  10054. }
  10055. return null;
  10056. }
  10057. numAttributes() {
  10058. return this._attributes.length;
  10059. }
  10060. addAttribute(name, type, is_parameter, is_buffer) {
  10061. is_parameter = is_parameter || false;
  10062. is_buffer = is_buffer || false;
  10063. const slot = this._attributes.length;
  10064. this._attributes.push({ name, type, is_parameter, is_buffer });
  10065. this._attributeTypes.push(type);
  10066. return slot;
  10067. }
  10068. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  10069. is_parameter = is_parameter || false;
  10070. is_buffer = is_buffer || false;
  10071. const slot_idx = this.findAttributeSlot(name);
  10072. if (slot_idx === null) {
  10073. return this.addAttribute(name, ty, is_parameter, is_buffer);
  10074. }
  10075. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  10076. // const TypePtr& atype = getAttribute(*slot_idx);
  10077. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10078. return slot_idx;
  10079. }
  10080. findAttributeSlot(name) {
  10081. for (let pos = 0; pos < this._attributes.length; pos++) {
  10082. if (name === this._attributes[pos].name) {
  10083. return pos;
  10084. }
  10085. }
  10086. return null;
  10087. }
  10088. findAttribute(name) {
  10089. const slot = this.findAttributeSlot(name);
  10090. if (slot !== null) {
  10091. return this._attributes[slot].type;
  10092. }
  10093. return null;
  10094. }
  10095. hasAttribute(name) {
  10096. return this._attributes.find((attr) => attr.name === name);
  10097. }
  10098. getAttribute(arg) {
  10099. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10100. return this._attributes[slot].type;
  10101. }
  10102. getAttributeName(slot) {
  10103. return this._attributes[slot].name;
  10104. }
  10105. addConstant(name, value) {
  10106. this._constants.set(name, value);
  10107. }
  10108. hasConstant(name) {
  10109. return this._constants.has(name);
  10110. }
  10111. getProperty(name) {
  10112. for (const prop of this._properties) {
  10113. if (name === prop.name) {
  10114. return prop;
  10115. }
  10116. }
  10117. return null;
  10118. }
  10119. containedTypes() {
  10120. return this._attributeTypes;
  10121. }
  10122. createWithContained(contained_types) {
  10123. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10124. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10125. for (let i = 0; i < this._attributes.length; i++) {
  10126. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10127. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10128. }
  10129. for (const method of this.methods()) {
  10130. ptr.addMethod(method);
  10131. }
  10132. return ptr;
  10133. }
  10134. str() {
  10135. return this.qualified_name();
  10136. }
  10137. });
  10138. this.registerType('torch.EnumType', class extends torch.Type {
  10139. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10140. super('EnumType', qualified_class_name);
  10141. this._name = qualified_class_name;
  10142. this._value_type = value_type;
  10143. this._enum_names_values = enum_names_values;
  10144. this._cu = cu;
  10145. }
  10146. static create(qualified_class_name, value, enum_names_values, cu) {
  10147. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10148. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10149. }
  10150. torch._C.TORCH_CHECK(false);
  10151. return null;
  10152. }
  10153. name() {
  10154. return this._name;
  10155. }
  10156. get annotation_str() {
  10157. return this._name.qualifiedName();
  10158. }
  10159. enumNamesValues() {
  10160. return this._enum_names_values;
  10161. }
  10162. compilation_unit() {
  10163. return this._cu;
  10164. }
  10165. getValueType() {
  10166. return this._value_type;
  10167. }
  10168. equals(rhs) {
  10169. if (rhs instanceof torch.EnumType) {
  10170. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10171. }
  10172. return false;
  10173. }
  10174. isSubtypeOf(rhs) {
  10175. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10176. return true;
  10177. }
  10178. return super.isSubtypeOf(rhs);
  10179. }
  10180. });
  10181. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10182. if (args.length === 1) {
  10183. const [to_flatten] = args;
  10184. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10185. const to_fill = [];
  10186. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10187. to_flatten.splice(0, to_flatten.length);
  10188. to_flatten.push(...to_fill);
  10189. } else if (args.length === 2) {
  10190. const [reference, to_fill] = args;
  10191. for (const type of reference) {
  10192. torch._C.flattenUnion(type, to_fill);
  10193. }
  10194. torch._C.filterDuplicateSubtypes(to_fill);
  10195. torch._C.sortUnion(to_fill);
  10196. } else {
  10197. throw new python.Error('Not implemented.');
  10198. }
  10199. });
  10200. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10201. if (type instanceof torch.UnionType) {
  10202. for (const inner of type.containedTypes()) {
  10203. torch._C.flattenUnion(inner, to_fill);
  10204. }
  10205. } else if (type instanceof torch.OptionalType) {
  10206. const inner = type.getElementType();
  10207. torch._C.flattenUnion(inner, to_fill);
  10208. to_fill.push(torch.NoneType.get());
  10209. } else if (type instanceof torch.NumberType) {
  10210. to_fill.push(torch.IntType.get());
  10211. to_fill.push(torch.FloatType.get());
  10212. to_fill.push(torch.ComplexType.get());
  10213. } else {
  10214. to_fill.push(type);
  10215. }
  10216. });
  10217. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10218. if (types.length === 0) {
  10219. // return;
  10220. }
  10221. /*
  10222. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10223. // We don't want nested Optionals. Also, prematurely unifying to
  10224. // `Optional` could prevent us from coalescing other types
  10225. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10226. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10227. return null;
  10228. } else {
  10229. return unifyTypes(t1, t2, default_to_union=false);
  10230. }
  10231. };
  10232. size_t end_idx = types->size()-1;
  10233. for (size_t i = types->size()-1; i > 0; --i) {
  10234. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10235. std::optional<TypePtr> unified;
  10236. unified = get_supertype((*types)[i], (*types)[j]);
  10237. if (unified) {
  10238. (*types)[j] = *unified;
  10239. (*types)[i] = (*types)[end_idx];
  10240. --end_idx;
  10241. break;
  10242. }
  10243. if (j == 0) {
  10244. break;
  10245. }
  10246. }
  10247. }
  10248. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10249. */
  10250. });
  10251. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10252. /*
  10253. std::sort(types->begin(), types->end(),
  10254. [](const TypePtr& a, const TypePtr& b) -> bool {
  10255. if (a->kind() != b->kind()) {
  10256. return a->kind() < b->kind();
  10257. }
  10258. return a->str() < b->str();
  10259. });
  10260. */
  10261. });
  10262. this.registerType('torch.UnionType', class extends torch.Type {
  10263. constructor(reference, kind) {
  10264. super(kind || 'UnionType');
  10265. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10266. this._types = [];
  10267. torch._C.standardizeVectorForUnion(reference, this._types);
  10268. if (this._types.length === 1) {
  10269. throw new python.Error('Invalid union type reference.');
  10270. }
  10271. this._can_hold_none = false;
  10272. this._has_free_variables = false;
  10273. for (const type of this._types) {
  10274. if (type instanceof torch.NoneType) {
  10275. this._can_hold_none = true;
  10276. }
  10277. if (type.hasFreeVariables()) {
  10278. this._has_free_variables = true;
  10279. }
  10280. }
  10281. }
  10282. static create(reference) {
  10283. const union_type = new torch.UnionType(reference);
  10284. /*
  10285. bool int_found = false;
  10286. bool float_found = false;
  10287. bool complex_found = false;
  10288. bool nonetype_found = false;
  10289. const update_is_opt_flags = [&](const TypePtr& t) {
  10290. if (t == IntType::get()) {
  10291. int_found = true;
  10292. } else if (t == FloatType::get()) {
  10293. float_found = true;
  10294. } else if (t == ComplexType::get()) {
  10295. complex_found = true;
  10296. } else if (t == NoneType::get()) {
  10297. nonetype_found = true;
  10298. }
  10299. };
  10300. for (const auto& t : union_type->containedTypes()) {
  10301. update_is_opt_flags(t);
  10302. }
  10303. bool numbertype_found = int_found && float_found && complex_found;
  10304. if (nonetype_found) {
  10305. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10306. return OptionalType::create(NumberType::get());
  10307. }
  10308. if (union_type->containedTypes().size() == 2) {
  10309. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10310. ? union_type->containedTypes()[0]
  10311. : union_type->containedTypes()[1];
  10312. return OptionalType::create(not_none);
  10313. }
  10314. }
  10315. */
  10316. return union_type;
  10317. }
  10318. containedTypes() {
  10319. return this._types;
  10320. }
  10321. isUnionType() {
  10322. return true;
  10323. }
  10324. hasFreeVariables() {
  10325. return this._has_free_variables;
  10326. }
  10327. equals(rhs) {
  10328. if (rhs instanceof torch.UnionType) {
  10329. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10330. return false;
  10331. }
  10332. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10333. } else if (rhs instanceof torch.OptionalType) {
  10334. if (rhs.getElementType() === torch.NumberType.get()) {
  10335. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10336. }
  10337. const optional_lhs = this.toOptional();
  10338. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10339. } else if (rhs instanceof torch.NumberType) {
  10340. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10341. }
  10342. return false;
  10343. }
  10344. isSubtypeOf(rhs) {
  10345. const rhs_types = [];
  10346. if (rhs instanceof torch.UnionType) {
  10347. if (this.containedTypes() === rhs.containedTypes()) {
  10348. return true;
  10349. }
  10350. for (const typePtr of rhs.containedTypes()) {
  10351. rhs_types.push(typePtr);
  10352. }
  10353. } else if (rhs instanceof torch.OptionalType) {
  10354. rhs_types.push(torch.NoneType.get());
  10355. if (rhs.getElementType() === torch.NumberType.get()) {
  10356. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10357. rhs_types.push(...number_types);
  10358. } else {
  10359. rhs_types.push(rhs.getElementType());
  10360. }
  10361. } else if (rhs instanceof torch.NumberType) {
  10362. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10363. rhs_types.push(...number_types);
  10364. } else {
  10365. rhs_types.push(rhs);
  10366. }
  10367. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10368. }
  10369. });
  10370. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10371. constructor(contained) {
  10372. super([contained, torch.NoneType.get()], 'OptionalType');
  10373. let is_numbertype = false;
  10374. if (contained instanceof torch.UnionType) {
  10375. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10376. }
  10377. if (super.containedTypes().length === 2) {
  10378. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10379. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10380. this._contained = torch.NumberType.get();
  10381. this._types.splice(0, this._types.length);
  10382. this._types.push(torch.NumberType.get());
  10383. this._types.push(torch.NoneType.get());
  10384. } else {
  10385. const to_subtract = [torch.NoneType.get()];
  10386. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10387. this._contained = torch.UnionType.create([without_none]);
  10388. }
  10389. this._has_free_variables = contained.hasFreeVariables();
  10390. }
  10391. static create(elem) {
  10392. return new torch.OptionalType(elem);
  10393. }
  10394. getElementType() {
  10395. return this._contained;
  10396. }
  10397. equals(rhs) {
  10398. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10399. }
  10400. isSubtypeOf(rhs) {
  10401. if (rhs instanceof torch.OptionalType) {
  10402. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10403. } else if (rhs instanceof torch.UnionType) {
  10404. throw new python.Error('Not implemented.');
  10405. }
  10406. // return super.isSubtypeOf(rhs);
  10407. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10408. }
  10409. containedTypes() {
  10410. return [this._contained];
  10411. }
  10412. createWithContained(contained_types) {
  10413. torch._C.AT_ASSERT(contained_types.length === 1);
  10414. return torch.OptionalType.create(contained_types[0]);
  10415. }
  10416. subtractTypeSetFrom(to_subtract, from) {
  10417. const types = [];
  10418. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10419. for (const t of from) {
  10420. if (!should_subtract(t)) {
  10421. types.push(t);
  10422. }
  10423. }
  10424. if (types.length === 0) {
  10425. return null;
  10426. } else if (types.length === 1) {
  10427. return types[0];
  10428. }
  10429. return torch.UnionType.create(types);
  10430. }
  10431. str() {
  10432. return `${this.getElementType().str()}?`;
  10433. }
  10434. __str__() {
  10435. return `Optional[${this.getElementType().__str__()}]`;
  10436. }
  10437. });
  10438. this.registerType('torch.ListType', class extends torch.Type {
  10439. constructor(elem) {
  10440. super('ListType');
  10441. this._elem = elem;
  10442. }
  10443. static create(elem) {
  10444. return new torch.ListType(elem);
  10445. }
  10446. getElementType() {
  10447. return this._elem;
  10448. }
  10449. equals(rhs) {
  10450. if (rhs instanceof torch.ListType) {
  10451. return this.getElementType().equals(rhs.getElementType());
  10452. }
  10453. return false;
  10454. }
  10455. isSubtypeOf(rhs) {
  10456. if (super.isSubtypeOf(rhs)) {
  10457. return true;
  10458. }
  10459. if (rhs.kind() === 'AnyListType') {
  10460. return true;
  10461. }
  10462. return false;
  10463. }
  10464. containedTypes() {
  10465. return [this._elem];
  10466. }
  10467. createWithContained(contained_types) {
  10468. return new torch.ListType(contained_types[0]);
  10469. }
  10470. hasFreeVariables() {
  10471. return this.getElementType().hasFreeVariables();
  10472. }
  10473. str() {
  10474. return `${this.getElementType().str()}[]`;
  10475. }
  10476. __str__() {
  10477. return `List[${this.getElementType().__str__()}]`;
  10478. }
  10479. });
  10480. this.registerType('torch.FutureType', class extends torch.Type {
  10481. constructor(elem) {
  10482. super('FutureType');
  10483. this._elem = elem;
  10484. }
  10485. static create(elem) {
  10486. return new torch.FutureType(elem);
  10487. }
  10488. getElementType() {
  10489. return this._elem;
  10490. }
  10491. containedTypes() {
  10492. throw new python.Error('Not implemented.');
  10493. }
  10494. str() {
  10495. return `Future(${this.getElementType().str()})`;
  10496. }
  10497. __str__() {
  10498. return `Future[${this.getElementType().__str__()}]`;
  10499. }
  10500. });
  10501. this.registerType('torch.RRefType', class extends torch.Type {
  10502. constructor(elem) {
  10503. super('RRefType');
  10504. this._elem = elem;
  10505. }
  10506. static create(elem) {
  10507. return new torch.RRefType(elem);
  10508. }
  10509. getElementType() {
  10510. return this._elem;
  10511. }
  10512. containedTypes() {
  10513. throw new python.Error('Not implemented.');
  10514. }
  10515. str() {
  10516. return `RRef(${this.getElementType().str()})`;
  10517. }
  10518. __str__() {
  10519. return `RRef[${this.getElementType().__str__()}]`;
  10520. }
  10521. });
  10522. this.registerType('torch.AwaitType', class extends torch.Type {
  10523. constructor(elem) {
  10524. super('AwaitType');
  10525. this._elem = elem;
  10526. }
  10527. static get(elem) {
  10528. return new torch.AwaitType(elem);
  10529. }
  10530. getElementType() {
  10531. return this._elem;
  10532. }
  10533. containedTypes() {
  10534. throw new python.Error('Not implemented.');
  10535. }
  10536. str() {
  10537. return `Await(${this.getElementType().str()})`;
  10538. }
  10539. __str__() {
  10540. return `Await[${this.getElementType().__str__()}]`;
  10541. }
  10542. });
  10543. this.registerType('torch.TupleType', class extends torch.Type {
  10544. constructor(elements, annotation_str, schema) {
  10545. super('TupleType', annotation_str);
  10546. this._elements = elements;
  10547. this._has_free_variables = elements.some((v) => {
  10548. if (!v) {
  10549. throw new python.Error('Can not create tuple with None type');
  10550. }
  10551. return v.hasFreeVariables();
  10552. });
  10553. this._schema = schema;
  10554. }
  10555. static create(elements) {
  10556. return new torch.TupleType(elements, null, null);
  10557. }
  10558. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10559. const args = [];
  10560. for (let i = 0; i < field_names.length; i++) {
  10561. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10562. args.push(arg);
  10563. }
  10564. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10565. return new torch.TupleType(field_types, qualified_name, schema);
  10566. }
  10567. elements() {
  10568. return this._elements;
  10569. }
  10570. name() {
  10571. return this.annotation_str;
  10572. }
  10573. containedTypes() {
  10574. return this._elements;
  10575. }
  10576. createWithContained(createWithContained) {
  10577. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10578. }
  10579. hasFreeVariables() {
  10580. return this._has_free_variables;
  10581. }
  10582. schema() {
  10583. return this._schema;
  10584. }
  10585. str() {
  10586. if (this._schema) {
  10587. return `NamedTuple(...)`;
  10588. }
  10589. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10590. }
  10591. __str__() {
  10592. if (this.annotation_str) {
  10593. return this.annotation_str;
  10594. }
  10595. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10596. }
  10597. });
  10598. this.registerType('torch.AnyType', class extends torch.Type {
  10599. constructor() {
  10600. super('AnyType');
  10601. }
  10602. static get() {
  10603. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10604. return torch.AnyType.value;
  10605. }
  10606. str() {
  10607. return 'Any';
  10608. }
  10609. __str__() {
  10610. return 'Any';
  10611. }
  10612. });
  10613. this.registerType('torch.NoneType', class extends torch.Type {
  10614. constructor() {
  10615. super('NoneType');
  10616. }
  10617. static get() {
  10618. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10619. return torch.NoneType.value;
  10620. }
  10621. equals(rhs) {
  10622. return this.kind() === rhs.kind();
  10623. }
  10624. isSubtypeOf(rhs) {
  10625. if (rhs.kind() === 'OptionalType') {
  10626. return true;
  10627. }
  10628. return super.isSubtypeOf(rhs);
  10629. }
  10630. str() {
  10631. return 'NoneType';
  10632. }
  10633. __str__() {
  10634. return 'NoneType';
  10635. }
  10636. });
  10637. this.registerType('torch.TensorType', class extends torch.Type {
  10638. constructor() {
  10639. super('TensorType');
  10640. this._is_inferred = false;
  10641. }
  10642. static get() {
  10643. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10644. return torch.TensorType.value;
  10645. }
  10646. equals(rhs) {
  10647. return this.kind() === rhs.kind();
  10648. }
  10649. isInferredType() {
  10650. return this._is_inferred;
  10651. }
  10652. str() {
  10653. return 'Tensor';
  10654. }
  10655. __str__() {
  10656. return 'Tensor';
  10657. }
  10658. });
  10659. this.registerType('torch.NumberType', class extends torch.Type {
  10660. constructor() {
  10661. super('NumberType');
  10662. }
  10663. static get() {
  10664. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10665. return torch.NumberType.value;
  10666. }
  10667. str() {
  10668. return 'Scalar';
  10669. }
  10670. __str__() {
  10671. return 'number';
  10672. }
  10673. });
  10674. this.registerType('torch.BoolType', class extends torch.Type {
  10675. constructor() {
  10676. super('BoolType');
  10677. }
  10678. static get() {
  10679. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10680. return torch.BoolType.value;
  10681. }
  10682. equals(rhs) {
  10683. return this.kind() === rhs.kind();
  10684. }
  10685. str() {
  10686. return 'bool';
  10687. }
  10688. __str__() {
  10689. return 'bool';
  10690. }
  10691. });
  10692. this.registerType('torch.IntType', class extends torch.Type {
  10693. constructor() {
  10694. super('IntType');
  10695. }
  10696. static get() {
  10697. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10698. return torch.IntType.value;
  10699. }
  10700. equals(rhs) {
  10701. return this.kind() === rhs.kind();
  10702. }
  10703. isSubtypeOf(rhs) {
  10704. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10705. }
  10706. str() {
  10707. return 'int';
  10708. }
  10709. __str__() {
  10710. return 'int';
  10711. }
  10712. });
  10713. this.registerType('torch.SymIntType', class extends torch.Type {
  10714. constructor() {
  10715. super('SymIntType');
  10716. }
  10717. static get() {
  10718. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10719. return torch.SymIntType.value;
  10720. }
  10721. equals(rhs) {
  10722. return this.kind() === rhs.kind();
  10723. }
  10724. str() {
  10725. return 'SymInt';
  10726. }
  10727. __str__() {
  10728. return 'int';
  10729. }
  10730. });
  10731. this.registerType('torch.FloatType', class extends torch.Type {
  10732. constructor() {
  10733. super('FloatType');
  10734. }
  10735. static get() {
  10736. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10737. return torch.FloatType.value;
  10738. }
  10739. equals(rhs) {
  10740. return this.kind() === rhs.kind();
  10741. }
  10742. isSubtypeOf(rhs) {
  10743. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10744. }
  10745. str() {
  10746. return 'float';
  10747. }
  10748. __str__() {
  10749. return 'float';
  10750. }
  10751. });
  10752. this.registerType('torch.StringType', class extends torch.Type {
  10753. constructor() {
  10754. super('StringType');
  10755. }
  10756. static get() {
  10757. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10758. return torch.StringType.value;
  10759. }
  10760. equals(rhs) {
  10761. return this.kind() === rhs.kind();
  10762. }
  10763. str() {
  10764. return 'str';
  10765. }
  10766. __str__() {
  10767. return 'str';
  10768. }
  10769. });
  10770. this.registerType('torch.ComplexType', class extends torch.Type {
  10771. constructor() {
  10772. super('ComplexType');
  10773. }
  10774. static get() {
  10775. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10776. return torch.ComplexType.value;
  10777. }
  10778. equals(rhs) {
  10779. return this.kind() === rhs.kind();
  10780. }
  10781. isSubtypeOf(rhs) {
  10782. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10783. }
  10784. str() {
  10785. return 'complex';
  10786. }
  10787. __str__() {
  10788. return 'complex';
  10789. }
  10790. });
  10791. this.registerType('torch.DictType', class extends torch.Type {
  10792. constructor(key, value) {
  10793. super('DictType');
  10794. this.types = [key, value];
  10795. }
  10796. static create(key, value) {
  10797. let kind = key.kind();
  10798. if (key instanceof torch._C.DynamicType) {
  10799. kind = key.dynamicKind();
  10800. }
  10801. switch (kind) {
  10802. case 'AnyType':
  10803. case 'IntType':
  10804. case 'BoolType':
  10805. case 'FloatType':
  10806. case 'ComplexType':
  10807. case 'StringType':
  10808. case 'TensorType':
  10809. case 'DeviceObjType':
  10810. return new torch.DictType(key, value);
  10811. default:
  10812. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10813. }
  10814. }
  10815. createWithContained(contained_types) {
  10816. if (contained_types.length !== 2) {
  10817. throw new python.Error('Expected 2 contained types.');
  10818. }
  10819. return torch.DictType.create(contained_types[0], contained_types[1]);
  10820. }
  10821. getKeyType() {
  10822. return this.types[0];
  10823. }
  10824. getValueType() {
  10825. return this.types[1];
  10826. }
  10827. hasFreeVariables() {
  10828. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10829. }
  10830. containedTypes() {
  10831. return this.types;
  10832. }
  10833. equals(rhs) {
  10834. if (rhs instanceof torch.DictType) {
  10835. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10836. }
  10837. return false;
  10838. }
  10839. str() {
  10840. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10841. }
  10842. __str__() {
  10843. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10844. }
  10845. });
  10846. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10847. constructor() {
  10848. super('DeviceObjType');
  10849. }
  10850. static get() {
  10851. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10852. return torch.DeviceObjType.value;
  10853. }
  10854. str() {
  10855. return 'Device';
  10856. }
  10857. __str__() {
  10858. return 'Device';
  10859. }
  10860. });
  10861. this.registerType('torch.StreamObjType', class extends torch.Type {
  10862. constructor() {
  10863. super('StreamObjType');
  10864. }
  10865. str() {
  10866. return 'Stream';
  10867. }
  10868. __str__() {
  10869. return 'Stream';
  10870. }
  10871. });
  10872. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10873. constructor() {
  10874. super('GeneratorType');
  10875. }
  10876. static get() {
  10877. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10878. return torch._C._GeneratorType.value;
  10879. }
  10880. str() {
  10881. return 'Generator';
  10882. }
  10883. __str__() {
  10884. return 'Generator';
  10885. }
  10886. });
  10887. this.registerType('torch.InterfaceType', class extends torch.Type {
  10888. constructor() {
  10889. super('InterfaceType');
  10890. }
  10891. });
  10892. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10893. constructor() {
  10894. super('DynamicType');
  10895. }
  10896. });
  10897. this.registerType('torch._C.FunctionType', class extends torch.Type {
  10898. constructor(func) {
  10899. super('FunctionType');
  10900. this._func = func;
  10901. }
  10902. static create(func) {
  10903. return new torch._C.FunctionType(func);
  10904. }
  10905. function() {
  10906. return this._func;
  10907. }
  10908. });
  10909. this.registerType('torch._C.VarType', class extends torch.Type {
  10910. constructor(name) {
  10911. super('VarType', name);
  10912. }
  10913. static create(name) {
  10914. return new torch._C.VarType(name);
  10915. }
  10916. name() {
  10917. return this._annotation_str;
  10918. }
  10919. hasFreeVariables() {
  10920. return true;
  10921. }
  10922. });
  10923. this.registerType('torch._C.AliasInfo', class {
  10924. constructor() {
  10925. this.is_write = false;
  10926. this.before_set = [];
  10927. this.after_set = [];
  10928. this.containedTypes = [];
  10929. }
  10930. addBeforeSet(value) {
  10931. this.before_set.push(value);
  10932. }
  10933. addAfterSet(value) {
  10934. this.after_set.push(value);
  10935. }
  10936. addContainedType(alias_info) {
  10937. this.containedTypes.push(alias_info);
  10938. }
  10939. str() {
  10940. const list = ['('];
  10941. list.push(this.before_set.join('|'));
  10942. if (this.after_set.length > 0) {
  10943. list.push(' -> ');
  10944. list.push(this.after_set.join('|'));
  10945. }
  10946. if (this.is_write) {
  10947. list.push('!');
  10948. }
  10949. list.push(')');
  10950. return list.join('');
  10951. }
  10952. });
  10953. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  10954. if (str.startsWith('"') && str.endsWith('"')) {
  10955. return str.slice(1, -1);
  10956. }
  10957. if (str.startsWith("'") && str.endsWith("'")) {
  10958. return str.slice(1, -1);
  10959. }
  10960. throw new python.Error(`Invalid string literal '${str}'.`);
  10961. // inline std::string parseStringLiteral(
  10962. });
  10963. this.registerType('torch._C.Token', class {
  10964. constructor() {
  10965. this.kind = '';
  10966. this.value = '';
  10967. }
  10968. text() {
  10969. return this.value;
  10970. }
  10971. });
  10972. this.registerType('torch._C.Lexer', class {
  10973. constructor(buffer) {
  10974. this.buffer = buffer;
  10975. this.position = 0;
  10976. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  10977. this.next();
  10978. }
  10979. cur() {
  10980. return this.next_tokens[0];
  10981. }
  10982. lookahead() {
  10983. if (!this.next_tokens[1].kind) {
  10984. this.position += this.cur().text().length;
  10985. this.lex(this.next_tokens[1]);
  10986. }
  10987. return this.next_tokens[1];
  10988. }
  10989. next() {
  10990. const [cur] = this.next_tokens;
  10991. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  10992. this.next_tokens[1].kind = '';
  10993. this.next_tokens[3] = cur;
  10994. const [token] = this.next_tokens;
  10995. if (token.kind) {
  10996. return cur;
  10997. }
  10998. this.position += cur.text().length;
  10999. this.lex(token);
  11000. return cur;
  11001. }
  11002. nextIf(kind) {
  11003. if (this.cur().kind !== kind) {
  11004. return false;
  11005. }
  11006. this.next();
  11007. return true;
  11008. }
  11009. expect(kind) {
  11010. if (this.cur().kind !== kind) {
  11011. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  11012. }
  11013. return this.next();
  11014. }
  11015. lex(token) {
  11016. while (this.buffer[this.position] === ' ') {
  11017. this.position += 1;
  11018. }
  11019. let i = this.position;
  11020. if (i >= this.buffer.length) {
  11021. token.kind = '\0';
  11022. token.value = '';
  11023. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  11024. token.kind = '...';
  11025. token.value = '...';
  11026. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  11027. this.kind = '[]';
  11028. this.value = '[]'; */
  11029. } else if (this.buffer[i] === '(' || this.buffer[i] === ')' || this.buffer[i] === ':' || this.buffer[i] === '.' || this.buffer[i] === '[' || this.buffer[i] === ']' || this.buffer[i] === ',' || this.buffer[i] === '=' || this.buffer[i] === '?' || this.buffer[i] === '!' || this.buffer[i] === '*' || this.buffer[i] === '|') {
  11030. token.kind = this.buffer[i];
  11031. token.value = this.buffer[i];
  11032. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  11033. i += 1;
  11034. while (i < this.buffer.length && ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || (this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '_')) {
  11035. i += 1;
  11036. }
  11037. token.kind = 'id';
  11038. token.value = this.buffer.slice(this.position, i);
  11039. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  11040. token.kind = '->';
  11041. token.value = '->';
  11042. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  11043. i += 1;
  11044. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  11045. i += 1;
  11046. }
  11047. token.kind = '#';
  11048. token.value = this.buffer.slice(this.position, i);
  11049. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  11050. const quote = this.buffer[i];
  11051. i += 1;
  11052. while (i < this.buffer.length && this.buffer[i] !== quote) {
  11053. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  11054. }
  11055. i += 1;
  11056. token.kind = 'string';
  11057. token.value = this.buffer.slice(this.position, i);
  11058. } else {
  11059. throw new python.Error(`Unsupported token at '${this.position}'.`);
  11060. }
  11061. }
  11062. });
  11063. this.registerType('torch._C.SchemaTypeParser', class {
  11064. constructor(L, complete_tensor_types, allow_typevars) {
  11065. this.L = L;
  11066. this.complete_tensor_types = complete_tensor_types;
  11067. this._allow_typevars = allow_typevars;
  11068. }
  11069. parseType() {
  11070. const r = this.parseFakeAndRealType();
  11071. return { first: r[0], second: r[2] };
  11072. }
  11073. parseBaseType() {
  11074. const L = this.L;
  11075. const tok = L.cur();
  11076. const text = tok.text();
  11077. L.next();
  11078. switch (text) {
  11079. case 'Tensor': return torch.TensorType.get();
  11080. case 'bool': return torch.BoolType.get();
  11081. case 'int': return torch.IntType.get();
  11082. case 'float': return torch.FloatType.get();
  11083. case 'complex': return torch.ComplexType.get();
  11084. case 'str': return torch.StringType.get();
  11085. case 'SymInt': return torch.SymIntType.get();
  11086. case 'Scalar': return torch.NumberType.get();
  11087. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11088. case 'Device': return torch.DeviceObjType.get();
  11089. case 'Layout': return torch.Type.get('Layout');
  11090. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11091. case 'Generator': return torch._C._GeneratorType.get();
  11092. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11093. case 'Any': return torch.AnyType.get();
  11094. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11095. case 'Dimname': return torch.StringType.get();
  11096. case 'QScheme': return torch.Type.get('QSchemeType');
  11097. case 'Stream': return torch.StreamObjType.get();
  11098. case 'Storage': return torch.Type.get('Storage');
  11099. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11100. case 'NoneType': return torch.NoneType.get();
  11101. default: throw new python.Error(`Unsupported type '${text}'.`);
  11102. }
  11103. }
  11104. parseFakeAndRealType() {
  11105. const L = this.L;
  11106. let fake_value = null;
  11107. let real_value = null;
  11108. let alias_info = null;
  11109. if (L.nextIf('(')) {
  11110. const types = [];
  11111. while (!L.nextIf(')')) {
  11112. const r = this.parseType();
  11113. types.push(r.first);
  11114. if (alias_info && r.second) {
  11115. alias_info.addContainedType(r.second);
  11116. }
  11117. L.nextIf(',');
  11118. }
  11119. real_value = torch.TupleType.create(types);
  11120. fake_value = real_value;
  11121. } else if (L.cur().text() === 'Future') {
  11122. L.next();
  11123. L.expect('(');
  11124. const p = this.parseType();
  11125. const subtype = p.first;
  11126. // const subalias = p.second;
  11127. L.expect(')');
  11128. real_value = torch.FutureType.create(subtype);
  11129. fake_value = real_value;
  11130. } else if (L.cur().text() === 'Await') {
  11131. L.next();
  11132. L.expect('(');
  11133. const p = this.parseType();
  11134. const subtype = p.first;
  11135. // const subalias = p.second;
  11136. L.expect(')');
  11137. real_value = torch.AwaitType.get(subtype);
  11138. fake_value = real_value;
  11139. } else if (L.cur().text() === 'RRef') {
  11140. L.next();
  11141. L.expect('(');
  11142. const p = this.parseType();
  11143. const subtype = p.first;
  11144. // const subalias = p.second;
  11145. L.expect(')');
  11146. real_value = torch.RRefType.create(subtype);
  11147. fake_value = real_value;
  11148. } else if (L.cur().text() === 'Tensor') {
  11149. L.next();
  11150. real_value = torch.TensorType.get();
  11151. fake_value = real_value;
  11152. alias_info = this.parseAliasAnnotation();
  11153. } else if (L.cur().text() === 'Dict') {
  11154. L.next();
  11155. L.expect('(');
  11156. const key_type = this.parseType().first;
  11157. L.expect(',');
  11158. const value_type = this.parseType().first;
  11159. L.expect(')');
  11160. alias_info = this.parseAliasAnnotation();
  11161. real_value = torch.DictType.create(key_type, value_type);
  11162. fake_value = real_value;
  11163. } else if (L.nextIf('Union')) {
  11164. L.next();
  11165. L.expect('(');
  11166. const types = [];
  11167. types.push(this.parseType().first);
  11168. while (L.cur().kind !== ')') {
  11169. L.expect(',');
  11170. types.push(this.parseType().first);
  11171. }
  11172. L.expect(')');
  11173. alias_info = this.parseAliasAnnotation();
  11174. real_value = new torch.UnionType(types);
  11175. fake_value = real_value;
  11176. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11177. fake_value = real_value = parseRefinedTensor();
  11178. alias_info = parseAliasAnnotation(); */
  11179. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11180. L.next();
  11181. L.expect('.');
  11182. const torch_tok = L.expect('id');
  11183. if (torch_tok.text() !== 'torch') {
  11184. throw new python.Error('Expected classes namespace.');
  11185. }
  11186. L.expect('.');
  11187. const classes_tok = L.expect('id');
  11188. if (classes_tok.text() !== 'classes') {
  11189. throw new python.Error('Expected classes namespace.');
  11190. }
  11191. L.expect('.');
  11192. const ns_tok = L.expect('id');
  11193. L.expect('.');
  11194. const class_tok = L.expect('id');
  11195. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11196. fake_value = real_value;
  11197. if (!fake_value) {
  11198. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11199. }
  11200. } else {
  11201. real_value = this.parseBaseType();
  11202. fake_value = real_value;
  11203. if (real_value.kind() === 'ScalarTypeType' ||
  11204. real_value.kind() === 'MemoryFormat' ||
  11205. real_value.kind() === 'Layout' ||
  11206. real_value.kind() === 'SymIntType') {
  11207. fake_value = torch.IntType.get();
  11208. }
  11209. alias_info = this.parseAliasAnnotation();
  11210. }
  11211. while (true) {
  11212. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11213. L.expect('[');
  11214. L.expect(']');
  11215. fake_value = torch.ListType.create(fake_value);
  11216. real_value = torch.ListType.create(real_value);
  11217. let container = this.parseAliasAnnotation();
  11218. if (alias_info) {
  11219. if (!container) {
  11220. container = new torch._C.AliasInfo();
  11221. container.is_write = alias_info.is_write;
  11222. }
  11223. container.addContainedType(alias_info);
  11224. }
  11225. alias_info = container;
  11226. } else if (L.nextIf('?')) {
  11227. fake_value = torch.OptionalType.create(fake_value);
  11228. real_value = torch.OptionalType.create(real_value);
  11229. } else {
  11230. break;
  11231. }
  11232. }
  11233. return [fake_value, real_value, alias_info];
  11234. }
  11235. parseAliasAnnotation() {
  11236. const L = this.L;
  11237. let alias_info = null;
  11238. if (L.nextIf('(')) {
  11239. alias_info = new torch._C.AliasInfo();
  11240. do {
  11241. alias_info.addBeforeSet(L.cur().text());
  11242. L.next();
  11243. if (L.nextIf('!')) {
  11244. alias_info.is_write = true;
  11245. }
  11246. }
  11247. while (L.nextIf('|'));
  11248. if (L.nextIf('->')) {
  11249. do {
  11250. alias_info.addAfterSet(L.cur().text());
  11251. L.next();
  11252. }
  11253. while (L.nextIf('|'));
  11254. }
  11255. L.expect(')');
  11256. }
  11257. return alias_info;
  11258. }
  11259. });
  11260. this.registerType('torch.Argument', class {
  11261. constructor(...args) {
  11262. // torch/aten/src/ATen/core/function_schema.h
  11263. this.N = null;
  11264. this.default_value = null;
  11265. this.kwarg_only = false;
  11266. this.alias_info = null;
  11267. if (args.length === 2) {
  11268. [this.name, this.type] = args;
  11269. this.real_type = this.type;
  11270. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11271. [this.name, this.type, this.real_type] = args;
  11272. } else if (args.length === 6) {
  11273. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11274. } else if (args.length === 7) {
  11275. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11276. } else {
  11277. throw new python.Error('Invalid arguments.');
  11278. }
  11279. const is_alias = this.alias_info && this.alias_info.is_write;
  11280. this.is_out = this.kwarg_only && is_alias;
  11281. }
  11282. has_default_value() {
  11283. return this.default_value !== undefined;
  11284. }
  11285. is_inferred_type() {
  11286. if (this.type instanceof torch.TensorType) {
  11287. return this.type.isInferredType();
  11288. }
  11289. return false;
  11290. }
  11291. str() {
  11292. const list = [];
  11293. const type = this.real_type;
  11294. const is_opt = type instanceof torch.OptionalType;
  11295. const unopt_type = is_opt ? type.getElementType() : type;
  11296. if (unopt_type instanceof torch.ListType) {
  11297. list.push(unopt_type.getElementType().str());
  11298. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11299. list.push(this.alias_info.containedTypes[0].str());
  11300. }
  11301. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11302. } else {
  11303. list.push(unopt_type.str());
  11304. }
  11305. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11306. list.push(this.alias_info.str());
  11307. }
  11308. if (is_opt) {
  11309. list.push('?');
  11310. }
  11311. if (this.name) {
  11312. list.push(' ');
  11313. list.push(this.name);
  11314. }
  11315. if (this.default_value !== undefined) {
  11316. const value = this.default_value;
  11317. if (value === null) {
  11318. list.push('=None');
  11319. } else if (typeof value === 'boolean') {
  11320. list.push('=');
  11321. list.push(value ? 'True' : 'False');
  11322. } else if (typeof value === 'string') {
  11323. list.push(`="${value}"`);
  11324. } else if (typeof value === 'number') {
  11325. list.push(`=${value}`);
  11326. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11327. list.push(`.`);
  11328. }
  11329. } else if (Array.isArray(value)) {
  11330. list.push(`=[${value.join(', ')}]`);
  11331. }
  11332. }
  11333. return list.join('');
  11334. }
  11335. });
  11336. torch._C.TypeKind = {
  11337. StringType: 'StringType',
  11338. NumberType: 'NumberType',
  11339. IntType: 'IntType',
  11340. BoolType: 'BoolType',
  11341. DynamicType: 'DynamicType',
  11342. OptionalType: 'OptionalType',
  11343. FloatType: 'FloatType',
  11344. ComplexType: 'ComplexType',
  11345. ListType: 'ListType',
  11346. };
  11347. this.registerType('torch._C.List', class extends Array {
  11348. constructor(type, elements) {
  11349. super(elements ? elements.length : 0);
  11350. if (Array.isArray(elements)) {
  11351. for (let i = 0; i < elements.length; i++) {
  11352. this[i] = elements[i];
  11353. }
  11354. }
  11355. this.type = type;
  11356. }
  11357. elementType() {
  11358. return this.type;
  11359. }
  11360. });
  11361. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11362. return new Map();
  11363. });
  11364. this.registerFunction('torch._C.string_to_type_lut', () => {
  11365. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11366. const map = new Map();
  11367. map.set('Tensor', torch.TensorType.get());
  11368. map.set('int', torch.IntType.get());
  11369. map.set('float', torch.FloatType.get());
  11370. map.set('bool', torch.BoolType.get());
  11371. map.set('complex', torch.ComplexType.get());
  11372. map.set('str', torch.StringType.get());
  11373. map.set('Device', torch.DeviceObjType.get());
  11374. map.set('number', torch.NumberType.get());
  11375. map.set('None', torch.NoneType.get());
  11376. map.set('NoneType', torch.NoneType.get());
  11377. map.set('Any', torch.AnyType.get());
  11378. map.set('list', torch.Type.get('AnyListType'));
  11379. map.set('tuple', torch.Type.get('AnyTupleType'));
  11380. torch._C.string_to_type_lut.basePythonTypes = map;
  11381. }
  11382. return torch._C.string_to_type_lut.basePythonTypes;
  11383. });
  11384. this.registerType('torch._C.ScriptTypeParser', class {
  11385. constructor(resolver) {
  11386. this._resolver = resolver;
  11387. }
  11388. parseSchemaFromDef(def, skip_self) {
  11389. const name = def.name;
  11390. const args = this.parseArgsFromDecl(def, skip_self);
  11391. const returns = this.parseReturnFromDecl(def);
  11392. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11393. }
  11394. parseArgsFromDecl(decl, skip_self) {
  11395. const retval = [];
  11396. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11397. throw new python.Error('Unsupported function argument.');
  11398. }
  11399. const params = decl.args.args.slice();
  11400. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11401. const start = skip_self ? 1 : 0;
  11402. for (let i = start; i < params.length; i++) {
  11403. const decl_arg = params[i];
  11404. const N = null;
  11405. const default_value = undefined;
  11406. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11407. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11408. retval.push(arg);
  11409. }
  11410. return retval;
  11411. }
  11412. parseReturnFromDecl(decl) {
  11413. if (!decl.returns) {
  11414. return [];
  11415. }
  11416. if (this.parseBroadcastList(decl.returns)) {
  11417. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11418. }
  11419. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11420. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11421. }
  11422. parseTypeFromExpr(expr) {
  11423. if (this._resolver) {
  11424. if (expr instanceof ast.Name) {
  11425. const type = this._resolver.resolveType(expr.id);
  11426. if (type) {
  11427. return type;
  11428. }
  11429. }
  11430. }
  11431. return this.parseTypeFromExprImpl(expr);
  11432. }
  11433. parseTypeFromExprImpl(expr) {
  11434. if (expr instanceof ast.Subscript) {
  11435. const value_name = this.parseBaseTypeName(expr.value);
  11436. if (!value_name) {
  11437. throw new python.Error('Subscripted type must be a type identifier.');
  11438. }
  11439. return this.subscriptToType(value_name, expr);
  11440. }
  11441. const name = this.parseBaseTypeName(expr);
  11442. if (name) {
  11443. const itr = torch._C.string_to_type_lut().get(name);
  11444. if (itr) {
  11445. return itr;
  11446. }
  11447. if (this._resolver) {
  11448. const typePtr = this._resolver.resolveType(name, expr);
  11449. if (typePtr) {
  11450. return typePtr;
  11451. }
  11452. }
  11453. }
  11454. throw new python.Error(`Unknown type name '${name}'.`);
  11455. }
  11456. parseBaseTypeName(expr) {
  11457. if (expr instanceof ast.Name) {
  11458. return expr.id;
  11459. } else if (expr instanceof ast.Constant && expr.value === null) {
  11460. return 'None';
  11461. } else if (expr instanceof ast.Attribute) {
  11462. const name = expr.attr;
  11463. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11464. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11465. return name;
  11466. }
  11467. return torch._C.collectQualname(expr);
  11468. }
  11469. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11470. }
  11471. parseBroadcastList(/* expr */) {
  11472. return null;
  11473. }
  11474. parseType(str) {
  11475. const expr = ast.parse(str);
  11476. return this.parseTypeFromExpr(expr.body[0].value);
  11477. }
  11478. subscriptToType(typeName, subscript) {
  11479. if (typeName === 'Tuple' || typeName === 'tuple') {
  11480. const subscript_expr_types = [];
  11481. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11482. for (const expr of elts) {
  11483. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11484. }
  11485. return torch.TupleType.create(subscript_expr_types);
  11486. } else if (typeName === 'List' || typeName === 'list') {
  11487. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11488. throw new python.Error('List type must have exactly one element type.');
  11489. }
  11490. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11491. return torch.ListType.create(elem_type);
  11492. } else if (typeName === 'Optional') {
  11493. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11494. throw new python.Error('Optional type must have exactly one element type.');
  11495. }
  11496. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11497. return torch.OptionalType.create(elem_type);
  11498. } else if (typeName === 'Union') {
  11499. const subscript_expr_types = [];
  11500. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11501. for (const expr of elts) {
  11502. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11503. }
  11504. return torch.UnionType.create(subscript_expr_types);
  11505. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11506. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11507. if (elts.length !== 1) {
  11508. throw new python.Error('Future type must have exactly one element type.');
  11509. }
  11510. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11511. return torch.FutureType.create(elem_type);
  11512. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11513. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11514. if (elts.length !== 1) {
  11515. throw new python.Error('Await type must have exactly one element type.');
  11516. }
  11517. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11518. return torch.AwaitType.create(elem_type);
  11519. } else if (typeName === 'RRef') {
  11520. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11521. if (elts.length !== 1) {
  11522. throw new python.Error('RRef type must have exactly one element type.');
  11523. }
  11524. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11525. return torch.RRefType.create(elem_type);
  11526. } else if (typeName === 'Dict' || typeName === 'dict') {
  11527. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11528. if (elts.length !== 2) {
  11529. throw new python.Error('Dict type must have exactly two element types.');
  11530. }
  11531. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11532. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11533. return torch.DictType.create(key_type, value_type);
  11534. }
  11535. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11536. }
  11537. });
  11538. this.registerFunction('torch._C.isTorch', (expr) => {
  11539. return expr instanceof ast.Name && expr.id === 'torch';
  11540. });
  11541. this.registerFunction('torch._C.collectQualname', (select) => {
  11542. const base = select.value;
  11543. if (base instanceof ast.Name) {
  11544. return `${base.id}.${select.attr}`;
  11545. }
  11546. const basename = torch._C.collectQualname(base);
  11547. return `${basename}.${select.attr}`;
  11548. });
  11549. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11550. constructor(overloadpacket, op, op_dk, schema, tags) {
  11551. super();
  11552. this._op = op;
  11553. this._op_dk = op_dk;
  11554. this._schema = schema;
  11555. this._overloadpacket = overloadpacket;
  11556. this._tags = tags;
  11557. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11558. this._name = this._schema.name;
  11559. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11560. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11561. this.__module__ = overloadpacket.__module__;
  11562. op.__module__ = overloadpacket.__module__;
  11563. this.__qualname__ = self._name;
  11564. this.__annotations__ = {};
  11565. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11566. let is_write = null;
  11567. for (const a of this._schema.arguments) {
  11568. if (a.alias_info) {
  11569. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11570. }
  11571. }
  11572. this.is_view = is_write !== null && !is_write;
  11573. }
  11574. name() {
  11575. return this._name;
  11576. }
  11577. });
  11578. this.registerType('torch._ops.OpOverloadPacket', class {
  11579. constructor(qualified_op_name, op_name, op, overload_names) {
  11580. this._qualified_op_name = qualified_op_name;
  11581. this.__name__ = op_name;
  11582. this._op = op;
  11583. this._overload_names = overload_names;
  11584. this._dir = [];
  11585. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11586. }
  11587. get _schemas() {
  11588. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11589. }
  11590. __getattr__(key) {
  11591. key = key === 'default' ? '' : key;
  11592. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11593. const [op_, op_dk_, tags] = op_dk_tags;
  11594. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11595. const overload = this._has_script_object_arg(schema) ?
  11596. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11597. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11598. builtins.setattr(self, key, overload);
  11599. this._dir.push(key);
  11600. return overload;
  11601. }
  11602. _has_script_object_arg(schema) {
  11603. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11604. }
  11605. __call__(...args) {
  11606. const fn = execution._operators.get(this._qualified_op_name);
  11607. if (!fn) {
  11608. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11609. }
  11610. return fn(...args);
  11611. }
  11612. });
  11613. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11614. constructor(name) {
  11615. super(`torch.ops.${name}`);
  11616. this.name = name;
  11617. this._dir = [];
  11618. }
  11619. __getattr__(op_name) {
  11620. const namespace_name = this.name;
  11621. const qualified_op_name = `${namespace_name}::${op_name}`;
  11622. const module_name = `${this.__module__}.${namespace_name}`;
  11623. let op = null;
  11624. let overload_names = null;
  11625. try {
  11626. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11627. } catch {
  11628. // continue regardless of error
  11629. }
  11630. if (!op) {
  11631. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11632. }
  11633. op.__module__ = module_name;
  11634. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11635. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11636. builtins.setattr(this, op_name, opoverloadpacket);
  11637. this._dir.push(op_name);
  11638. return opoverloadpacket;
  11639. }
  11640. _get_packet(qualname, op_module) {
  11641. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11642. if (op) {
  11643. // torch.jit._builtins._register_builtin(op, qualname);
  11644. }
  11645. op.__module__ = op_module;
  11646. return [op, overload_names];
  11647. }
  11648. });
  11649. this.registerType('torch._C.graph_node_list', class {
  11650. constructor(head) {
  11651. this.head = head;
  11652. }
  11653. front() {
  11654. return this.head.next;
  11655. }
  11656. end() {
  11657. return this.head.prev;
  11658. }
  11659. [Symbol.iterator]() {
  11660. let current = this.head.next;
  11661. const prev = this.head.prev;
  11662. return {
  11663. next() {
  11664. if (current !== prev) {
  11665. const value = current;
  11666. current = current.next;
  11667. return { value, done: false };
  11668. }
  11669. return { done: true };
  11670. }
  11671. };
  11672. }
  11673. });
  11674. this.registerType('torch.Graph', class {
  11675. constructor() {
  11676. this._next_unique = 0;
  11677. this._unique_names = new Map();
  11678. this._name_base_suffix = new Map();
  11679. this.all_nodes = new Set();
  11680. this.all_values = new Set();
  11681. this.all_blocks = new Set();
  11682. this._block = new torch.Block(this, null);
  11683. this._insert_before = this.return_node();
  11684. }
  11685. insert(opname, args, kwargs, range) {
  11686. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11687. }
  11688. create(kind, ...args) {
  11689. let inputs = null;
  11690. let num_outputs = 1;
  11691. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11692. [inputs, num_outputs] = args;
  11693. } else if (args.length === 1) {
  11694. if (typeof args[0] === 'number') {
  11695. [num_outputs] = args;
  11696. } else if (Array.isArray(args[0])) {
  11697. [inputs] = args;
  11698. }
  11699. }
  11700. const n = new torch.Node(this, kind);
  11701. if (inputs) {
  11702. for (const i of inputs) {
  11703. n.addInput(i);
  11704. }
  11705. }
  11706. for (let i = 0; i < num_outputs; i++) {
  11707. n.addOutput();
  11708. }
  11709. return n;
  11710. }
  11711. createClone(n, value_map, copy_blocks) {
  11712. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11713. const r = n.allocNewInstance(this);
  11714. for (const o of n.outputs()) {
  11715. r.addOutput().copyMetadata(o);
  11716. }
  11717. r.cloneFrom(n);
  11718. for (const i of n.inputs()) {
  11719. r.addInput(value_map(i));
  11720. }
  11721. if (copy_blocks) {
  11722. for (const b of n.blocks()) {
  11723. r.addBlock().cloneFrom(b, value_map);
  11724. }
  11725. }
  11726. return r;
  11727. }
  11728. createNone() {
  11729. const n = this.create('prim::Constant');
  11730. n.output().setType(torch.NoneType.get());
  11731. return n;
  11732. }
  11733. createUninitialized(typ) {
  11734. const n = this.create('prim::Uninitialized');
  11735. n.output().setType(typ);
  11736. return n;
  11737. }
  11738. createEnumValue(e) {
  11739. const enum_type = e.type().expect(torch.EnumType);
  11740. const n = this.create('prim::EnumValue', [e]);
  11741. n.output().setType(enum_type.getValueType());
  11742. return n;
  11743. }
  11744. createList(contained_type, values) {
  11745. const n = this.create('prim::ListConstruct', values);
  11746. for (const v of values) {
  11747. if (!v.type().isSubtypeOf(contained_type)) {
  11748. throw new python.Error('Invalid list item.');
  11749. }
  11750. }
  11751. n.output().setType(torch.ListType.create(contained_type));
  11752. return n;
  11753. }
  11754. createListUnpack(v, size) {
  11755. const list_type = v.type().expect(torch.ListType);
  11756. const elem_type = list_type.getElementType();
  11757. const n = this.create('prim::ListUnpack', [v], 0);
  11758. for (let i = 0; i < size; i++) {
  11759. n.addOutput().setType(elem_type);
  11760. }
  11761. return n;
  11762. }
  11763. createTuple(values, tuple_type) {
  11764. if (!tuple_type) {
  11765. const types = values.map((v) => v.type());
  11766. tuple_type = torch.TupleType.create(types);
  11767. }
  11768. const n = this.create('prim::TupleConstruct', values);
  11769. n.output().setType(tuple_type);
  11770. return n;
  11771. }
  11772. createTupleUnpack(v) {
  11773. const tt = v.type().expect(torch.TupleType);
  11774. const n = this.create('prim::TupleUnpack', [v], 0);
  11775. for (const element of tt.elements()) {
  11776. n.addOutput().setType(element);
  11777. }
  11778. return n;
  11779. }
  11780. createTupleIndex(tup, idx, output_type) {
  11781. const n = this.create('prim::TupleIndex', [tup, idx]);
  11782. n.output().setType(output_type);
  11783. return n;
  11784. }
  11785. createTupleSlice(tup, beg, step_size, num_values) {
  11786. const new_vals = [];
  11787. const tt = tup.type().expect(torch.TupleType);
  11788. let i = beg;
  11789. for (let j = 0; j < num_values; j++) {
  11790. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11791. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11792. new_vals.push(tupleIndex.output());
  11793. i += step_size;
  11794. }
  11795. const n = this.createTuple(new_vals);
  11796. return n;
  11797. }
  11798. createDict(key_type, value_type, keys, values) {
  11799. if (keys.length !== values.length) {
  11800. throw new python.Error('Invalid dictionary size.');
  11801. }
  11802. const n = this.create('prim::DictConstruct');
  11803. const length = keys.length;
  11804. for (let i = 0; i < length; i++) {
  11805. if (!keys[i].type().isSubtypeOf(key_type)) {
  11806. throw new python.Error('Invalid key.');
  11807. }
  11808. if (!values[i].type().isSubtypeOf(value_type)) {
  11809. throw new python.Error('Invalid value.');
  11810. }
  11811. n.addInput(keys[i]);
  11812. n.addInput(values[i]);
  11813. }
  11814. n.output().setType(torch.DictType.create(key_type, value_type));
  11815. return n;
  11816. }
  11817. createObject(type) {
  11818. const node = this.create('prim::CreateObject');
  11819. node.output().setType(type);
  11820. return node;
  11821. }
  11822. createIsInstance(v, types) {
  11823. const n = this.create('prim::isinstance', [v], 1);
  11824. n.tys_('types', types);
  11825. n.output().setType(torch.BoolType.get());
  11826. return n;
  11827. }
  11828. createSetAttr(obj, field, newValue) {
  11829. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11830. n.s_('name', field);
  11831. return n;
  11832. }
  11833. createGetAttr(obj, field) {
  11834. const n = this.create('prim::GetAttr', [obj]);
  11835. n.s_('name', field);
  11836. const classType = obj.type();
  11837. const outputType = classType.getAttribute(field);
  11838. n.output().setType(outputType);
  11839. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11840. return n;
  11841. }
  11842. createLoad(name, type) {
  11843. const n = this.create('prim::Load', [], 1);
  11844. n.s_('name', name);
  11845. n.output().setType(type);
  11846. return n;
  11847. }
  11848. createStore(name, v) {
  11849. const n = this.create('prim::Store', [v], 0);
  11850. n.s_('name', name);
  11851. return n;
  11852. }
  11853. inputs() {
  11854. return this._block.inputs();
  11855. }
  11856. outputs() {
  11857. return this._block.outputs();
  11858. }
  11859. nodes() {
  11860. return this._block.nodes();
  11861. }
  11862. param_node() {
  11863. return this._block.param_node();
  11864. }
  11865. return_node() {
  11866. return this._block.return_node();
  11867. }
  11868. block() {
  11869. return this._block;
  11870. }
  11871. addInput(name) {
  11872. return this._block.addInput(name);
  11873. }
  11874. insertNode(node) {
  11875. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11876. return node.insertBefore(this._insert_before);
  11877. }
  11878. insertConstant(val, loc, scope) {
  11879. return torch._C.insertConstant(this, val, loc, scope);
  11880. }
  11881. insertMethodCall(method_name, matched) {
  11882. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11883. .s_('name', method_name)
  11884. .output().setType(matched.return_types[0]);
  11885. return result;
  11886. }
  11887. insertUncheckedCast(v, type) {
  11888. const n = this.create('prim::unchecked_cast', [v]);
  11889. this.insertNode(n);
  11890. n.output().setType(type);
  11891. return n.output();
  11892. }
  11893. insertToList(v, type) {
  11894. let dim = 0;
  11895. let ptr = type;
  11896. while (ptr instanceof torch.ListType) {
  11897. ptr = ptr.getElementType();
  11898. dim += 1;
  11899. }
  11900. let elem_ty = 0;
  11901. if (ptr instanceof torch.IntType) {
  11902. elem_ty = 0;
  11903. } else if (ptr instanceof torch.FloatType) {
  11904. elem_ty = 1;
  11905. } else if (ptr instanceof torch.BoolType) {
  11906. elem_ty = 2;
  11907. } else if (ptr instanceof torch.ComplexType) {
  11908. elem_ty = 3;
  11909. } else {
  11910. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  11911. }
  11912. const dim_val = this.insertConstant(dim);
  11913. const elem_ty_val = this.insertConstant(elem_ty);
  11914. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  11915. n.output().setType(type);
  11916. return n.output();
  11917. }
  11918. insertFunctionCall(callee, matched) {
  11919. const func_name = callee.name();
  11920. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  11921. const inputs = [fn_constant, ...matched.inputs];
  11922. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  11923. return result;
  11924. }
  11925. insertPoint() {
  11926. return this._insert_before;
  11927. }
  11928. setInsertPoint(node) {
  11929. if (node instanceof torch.Block) {
  11930. node = node.return_node();
  11931. }
  11932. this._insert_before = node;
  11933. }
  11934. freeNode(n) {
  11935. this.all_nodes.delete(n);
  11936. }
  11937. freeValue(v) {
  11938. v.setDebugName('');
  11939. this.all_values.delete(v);
  11940. }
  11941. freeBlock(b) {
  11942. this.all_blocks.delete(b);
  11943. }
  11944. copy() {
  11945. const new_g = new torch.Graph();
  11946. new_g.cloneFrom(this);
  11947. return new_g;
  11948. }
  11949. cloneFrom(src) {
  11950. const env = (v) => {
  11951. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  11952. };
  11953. this.block().cloneFrom(src.block(), env);
  11954. }
  11955. set_op_version(version) {
  11956. this._op_version = version;
  11957. }
  11958. get_op_version() {
  11959. return this._op_version;
  11960. }
  11961. print(out, print_source_locations) {
  11962. out.write('graph(');
  11963. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  11964. out.write('):\n');
  11965. const groups = [];
  11966. for (const node of this.nodes()) {
  11967. node.print(out, 1, groups, print_source_locations);
  11968. }
  11969. out.write(' return (');
  11970. torch._C.printValueRefs(out, this.outputs());
  11971. out.write(')\n');
  11972. for (let i = 0; i < groups.length; i++) {
  11973. const fg = groups[i];
  11974. out.write('with ');
  11975. out.write(fg.kind());
  11976. out.write(`_${i} = `);
  11977. out.write(fg.g('Subgraph'));
  11978. }
  11979. return out;
  11980. }
  11981. toString() {
  11982. const out = new io.StringIO();
  11983. this.print(out, true);
  11984. return out.toString();
  11985. }
  11986. });
  11987. this.registerType('torch.Block', class {
  11988. constructor(graph, node) {
  11989. this._graph = graph;
  11990. this._input = graph.create('prim::Param', 0);
  11991. this._output = graph.create('prim::Return', 0);
  11992. this._owning_node = node;
  11993. this._input.next = this._output;
  11994. this._input.prev = this._output;
  11995. this._output.next = this._input;
  11996. this._output.prev = this._input;
  11997. this._graph.all_blocks.add(this);
  11998. this._output._owning_block = this;
  11999. // output_.topo_position_ = kUpperBound;
  12000. this._input._owning_block = this;
  12001. // input_.topo_position_ = kLowerBound;
  12002. }
  12003. inputs() {
  12004. return this._input.outputs();
  12005. }
  12006. outputs() {
  12007. return this._output.inputs();
  12008. }
  12009. nodes() {
  12010. return new torch._C.graph_node_list(this._input);
  12011. }
  12012. return_node() {
  12013. return this._output;
  12014. }
  12015. param_node() {
  12016. return this._input;
  12017. }
  12018. owningNode() {
  12019. return this._owning_node;
  12020. }
  12021. owningGraph() {
  12022. return this._graph;
  12023. }
  12024. addInput(name) {
  12025. const value = this._input.addOutput();
  12026. value.setDebugName(name || '');
  12027. return value;
  12028. }
  12029. registerOutput(value) {
  12030. this._output.addInput(value);
  12031. return this.outputs().length - 1;
  12032. }
  12033. appendNode(n) {
  12034. if (n._graph !== this._graph || n.inBlockList()) {
  12035. throw new python.Error('Node not in graph.');
  12036. }
  12037. n.insertBefore(this._output);
  12038. return n;
  12039. }
  12040. cloneFrom(src, value_map) {
  12041. const local_map = new Map();
  12042. const env = (v) => {
  12043. if (local_map.has(v)) {
  12044. return local_map.get(v);
  12045. }
  12046. return value_map(v);
  12047. };
  12048. const graph = this.owningGraph();
  12049. for (const input of src.inputs()) {
  12050. local_map.set(input, this.addInput().copyMetadata(input));
  12051. }
  12052. for (const node of src.nodes()) {
  12053. const new_node = this.appendNode(graph.createClone(node, env));
  12054. for (let i = 0; i < node.outputs().length; i++) {
  12055. const oo = node.outputs()[i];
  12056. const no = new_node.outputs()[i];
  12057. local_map.set(oo, no);
  12058. no.copyMetadata(oo);
  12059. }
  12060. }
  12061. for (const output of src.outputs()) {
  12062. this.registerOutput(env(output));
  12063. }
  12064. }
  12065. eraseOutput(i) {
  12066. this._output.removeInput(i);
  12067. }
  12068. destroy() {
  12069. this._output.removeAllInputs();
  12070. for (const n of this.nodes()) {
  12071. n.destroy();
  12072. }
  12073. this._output.destroy();
  12074. this._input.destroy();
  12075. this._graph.freeBlock(this);
  12076. }
  12077. });
  12078. this.registerType('torch.Node', class {
  12079. constructor(graph, kind) {
  12080. this._kind = kind;
  12081. this._graph = graph;
  12082. this._owning_block = null;
  12083. this._values = new Map();
  12084. this._inputs = [];
  12085. this._outputs = [];
  12086. this._blocks = [];
  12087. this._graph.all_nodes.add(this);
  12088. this._prev = null;
  12089. this._next = null;
  12090. this._source_range = null;
  12091. this._op = null;
  12092. }
  12093. owningGraph() {
  12094. return this._graph;
  12095. }
  12096. owningBlock() {
  12097. return this._owning_block;
  12098. }
  12099. kind() {
  12100. return this._kind;
  12101. }
  12102. schema() {
  12103. if (this._op) {
  12104. return this._op.schema();
  12105. }
  12106. // Node::schema() throws while torch.Node.schema() does not.
  12107. const op = this.maybeOperator();
  12108. if (op) {
  12109. return op.schema();
  12110. }
  12111. return null;
  12112. // return this.getOperator().schema();
  12113. }
  12114. hasNamedInput(name) {
  12115. for (const argument of this.schema().arguments) {
  12116. if (argument.name === name) {
  12117. return true;
  12118. }
  12119. }
  12120. return false;
  12121. }
  12122. matches(schema) {
  12123. if (torch._C.isBlockListedSchema(schema)) {
  12124. return false;
  12125. }
  12126. if (this.kind() !== schema.name) {
  12127. return false;
  12128. }
  12129. const actuals = this.inputs();
  12130. const formals = schema.arguments;
  12131. if (actuals.length < formals.length) {
  12132. return false;
  12133. }
  12134. const type_env = new Map();
  12135. for (let i = 0; i < formals.length; i++) {
  12136. let formal = formals[i].type;
  12137. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12138. if (!matched_type.success()) {
  12139. return false;
  12140. }
  12141. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12142. if (resolved) {
  12143. formal = resolved;
  12144. }
  12145. if (!actuals[i].type().isSubtypeOf(formal)) {
  12146. return false;
  12147. }
  12148. }
  12149. if (!schema.is_vararg && actuals.length !== formals.length) {
  12150. return false;
  12151. }
  12152. return true;
  12153. }
  12154. mustBeNone() {
  12155. return this._kind === 'prim::AutogradZero' ||
  12156. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12157. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12158. }
  12159. maybeSchema() {
  12160. const op = this.maybeOperator();
  12161. if (op) {
  12162. return op.schema();
  12163. }
  12164. return null;
  12165. }
  12166. maybeOperator() {
  12167. if (!this._op) {
  12168. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12169. for (const candidate of candidates) {
  12170. if (this.matches(candidate.schema())) {
  12171. this._op = candidate;
  12172. break;
  12173. }
  12174. }
  12175. }
  12176. return this._op;
  12177. }
  12178. getOperator() {
  12179. const maybe = this.maybeOperator();
  12180. if (maybe) {
  12181. return maybe;
  12182. }
  12183. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12184. }
  12185. getOperation() {
  12186. return this.getOperator().getOperation(this);
  12187. }
  12188. isNondeterministic() {
  12189. const schema = this.maybeSchema();
  12190. if (!this.kind().startsWith('aten::')) {
  12191. return false;
  12192. }
  12193. if (!schema) {
  12194. return false;
  12195. }
  12196. const schema_info = new torch._C.SchemaInfo(schema);
  12197. if (this.hasNamedInput('train')) {
  12198. throw new python.Error('Not Implemented.');
  12199. // const value = constant_as<bool>(this.namedInput("train"));
  12200. // if (value) {
  12201. // schema_info.addArgumentValue('train', value);
  12202. // }
  12203. }
  12204. return schema_info.is_nondeterministic();
  12205. }
  12206. hasSideEffects() {
  12207. switch (this._kind) {
  12208. case 'prim::PythonOp':
  12209. case 'prim::IgnoredPythonOp':
  12210. case 'prim::Print':
  12211. case 'prim::RaiseException':
  12212. case 'aten::warn':
  12213. case 'aten::save':
  12214. case 'aten::manual_seed':
  12215. case 'prim::AddStatValue':
  12216. case 'prim::TimePoint':
  12217. case 'prim::CallFunction':
  12218. case 'prim::CallMethod':
  12219. case 'prim::BailoutTemplate':
  12220. case 'prim::BailOut':
  12221. case 'prim::rpc_async':
  12222. case 'prim::rpc_sync':
  12223. case 'prim::rpc_remote':
  12224. case 'aten::wait':
  12225. case 'cuda::set_stream':
  12226. case 'cuda::_set_device':
  12227. case 'cuda::_current_device':
  12228. case 'cuda::synchronize':
  12229. case 'prim::Enter':
  12230. case 'prim::Exit':
  12231. return true;
  12232. default:
  12233. break;
  12234. }
  12235. const op = this.maybeOperator();
  12236. if (!op) {
  12237. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12238. return false;
  12239. }
  12240. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12241. torch._C.TORCH_INTERNAL_ASSERT(
  12242. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12243. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12244. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12245. }
  12246. switch (op.aliasAnalysisKind()) {
  12247. case 'PURE_FUNCTION':
  12248. case 'FROM_SCHEMA':
  12249. case 'INTERNAL_SPECIAL_CASE':
  12250. return false;
  12251. case 'CONSERVATIVE':
  12252. return true;
  12253. default:
  12254. break;
  12255. }
  12256. torch._C.TORCH_INTERNAL_ASSERT(false);
  12257. return false;
  12258. }
  12259. inputs() {
  12260. return this._inputs;
  12261. }
  12262. outputs() {
  12263. return this._outputs;
  12264. }
  12265. input(i) {
  12266. if (i === undefined) {
  12267. torch._C.AT_ASSERT(this._inputs.length === 1);
  12268. return this._inputs[0];
  12269. }
  12270. return this._inputs[i];
  12271. }
  12272. output(i) {
  12273. if (i === undefined) {
  12274. torch._C.AT_ASSERT(this._outputs.length === 1);
  12275. return this._outputs[0];
  12276. }
  12277. return this._outputs[i];
  12278. }
  12279. hasUses() {
  12280. for (const o of this.outputs()) {
  12281. if (o.uses().length > 0) {
  12282. return true;
  12283. }
  12284. }
  12285. return false;
  12286. }
  12287. blocks() {
  12288. return this._blocks;
  12289. }
  12290. insertInput(i, value) {
  12291. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12292. this._op = null;
  12293. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12294. const use = this.findUseForInput(use_itr);
  12295. use.offset += 1;
  12296. }
  12297. this._inputs.splice(i, 0, value);
  12298. value._uses.push(new torch.Use(this, i));
  12299. return value;
  12300. }
  12301. addInput(value) {
  12302. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12303. this._op = null;
  12304. const use = new torch.Use(this, this._inputs.length);
  12305. value.uses().push(use);
  12306. this._inputs.push(value);
  12307. return value;
  12308. }
  12309. addOutput() {
  12310. const value = new torch.Value(this, this._outputs.length);
  12311. this._outputs.push(value);
  12312. return value;
  12313. }
  12314. addBlock() {
  12315. this._op = null;
  12316. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12317. return this._blocks[this._blocks.length - 1];
  12318. }
  12319. get prev() {
  12320. return this._prev;
  12321. }
  12322. set prev(value) {
  12323. this._prev = value;
  12324. }
  12325. get next() {
  12326. return this._next;
  12327. }
  12328. set next(value) {
  12329. this._next = value;
  12330. }
  12331. insertBefore(n) {
  12332. if (!n.inBlockList()) {
  12333. throw new python.Error('Node not in block.');
  12334. }
  12335. this.insertAfter(n.prev);
  12336. return this;
  12337. }
  12338. insertAfter(n) {
  12339. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12340. torch._C.AT_ASSERT(n.owningBlock());
  12341. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12342. this._owning_block = n.owningBlock();
  12343. const next = n.next;
  12344. n.next = this;
  12345. this.prev = n;
  12346. this.next = next;
  12347. next.prev = this;
  12348. // this.assignTopoPosition();
  12349. return this;
  12350. }
  12351. allocNewInstance(g) {
  12352. return new torch.Node(g, this.kind());
  12353. }
  12354. cloneFrom(s) {
  12355. this._source_range = s._source_range;
  12356. if (s._scope && !s._scope.isBlank()) {
  12357. this._scope = s._scope;
  12358. }
  12359. this.copyAttributes(s);
  12360. this._callstack = s._callstack;
  12361. }
  12362. copyAttributes(rhs) {
  12363. this._values = new Map(rhs._values);
  12364. return this;
  12365. }
  12366. dropInput(i) {
  12367. torch._C.AT_ASSERT(i < this._inputs.length);
  12368. const input_node = this._inputs[i];
  12369. const use_it = this.findUseForInput(i);
  12370. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12371. this._inputs[i] = null;
  12372. return input_node;
  12373. }
  12374. eraseOutput(i) {
  12375. torch._C.AT_ASSERT(i < this._outputs.length);
  12376. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12377. this._op = null;
  12378. const n = this._outputs[i];
  12379. this._outputs.splice(i, 1);
  12380. this.owningGraph().freeValue(n);
  12381. for (let j = i; j < this._outputs.length; j++) {
  12382. this._outputs[j]._offset--;
  12383. }
  12384. }
  12385. eraseBlock(i) {
  12386. this._op = null;
  12387. const n = this._blocks[i];
  12388. this._blocks.splice(i, 1);
  12389. n.destroy();
  12390. }
  12391. findUseForInput(i) {
  12392. const input_uses = this._inputs[i]._uses;
  12393. for (const use_it of input_uses) {
  12394. if (use_it.user === this && use_it.offset === i) {
  12395. return use_it;
  12396. }
  12397. }
  12398. throw new python.Error('Input use not found.');
  12399. }
  12400. moveBefore(n) {
  12401. this.removeFromList();
  12402. this.insertBefore(n);
  12403. }
  12404. removeInput(i) {
  12405. this._op = null;
  12406. this.dropInput(i);
  12407. for (let j = i + 1; j < this._inputs.length; j++) {
  12408. const it = this.findUseForInput(j);
  12409. it.offset--;
  12410. }
  12411. this._inputs.splice(i, 1);
  12412. }
  12413. removeAllInputs() {
  12414. this._op = null;
  12415. for (let i = 0; i < this._inputs.length; i++) {
  12416. this.dropInput(i);
  12417. }
  12418. this._inputs = [];
  12419. }
  12420. inBlockList() {
  12421. return this.next !== null;
  12422. }
  12423. removeFromList() {
  12424. this._owning_block = null;
  12425. const next = this.next;
  12426. const prev = this.prev;
  12427. prev.next = next;
  12428. next.prev = prev;
  12429. this.next = null;
  12430. this.prev = null;
  12431. }
  12432. destroy() {
  12433. while (this.outputs().length > 0) {
  12434. this.eraseOutput(this.outputs().length - 1);
  12435. }
  12436. while (this.blocks().length > 0) {
  12437. this.eraseBlock(this.blocks().length - 1);
  12438. }
  12439. this.removeAllInputs();
  12440. if (this.inBlockList()) {
  12441. this.removeFromList();
  12442. }
  12443. this._graph.freeNode(this);
  12444. }
  12445. replaceAllUsesWith(n) {
  12446. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12447. const nOutputs = this.outputs().length;
  12448. for (let i = 0; i < nOutputs; i++) {
  12449. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12450. }
  12451. }
  12452. s_(name, value) {
  12453. this._values.set(name, [value, 's']);
  12454. return this;
  12455. }
  12456. s(name) {
  12457. return this._values.get(name)[0];
  12458. }
  12459. ss_(name, value) {
  12460. this._values.set(name, [value, 'ss']);
  12461. return this;
  12462. }
  12463. ss(name) {
  12464. return this._values.get(name)[0];
  12465. }
  12466. i_(name, value) {
  12467. this._values.set(name, [value, 'i']);
  12468. return this;
  12469. }
  12470. i(name) {
  12471. return this._values.get(name)[0];
  12472. }
  12473. f_(name, value) {
  12474. this._values.set(name, [value, 'f']);
  12475. return this;
  12476. }
  12477. f(name) {
  12478. return this._values.get(name)[0];
  12479. }
  12480. c_(name, value) {
  12481. this._values.set(name, [value, 'c']);
  12482. return this;
  12483. }
  12484. c(name) {
  12485. return this._values.get(name)[0];
  12486. }
  12487. t_(name, value) {
  12488. this._values.set(name, [value, 't']);
  12489. return this;
  12490. }
  12491. t(name) {
  12492. return this._values.get(name)[0];
  12493. }
  12494. tys_(name, value) {
  12495. this._values.set(name, [value, 'tys']);
  12496. return this;
  12497. }
  12498. tys(name) {
  12499. return this._values.get(name)[0];
  12500. }
  12501. ival_(name, value) {
  12502. this._values.set(name, [value, 'ival']);
  12503. return this;
  12504. }
  12505. ival(name) {
  12506. return this._values.get(name)[0];
  12507. }
  12508. hasAttribute(name) {
  12509. return this._values.has(name);
  12510. }
  12511. hasAttributes() {
  12512. return this._values.size > 0;
  12513. }
  12514. attributeNames() {
  12515. return Array.from(this._values.keys());
  12516. }
  12517. kindOf(name) {
  12518. return this._values.get(name)[1];
  12519. }
  12520. setSourceRange(r) {
  12521. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12522. this._source_range = r;
  12523. return this;
  12524. }
  12525. sourceRange() {
  12526. if (this._source_range) {
  12527. return this._source_range;
  12528. }
  12529. return new torch._C.SourceRange();
  12530. }
  12531. print_attributes(out, ignore_subgraph) {
  12532. ignore_subgraph = ignore_subgraph || false;
  12533. out.write('[');
  12534. const names = this.attributeNames();
  12535. for (let i = 0; i < names.length; i++) {
  12536. const name = names[i];
  12537. if (ignore_subgraph && name === 'Subgraph') {
  12538. continue;
  12539. }
  12540. if (i > 0) {
  12541. out.write(', ');
  12542. }
  12543. out.write(`${name}=`);
  12544. this.printAttrValue(out, name);
  12545. }
  12546. out.write(']');
  12547. }
  12548. printTypeList(out, items) {
  12549. out.write('[');
  12550. for (let i = 0; i < items.length; i++) {
  12551. const item = items[i];
  12552. if (i++ > 0) {
  12553. out.write(', ');
  12554. }
  12555. out.write(item.str());
  12556. }
  12557. out.write(']');
  12558. }
  12559. printAttrValue(out, name) {
  12560. const kind = this.kindOf(name);
  12561. switch (kind) {
  12562. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12563. case 'ss': case 'ival': case 'ty':
  12564. out.write(this[kind](name));
  12565. break;
  12566. case 's':
  12567. out.write(`"${this.s(name)}"`);
  12568. break;
  12569. case 't':
  12570. out.write(`"{}"`);
  12571. break;
  12572. case 'ts': out.write('[<Tensors>]'); break;
  12573. case 'g': out.write('[<Graph>]'); break;
  12574. case 'gs': out.write('[<Graphs>]'); break;
  12575. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12576. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12577. }
  12578. }
  12579. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12580. print_source_locations = print_source_locations === false ? false : true;
  12581. print_attributes = print_attributes === false ? false : true;
  12582. print_scopes = print_scopes === false ? false : true;
  12583. print_body = print_body === false ? false : true;
  12584. const outs = this.outputs();
  12585. torch._C.indent(out, level);
  12586. torch._C.const_value_list_with_types(out, outs, ', ');
  12587. out.write(' = ');
  12588. if (this.kind() === 'prim::PythonOp') {
  12589. throw new python.Error('Not implemented.');
  12590. } else if (this.hasAttribute('Subgraph') && groups) {
  12591. throw new python.Error('Not implemented.');
  12592. } else {
  12593. out.write(this.kind());
  12594. if (print_attributes && this.hasAttributes()) {
  12595. this.print_attributes(out);
  12596. }
  12597. }
  12598. out.write('(');
  12599. torch._C.printValueRefs(out, this.inputs());
  12600. out.write(')');
  12601. if (print_scopes) {
  12602. //
  12603. }
  12604. if (print_source_locations) {
  12605. let r = this.sourceRange();
  12606. if (r.source()) {
  12607. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12608. if (orig) {
  12609. r = orig;
  12610. }
  12611. }
  12612. const file_line_col = r.file_line_col();
  12613. if (file_line_col !== null) {
  12614. const [filename, line, col] = file_line_col;
  12615. out.write(` # ${filename}:${line}:${col}`);
  12616. }
  12617. }
  12618. if (!print_body) {
  12619. return out;
  12620. }
  12621. out.write('\n');
  12622. for (let i = 0; i < this.blocks().length; i++) {
  12623. const b = this.blocks().at(i);
  12624. torch._C.indent(out, level + 1);
  12625. out.write(`block${i}(`);
  12626. torch._C.const_value_list_with_types(out, b.inputs());
  12627. out.write('):\n');
  12628. for (const nested of b.nodes()) {
  12629. nested.print(out, level + 2, groups);
  12630. }
  12631. torch._C.indent(out, level + 2);
  12632. out.write('-> (');
  12633. torch._C.printValueRefs(out, b.outputs());
  12634. out.write(')\n');
  12635. }
  12636. return out;
  12637. }
  12638. toString() {
  12639. const out = new io.StringIO();
  12640. this.print(out, 0, true);
  12641. return out.toString();
  12642. }
  12643. });
  12644. this.registerType('torch.Value', class {
  12645. constructor(node, offset) {
  12646. this._node = node;
  12647. this._offset = offset;
  12648. this._unique = node._graph._next_unique++;
  12649. this._uses = [];
  12650. this._node._graph.all_values.add(this);
  12651. }
  12652. unique() {
  12653. return this._unique;
  12654. }
  12655. node() {
  12656. return this._node;
  12657. }
  12658. owningGraph() {
  12659. return this._node.owningGraph();
  12660. }
  12661. uses() {
  12662. return this._uses;
  12663. }
  12664. hasUses() {
  12665. return this._uses.length > 0;
  12666. }
  12667. mustBeNone() {
  12668. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12669. }
  12670. mustNotBeNone() {
  12671. return this._node.kind() !== 'prim::AutogradAdd' &&
  12672. this.type() !== torch.NoneType.get() &&
  12673. !(this.type() instanceof torch.OptionalType) &&
  12674. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12675. }
  12676. isValidName(name) {
  12677. if (name.length === 0) {
  12678. return true;
  12679. }
  12680. if (torch._C.isNumber(name)) {
  12681. return false;
  12682. }
  12683. return true;
  12684. }
  12685. hasDebugName() {
  12686. return this._unique_name && this._unique_name.length > 0;
  12687. }
  12688. setDebugName(name) {
  12689. if (!this.isValidName(name)) {
  12690. throw new python.Error(`Invalid name '${name}'.`);
  12691. }
  12692. const names = this.node().owningGraph()._unique_names;
  12693. if (this.hasDebugName()) {
  12694. names.delete(this._unique_name);
  12695. this._unique_name = '';
  12696. }
  12697. if (!name) {
  12698. return this;
  12699. }
  12700. const old_owner_of_name = names.get(name);
  12701. if (old_owner_of_name) {
  12702. let suffix = 1;
  12703. let name_base = name;
  12704. const last_dot_pos = name.lastIndexOf('.');
  12705. if (last_dot_pos !== -1) {
  12706. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12707. suffix = Number(name.substring(last_dot_pos + 1));
  12708. name_base = name.substring(0, last_dot_pos);
  12709. }
  12710. }
  12711. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12712. if (names_suffixes.has(name_base)) {
  12713. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12714. }
  12715. let replacement_name = null;
  12716. do {
  12717. replacement_name = `${name_base}.${suffix++}`;
  12718. } while (names.has(replacement_name));
  12719. names_suffixes.set(name_base, suffix);
  12720. old_owner_of_name.setDebugName(replacement_name);
  12721. }
  12722. names.set(name, this);
  12723. this._unique_name = name;
  12724. return this;
  12725. }
  12726. debugName() {
  12727. if (this.hasDebugName()) {
  12728. return this._unique_name;
  12729. }
  12730. return this.unique().toString();
  12731. }
  12732. type() {
  12733. return this._type;
  12734. }
  12735. setType(type) {
  12736. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12737. if (type instanceof torch._C.DynamicType) {
  12738. type = type.fallback();
  12739. }
  12740. this._type = type;
  12741. for (const use of this._uses) {
  12742. use.user._op = null;
  12743. }
  12744. return this;
  12745. }
  12746. set value(value) { // remove
  12747. if (value instanceof torch.Value) {
  12748. throw new python.Error('Value cannot be a value.');
  12749. }
  12750. this._value = value;
  12751. }
  12752. get value() { // remove
  12753. return this._value;
  12754. }
  12755. replaceFirstUseWith(newValue) {
  12756. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12757. const [u] = this.uses();
  12758. u.user._inputs[u.offset] = newValue;
  12759. newValue._uses.push(u);
  12760. this._uses.shift();
  12761. }
  12762. replaceAllUsesWith(newValue) {
  12763. while (this.uses().length > 0) {
  12764. this.replaceFirstUseWith(newValue);
  12765. }
  12766. }
  12767. copyMetadata(from) {
  12768. this.setType(from.type());
  12769. if (from.hasDebugName()) {
  12770. this.setDebugName(from.debugName());
  12771. }
  12772. return this;
  12773. }
  12774. toString() {
  12775. return `${this.debugName()} : ${this.type().toString()}`;
  12776. }
  12777. });
  12778. this.registerType('torch.Use', class {
  12779. constructor(user, offset) {
  12780. this.user = user;
  12781. this.offset = offset;
  12782. }
  12783. });
  12784. this.registerType('torch._C.IValue', class {
  12785. constructor(value, tag) {
  12786. this.value = value;
  12787. if (tag) {
  12788. this.tag = tag;
  12789. } else if (value === undefined) {
  12790. this.tag = 'None';
  12791. this.value = null;
  12792. } else if (typeof value === 'boolean') {
  12793. this.tag = 'Bool';
  12794. } else if (typeof value === 'string') {
  12795. this.tag = 'String';
  12796. } else if (value instanceof torch.Tensor) {
  12797. this.tag = 'Tensor';
  12798. } else if (value instanceof torch.ScriptObject) {
  12799. this.tag = 'Object';
  12800. } else if (Array.isArray(value)) {
  12801. this.tag = 'GenericList';
  12802. } else if (value instanceof torch._C.Tuple) {
  12803. this.tag = 'Tuple';
  12804. } else if (value instanceof torch.device) {
  12805. this.tag = 'Device';
  12806. } else if (Number.isInteger(value)) {
  12807. this.tag = 'Int';
  12808. } else if (typeof value === 'number') {
  12809. this.tag = 'Double';
  12810. } else if (value instanceof builtins.complex) {
  12811. this.tag = 'ComplexDouble';
  12812. } else if (value instanceof torch._C.EnumHolder) {
  12813. this.tag = 'Enum';
  12814. } else {
  12815. throw new python.Error('Unsupported type.');
  12816. }
  12817. }
  12818. isNone() {
  12819. return this.tag === 'None';
  12820. }
  12821. isBool() {
  12822. return this.tag === 'Bool';
  12823. }
  12824. toBool() {
  12825. return this.value;
  12826. }
  12827. isObject() {
  12828. return this.tag === 'Object';
  12829. }
  12830. toObject() {
  12831. return this.value;
  12832. }
  12833. isTensor() {
  12834. return this.tag === 'Tensor';
  12835. }
  12836. toTensor() {
  12837. return this.value;
  12838. }
  12839. isDouble() {
  12840. return this.tag === 'Double';
  12841. }
  12842. toDouble() {
  12843. return this.value;
  12844. }
  12845. isComplexDouble() {
  12846. return this.tag === 'ComplexDouble' || this.tag === 'Complex';
  12847. }
  12848. toComplexDouble() {
  12849. return this.value;
  12850. }
  12851. isInt() {
  12852. return this.tag === 'Int';
  12853. }
  12854. toInt() {
  12855. if (this.isInt()) {
  12856. return this.value;
  12857. } else if (this.isSymInt()) {
  12858. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12859. }
  12860. throw new python.Error('Expected int.');
  12861. }
  12862. isString() {
  12863. return this.tag === 'String';
  12864. }
  12865. toStringRef() {
  12866. return this.value;
  12867. }
  12868. isList() {
  12869. return this.tag === 'GenericList';
  12870. }
  12871. toList() {
  12872. return this.value;
  12873. }
  12874. toListRef() {
  12875. return this.value;
  12876. }
  12877. isBoolList() {
  12878. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12879. }
  12880. isIntList() {
  12881. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12882. }
  12883. isDoubleList() {
  12884. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12885. }
  12886. isDevice() {
  12887. return this.tag === 'Device';
  12888. }
  12889. toDevice() {
  12890. return this.value;
  12891. }
  12892. isGenerator() {
  12893. return this.tag === 'Generator';
  12894. }
  12895. isStream() {
  12896. return this.tag === 'Stream';
  12897. }
  12898. isGenericDict() {
  12899. return this.tag === 'GenericDict';
  12900. }
  12901. isEnum() {
  12902. return this.tag === 'Enum';
  12903. }
  12904. toEnumHolder() {
  12905. return this.value;
  12906. }
  12907. isTuple() {
  12908. return this.tag === 'Tuple';
  12909. }
  12910. toTupleRef() {
  12911. return this.value;
  12912. }
  12913. isCustomClass() {
  12914. return torch._C.isCustomClass(this);
  12915. }
  12916. equals(rhs) {
  12917. switch (this.tag) {
  12918. case 'None': return rhs.isNone();
  12919. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  12920. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  12921. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  12922. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  12923. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  12924. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  12925. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  12926. case 'GenericList': {
  12927. if (rhs.isList()) {
  12928. const a = this.toList();
  12929. const b = rhs.toList();
  12930. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  12931. }
  12932. return false;
  12933. }
  12934. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  12935. }
  12936. }
  12937. is(rhs) {
  12938. return this.equals(rhs);
  12939. }
  12940. type() {
  12941. switch (this.tag) {
  12942. case 'None': return torch.NoneType.get();
  12943. case 'Bool': return torch.BoolType.get();
  12944. case 'Int': return torch.IntType.get();
  12945. case 'Double': return torch.FloatType.get();
  12946. case 'String': return torch.StringType.get();
  12947. case 'Device': return torch.DeviceObjType.get();
  12948. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  12949. case 'Enum': return this.toEnumHolder().type();
  12950. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  12951. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  12952. }
  12953. }
  12954. });
  12955. this.registerFunction('torch._C.indent', (out, level) => {
  12956. for (let i = 0; i < level; i++) {
  12957. out.write(' ');
  12958. }
  12959. return out;
  12960. });
  12961. this.registerFunction('torch._C.printValueRef', (out, n) => {
  12962. out.write(`%${n.debugName()}`);
  12963. });
  12964. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  12965. for (let i = 0; i < nodes.length; i++) {
  12966. const n = nodes[i];
  12967. if (i > 0) {
  12968. out.write(', ');
  12969. }
  12970. torch._C.printValueRef(out, n);
  12971. }
  12972. return out;
  12973. });
  12974. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  12975. for (let i = 0; i < values.length; i++) {
  12976. const n = values[i];
  12977. if (i > 0) {
  12978. out.write(delim);
  12979. }
  12980. torch._C.printValueRef(out, n);
  12981. out.write(' : ');
  12982. out.write(n.type().str());
  12983. }
  12984. });
  12985. this.register('torch.jit._script');
  12986. this.register('torch.jit._trace');
  12987. this.registerType('torch._C.Parser', class {
  12988. constructor(source) {
  12989. this.L = source;
  12990. }
  12991. parse() {
  12992. const p = ast.parse(this.L.text_str(), this.L.filename());
  12993. return p;
  12994. }
  12995. parseExp() {
  12996. const expr = ast.parse(this.L.text_str());
  12997. return expr.body[0].value;
  12998. }
  12999. });
  13000. this.registerType('torch._C.StringCordView', class {
  13001. });
  13002. this.registerType('torch._C.Source', class {
  13003. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  13004. if (text_view instanceof Uint8Array) {
  13005. const decoder = new TextDecoder('utf-8');
  13006. this._text_view = decoder.decode(text_view);
  13007. } else if (typeof text_view === 'string') {
  13008. this._text_view = text_view;
  13009. } else {
  13010. throw new python.Error('Invalid text view.');
  13011. }
  13012. this._filename = filename;
  13013. this._starting_line_no = starting_line_no;
  13014. this._gen_ranges = gen_ranges;
  13015. this.calc_line_start_offsets();
  13016. }
  13017. text_str() {
  13018. return this._text_view;
  13019. }
  13020. size() {
  13021. return this._text_view.length;
  13022. }
  13023. filename() {
  13024. return this._filename;
  13025. }
  13026. calc_line_start_offsets() {
  13027. let pos = 0;
  13028. this._line_starting_offsets = [0];
  13029. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  13030. pos += 1;
  13031. this._line_starting_offsets.push(pos);
  13032. }
  13033. }
  13034. offset_for_line(line) {
  13035. return this._line_starting_offsets[line];
  13036. }
  13037. lineno_for_offset(offset) {
  13038. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  13039. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  13040. }
  13041. lineno_to_source_lineno(lineno) {
  13042. if (this._filename) {
  13043. return lineno + this._starting_line_no;
  13044. }
  13045. return lineno;
  13046. }
  13047. findSourceRangeThatGenerated(range) {
  13048. if (!this._gen_ranges) {
  13049. return null;
  13050. }
  13051. return this._gen_ranges.findSourceRangeThatGenerated(range);
  13052. }
  13053. });
  13054. this.registerType('torch._C.SourceRange', class {
  13055. constructor(...args) {
  13056. if (args.length === 0) {
  13057. this._source_view = null;
  13058. } else if (args.length === 2) {
  13059. let node = null;
  13060. [this._source_view, node] = args;
  13061. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  13062. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  13063. } else if (args.length === 3) {
  13064. [this._source_view, this._start, this._end] = args;
  13065. } else {
  13066. throw new python.Error('Not implemented.');
  13067. }
  13068. }
  13069. source() {
  13070. return this._source_view;
  13071. }
  13072. file_line_col() {
  13073. if (!this._source_view || this.source().filename() === null) {
  13074. return null;
  13075. }
  13076. const lineno = this._source_view.lineno_for_offset(this._start);
  13077. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  13078. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  13079. }
  13080. start() {
  13081. return this._start;
  13082. }
  13083. toString() {
  13084. const loc = this.file_line_col();
  13085. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  13086. }
  13087. });
  13088. this.registerType('torch._C.QualifiedName', class {
  13089. constructor(...args) {
  13090. let name = null;
  13091. if (args.length === 1 && typeof args[0] === 'string') {
  13092. [name] = args;
  13093. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13094. name = args[0].join('.');
  13095. } else {
  13096. name = `${args[0].qualifiedName()}.${args[1]}`;
  13097. }
  13098. const index = name.lastIndexOf('.');
  13099. this._qualifiedName = name;
  13100. this._prefix = index === -1 ? '' : name.substring(0, index);
  13101. this._name = index === -1 ? name : name.substring(index + 1);
  13102. }
  13103. qualifiedName() {
  13104. return this._qualifiedName; // "foo.bar.baz"
  13105. }
  13106. prefix() {
  13107. return this._prefix; // "foo.bar"
  13108. }
  13109. name() {
  13110. return this._name; // "baz"
  13111. }
  13112. atoms() {
  13113. return this._qualifiedName.split('.');
  13114. }
  13115. });
  13116. this.registerType('torch._C.Resolver', class {
  13117. resolveValue() {
  13118. throw new python.Error('Not implemented.');
  13119. }
  13120. resolveType() {
  13121. throw new python.Error('Not implemented.');
  13122. }
  13123. });
  13124. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13125. torch._C.customClasses = torch._C.customClasses || new Map();
  13126. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13127. const name = class_type.name().qualifiedName();
  13128. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13129. torch._C.customClasses.set(name, class_type);
  13130. });
  13131. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13132. torch._C.customClasses = torch._C.customClasses || new Map();
  13133. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13134. return ret;
  13135. });
  13136. this.registerFunction('torch._C.isCustomClass', (v) => {
  13137. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13138. });
  13139. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13140. constructor(cu, constant_table, source_loader, version) {
  13141. super();
  13142. this._cu = cu;
  13143. this._constant_table = constant_table;
  13144. this._source_loader = source_loader;
  13145. this._version = version;
  13146. this._loaded_sources = new Set();
  13147. this._sources = new Map();
  13148. const sources = this._sources;
  13149. ast.AST.prototype.range = function() {
  13150. if (!this._range) {
  13151. if (sources.has(this.filename)) {
  13152. const source_view = sources.get(this.filename);
  13153. this._range = new torch._C.SourceRange(source_view, this);
  13154. } else {
  13155. this._range = new torch._C.SourceRange();
  13156. }
  13157. }
  13158. return this._range;
  13159. };
  13160. this._to_be_defined = new Map();
  13161. this._env = new Map([
  13162. ['torch', new torch._C.BuiltinModule('aten', version)],
  13163. ['ops', new torch._C.OpsValue(version)],
  13164. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13165. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13166. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13167. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13168. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13169. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13170. ]);
  13171. }
  13172. loadType(name) {
  13173. const type_parser = new torch._C.ScriptTypeParser(this);
  13174. return type_parser.parseType(name.qualifiedName());
  13175. }
  13176. resolveType(name) {
  13177. name = new torch._C.QualifiedName(name);
  13178. return this.findNamedType(name);
  13179. }
  13180. resolveValue(name, m, loc) {
  13181. if (this._env.has(name)) {
  13182. return this._env.get(name);
  13183. }
  13184. const graph = m.graph();
  13185. switch (name) {
  13186. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13187. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13188. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13189. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13190. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13191. default: return null;
  13192. }
  13193. }
  13194. findNamedType(name) {
  13195. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13196. if (custom_class) {
  13197. return custom_class;
  13198. }
  13199. this.parseSourceIfNeeded(name.prefix());
  13200. const key = name.qualifiedName();
  13201. const it = this._to_be_defined.get(key);
  13202. if (it && it instanceof ast.ClassDef) {
  13203. this._to_be_defined.delete(key);
  13204. this.importNamedType(name.prefix(), it);
  13205. }
  13206. return this._cu.get_type(name);
  13207. }
  13208. importNamedType(qualifier, class_def) {
  13209. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13210. if (class_def.bases.length === 0) {
  13211. this.importClass(qualified_name, class_def, false);
  13212. return;
  13213. }
  13214. const superclass_name = class_def.bases[0].id;
  13215. if (superclass_name === 'Module') {
  13216. this.importClass(qualified_name, class_def, true);
  13217. } else if (superclass_name === 'NamedTuple') {
  13218. this.importNamedTuple(qualified_name, class_def);
  13219. } else if (superclass_name === 'Interface') {
  13220. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13221. } else if (superclass_name === 'ModuleInterface') {
  13222. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13223. } else if (superclass_name === 'Enum') {
  13224. this.importEnum(qualified_name, class_def);
  13225. } else {
  13226. throw new python.Error('TorchScript does not support class inheritance.');
  13227. }
  13228. }
  13229. importClass(qualified_classname, class_def, is_module) {
  13230. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13231. return;
  13232. }
  13233. const parameter_names = new Set();
  13234. const buffer_names = new Set();
  13235. const methods = [];
  13236. const method_resolvers = [];
  13237. const attributes = [];
  13238. const constants = [];
  13239. const pre_hook_names = new Set();
  13240. const pre_hook_def_map = new Map();
  13241. const hook_names = new Set();
  13242. const hook_def_map = new Map();
  13243. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13244. for (const stmt of class_def.body) {
  13245. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13246. let target = null;
  13247. let annotation = null;
  13248. let value = null;
  13249. if (stmt instanceof ast.Assign) {
  13250. [target] = stmt.targets;
  13251. value = stmt.value;
  13252. } else {
  13253. target = stmt.target;
  13254. annotation = stmt.annotation;
  13255. value = stmt.value;
  13256. }
  13257. if (target instanceof ast.Name) {
  13258. const name = this._cu.execution.identifier(target);
  13259. switch (name) {
  13260. case '__annotations__': {
  13261. continue;
  13262. }
  13263. case '__parameters__': {
  13264. for (const elt of value.elts) {
  13265. parameter_names.add(elt.value);
  13266. }
  13267. break;
  13268. }
  13269. case '__buffers__': {
  13270. for (const elt of value.elts) {
  13271. buffer_names.add(elt.value);
  13272. }
  13273. break;
  13274. }
  13275. case '__forward_pre_hooks__': {
  13276. for (const elt of value.elts) {
  13277. pre_hook_names.add(elt.value);
  13278. }
  13279. break;
  13280. }
  13281. case '__forward_hooks__': {
  13282. for (const elt of value.elts) {
  13283. hook_names.add(elt.value);
  13284. }
  13285. break;
  13286. }
  13287. default: {
  13288. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13289. if (fixed_up) {
  13290. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13291. } else if (value) {
  13292. constants.push({ name, value, annotation });
  13293. } else {
  13294. attributes.push({ name, value, annotation });
  13295. }
  13296. break;
  13297. }
  13298. }
  13299. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13300. const name = target.slice.value;
  13301. attributes.push({ name, value, annotation: stmt.value });
  13302. continue;
  13303. } else {
  13304. throw new python.Error('Unexpected statement kind in module metadata.');
  13305. }
  13306. } else if (stmt instanceof ast.FunctionDef) {
  13307. const def = stmt;
  13308. const def_name = def.name;
  13309. if (pre_hook_names.has(def_name)) {
  13310. pre_hook_def_map.set(def_name, def);
  13311. } else if (hook_names.has(def_name)) {
  13312. hook_def_map.set(def_name, def);
  13313. } else {
  13314. methods.push(def);
  13315. method_resolvers.push(this);
  13316. }
  13317. } else {
  13318. throw new python.Error('Unexpected statement kind in class body.');
  13319. }
  13320. }
  13321. const type_parser = new torch._C.ScriptTypeParser(this);
  13322. for (const assign of attributes) {
  13323. const name = assign.name;
  13324. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13325. const is_parameter = parameter_names.has(name);
  13326. const is_buffer = buffer_names.has(name);
  13327. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13328. }
  13329. for (const constant of constants) {
  13330. class_type.addConstant(constant.name, constant.value);
  13331. }
  13332. this._cu.register_type(class_type);
  13333. const self = new torch._C.SimpleSelf(class_type);
  13334. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13335. }
  13336. importEnum(qualified_name, enum_def) {
  13337. const names_values = [];
  13338. let value_type = null;
  13339. const set_or_check_type = (t) => {
  13340. if (!value_type) {
  13341. value_type = t;
  13342. } else if (value_type !== t) {
  13343. throw new python.Error('Enum class with varying value types are not supported.');
  13344. }
  13345. };
  13346. for (const stmt of enum_def.body) {
  13347. if (stmt instanceof ast.Assign === false) {
  13348. throw new python.Error('Unexpected statement in Enum class body.');
  13349. }
  13350. const assign = stmt;
  13351. const name = assign.targets[0].id;
  13352. let ivalue = null;
  13353. const rhs = assign.value;
  13354. switch (rhs.type) {
  13355. case 'str':
  13356. ivalue = new torch._C.IValue(rhs.value, 'String');
  13357. set_or_check_type(torch.StringType.get());
  13358. break;
  13359. case 'int':
  13360. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13361. set_or_check_type(torch.IntType.get());
  13362. break;
  13363. case 'float':
  13364. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13365. set_or_check_type(torch.FloatType.get());
  13366. break;
  13367. default:
  13368. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13369. }
  13370. names_values.push([name, ivalue]);
  13371. }
  13372. if (!value_type) {
  13373. throw new python.Error('No enum values defined.');
  13374. }
  13375. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13376. this._cu.register_type(enum_type);
  13377. }
  13378. importNamedTuple(qualified_name, named_tuple_def) {
  13379. const type_parser = new torch._C.ScriptTypeParser(this);
  13380. const field_names = [];
  13381. const field_types = [];
  13382. const field_defaults = [];
  13383. for (const stmt of named_tuple_def.body) {
  13384. if (stmt instanceof ast.AnnAssign === false) {
  13385. throw new python.Error('Unexpected statement in NamedTuple body.');
  13386. }
  13387. const assign = stmt;
  13388. const target = this._cu.execution.identifier(stmt.target);
  13389. // const annotation = this._cu.execution.type(stmt.annotation);
  13390. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13391. field_names.push(target);
  13392. // field_types.push(annotation);
  13393. field_types.push(type);
  13394. }
  13395. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13396. this._cu.register_type(tt);
  13397. }
  13398. importFunction(qualifier, def) {
  13399. const definitions = [def];
  13400. const resolvers = [this];
  13401. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13402. }
  13403. parseSourceIfNeeded(qualifier) {
  13404. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13405. return;
  13406. }
  13407. this._loaded_sources.add(qualifier);
  13408. const src = this._source_loader(qualifier);
  13409. if (!src) {
  13410. return;
  13411. }
  13412. this._sources.set(src.filename(), src);
  13413. const p = new torch._C.Parser(src);
  13414. const L = p.parse();
  13415. this.parsePossibleVersionNumber(p);
  13416. for (const stmt of L.body) {
  13417. if (stmt instanceof ast.ClassDef) {
  13418. const name = `${qualifier}.${stmt.name}`;
  13419. this._to_be_defined.set(name, stmt);
  13420. } else if (stmt instanceof ast.FunctionDef) {
  13421. const name = `${qualifier}.${stmt.name}`;
  13422. this._to_be_defined.set(name, stmt);
  13423. }
  13424. }
  13425. }
  13426. parsePossibleVersionNumber(/* p */) {
  13427. }
  13428. parseImports(/* p */) {
  13429. }
  13430. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13431. const replacements = new Map([
  13432. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13433. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13434. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13435. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13436. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13437. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13438. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13439. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13440. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13441. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13442. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13443. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13444. ]);
  13445. const mangleRe = /\.___torch_mangle_\d+/g;
  13446. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13447. if (replacements.has(demangled_classname)) {
  13448. const lhs = assign.target;
  13449. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13450. return null;
  13451. }
  13452. const type = assign.annotation.id;
  13453. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13454. if (lhs.id === attr_name && type === expected_type) {
  13455. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13456. const typename_expr = p.parseExp();
  13457. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13458. }
  13459. }
  13460. return null;
  13461. }
  13462. LEGACY_import_methods(mod, src) {
  13463. const self = new torch._C.SimpleSelf(mod.type());
  13464. const prefix = mod.type().name();
  13465. const p = new torch._C.Parser(src);
  13466. const L = p.parse();
  13467. this.parsePossibleVersionNumber(L);
  13468. this.parseImports(L);
  13469. const definitions = [];
  13470. const resolvers = [];
  13471. for (const def of L.body) {
  13472. if (def instanceof ast.FunctionDef) {
  13473. definitions.push(def);
  13474. resolvers.push(this);
  13475. }
  13476. }
  13477. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13478. }
  13479. findFunction(name) {
  13480. this.parseSourceIfNeeded(name.prefix());
  13481. const key = name.qualifiedName();
  13482. const it = this._to_be_defined.get(key);
  13483. if (it && it instanceof ast.FunctionDef) {
  13484. this._to_be_defined.delete(key);
  13485. this.importFunction(name.prefix(), it);
  13486. }
  13487. return this._cu.find_function(name);
  13488. }
  13489. });
  13490. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13491. constructor(otherResolver, functionTable) {
  13492. super();
  13493. this._otherResolver = otherResolver;
  13494. this._functionTable = functionTable;
  13495. }
  13496. resolveValue(name, m, loc) {
  13497. const it = this._functionTable.get(name);
  13498. if (it) {
  13499. return new torch._C.FunctionValue(it);
  13500. }
  13501. return this._otherResolver.resolveValue(name, m, loc);
  13502. }
  13503. resolveType(name, loc) {
  13504. return this._otherResolver.resolveType(name, loc);
  13505. }
  13506. });
  13507. this.registerType('torch._C.SourceRangeDeserializer', class {
  13508. constructor(text_table) {
  13509. this.cached_sources = new Map();
  13510. this._text_table = text_table || [];
  13511. }
  13512. deserialize(iv) {
  13513. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13514. const [file, start, end] = iv;
  13515. const source = this.deserialize_source(file);
  13516. return new torch._C.SourceRange(source, start, end);
  13517. }
  13518. deserialize_source(iv) {
  13519. const tup = iv;
  13520. if (this.cached_sources.has(tup)) {
  13521. return this.cached_sources.get(tup);
  13522. }
  13523. let source = null;
  13524. const tup_elems = tup;
  13525. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13526. if (this._text_table.length > 0) {
  13527. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13528. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13529. const filename = this._text_table[fnameIndex];
  13530. const pieces = [];
  13531. const strs = [];
  13532. for (const i of textIndex) {
  13533. pieces.push(this._text_table[i]);
  13534. strs.push(this._text_table[i]);
  13535. }
  13536. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13537. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13538. } else {
  13539. const [text, filename, starting_line_no] = tup_elems;
  13540. source = new torch._C.Source(text, filename, starting_line_no);
  13541. }
  13542. this.cached_sources.set(tup, source);
  13543. return source;
  13544. }
  13545. });
  13546. this.registerType('torch._C.SourceRangeUnpickler', class {
  13547. });
  13548. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13549. constructor (data) {
  13550. super();
  13551. this.data = data;
  13552. this.deserializer = null;
  13553. this.unpickled_records = null;
  13554. }
  13555. unpickle() {
  13556. if (this.unpickled_records) {
  13557. return;
  13558. }
  13559. const unpickler = new pickle.Unpickler(this.data);
  13560. const ivalues = unpickler.load();
  13561. torch._C.TORCH_CHECK(ivalues.length > 0);
  13562. this.unpickled_records = [];
  13563. let lines = null;
  13564. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13565. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13566. lines = ivalues[2];
  13567. } else {
  13568. this.deserializer = new torch._C.SourceRangeDeserializer();
  13569. lines = ivalues;
  13570. }
  13571. for (const tup_elems of lines) {
  13572. const [offset, range] = tup_elems;
  13573. const source_range = this.deserializer.deserialize(range);
  13574. this.unpickled_records.push([offset, source_range]);
  13575. }
  13576. }
  13577. findSourceRangeThatGenerated(range) {
  13578. this.unpickle();
  13579. const start = range.start();
  13580. const records = this.unpickled_records;
  13581. for (let i = 0; i < records.length; i++) {
  13582. const [offset, target] = records[i];
  13583. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13584. if (start >= offset && start < next) {
  13585. return target;
  13586. }
  13587. }
  13588. return null;
  13589. }
  13590. });
  13591. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13592. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13593. });
  13594. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13595. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13596. if (!reader.has_record(path)) {
  13597. return null;
  13598. }
  13599. const stream = reader.get_record(path);
  13600. let gen_ranges = null;
  13601. const debug_file = `${path}.debug_pkl`;
  13602. if (reader.has_record(debug_file)) {
  13603. const debug_stream = reader.get_record(debug_file);
  13604. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13605. }
  13606. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13607. });
  13608. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13609. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13610. this._compilation_unit = cu;
  13611. this._reader = reader;
  13612. this._storage_context = storage_context;
  13613. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13614. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13615. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13616. this._constant_table = [];
  13617. const SourceLoader = (qualifier) => {
  13618. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13619. };
  13620. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13621. }
  13622. deserialize() {
  13623. const execution = this._compilation_unit.execution;
  13624. const code_prefix = this._code_prefix;
  13625. for (const name of this._reader.get_all_records()) {
  13626. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13627. const file = name.substring(code_prefix.length);
  13628. const stream = this._reader.get_record(name);
  13629. const buffer = stream.peek();
  13630. execution.add(file, buffer);
  13631. }
  13632. }
  13633. const torch = execution.import('torch');
  13634. execution.builtins.torch = torch;
  13635. execution.builtins.Tensor = torch.Tensor;
  13636. execution.builtins.ops = torch.ops;
  13637. execution.builtins.inf = torch.inf;
  13638. execution.builtins.CONSTANTS = {};
  13639. execution._resolver = this._source_importer;
  13640. if (this._reader.has_record('model.json')) {
  13641. return this.LEGACY_deserialize();
  13642. }
  13643. const constants = this.readArchive('constants');
  13644. for (let i = 0; i < constants.length; i++) {
  13645. let val = constants[i];
  13646. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13647. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13648. const obj = torch.ScriptObject.create(type);
  13649. obj._ivalue = val;
  13650. val = obj;
  13651. }
  13652. execution.builtins.CONSTANTS[`c${i}`] = val;
  13653. this._constant_table.push(val);
  13654. }
  13655. const obj = this.readArchive('data');
  13656. const convertObject = (obj) => {
  13657. if (obj.__class__) {
  13658. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13659. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13660. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13661. for (let i = 0; i < type.numAttributes(); i++) {
  13662. const k = type.getAttributeName(i);
  13663. const t = type.getAttribute(i);
  13664. const v = obj[k];
  13665. if (t instanceof torch.ClassType) {
  13666. module.__setattr__(k, convertObject(v));
  13667. } else {
  13668. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13669. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13670. type._attributes[i].type = this._source_importer.resolveType(name);
  13671. }
  13672. module.__setattr__(k, obj[k]);
  13673. }
  13674. }
  13675. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13676. if (value && value.__class__ === builtins.method) {
  13677. module[key] = value;
  13678. }
  13679. }
  13680. return module;
  13681. }
  13682. throw new python.Error('Module class not found.');
  13683. };
  13684. return convertObject(obj);
  13685. }
  13686. LEGACY_deserialize() {
  13687. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13688. const execution = this._compilation_unit.execution;
  13689. const caffe2 = execution.proto.caffe2;
  13690. const torch = execution.import('torch');
  13691. const stream = this._reader.get_record('model.json');
  13692. const buffer = stream.peek();
  13693. const decoder = new TextDecoder('utf-8');
  13694. const content = decoder.decode(buffer);
  13695. const obj = JSON.parse(content);
  13696. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13697. const tensorTypeMap = new Map([
  13698. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13699. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13700. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13701. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13702. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13703. [caffe2.TensorProto.DataType.INT64, 'Long']
  13704. ]);
  13705. const tensor_table = (model.tensors || []).map((constant) => {
  13706. const key = constant.data.key;
  13707. if (!tensorTypeMap.has(constant.data_type)) {
  13708. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13709. }
  13710. const type = tensorTypeMap.get(constant.data_type);
  13711. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13712. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13713. const storage_type = execution.resolve(`torch.${type}Storage`);
  13714. const size = (shape || []).reduce((a, b) => a * b, 1);
  13715. const offset = parseInt(constant.offset, 10) || 0;
  13716. const storage = new storage_type(size);
  13717. const itemsize = storage.dtype.itemsize();
  13718. const stream = this._reader.get_record(key);
  13719. if (stream) {
  13720. const buffer = stream.peek();
  13721. const length = size * itemsize;
  13722. const data = buffer.slice(offset, offset + length);
  13723. storage._set_cdata(data);
  13724. }
  13725. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13726. tensor.name = key;
  13727. return tensor;
  13728. });
  13729. execution.builtins.CONSTANTS = {};
  13730. for (let i = 0; i < tensor_table.length; i++) {
  13731. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13732. }
  13733. const attributes = [];
  13734. if (this._reader.has_record('attributes.pkl')) {
  13735. const stream = this._reader.get_record('attributes.pkl');
  13736. const buffer = stream.peek();
  13737. const unpickler = new pickle.Unpickler(buffer);
  13738. const obj = unpickler.load();
  13739. attributes.push(...obj);
  13740. }
  13741. this._LEGACY_moduleStack = ['__torch__'];
  13742. const module_def = model.main_module;
  13743. for (const tensor of tensor_table) {
  13744. this._constant_table.push(tensor);
  13745. }
  13746. return this.LEGACY_convertModule(module_def);
  13747. }
  13748. LEGACY_convertModule(module_def) {
  13749. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13750. const numPushed = atoms.length;
  13751. for (const atom of atoms) {
  13752. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13753. this._LEGACY_moduleStack.push(sanitized);
  13754. }
  13755. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13756. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13757. for (const sub_def of module_def.submodules || []) {
  13758. const submodule = this.LEGACY_convertModule(sub_def);
  13759. module.register_module(sub_def.name, submodule);
  13760. }
  13761. for (const param_def of module_def.parameters || []) {
  13762. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13763. if (param_def.isBuffer) {
  13764. module.register_buffer(param_def.name, tensor);
  13765. } else {
  13766. module.register_parameter(param_def.name, tensor, false);
  13767. }
  13768. }
  13769. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13770. for (const attr_def of module_def.attributes || []) {
  13771. if (module.hasattr(attr_def.name)) {
  13772. continue;
  13773. }
  13774. throw new python.Error('Not implemented.');
  13775. // IValue ivalue;
  13776. // if (attr_def.id() >= 0) {
  13777. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13778. // }
  13779. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13780. }
  13781. if (module_def.torchscript_arena) {
  13782. const key = module_def.torchscript_arena.key;
  13783. const file = key.substring('code/'.length);
  13784. const name = file.replace(/\.py$/, '').split('/').join('.');
  13785. const code = execution.import(name);
  13786. if (code.forward.__class__ === execution.builtins.function) {
  13787. module.forward = code.forward;
  13788. }
  13789. }
  13790. // let gen_ranges = null;
  13791. if (module_def.torchscript_debug_arena) {
  13792. throw new python.Error('Not implemented.');
  13793. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13794. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13795. }
  13796. if (module_def.torchscript_arena) {
  13797. const filename = module_def.torchscript_arena.key;
  13798. const stream = this._reader.get_record(filename);
  13799. const data = stream.peek();
  13800. const src = new torch._C.Source(data, filename);
  13801. this._source_importer.LEGACY_import_methods(module, src);
  13802. }
  13803. if (module_def.get_state_attribute_id) {
  13804. throw new python.Error('Not implemented.');
  13805. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13806. }
  13807. /*
  13808. const module_type = module._ivalue().type();
  13809. const N = module_type.numAttributes();
  13810. for (let i = 0; i < N; ++i) {
  13811. const v = module._ivalue().getSlot(i);
  13812. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13813. torch._C.TORCH_CHECK(!v.isNone());
  13814. }
  13815. }
  13816. */
  13817. for (let i = 0; i < numPushed; i++) {
  13818. this._LEGACY_moduleStack.pop();
  13819. }
  13820. return module;
  13821. }
  13822. readArchive(archive_name) {
  13823. const type_resolver = (qn) => {
  13824. const cls = this._source_importer.loadType(qn);
  13825. return cls;
  13826. };
  13827. const ObjLoaderFunc = (/* type, ivalue */) => {
  13828. };
  13829. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13830. }
  13831. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13832. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13833. const stream = stream_reader.get_record(picklename);
  13834. if (!stream) {
  13835. throw new python.Error(`File '${picklename}' is not found.`);
  13836. }
  13837. const buffer = stream.peek();
  13838. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13839. const read_record = (name) => {
  13840. const stream = stream_reader.get_record(tensor_dir_path + name);
  13841. return stream.length <= 0x40000 ? stream.peek() : stream;
  13842. };
  13843. const execution = this._compilation_unit.execution;
  13844. const pickle = execution.__import__('pickle');
  13845. const Unpickler = class extends pickle.Unpickler {
  13846. find_class(module, name) {
  13847. return super.find_class(module, name);
  13848. }
  13849. };
  13850. const unpickler = new Unpickler(buffer);
  13851. unpickler.persistent_load = (saved_id) => {
  13852. if (saved_id[0] !== 'storage') {
  13853. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13854. }
  13855. const [, storage_type, key, , size] = saved_id;
  13856. if (storage_context && storage_context.has_storage(key)) {
  13857. return storage_context.get_storage(key);
  13858. }
  13859. const storage = new storage_type(size);
  13860. if (!storage._set_cdata) {
  13861. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  13862. }
  13863. const storage_ptr = read_record(key);
  13864. storage._set_cdata(storage_ptr);
  13865. if (storage_context) {
  13866. storage_context.add_storage(key);
  13867. }
  13868. return storage;
  13869. };
  13870. return unpickler.load();
  13871. }
  13872. });
  13873. this.registerType('torch._C.WithInsertPoint', class {
  13874. constructor(...args) {
  13875. let n = null;
  13876. if (args.length === 1 && args[0] instanceof torch.Block) {
  13877. const [b] = args;
  13878. n = b.return_node();
  13879. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13880. [n] = args;
  13881. } else {
  13882. throw new python.Error('Invalid arguments.');
  13883. }
  13884. this._prev = n.owningGraph().insertPoint();
  13885. n.owningGraph().setInsertPoint(n);
  13886. }
  13887. dispose() {
  13888. this._prev.owningGraph().setInsertPoint(this._prev);
  13889. }
  13890. });
  13891. this.registerType('torch._C.Environment', class {
  13892. constructor(method, resolver, b, next) {
  13893. this.method = method;
  13894. this.resolver = resolver;
  13895. this.b = b;
  13896. this.next = next;
  13897. this.value_table = new Map();
  13898. this.type_table = new Map();
  13899. this.error_messages = new Map();
  13900. }
  13901. setVariableTypeError(name, msg) {
  13902. /* eslint-disable consistent-this */
  13903. let runner = this;
  13904. /* eslint-enable consistent-this */
  13905. while (runner.next) {
  13906. runner = runner.next;
  13907. }
  13908. runner.error_messages.set(name, msg);
  13909. }
  13910. insertLoad(name, type) {
  13911. const g = this.b.owningGraph();
  13912. const load = g.insertNode(g.createLoad(name, type));
  13913. if (torch._C.meaningfulName(name)) {
  13914. load.output().setDebugName(name);
  13915. }
  13916. return new torch._C.SimpleValue(load.output());
  13917. }
  13918. insertStore(name, loc, v, type) {
  13919. const g = this.b.owningGraph();
  13920. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  13921. this.type_table.set(name, type);
  13922. }
  13923. findInThisFrame(name) {
  13924. if (this.value_table.has(name)) {
  13925. return this.value_table.get(name);
  13926. }
  13927. if (this.type_table.has(name)) {
  13928. return this.insertLoad(name, this.type_table.get(name));
  13929. }
  13930. return null;
  13931. }
  13932. findInParentFrame(name) {
  13933. return this.next ? this.next.findInAnyFrame(name) : null;
  13934. }
  13935. setType(name, type) {
  13936. this.type_table.set(name, type);
  13937. }
  13938. findInAnyFrame(name) {
  13939. /* eslint-disable consistent-this */
  13940. const self = this;
  13941. /* eslint-enable consistent-this */
  13942. for (let runner = self; runner; runner = runner.next) {
  13943. const r = runner.findInThisFrame(name);
  13944. if (r) {
  13945. return r;
  13946. }
  13947. }
  13948. return null;
  13949. }
  13950. block() {
  13951. return this.b;
  13952. }
  13953. setVar(loc, name, value) {
  13954. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  13955. }
  13956. setSugaredVar(loc, name, value, annotated_type) {
  13957. let as_simple_value = torch._C.asSimple(value);
  13958. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  13959. as_simple_value.setDebugName(name);
  13960. }
  13961. const parent = this.findInParentFrame(name);
  13962. if (parent) {
  13963. if (annotated_type) {
  13964. throw new python.Error('Type already defined in an outer block.');
  13965. }
  13966. if (!as_simple_value) {
  13967. throw new python.Error('Only reassignments to first-class values are allowed.');
  13968. }
  13969. const simple_parent = torch._C.asSimple(parent);
  13970. if (!simple_parent) {
  13971. throw new python.Error('Only reassignments to first-class values are allowed.');
  13972. }
  13973. const parent_type = torch._C.unshapedType(simple_parent.type());
  13974. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  13975. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  13976. throw new python.Error('Incompatible types.');
  13977. }
  13978. }
  13979. if (as_simple_value) {
  13980. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  13981. throw new python.Error('Invalid type.');
  13982. }
  13983. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  13984. this.insertStore(name, loc, as_simple_value, value_store_type);
  13985. } else {
  13986. this.value_table.set(name, value);
  13987. }
  13988. }
  13989. getSugaredVar(ident, range, required) {
  13990. required = required || true;
  13991. let retval = this.findInAnyFrame(ident);
  13992. if (!retval) {
  13993. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  13994. ['print', new torch._C.PrintValue()],
  13995. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  13996. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  13997. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  13998. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  13999. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  14000. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  14001. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  14002. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  14003. ['range', torch._C.SpecialFormValue.create('prim::range')],
  14004. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  14005. ]);
  14006. if (torch._C.Environment.globals.has(ident)) {
  14007. retval = torch._C.Environment.globals.get(ident);
  14008. }
  14009. }
  14010. if (!retval) {
  14011. const type = this.resolver.resolveType(ident, range);
  14012. if (type instanceof torch.TupleType) {
  14013. retval = new torch.jit.NamedTupleConstructor(type);
  14014. }
  14015. }
  14016. if (!retval) {
  14017. retval = this.resolver.resolveValue(ident, this.method, range);
  14018. }
  14019. if (!retval) {
  14020. const type = this.resolver.resolveType(ident, range);
  14021. if (type instanceof torch.ClassType) {
  14022. retval = new torch.jit.ClassValue(type);
  14023. }
  14024. }
  14025. if (!retval && required) {
  14026. throw new python.Error(`The name '${ident}' is not defined.`);
  14027. }
  14028. return retval;
  14029. }
  14030. getVar(ident, range) {
  14031. return this.getSugaredVar(ident, range).asValue(range, this.method);
  14032. }
  14033. definedVariables() {
  14034. return Array.from(this.type_table.keys());
  14035. }
  14036. });
  14037. this.registerType('torch._C.Refinement', class {
  14038. constructor(identifier, type) {
  14039. this._identifier = identifier;
  14040. this._type = type;
  14041. }
  14042. identifier() {
  14043. return this._identifier;
  14044. }
  14045. type() {
  14046. return this._type;
  14047. }
  14048. });
  14049. this.registerType('torch._C.RefinementSet', class {
  14050. constructor(...args) {
  14051. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  14052. this._true_refinements = [args[0]];
  14053. this._false_refinements = [];
  14054. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  14055. this._true_refinements = [args[0]];
  14056. this._false_refinements = [args[1]];
  14057. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  14058. [this._true_refinements, this._false_refinements] = args;
  14059. } else {
  14060. throw new python.Error('Not implemented.');
  14061. }
  14062. }
  14063. Not() {
  14064. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  14065. }
  14066. activeRefinements() {
  14067. return this._true_refinements;
  14068. }
  14069. });
  14070. this.registerFunction('torch._C.CondValue', class {
  14071. constructor(...args) {
  14072. if (args.length === 3) {
  14073. [this._value, this._refinements, this._static_if] = args;
  14074. } else if (args.length === 4) {
  14075. const [g, loc, static_value, refinements] = args;
  14076. this._value = g.insertConstant(static_value, loc);
  14077. this._refinements = refinements;
  14078. this._static_if = static_value;
  14079. } else {
  14080. throw new python.Error('Invalid number of arguments.');
  14081. }
  14082. }
  14083. value() {
  14084. return this._value;
  14085. }
  14086. staticIf() {
  14087. return this._static_if;
  14088. }
  14089. refinements() {
  14090. return this._refinements;
  14091. }
  14092. });
  14093. this.registerFunction('torch._C.asSimple', (value) => {
  14094. if (value instanceof torch._C.SimpleValue) {
  14095. return value.getValue();
  14096. }
  14097. return null;
  14098. });
  14099. this.registerFunction('torch._C.isNumber', (str) => {
  14100. return /^[0-9]+$/.test(str);
  14101. });
  14102. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14103. if (torch._C.isNumber(field)) {
  14104. return `_${field}`;
  14105. }
  14106. return field;
  14107. });
  14108. this.registerFunction('torch._C.meaningfulName', (name) => {
  14109. if (name.length === 0) {
  14110. return false;
  14111. }
  14112. if (name[0] === '$') {
  14113. return false;
  14114. }
  14115. if (name[0] !== '_') {
  14116. return true;
  14117. }
  14118. return !/\d+/.test(name.slice(1));
  14119. });
  14120. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14121. const key = `${val.value}:${val.tag}`;
  14122. const existing_constant = map.get(key);
  14123. if (existing_constant) {
  14124. return existing_constant;
  14125. }
  14126. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14127. const new_constant = graph.insertConstant(val, r);
  14128. map.set(key, new_constant);
  14129. guard.dispose();
  14130. return new_constant;
  14131. });
  14132. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14133. if (schema.overload_name) {
  14134. return `${schema.name}.${schema.overload_name}`;
  14135. }
  14136. return schema.name;
  14137. });
  14138. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14139. const value_map_func = (v) => value_map.get(v);
  14140. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14141. for (let i = 0; i < inputs.length; i++) {
  14142. value_map.set(callee.inputs()[i], inputs[i]);
  14143. }
  14144. for (const node of callee.nodes()) {
  14145. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14146. for (let i = 0; i < node.outputs().length; i++) {
  14147. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14148. }
  14149. }
  14150. const outputs = [];
  14151. for (const output of callee.outputs()) {
  14152. outputs.push(value_map_func(output));
  14153. }
  14154. return outputs;
  14155. });
  14156. this.registerType('TemplateEnv', class {
  14157. });
  14158. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14159. constructor() {
  14160. this.state = 'UNINITIALIZED';
  14161. this._builtins_by_name = new Map();
  14162. }
  14163. getAllBuiltinFunctionsFor(name) {
  14164. if (this.state === 'UNINITIALIZED') {
  14165. this.loadBuiltinFunctions();
  14166. this.state = 'INITIALIZED';
  14167. }
  14168. if (!this._builtins_by_name.has(name)) {
  14169. return [];
  14170. }
  14171. return this._builtins_by_name.get(name);
  14172. }
  14173. loadBuiltinFunctions() {
  14174. /*
  14175. for (const scalar of ['float', 'int', 'complex']) {
  14176. const env = new torch.C.TemplateEnv();
  14177. env.s('Scalar', scalar);
  14178. this.loadSource(scalar_operators_source.format(env), 'aten');
  14179. }
  14180. for (const scalar of ['float', 'int']) {
  14181. const env = new torch.C.TemplateEnv();
  14182. env.s('Scalar', scalar);
  14183. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14184. }
  14185. using str_pair = std::pair<std::string, std::string>;
  14186. const std::vector<str_pair> name_len = {
  14187. str_pair('single', '1'),
  14188. str_pair('pair', '2'),
  14189. str_pair('triple', '3'),
  14190. str_pair('quadruple', '4'),
  14191. };
  14192. for (const auto scalar : {'float', 'int'}) {
  14193. for (const auto& pair : name_len) {
  14194. const env = new torch.C.TemplateEnv();
  14195. env.s('Scalar', scalar);
  14196. env.s('name', pair.first);
  14197. env.s('Length', pair.second);
  14198. this.loadSource(_ntuple_ops.format(env), 'aten');
  14199. }
  14200. }
  14201. for (auto rhs : {'number', 'Tensor'}) {
  14202. at::jit::TemplateEnv env;
  14203. env.s('Rhs_Type', rhs);
  14204. this.loadSource(floordiv.format(env), 'aten');
  14205. }
  14206. this.loadSource(aten_ops, 'aten');
  14207. this.loadSource(aten_ops_additional, 'aten');
  14208. this.loadSource(tensor_properties, 'prim');
  14209. */
  14210. }
  14211. loadSource(/* source, the_namespace */) {
  14212. }
  14213. });
  14214. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14215. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14216. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14217. });
  14218. this.registerFunction('torch._C.get_operator_version_map', () => {
  14219. return new Map();
  14220. });
  14221. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14222. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14223. let arg_type = arg.type;
  14224. if (arg_type instanceof torch._C.DynamicType) {
  14225. arg_type = arg_type.fallback();
  14226. }
  14227. const argument_is_list = arg_type instanceof torch.ListType;
  14228. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14229. const arg_is_broadcasting_list = arg.N > 0;
  14230. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14231. });
  14232. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14233. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14234. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14235. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14236. return true;
  14237. }
  14238. return false;
  14239. });
  14240. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14241. if (opt_type instanceof torch._C.DynamicType) {
  14242. return torch._C.unwrapOptional(opt_type.fallback());
  14243. }
  14244. if (opt_type instanceof torch.OptionalType) {
  14245. return opt_type.getElementType();
  14246. }
  14247. return opt_type;
  14248. });
  14249. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14250. const possibleSchemas = [];
  14251. if (version === undefined) {
  14252. return possibleSchemas;
  14253. }
  14254. for (const entry of torch._C.get_operator_version_map()) {
  14255. const old_symbol_name = entry.first;
  14256. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14257. if (base_name === name) {
  14258. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14259. if (possibleUpgrader.has_value()) {
  14260. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14261. }
  14262. }
  14263. }
  14264. return possibleSchemas;
  14265. });
  14266. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14267. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14268. return current_version < latest_update;
  14269. });
  14270. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14271. const it = torch._C.get_operator_version_map().get(name);
  14272. if (it) {
  14273. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14274. }
  14275. return true;
  14276. });
  14277. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14278. if (values.length === 1) {
  14279. return values[0];
  14280. }
  14281. let named_tuple = null;
  14282. if (field_names) {
  14283. const types = values.map((v) => v.type());
  14284. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14285. }
  14286. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14287. });
  14288. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14289. const v_type = value.type();
  14290. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14291. return false;
  14292. }
  14293. const arg_type = torch._C.unwrapOptional(arg.type);
  14294. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14295. });
  14296. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14297. const list_type = list_type_;
  14298. if (list_type instanceof torch.ListType === false) {
  14299. return false;
  14300. }
  14301. if (type.isSubtypeOf(list_type_)) {
  14302. return true;
  14303. }
  14304. if (type instanceof torch.TupleType) {
  14305. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14306. }
  14307. return false;
  14308. });
  14309. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14310. for (let i = 0; i < kwargs.length; i++) {
  14311. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14312. return i;
  14313. }
  14314. if (kwargs[i].name() === name) {
  14315. return i;
  14316. }
  14317. }
  14318. return null;
  14319. });
  14320. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14321. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14322. const list_elements = [];
  14323. for (const named_value of varargs) {
  14324. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14325. if (!matched_value) {
  14326. return null;
  14327. }
  14328. list_elements.push(matched_value);
  14329. }
  14330. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14331. });
  14332. this.registerType('torch._C.MatchTypeReturn', class {
  14333. constructor(reason) {
  14334. this._reason = reason;
  14335. }
  14336. static Success() {
  14337. return new torch._C.MatchTypeReturn(null);
  14338. }
  14339. success() {
  14340. return this._reason === null;
  14341. }
  14342. });
  14343. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14344. if (!formal.hasFreeVariables()) {
  14345. if (formal instanceof torch._C.DynamicType) {
  14346. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14347. }
  14348. return torch._C.MatchTypeReturn.Success();
  14349. }
  14350. if (formal instanceof torch._C.VarType) {
  14351. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14352. if (it === null) {
  14353. type_env.set(formal.name(), actual);
  14354. return torch._C.MatchTypeReturn.Success();
  14355. } else if (torch._C.unifyTypes(it, actual)) {
  14356. return torch._C.MatchTypeReturn.Success();
  14357. }
  14358. return new torch._C.MatchTypeReturn('Cannot match var.');
  14359. } else if (formal instanceof torch.ListType) {
  14360. if (actual instanceof torch.ListType) {
  14361. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14362. if (!innerMatch.success()) {
  14363. return innerMatch;
  14364. }
  14365. return torch._C.MatchTypeReturn.Success();
  14366. } else if (actual instanceof torch.TupleType) {
  14367. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14368. if (maybe_tuple_unified) {
  14369. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14370. }
  14371. }
  14372. return new torch._C.MatchTypeReturn('Cannot match list.');
  14373. } else if (formal instanceof torch.TupleType) {
  14374. if (actual instanceof torch.TupleType) {
  14375. if (formal.elements().length !== actual.elements().length) {
  14376. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14377. }
  14378. for (let i = 0; i < formal.elements().length; i++) {
  14379. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14380. if (!result.success()) {
  14381. return result;
  14382. }
  14383. }
  14384. return torch._C.MatchTypeReturn.Success();
  14385. }
  14386. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14387. } else if (formal instanceof torch.FutureType) {
  14388. if (actual instanceof torch.FutureType) {
  14389. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14390. if (!innerMatch.success()) {
  14391. return innerMatch;
  14392. }
  14393. return torch._C.MatchTypeReturn.Success();
  14394. }
  14395. return new torch._C.MatchTypeReturn('Cannot match future.');
  14396. } else if (formal instanceof torch.AwaitType) {
  14397. if (actual instanceof torch.AwaitType) {
  14398. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14399. if (!innerMatch.success()) {
  14400. return innerMatch;
  14401. }
  14402. return torch._C.MatchTypeReturn.Success();
  14403. }
  14404. return new torch._C.MatchTypeReturn('Cannot match await.');
  14405. } else if (formal instanceof torch.RRefType) {
  14406. if (actual instanceof torch.RRefType) {
  14407. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14408. if (!innerMatch.success()) {
  14409. return innerMatch;
  14410. }
  14411. return torch._C.MatchTypeReturn.Success();
  14412. }
  14413. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14414. } else if (formal instanceof torch.OptionalType) {
  14415. if (actual instanceof torch.OptionalType) {
  14416. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14417. if (!optionedMatch.success()) {
  14418. return optionedMatch;
  14419. }
  14420. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14421. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14422. }
  14423. return torch._C.MatchTypeReturn.Success();
  14424. } else if (formal instanceof torch.DictType) {
  14425. if (actual instanceof torch.DictType) {
  14426. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14427. if (!key_match.success()) {
  14428. return key_match;
  14429. }
  14430. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14431. if (!value_match.success()) {
  14432. return value_match;
  14433. }
  14434. return torch._C.MatchTypeReturn.Success();
  14435. }
  14436. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14437. }
  14438. throw new python.Error('Unhandled free variable container.');
  14439. });
  14440. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14441. let value = named_value.value(graph);
  14442. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14443. const repeated = Array(arg.N).fill(value);
  14444. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14445. }
  14446. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14447. if (!matched.success()) {
  14448. if (failure_messages) {
  14449. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14450. }
  14451. return null;
  14452. }
  14453. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14454. if (!concrete_type) {
  14455. if (failure_messages) {
  14456. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14457. }
  14458. return null;
  14459. }
  14460. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14461. if (!value.type().isSubtypeOf(concrete_type)) {
  14462. if (failure_messages) {
  14463. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14464. }
  14465. return null;
  14466. }
  14467. return value;
  14468. });
  14469. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14470. if (concrete_type instanceof torch.OptionalType) {
  14471. const op = concrete_type;
  14472. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14473. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14474. }
  14475. }
  14476. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14477. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14478. }
  14479. if (value.type() instanceof torch.TupleType) {
  14480. const value_tuple = value.type();
  14481. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14482. const unpacked = torch._C.createTupleUnpack(value);
  14483. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14484. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14485. }
  14486. if (concrete_type instanceof torch.TupleType) {
  14487. const concrete_tuple = concrete_type;
  14488. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14489. concrete_tuple.elements().length === value_tuple.elements().length) {
  14490. const unpacked = torch._C.createTupleUnpack(value);
  14491. const converted = [];
  14492. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14493. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14494. }
  14495. value = graph.insertNode(graph.createTuple(converted)).output();
  14496. }
  14497. }
  14498. }
  14499. if (allow_conversions) {
  14500. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14501. const value_equals_number = value.type() === torch.NumberType.get();
  14502. const concrete_float = concrete_type === torch.FloatType.get();
  14503. const concrete_complex = concrete_type === torch.ComplexType.get();
  14504. const concrete_int = concrete_type === torch.IntType.get();
  14505. const concrete_number = concrete_type === torch.NumberType.get();
  14506. if (value_isa_tensor) {
  14507. if (concrete_float) {
  14508. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14509. } else if (concrete_complex) {
  14510. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14511. } else if (concrete_int) {
  14512. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14513. } else if (concrete_number) {
  14514. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14515. }
  14516. } else if (value_equals_number) {
  14517. if (concrete_float) {
  14518. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14519. } else if (concrete_complex) {
  14520. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14521. } else if (concrete_int) {
  14522. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14523. }
  14524. } else if (value.type() === torch.BoolType.get()) {
  14525. if (concrete_float) {
  14526. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14527. } else if (concrete_int || concrete_number) {
  14528. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14529. }
  14530. }
  14531. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14532. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14533. }
  14534. }
  14535. return value;
  14536. });
  14537. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14538. if (!type.hasFreeVariables()) {
  14539. if (type instanceof torch._C.DynamicType) {
  14540. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14541. }
  14542. return type;
  14543. }
  14544. if (type instanceof torch._C.VarType) {
  14545. return type_env.get(type.annotation_str);
  14546. }
  14547. const contained = type.containedTypes();
  14548. if (contained.length === 0) {
  14549. return type;
  14550. }
  14551. const new_contained = [];
  14552. for (const t of contained) {
  14553. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14554. if (!r) {
  14555. return null;
  14556. }
  14557. new_contained.push(r);
  14558. }
  14559. return type.withContained(new_contained);
  14560. });
  14561. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14562. if (torch._C.isBlockListedSchema(schema)) {
  14563. return null;
  14564. }
  14565. const err = null;
  14566. const type_env = new Map();
  14567. const positional_inputs = [];
  14568. const used_kwarg = kwargs.map(() => false);
  14569. const is_aten = schema.name.startsWith('aten::');
  14570. let used_args = 0;
  14571. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14572. const arg = schema.arguments[schema_i];
  14573. let actual_named_value = null;
  14574. if (arg.name === 'self' && self) {
  14575. actual_named_value = self;
  14576. self = null;
  14577. } else if (!arg.kwarg_only && used_args < args.length) {
  14578. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14579. const value = args[used_args].value(graph);
  14580. const actual_type = value.type();
  14581. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14582. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14583. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14584. if (!list) {
  14585. return null;
  14586. }
  14587. used_args = args.length;
  14588. positional_inputs.push(list);
  14589. continue;
  14590. }
  14591. }
  14592. actual_named_value = args[used_args];
  14593. used_args++;
  14594. } else {
  14595. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14596. if (Number.isInteger(kwarg_idx)) {
  14597. const nv = kwargs[kwarg_idx];
  14598. if (used_kwarg[kwarg_idx]) {
  14599. if (failure_messages) {
  14600. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14601. }
  14602. return null;
  14603. }
  14604. used_kwarg[kwarg_idx] = true;
  14605. actual_named_value = nv;
  14606. } else if (arg.has_default_value()) {
  14607. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14608. } else {
  14609. if (failure_messages) {
  14610. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14611. }
  14612. return null;
  14613. }
  14614. }
  14615. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14616. if (!positional) {
  14617. return null;
  14618. }
  14619. positional_inputs.push(positional);
  14620. }
  14621. if (self !== null) {
  14622. if (failure_messages) {
  14623. throw new python.Error('Provided self argument not used in schema.');
  14624. }
  14625. return null;
  14626. }
  14627. if (schema.is_vararg) {
  14628. for (; used_args < args.length; used_args++) {
  14629. positional_inputs.push(args[used_args].value(graph));
  14630. }
  14631. }
  14632. if (used_args < args.length) {
  14633. if (failure_messages) {
  14634. throw new python.Error('Too many positional arguments.');
  14635. }
  14636. return null;
  14637. }
  14638. for (let i = 0; i < kwargs.length; i++) {
  14639. const nv = kwargs[i];
  14640. if (!used_kwarg[i]) {
  14641. if (failure_messages) {
  14642. if (schema.argumentIndexWithName(nv.name()) === null) {
  14643. throw new python.Error('Keyword argument unknown.');
  14644. } else {
  14645. throw new python.Error('Keyword argument specified twice.');
  14646. }
  14647. }
  14648. return null;
  14649. }
  14650. }
  14651. const returns = schema.returns;
  14652. const return_types = returns.map((r) => {
  14653. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14654. if (!result) {
  14655. throw new python.Error('Unbound type variable.');
  14656. }
  14657. return result;
  14658. });
  14659. const return_has_field_names = returns.every((r) => !r.name);
  14660. let return_field_names = null;
  14661. if (return_has_field_names) {
  14662. return_field_names = returns.map((r) => r.name);
  14663. }
  14664. const schema_name = torch._C.getFullSchemaName(schema);
  14665. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14666. });
  14667. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14668. self = self || null;
  14669. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14670. if (result) {
  14671. return result;
  14672. }
  14673. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14674. });
  14675. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14676. self = self || null;
  14677. render_errors = render_errors || false;
  14678. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14679. if (schemas.length === 1) {
  14680. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14681. }
  14682. for (const allow_conversions of [false, true]) {
  14683. for (let i = 0; i < schemas.length; i++) {
  14684. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14685. if (matched_schema) {
  14686. return [i, matched_schema];
  14687. }
  14688. }
  14689. }
  14690. if (!render_errors) {
  14691. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14692. }
  14693. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14694. });
  14695. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14696. const variants = torch._C.getAllOperatorsFor(name);
  14697. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14698. const graph_version = graph.get_op_version();
  14699. const schemas = [];
  14700. const upgrader_schemas = [];
  14701. for (const op of variants) {
  14702. let found_upgrader = false;
  14703. const op_name = torch._C.getFullSchemaName(op.schema());
  14704. if (Number.isInteger(graph_version)) {
  14705. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14706. if (version_entry) {
  14707. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14708. if (old_schema_entry.has_value()) {
  14709. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14710. upgrader_schemas.push(old_schema);
  14711. found_upgrader = true;
  14712. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14713. throw new python.Error('Valid upgrader must be present.');
  14714. }
  14715. }
  14716. }
  14717. if (!found_upgrader) {
  14718. schemas.push(op.schema());
  14719. }
  14720. }
  14721. if (variants.length === 0) {
  14722. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14723. for (const old_schema_entry of oldSchemas) {
  14724. const old_schema = torch._C.parseSchema(old_schema_entry);
  14725. upgrader_schemas.push(old_schema);
  14726. }
  14727. }
  14728. for (const schema of upgrader_schemas) {
  14729. schemas.push(schema);
  14730. }
  14731. for (const method of builtin_functions) {
  14732. method.ensure_defined();
  14733. schemas.push(method.getSchema());
  14734. }
  14735. if (schemas.length === 0) {
  14736. const user_function_name = name;
  14737. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  14738. }
  14739. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14740. if (matched[0] < variants.length + upgrader_schemas.length) {
  14741. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14742. }
  14743. const fn = builtin_functions[matched.first - variants.size()];
  14744. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14745. });
  14746. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14747. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14748. for (const ret of matched_schema.return_types) {
  14749. n.addOutput().setType(ret);
  14750. }
  14751. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14752. n.getOperation();
  14753. } else {
  14754. n.setHistoricSchemaName(matched_schema.schema_name);
  14755. }
  14756. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14757. });
  14758. this.registerFunction('torch._C.unshapedType', (type) => {
  14759. if (type.isSubtypeOf(torch.TensorType.get())) {
  14760. return torch.TensorType.get();
  14761. }
  14762. const contained = type.containedTypes();
  14763. if (contained.length === 0) {
  14764. return type;
  14765. }
  14766. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14767. });
  14768. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14769. default_to_union = default_to_union || false;
  14770. type_hint = type_hint || null;
  14771. if (t1.isSubtypeOf(t2)) {
  14772. return t2;
  14773. } else if (t2.isSubtypeOf(t1)) {
  14774. return t1;
  14775. }
  14776. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14777. return t1.merge(t2);
  14778. }
  14779. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14780. return torch.OptionalType.create(t2);
  14781. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14782. return torch.OptionalType.create(t1);
  14783. }
  14784. if (t1 instanceof torch.OptionalType) {
  14785. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14786. if (elem) {
  14787. return torch.OptionalType.create(elem);
  14788. }
  14789. } else if (t2 instanceof torch.OptionalType) {
  14790. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14791. if (elem) {
  14792. return torch.OptionalType.create(elem);
  14793. }
  14794. }
  14795. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14796. if (t1.elements().size() !== t2.elements().size()) {
  14797. return null;
  14798. }
  14799. const elements = [];
  14800. for (let i = 0; i < t1.elements().length; i++) {
  14801. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14802. if (elem) {
  14803. elements.push(elem);
  14804. } else {
  14805. return null;
  14806. }
  14807. }
  14808. return torch.TupleType.create(elements);
  14809. }
  14810. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14811. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14812. if (elem) {
  14813. return torch.FutureType.create(elem);
  14814. }
  14815. }
  14816. const t1_unshaped = torch._C.unshapedType(t1);
  14817. const t2_unshaped = torch._C.unshapedType(t2);
  14818. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14819. return t2_unshaped;
  14820. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14821. return t1_unshaped;
  14822. }
  14823. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14824. return type_hint;
  14825. }
  14826. return null;
  14827. });
  14828. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14829. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14830. if (default_to_union && !unified) {
  14831. return torch.UnionType.create([t1, t2]);
  14832. }
  14833. return unified;
  14834. });
  14835. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14836. if (elements.length === 0) {
  14837. return null;
  14838. }
  14839. let [ret_type] = elements;
  14840. for (let i = 1; i < elements.length && ret_type; i++) {
  14841. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14842. if (!maybe_unified) {
  14843. return null;
  14844. }
  14845. ret_type = maybe_unified;
  14846. }
  14847. return ret_type;
  14848. });
  14849. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14850. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14851. });
  14852. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14853. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14854. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14855. ivalue.isDevice() || ivalue.isEnum()) {
  14856. return true;
  14857. }
  14858. if (ivalue.isTensor()) {
  14859. return torch._C.insertableTensor(ivalue.toTensor());
  14860. }
  14861. if (ivalue.isList() || ivalue.isTuple()) {
  14862. let elems = [];
  14863. if (ivalue.isTuple()) {
  14864. elems = ivalue.toTupleRef().elements();
  14865. } else {
  14866. elems = ivalue.toListRef();
  14867. }
  14868. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14869. }
  14870. if (ivalue.isGenericDict()) {
  14871. const dict = ivalue.toGenericDict();
  14872. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14873. }
  14874. return false;
  14875. });
  14876. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14877. loc = loc || null;
  14878. scope = scope || null;
  14879. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14880. if (value !== undefined) {
  14881. return value;
  14882. }
  14883. throw new python.Error('Unsupported value kind.');
  14884. });
  14885. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14886. if (val instanceof torch._C.IValue) {
  14887. const n = g.create('prim::Constant');
  14888. if (val.isTensor()) {
  14889. const ref = val.toTensor();
  14890. if (!torch._C.insertableTensor(val.toTensor())) {
  14891. n.destroy();
  14892. return null;
  14893. }
  14894. if (!ref.defined()) {
  14895. n.destroy();
  14896. return g.insertNode(g.createNone()).output();
  14897. }
  14898. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  14899. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  14900. n.t_('value', ref);
  14901. } else if (val.isInt()) {
  14902. n.i_('value', val.toInt());
  14903. n.output().setType(torch.IntType.get());
  14904. } else if (val.isDouble()) {
  14905. n.f_('value', val.toDouble());
  14906. n.output().setType(torch.FloatType.get());
  14907. } else if (val.isComplexDouble()) {
  14908. n.c_('value', val.toComplexDouble());
  14909. n.output().setType(torch.ComplexType.get());
  14910. } else if (val.isBool()) {
  14911. n.i_('value', val.toBool());
  14912. n.output().setType(torch.BoolType.get());
  14913. } else if (val.isList()) {
  14914. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  14915. if (fast_path_list || torch._C.insertableIValue(val)) {
  14916. n.ival_('value', val);
  14917. n.output().setType(val.type());
  14918. } else {
  14919. n.destroy();
  14920. return null;
  14921. }
  14922. } else if (val.isString()) {
  14923. n.s_('value', val.toStringRef());
  14924. n.output().setType(torch.StringType.get());
  14925. } else if (val.isDevice()) {
  14926. n.s_('value', val.toDevice().__str__());
  14927. n.output().setType(torch.DeviceObjType.get());
  14928. } else if (val.isGenerator()) {
  14929. n.ival_('value', val.toGenerator());
  14930. n.output().setType(torch._C_._GeneratorType.get());
  14931. } else if (val.isStream()) {
  14932. n.ival_('value', val);
  14933. n.output().setType(torch.StreamObjType.get());
  14934. } else if (val.isNone()) {
  14935. n.output().setType(torch.NoneType.get());
  14936. // n.ival_('value', null); // remove
  14937. } else if (val.isTuple()) {
  14938. if (torch._C.insertableIValue(val)) {
  14939. n.ival_('value', val);
  14940. n.output().setType(val.type());
  14941. } else {
  14942. n.destroy();
  14943. return null;
  14944. }
  14945. } else if (val.isObject()) {
  14946. const ref = val.toObjectRef();
  14947. // see: [Constant Object Weak CompilationUnit Reference]
  14948. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  14949. n.ival_('value', val);
  14950. n.output().setType(val.type());
  14951. } else {
  14952. n.destroy();
  14953. return null;
  14954. }
  14955. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  14956. n.ival_('value', val);
  14957. n.output().setType(val.type());
  14958. } else {
  14959. n.destroy();
  14960. return null;
  14961. }
  14962. if (loc) {
  14963. n.setSourceRange(loc);
  14964. }
  14965. if (scope) {
  14966. n.setScope(scope);
  14967. }
  14968. return g.insertNode(n).output();
  14969. }
  14970. const n = g.create('prim::Constant');
  14971. let type = null;
  14972. if (val === null) {
  14973. n.ival_('value', val);
  14974. type = torch.NoneType.get();
  14975. } else if (typeof val === 'string') {
  14976. n.s_('value', val);
  14977. type = torch.StringType.get();
  14978. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  14979. n.ss_('value', val);
  14980. type = torch.ListType.create(torch.StringType.get());
  14981. } else if (typeof val === 'boolean') {
  14982. n.i_('value', val === true ? 1 : 0);
  14983. type = torch.BoolType.get();
  14984. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  14985. n.i_('value', val);
  14986. type = torch.IntType.get();
  14987. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  14988. n.f_('value', val);
  14989. type = torch.FloatType.get();
  14990. } else if (val instanceof torch.Tensor) {
  14991. n.t_('value', val);
  14992. type = torch.TensorType.get();
  14993. } else if (val instanceof torch.ScriptObject) {
  14994. n.ival_('value', val);
  14995. type = val.type();
  14996. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  14997. n.ival_('value', val);
  14998. type = torch.ListType.create(torch.IntType.get());
  14999. } else {
  15000. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  15001. }
  15002. if (type) {
  15003. n.output().setType(type);
  15004. }
  15005. if (loc) {
  15006. n.setSourceRange(loc);
  15007. }
  15008. if (scope) {
  15009. n.setScope(scope);
  15010. }
  15011. return g.insertNode(n).output();
  15012. });
  15013. this.registerFunction('torch._C.toIValue', (v) => {
  15014. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  15015. return null;
  15016. }
  15017. const node = v.node();
  15018. const type = v.type();
  15019. if (type.isSubtypeOf(torch.TensorType.get())) {
  15020. return new torch._C.IValue(node.t('value'), 'Tensor');
  15021. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  15022. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  15023. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  15024. return new torch._C.IValue(node.i('value'), 'Int');
  15025. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  15026. return new torch._C.IValue(node.f('value'), 'Double');
  15027. } else if (type.isSubtypeOf(torch.ComplexType.get()) && node.kindOf('value') === 'c') {
  15028. return new torch._C.IValue(node.c('value'), 'Complex');
  15029. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  15030. let list = node.ival('value');
  15031. list = list.isList ? list : new torch._C.IValue(list); // remove
  15032. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  15033. return list;
  15034. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  15035. const dict = node.ival('value');
  15036. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  15037. return dict;
  15038. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  15039. const tup = node.ival('value');
  15040. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  15041. return tup;
  15042. } else if (type === torch.StringType.get()) {
  15043. const s = new torch._C.IValue(node.s('value'), 'String');
  15044. return s;
  15045. } else if (type === torch.DeviceObjType.get()) {
  15046. const d = new torch.device(node.s('value'));
  15047. return new torch._C.IValue(d);
  15048. } else if (type === torch._C._GeneratorType.get()) {
  15049. throw new python.Error('Not implemented.');
  15050. // const generator = node.ival('value').toGenerator();
  15051. // return generator;
  15052. } else if (type === torch.StreamObjType.get()) {
  15053. throw new python.Error('Not implemented.');
  15054. // const s = node.ival('value').toStream();
  15055. // return s;
  15056. } else if (node.mustBeNone()) {
  15057. return new torch._C.IValue();
  15058. } else if (type.kind() === 'EnumType') {
  15059. const enum_val = node.ival('value');
  15060. return enum_val;
  15061. } else if (type instanceof torch.ClassType && !type.is_module()) {
  15062. const class_val = node.ival('value');
  15063. return new torch._C.IValue(class_val, 'Object');
  15064. }
  15065. throw new python.Error('Unsupported constant literal.');
  15066. });
  15067. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  15068. const ivalue = torch._C.toIValue(v);
  15069. if (ivalue) {
  15070. return ivalue[target]();
  15071. }
  15072. return default_value === undefined ? null : default_value;
  15073. });
  15074. this.registerType('torch._C.NamedValue', class {
  15075. constructor(...args) {
  15076. if (args.length === 1) {
  15077. if (args[0] instanceof torch.Value) {
  15078. [this._value] = args;
  15079. } else {
  15080. [this._ivalue] = args;
  15081. }
  15082. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  15083. [this._loc, this._name, this._value] = args;
  15084. } else {
  15085. throw new python.Error('Invalid argument.');
  15086. }
  15087. }
  15088. name() {
  15089. return this._name;
  15090. }
  15091. value(g) {
  15092. if (!this._value) {
  15093. return torch._C.insertConstant(g, this._ivalue);
  15094. }
  15095. return this._value;
  15096. }
  15097. type() {
  15098. if (this._value) {
  15099. return this._value.type();
  15100. }
  15101. return this._ivalue.type();
  15102. }
  15103. });
  15104. this.registerType('torch._C.SugaredValue', class {
  15105. kind() {
  15106. throw new python.Error('Not implemented.');
  15107. }
  15108. shouldEmitUnrolled() {
  15109. return this.staticLen() !== null;
  15110. }
  15111. });
  15112. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15113. constructor(value) {
  15114. super();
  15115. this._value = value;
  15116. }
  15117. kind() {
  15118. return `value of type '${this._value.type().annotation_str}'`;
  15119. }
  15120. asValue(/* range, m */) {
  15121. return this._value;
  15122. }
  15123. getValue() {
  15124. return this._value;
  15125. }
  15126. asTuple(loc, m, size_hint) {
  15127. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15128. if (this._value.type() instanceof torch.TupleType) {
  15129. const outputs = torch._C.createTupleUnpack(this._value);
  15130. return outputs.map((v) => make_simple_value(v));
  15131. } else if (this._value.type() instanceof torch.ListType) {
  15132. if (!size_hint) {
  15133. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15134. }
  15135. const graph = this._value.owningGraph();
  15136. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15137. return unpack.outputs().map((v) => make_simple_value(v));
  15138. } else if (this._value.type().kind() === 'AnyTupleType') {
  15139. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15140. }
  15141. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15142. }
  15143. attr(loc, m, field) {
  15144. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15145. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15146. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15147. }
  15148. }
  15149. if (this._value.type() instanceof torch.TupleType) {
  15150. throw new python.Error('Not implemented.');
  15151. }
  15152. if (this._value.type() instanceof torch.AwaitType) {
  15153. throw new python.Error('Not implemented.');
  15154. }
  15155. if (this._value.type() instanceof torch.ClassType) {
  15156. const classType = this._value.type();
  15157. if (classType.findMethod(field)) {
  15158. return new torch._C.MethodValue(this.getValue(), [field]);
  15159. }
  15160. if (classType.hasAttribute(field)) {
  15161. const g = m.graph();
  15162. const n = g.insertNode(g.createGetAttr(this._value, field));
  15163. return new torch._C.SimpleValue(n.output());
  15164. }
  15165. const prop = classType.getProperty(field);
  15166. if (prop) {
  15167. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15168. }
  15169. } else if (this._value.type() instanceof torch.InterfaceType) {
  15170. throw new python.Error('Not implemented.');
  15171. } else if (this._value.type() instanceof torch.EnumType) {
  15172. const g = m.graph();
  15173. if (field === 'name') {
  15174. const n = g.insertNode(g.createEnumName(this._value));
  15175. return new torch._C.SimpleValue(n.output());
  15176. }
  15177. if (field === 'value') {
  15178. const n = g.insertNode(g.createEnumValue(this._value));
  15179. return new torch._C.SimpleValue(n.output());
  15180. }
  15181. }
  15182. if (field === 'type') {
  15183. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15184. if (builtin) {
  15185. return builtin;
  15186. }
  15187. }
  15188. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15189. if (builtin) {
  15190. return builtin;
  15191. }
  15192. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15193. return torch._C.SpecialFormValue.create('prim::tolist');
  15194. }
  15195. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15196. return torch._C.SpecialFormValue.create('aten::index');
  15197. }
  15198. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15199. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15200. if (builtin) {
  15201. return builtin;
  15202. }
  15203. }
  15204. throw new python.Error('Object has no attribute or method.');
  15205. }
  15206. setAttr(loc, m, field, newValue) {
  15207. const type = this._value.type();
  15208. if (type instanceof torch.ClassType === false) {
  15209. throw new python.Error('Cannot set attribute on non-class type.');
  15210. }
  15211. const classType = type;
  15212. let expectedType = classType.findAttribute(field);
  15213. if (!expectedType) {
  15214. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15215. if (isInitializing) {
  15216. if (this.isRecursive(classType, newValue.type())) {
  15217. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15218. }
  15219. classType.addAttribute(field, newValue.type());
  15220. expectedType = newValue.type();
  15221. const insertPoint = m.graph().insertPoint();
  15222. const topLevelBlock = m.graph().block();
  15223. if (insertPoint.owningBlock() !== topLevelBlock) {
  15224. throw new python.Error('First assignment cannot be in a control-flow block.');
  15225. }
  15226. } else {
  15227. const prop = classType.getProperty(field);
  15228. if (prop && prop.setter) {
  15229. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15230. return;
  15231. }
  15232. if (prop && !prop.setter) {
  15233. throw new python.Error('Tried to set read-only attribute.');
  15234. }
  15235. throw new python.Error('Tried to set nonexistent attribute.');
  15236. }
  15237. }
  15238. torch._C.AT_ASSERT(expectedType);
  15239. const newType = newValue.type();
  15240. if (!newType.isSubtypeOf(expectedType)) {
  15241. throw new python.Error('Wrong type for attribute assignment.');
  15242. }
  15243. const g = m.graph();
  15244. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15245. }
  15246. getitem(loc, m, idx, type_hint) {
  15247. const val = this.getValue();
  15248. const val_type = val.type();
  15249. const g = m.graph();
  15250. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15251. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15252. } else if (val_type instanceof torch.DictType) {
  15253. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15254. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15255. return new torch._C.SimpleValue(g.insert('aten::select', [new torch._C.NamedValue(val), new torch._C.NamedValue(0), new torch._C.NamedValue(idx)], [], loc));
  15256. } else if (val_type instanceof torch.ClassType) {
  15257. const class_type = val_type;
  15258. if (class_type.is_module() && type_hint) {
  15259. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15260. res.setType(type_hint);
  15261. return new torch._C.SimpleValue(res);
  15262. }
  15263. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15264. }
  15265. throw new python.Error('Object is not subscriptable.');
  15266. }
  15267. });
  15268. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15269. constructor(self, method_names) {
  15270. super();
  15271. this._self = self;
  15272. this._method_names = method_names;
  15273. }
  15274. call(loc, f, args, kwargs /*, n_binders */) {
  15275. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15276. const schemas = [];
  15277. for (const method_name of this._method_names) {
  15278. const type = this._self.type();
  15279. if (type instanceof torch.ClassType) {
  15280. const class_type = type;
  15281. const method = class_type.getMethod(method_name);
  15282. method.ensure_defined();
  15283. schemas.push(method.getSchema());
  15284. } else if (type instanceof torch.InterfaceType) {
  15285. const interface_type = type;
  15286. schemas.push(interface_type.getMethod(method_name));
  15287. } else {
  15288. throw new python.Error('Method constructed that is not a class or interface.');
  15289. }
  15290. }
  15291. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15292. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15293. output.node().setSourceRange(loc);
  15294. return new torch._C.SimpleValue(output);
  15295. }
  15296. });
  15297. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15298. constructor(type) {
  15299. super();
  15300. this._type = type;
  15301. }
  15302. attr(loc, m, field) {
  15303. const hook = this._type.findHook(field);
  15304. if (hook) {
  15305. return new torch._C.FunctionValue(hook);
  15306. }
  15307. if (field !== '__new__') {
  15308. throw new python.Error('Tried to lookup unknown attribute on class.');
  15309. }
  15310. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15311. }
  15312. });
  15313. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15314. constructor(type) {
  15315. super();
  15316. this._type = type;
  15317. }
  15318. call(loc, m, args, kwargs /*, n_binders */) {
  15319. const g = m.graph();
  15320. const schema = this._type.schema();
  15321. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15322. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15323. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15324. self.setType(this._type);
  15325. return new torch._C.SimpleValue(self);
  15326. }
  15327. });
  15328. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15329. constructor(enum_type) {
  15330. super();
  15331. this._enum_type = enum_type;
  15332. }
  15333. attr(loc, m, field) {
  15334. const names_values = this._enum_type.enumNamesValues();
  15335. const it = names_values.find((nv) => nv[0] === field);
  15336. if (it === null) {
  15337. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15338. }
  15339. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15340. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15341. }
  15342. });
  15343. this.registerType('torch._C.EnumHolder', class {
  15344. constructor(type, name, value) {
  15345. this._type = type;
  15346. this._name = name;
  15347. this._value = value;
  15348. }
  15349. name() {
  15350. return this._name;
  15351. }
  15352. type() {
  15353. return this._type;
  15354. }
  15355. });
  15356. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15357. constructor(...args) {
  15358. super();
  15359. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15360. this._callees = [args[0]];
  15361. } else {
  15362. throw new python.Error('Not implemented.');
  15363. }
  15364. }
  15365. call(loc, f, args, kwargs /*, n_binders */) {
  15366. const schemas = [];
  15367. for (const callee of this._callees) {
  15368. callee.ensure_defined();
  15369. schemas.push(callee.getSchema());
  15370. }
  15371. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15372. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15373. output.node().setSourceRange(loc);
  15374. return new torch._C.SimpleValue(output);
  15375. }
  15376. });
  15377. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15378. });
  15379. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15380. call(loc, m, args, kwargs /*, n_binders */) {
  15381. const g = m.graph();
  15382. if (kwargs.length > 0) {
  15383. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15384. }
  15385. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15386. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15387. return new torch._C.NoneValue();
  15388. }
  15389. });
  15390. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15391. constructor(form) {
  15392. super();
  15393. this._form = form;
  15394. }
  15395. form() {
  15396. return this._form;
  15397. }
  15398. static create(form) {
  15399. return new torch._C.SpecialFormValue(form);
  15400. }
  15401. });
  15402. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15403. return new torch._C.MagicMethod(name, base);
  15404. });
  15405. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15406. constructor(symbol, self) {
  15407. super();
  15408. this.symbol = symbol;
  15409. this.self = self;
  15410. }
  15411. call(loc, m, args, kwargs /*, n_binders */) {
  15412. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15413. }
  15414. static tryCreate(symbol, self) {
  15415. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15416. if (!self) {
  15417. return new torch._C.BuiltinFunction(symbol, null);
  15418. }
  15419. const index = op.schema().argumentIndexWithName('self');
  15420. if (index) {
  15421. const type_env = new Map();
  15422. const formal_type = op.schema().arguments()[index].type();
  15423. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15424. if (!matched.success()) {
  15425. continue;
  15426. }
  15427. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15428. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15429. continue;
  15430. }
  15431. return new torch._C.BuiltinFunction(symbol, self);
  15432. }
  15433. }
  15434. return null;
  15435. }
  15436. });
  15437. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15438. constructor(name, version) {
  15439. super();
  15440. this.name = name;
  15441. this.version = version || null;
  15442. }
  15443. attr(loc, m, field) {
  15444. if (field === 'autograd') {
  15445. return new torch._C.BuiltinModule('aten', this.version);
  15446. }
  15447. const sym = `${this.name}::${field}`;
  15448. return new torch._C.BuiltinFunction(sym, null);
  15449. }
  15450. });
  15451. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15452. constructor(version) {
  15453. super();
  15454. this._version = version;
  15455. }
  15456. attr(loc, m, field) {
  15457. return new torch._C.BuiltinModule(field, this._version);
  15458. }
  15459. });
  15460. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15461. constructor(constants) {
  15462. super();
  15463. this._constants = constants;
  15464. this.non_holding_object_cache = new Map();
  15465. }
  15466. attr(loc, m, field) {
  15467. const offset = parseInt(field.substring(1), 10);
  15468. if (!Number.isInteger(offset)) {
  15469. throw new python.Error(`Invalid constant identifier '${field}.`);
  15470. }
  15471. if (offset < 0 || offset >= this._constants.length) {
  15472. throw new python.Error('Invalid constant index.');
  15473. }
  15474. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15475. let value = null;
  15476. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15477. const obj = ivalue.toObject();
  15478. if (!this.non_holding_object_cache.has(obj)) {
  15479. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15480. }
  15481. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15482. } else {
  15483. value = m.graph().insertConstant(this._constants[offset], loc);
  15484. }
  15485. value.setType(torch._C.unshapedType(value.type()));
  15486. return new torch._C.SimpleValue(value);
  15487. }
  15488. });
  15489. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15490. constructor(type, method) {
  15491. super(method, null);
  15492. this._type = type;
  15493. }
  15494. call(loc, m, args, kwargs, n_binders) {
  15495. if (args.length === 1 && kwargs.length === 0) {
  15496. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15497. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15498. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15499. const v = args[0].value(m.graph());
  15500. if (v.type().isSubtypeOf(this._type)) {
  15501. return new torch._C.SimpleValue(v);
  15502. } else if (this._type === torch.BoolType.get() && (v.type().isSubtypeOf(torch.Type.get('AnyListType')) || v.type().isSubtypeOf(torch.StringType.get()) || v.type() instanceof torch.DictType)) {
  15503. const len = len_op.call(loc, m, [v], [], 1);
  15504. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15505. }
  15506. }
  15507. return super.call(loc, m, args, kwargs, n_binders);
  15508. }
  15509. });
  15510. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15511. constructor(desugared_name, base) {
  15512. super();
  15513. this._base_value = base;
  15514. this._desugared_name = desugared_name;
  15515. }
  15516. call(loc, m, args, kwargs, n_binders) {
  15517. if (args.length > 0) {
  15518. const self = args[0].value(m.graph());
  15519. if (self.type() instanceof torch.ClassType) {
  15520. return new torch._C.SimpleValue(self)
  15521. .attr(loc, m, this._desugared_name)
  15522. .call(loc, m, args.slice(1), kwargs, n_binders);
  15523. }
  15524. }
  15525. if (!this._base_value) {
  15526. throw new python.Error('Invalid magic method.');
  15527. }
  15528. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15529. }
  15530. });
  15531. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15532. constructor(loc, m, inputs, static_len) {
  15533. super();
  15534. static_len = static_len || null;
  15535. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15536. throw new python.Error('Invalid range inputs.');
  15537. }
  15538. const g = m.graph();
  15539. if (inputs.length === 1) {
  15540. [this._end] = inputs;
  15541. this._start = g.insertConstant(0, loc);
  15542. this._step = g.insertConstant(1, loc);
  15543. this._has_only_end = true;
  15544. } else {
  15545. [this._start, this._end] = inputs;
  15546. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15547. this._has_only_end = false;
  15548. }
  15549. this._static_len = static_len;
  15550. }
  15551. staticLen() {
  15552. return this._static_len;
  15553. }
  15554. iter() {
  15555. return this;
  15556. }
  15557. len(loc, m) {
  15558. if (this._static_len) {
  15559. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15560. }
  15561. if (this._has_only_end) {
  15562. return this._end;
  15563. }
  15564. const g = m.graph();
  15565. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15566. }
  15567. getitem(loc, m, idx /*, type_hint */) {
  15568. if (this._has_only_end) {
  15569. return new torch._C.SimpleValue(idx);
  15570. }
  15571. const g = m.graph();
  15572. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15573. }
  15574. });
  15575. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15576. });
  15577. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15578. constructor(name, si) {
  15579. super();
  15580. this._basename = name;
  15581. this._si = si;
  15582. }
  15583. attr(loc, m, name) {
  15584. const fullName = new torch._C.QualifiedName(this._basename, name);
  15585. const serializable_type = this._si.findNamedType(fullName);
  15586. if (serializable_type) {
  15587. if (serializable_type instanceof torch.ClassType) {
  15588. return new torch._C.ClassValue(serializable_type);
  15589. } else if (serializable_type instanceof torch.TupleType) {
  15590. return new torch._C.NamedTupleConstructor(serializable_type);
  15591. } else if (serializable_type instanceof torch.EnumType) {
  15592. return new torch._C.SugaredEnumClass(serializable_type);
  15593. }
  15594. }
  15595. const fn = this._si.findFunction(fullName);
  15596. if (fn) {
  15597. return new torch._C.FunctionValue(fn);
  15598. }
  15599. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15600. }
  15601. });
  15602. this.registerType('torch.package.PackageImporter', class {
  15603. constructor(reader) {
  15604. this.zip_reader = reader;
  15605. }
  15606. load_pickle(module, resource) {
  15607. const name = `${module.replace(/\./, '/')}/${resource}`;
  15608. const stream = this.zip_reader.get_record(name);
  15609. const loaded_reduces = new Map();
  15610. this.storage_context = new torch._C.DeserializationStorageContext();
  15611. const unpickler = new pickle.Unpickler(stream);
  15612. unpickler.persistent_load = (saved_id) => {
  15613. switch (saved_id[0]) {
  15614. case 'storage': {
  15615. const [, storage_type, key, , size] = saved_id;
  15616. if (!this.storage_context.has_storage(key)) {
  15617. const storage = new storage_type(size);
  15618. if (!storage._set_cdata) {
  15619. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15620. }
  15621. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15622. const buffer = stream.peek();
  15623. storage._set_cdata(buffer);
  15624. this.storage_context.add_storage(key, storage);
  15625. }
  15626. return this.storage_context.get_storage(key);
  15627. }
  15628. case 'reduce_package': {
  15629. if (saved_id.length === 2) {
  15630. const [, func, args] = saved_id;
  15631. return execution.invoke(func, args);
  15632. }
  15633. const [, reduce_id, func, args] = saved_id;
  15634. if (!loaded_reduces.has(reduce_id)) {
  15635. const value = execution.invoke(func, [this].concat(args));
  15636. loaded_reduces.set(reduce_id, value);
  15637. }
  15638. return loaded_reduces.get(reduce_id);
  15639. }
  15640. default: {
  15641. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15642. }
  15643. }
  15644. };
  15645. const obj = unpickler.load();
  15646. this.storage_context = null;
  15647. return obj;
  15648. }
  15649. import_module(name) {
  15650. return execution.import(name);
  15651. }
  15652. });
  15653. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15654. const cu = new torch.jit.CompilationUnit();
  15655. cu.execution = execution;
  15656. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15657. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15658. module.forward = cpp_module.forward; // remove
  15659. return module;
  15660. });
  15661. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15662. switch (arguments.length) {
  15663. case 4: {
  15664. const [device, extra_files] = args;
  15665. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15666. return deserializer.deserialize(device, extra_files);
  15667. }
  15668. case 5: {
  15669. const [storage_context, device, ts_id] = args;
  15670. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15671. return deserializer.deserialize(device, null);
  15672. }
  15673. default: {
  15674. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15675. }
  15676. }
  15677. });
  15678. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15679. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15680. });
  15681. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15682. if (value instanceof torch.Node) {
  15683. const n = value;
  15684. if (n.kind() === 'prim::CallFunction') {
  15685. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15686. const function_constant = n.input(0).node();
  15687. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15688. return torch._C.tryToGraphFunction(fun_type.function());
  15689. }
  15690. if (n.kind() === 'prim::CallMethod') {
  15691. const name = n.s('name');
  15692. const class_type = n.input(0).type();
  15693. if (class_type instanceof torch.ClassType) {
  15694. const fn = class_type.getMethod(name);
  15695. return torch._C.tryToGraphFunction(fn);
  15696. }
  15697. }
  15698. return null;
  15699. } else if (value instanceof torch._C.Function) {
  15700. const fn = value;
  15701. if (!fn.isGraphFunction()) {
  15702. return null;
  15703. }
  15704. return fn;
  15705. }
  15706. throw new python.Error('Not implemented.');
  15707. });
  15708. this.registerType('torch._C.ModuleInstanceInfo', class {
  15709. constructor(module_type, instance_name) {
  15710. this._module_type = module_type;
  15711. this._instance_name = instance_name;
  15712. }
  15713. });
  15714. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15715. torch._C.TORCH_CHECK(step !== 0);
  15716. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15717. if (start._ === Number.MAX_SAFE_INTEGER) {
  15718. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15719. }
  15720. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15721. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15722. }
  15723. if (start._ < 0) {
  15724. start._ += length;
  15725. if (start._ < 0) {
  15726. start._ = (step < 0) ? -1 : 0;
  15727. }
  15728. } else if (start._ >= length) {
  15729. start._ = (step < 0) ? length - 1 : length;
  15730. }
  15731. if (stop._ < 0) {
  15732. stop._ += length;
  15733. if (stop._ < 0) {
  15734. stop._ = (step < 0) ? -1 : 0;
  15735. }
  15736. } else if (stop._ >= length) {
  15737. stop._ = (step < 0) ? length - 1 : length;
  15738. }
  15739. if (step < 0) {
  15740. if (stop._ < start._) {
  15741. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15742. }
  15743. } else if (start._ < stop._) {
  15744. return Math.floor((stop._ - start._ - 1) / step + 1);
  15745. }
  15746. return 0;
  15747. });
  15748. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15749. if (v.node().kind() === 'prim::TupleConstruct') {
  15750. return v.node().inputs();
  15751. }
  15752. const g = v.owningGraph();
  15753. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15754. });
  15755. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15756. /*
  15757. const new_node_cs = new_node.callstack();
  15758. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15759. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15760. if (new_node_cs) {
  15761. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15762. } else {
  15763. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15764. }
  15765. }
  15766. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15767. for (const block of new_node.blocks()) {
  15768. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15769. }
  15770. */
  15771. });
  15772. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15773. if (arg === undefined || typeof arg === 'boolean') {
  15774. const inline_optimized_graph = arg === undefined ? true : arg;
  15775. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15776. return torch._C.inlineCallTo(to_replace, callee, graph);
  15777. }
  15778. if (arg instanceof torch.Graph === false) {
  15779. throw new python.Error('Invalid argument.');
  15780. }
  15781. const callee_graph = arg;
  15782. const guard = new torch._C.WithInsertPoint(to_replace);
  15783. const value_map = new Map();
  15784. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15785. const new_callstack_entries = new Map();
  15786. let module_instance_info = null;
  15787. if (to_replace.kind() === 'prim::CallMethod') {
  15788. const class_type_ptr = to_replace.input(0).type();
  15789. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15790. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15791. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15792. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15793. } else {
  15794. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15795. }
  15796. }
  15797. const updated_nodes = new Set();
  15798. for (const kv of value_map) {
  15799. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15800. if (is_graph_input === -1) {
  15801. continue;
  15802. }
  15803. const new_node = kv[1].node();
  15804. if (updated_nodes.has(new_node)) {
  15805. continue;
  15806. }
  15807. updated_nodes.add(new_node);
  15808. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15809. }
  15810. const old_outputs = to_replace.outputs();
  15811. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15812. for (let i = 0; i < old_outputs.length; i++) {
  15813. if (old_outputs[i].hasDebugName()) {
  15814. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15815. }
  15816. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15817. }
  15818. to_replace.destroy();
  15819. guard.dispose();
  15820. return new_outputs;
  15821. });
  15822. this.registerFunction('torch._C.inlineCalls', (block) => {
  15823. for (const cur of block.nodes()) {
  15824. switch (cur.kind()) {
  15825. case 'prim::CallFunction': {
  15826. const graphFunction = torch._C.tryToGraphFunction(cur);
  15827. if (graphFunction) {
  15828. const function_constant = cur.input(0).node();
  15829. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15830. cur.removeInput(0);
  15831. let g = null;
  15832. const fallback = function_constant.hasAttribute('fallback');
  15833. if (fallback && graphFunction.get_executor().isOptimized()) {
  15834. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15835. if (!exec_plans.empty()) {
  15836. g = exec_plans.begin().second.graph;
  15837. torch._C.Inline(g);
  15838. }
  15839. }
  15840. if (g === null) {
  15841. g = graphFunction.optimized_graph();
  15842. }
  15843. torch._C.inlineCallTo(cur, graphFunction, g);
  15844. }
  15845. break;
  15846. }
  15847. case 'prim::CallMethod': {
  15848. const graphFunction = torch._C.tryToGraphFunction(cur);
  15849. if (graphFunction) {
  15850. torch._C.inlineCallTo(cur, graphFunction);
  15851. }
  15852. break;
  15853. }
  15854. default: {
  15855. for (const b of cur.blocks()) {
  15856. torch._C.inlineCalls(b);
  15857. }
  15858. }
  15859. }
  15860. }
  15861. });
  15862. this.registerFunction('torch._C.Inline', (graph) => {
  15863. torch._C.inlineCalls(graph.block());
  15864. });
  15865. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15866. torch._C.Inline(graph);
  15867. });
  15868. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15869. });
  15870. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15871. const cu = new torch.jit.CompilationUnit();
  15872. cu.execution = execution;
  15873. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15874. return torch.jit._script.wrap_cpp_module(cpp_module);
  15875. });
  15876. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15877. const init_fn = (script_module) => {
  15878. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15879. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15880. }
  15881. };
  15882. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15883. });
  15884. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15885. has_storage(name) {
  15886. return this.has(name);
  15887. }
  15888. get_storage(name) {
  15889. return this.get(name);
  15890. }
  15891. add_storage(name, storage) {
  15892. return this.set(name, storage);
  15893. }
  15894. });
  15895. this.registerType('torch.ScriptFunction', class {
  15896. constructor(name, graph /*, function_creator */) {
  15897. this._name = name;
  15898. this._graph = graph;
  15899. }
  15900. });
  15901. this.registerType('torch.ScriptMethod', class {
  15902. constructor(owner, value) {
  15903. this._owner = owner;
  15904. this._function = value;
  15905. }
  15906. get name() {
  15907. return this._function.name();
  15908. }
  15909. get owner() {
  15910. return this._owner;
  15911. }
  15912. __call__(/* args, kwargs */) {
  15913. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  15914. }
  15915. get graph() {
  15916. return this._function.graph();
  15917. }
  15918. get schema() {
  15919. // return this.function().getSchema();
  15920. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  15921. }
  15922. get code() {
  15923. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  15924. }
  15925. get code_with_constants() {
  15926. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  15927. }
  15928. });
  15929. this.registerType('torch.ScriptObject', class {
  15930. constructor(type) {
  15931. this._typ = type;
  15932. this._ivalue = {};
  15933. }
  15934. static create(type) {
  15935. if (type.is_module()) {
  15936. return new torch.ScriptModule(type);
  15937. }
  15938. return new torch.ScriptObject(type);
  15939. }
  15940. type() {
  15941. return this._typ;
  15942. }
  15943. _type() {
  15944. return this._typ; // torch.ClassType
  15945. }
  15946. __setstate__(state) {
  15947. const [attrs, qualname] = state;
  15948. this._typ = torch._C.getCustomClass(qualname);
  15949. if (!this._typ) {
  15950. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  15951. }
  15952. for (let i = 0; i < this._typ.numAttributes(); i++) {
  15953. const name = this._typ.getAttributeName(i);
  15954. this.__setattr__(name, attrs[i]);
  15955. }
  15956. }
  15957. find_method(basename) {
  15958. for (const fn of this.type().methods()) {
  15959. if (fn.name() === basename) {
  15960. return new torch.ScriptMethod(this /* _value() */, fn);
  15961. }
  15962. }
  15963. return null;
  15964. }
  15965. _get_method(name) {
  15966. const method = this.find_method(name);
  15967. if (method) {
  15968. return method;
  15969. }
  15970. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  15971. return null;
  15972. }
  15973. _has_method(name) {
  15974. return this.find_method(name) ? true : false;
  15975. }
  15976. _method_names() {
  15977. return this.type().methods().map((fn) => fn.name());
  15978. }
  15979. __setattr__(name, value) {
  15980. // if (this._type.hasContant(name))
  15981. this._ivalue[name] = value;
  15982. }
  15983. __getattr__(name) {
  15984. return this._ivalue[name];
  15985. }
  15986. hasattr(name) {
  15987. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  15988. }
  15989. getattr(name) {
  15990. return this.__getattr__(name);
  15991. }
  15992. _properties() {
  15993. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  15994. }
  15995. is_weak_compilation_ref() {
  15996. return true; // not implemented
  15997. }
  15998. });
  15999. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  16000. constructor(...args) {
  16001. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  16002. const [class_name, cu, shouldMangle] = args;
  16003. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  16004. } else {
  16005. super(...args);
  16006. }
  16007. }
  16008. get qualified_name() {
  16009. return this.type().qualified_name();
  16010. }
  16011. get code_with_constants() {
  16012. const const_map = {};
  16013. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  16014. return [null, const_map];
  16015. }
  16016. get graph() {
  16017. if (!this._graph) {
  16018. const fn = this._typ.getMethod('forward');
  16019. this._graph = fn.graph();
  16020. }
  16021. return this._graph;
  16022. }
  16023. static create_module_object(class_name, cu, shouldMangle) {
  16024. shouldMangle = shouldMangle || false;
  16025. if (!class_name.prefix()) {
  16026. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  16027. }
  16028. if (shouldMangle && cu.get_class(class_name)) {
  16029. class_name = cu.mangle(class_name);
  16030. }
  16031. const cls = torch.ClassType.create(class_name, cu, true);
  16032. cu.register_type(cls);
  16033. return [cls, cu];
  16034. }
  16035. register_module(name, module) {
  16036. this.type().addOrCheckAttribute(name, module.type());
  16037. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  16038. }
  16039. register_buffer(name, v) {
  16040. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  16041. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16042. }
  16043. register_parameter(name, v, is_buffer) {
  16044. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  16045. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16046. }
  16047. register_attribute(name, t, v, is_param, is_buffer) {
  16048. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  16049. // _ivalue()->setAttr(name, v);
  16050. }
  16051. });
  16052. this.registerType('torch.ModuleDict', class {
  16053. constructor(mod) {
  16054. this._module = mod;
  16055. }
  16056. items() {
  16057. const result = new Map();
  16058. const type = this._module.type();
  16059. for (let i = 0; i < type.numAttributes(); i++) {
  16060. const k = type.getAttributeName(i);
  16061. const t = type.getAttribute(i);
  16062. if (t && t.is_module()) {
  16063. result.set(k, this._module.__getattr__(k));
  16064. }
  16065. }
  16066. return result;
  16067. }
  16068. });
  16069. this.registerType('torch.ParameterDict', class {
  16070. constructor(mod) {
  16071. this._module = mod;
  16072. }
  16073. items() {
  16074. const result = new Map();
  16075. const type = this._module.type();
  16076. for (let i = 0; i < type.numAttributes(); i++) {
  16077. if (type.is_parameter(i)) {
  16078. const k = type.getAttributeName(i);
  16079. const v = this._module.__getattr__(k);
  16080. if (v instanceof torch.Tensor) {
  16081. result.set(k, v);
  16082. }
  16083. }
  16084. }
  16085. return result;
  16086. }
  16087. });
  16088. this.registerType('torch.BufferDict', class {
  16089. constructor(mod) {
  16090. this._module = mod;
  16091. }
  16092. items() {
  16093. const result = new Map();
  16094. const type = this._module.type();
  16095. for (let i = 0; i < type.numAttributes(); i++) {
  16096. if (type.is_buffer(i)) {
  16097. const t = type.getAttribute(i);
  16098. if (t.isSubtypeOf(torch.TensorType.get())) {
  16099. const k = type.getAttributeName(i);
  16100. const v = this._module.__getattr__(k);
  16101. result.set(k, v);
  16102. }
  16103. }
  16104. }
  16105. return result;
  16106. }
  16107. });
  16108. this.registerType('torch._C.to_ir', class {
  16109. constructor(def, _resolver, self, method) {
  16110. this.method = method;
  16111. this.graph = method.graph();
  16112. this.resolver = _resolver;
  16113. this.integral_constants = new Map();
  16114. this.fp_constants = new Map();
  16115. this.complex_constants = new Map();
  16116. this.exit_blocks = new Set();
  16117. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16118. this._loop_status = 'NOT_IN_LOOP';
  16119. this.environment_stack = null;
  16120. this._def_stack = [];
  16121. this._temp_name_count = 0;
  16122. torch._C.AT_ASSERT(this.resolver);
  16123. this.pushFrame(this.graph.block(), true);
  16124. if (self && def && def.args.args.length === 0) {
  16125. throw new python.Error('Method must have a self argument.');
  16126. }
  16127. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16128. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16129. torch._C.ConvertToSSA(this.graph);
  16130. torch._C.CanonicalizeModifiedLoops(this.graph);
  16131. torch._C.NormalizeOps(this.graph.block());
  16132. torch._C.runCleanupPasses(this.graph);
  16133. }
  16134. pushFrame(b, starts_def) {
  16135. starts_def = starts_def || false;
  16136. if (starts_def) {
  16137. this._def_stack.push({});
  16138. }
  16139. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16140. }
  16141. popFrame(ends_def) {
  16142. const old_frame = this.environment_stack;
  16143. this.environment_stack = this.environment_stack.next;
  16144. if (ends_def) {
  16145. this._def_stack.pop();
  16146. }
  16147. return old_frame;
  16148. }
  16149. emitDef(def, self, block) {
  16150. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16151. if (schema.returns.length === 1) {
  16152. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16153. }
  16154. const args = this.emitFormalArguments(def, self, schema, block);
  16155. this.emitStatements(def.body);
  16156. this.handleMaybeNoReturn(def, block);
  16157. const returns = [this.emitOutput(def, schema, block)];
  16158. return new torch.FunctionSchema(def.name, '', args, returns);
  16159. }
  16160. emitFormalArguments(def, self, schema, block) {
  16161. const args = [];
  16162. const params = def.args.args;
  16163. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16164. if (schema.arguments.length !== expected_annotation_size) {
  16165. throw new python.Error('Invalid formal arguments.');
  16166. }
  16167. let it = 0;
  16168. if (self) {
  16169. const param = params[it];
  16170. const name = param.arg;
  16171. const new_input = block.addInput().setDebugName(name);
  16172. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16173. args.push(new torch.Argument(name, new_input.type()));
  16174. it++;
  16175. }
  16176. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16177. let arg_annotation_idx = 0;
  16178. for (; it < params.length; it++) {
  16179. const param = params[it];
  16180. const name = param.arg;
  16181. const new_input = block.addInput();
  16182. if (torch._C.meaningfulName(name)) {
  16183. new_input.setDebugName(name);
  16184. }
  16185. let arg = schema.arguments[arg_annotation_idx++];
  16186. if (shouldDeriveType) {
  16187. if (schema.arguments.length === 1) {
  16188. throw new python.Error('Invalid schema.');
  16189. }
  16190. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16191. arg = arg.cloneWithType(inferredStateType);
  16192. }
  16193. args.push(arg);
  16194. new_input.setType(arg.type);
  16195. this.environment_stack.setVar(param.range(), name, new_input);
  16196. }
  16197. return args;
  16198. }
  16199. emitOutput(range, schema, block) {
  16200. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16201. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16202. block.registerOutput(placeholder_return);
  16203. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16204. }
  16205. emitStatements(stmts) {
  16206. for (let i = 0; i < stmts.length; i++) {
  16207. const stmt = stmts[i];
  16208. if (stmt instanceof ast.If) {
  16209. this.emitIf(stmt);
  16210. } else if (stmt instanceof ast.While) {
  16211. this.emitWhile(stmt);
  16212. } else if (stmt instanceof ast.For) {
  16213. this.emitFor(stmt);
  16214. } else if (stmt instanceof ast.Assign) {
  16215. this.emitAssignment(stmt);
  16216. } else if (stmt instanceof ast.AnnAssign) {
  16217. this.emitAssignment(stmt);
  16218. } else if (stmt instanceof ast.Expr) {
  16219. this.emitSugaredExpr(stmt.value, 0);
  16220. } else if (stmt instanceof ast.Return) {
  16221. this.emitReturn(stmt);
  16222. } else if (stmt instanceof ast.Pass) {
  16223. // pass
  16224. } else if (stmt instanceof ast.With) {
  16225. this.emitWith(stmt);
  16226. } else {
  16227. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16228. }
  16229. if (this.exit_blocks.has(this.environment_stack.block())) {
  16230. return;
  16231. }
  16232. }
  16233. }
  16234. emitWith(stmt) {
  16235. const targets = stmt.items;
  16236. const entered = [];
  16237. for (const target of targets) {
  16238. const e = target.context_expr;
  16239. const rhs = this.emitExpr(e);
  16240. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16241. entered.push(rhs);
  16242. if (rhs.type() instanceof torch.ClassType === false) {
  16243. throw new python.Error('With item expression must return an object.');
  16244. }
  16245. const rhsClass = rhs.type();
  16246. const enterMethod = rhsClass.findMethod('__enter__');
  16247. const exitMethod = rhsClass.findMethod('__exit__');
  16248. if (!enterMethod || !exitMethod) {
  16249. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16250. }
  16251. const enterSchema = enterMethod.getSchema();
  16252. if (enterSchema.arguments.length !== 1) {
  16253. throw new python.Error('__enter__ must have only one argument and one return value.');
  16254. }
  16255. const exitSchema = exitMethod.getSchema();
  16256. if (exitSchema.arguments.length === 4) {
  16257. for (let i = 1; i < 4; i++) {
  16258. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16259. throw new python.Error('Argument of __exit__ must have Any type.');
  16260. }
  16261. }
  16262. } else {
  16263. throw new python.Error('__exit__ must have four arguments');
  16264. }
  16265. n.output(0).setType(enterSchema.returns[0].type);
  16266. if (target.optional_vars) {
  16267. throw new python.Error('Not implemented.');
  16268. // Var i = target.var().get();
  16269. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16270. }
  16271. }
  16272. this.emitStatements(stmt.body);
  16273. while (entered.length > 0) {
  16274. const input = entered.pop();
  16275. const n = this.graph.create('prim::Exit');
  16276. this.graph.insertNode(n);
  16277. n.addInput(input);
  16278. }
  16279. }
  16280. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16281. let max_trip_count_val = null;
  16282. if (iter_val === null) {
  16283. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16284. } else {
  16285. max_trip_count_val = iter_val.len(range, this.method);
  16286. }
  16287. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16288. const body_block = n.addBlock();
  16289. {
  16290. const condition_block = n.addBlock();
  16291. this.pushFrame(condition_block);
  16292. let out = null;
  16293. if (cond) {
  16294. const insert = new torch._C.WithInsertPoint(condition_block);
  16295. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16296. insert.dispose();
  16297. } else {
  16298. const insert = new torch._C.WithInsertPoint(n);
  16299. out = this.graph.insertConstant(true, range);
  16300. insert.dispose();
  16301. }
  16302. condition_block.registerOutput(out);
  16303. this.popFrame();
  16304. }
  16305. n.addInput(max_trip_count_val);
  16306. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16307. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16308. {
  16309. this.pushFrame(body_block);
  16310. const guard = new torch._C.WithInsertPoint(body_block);
  16311. if (iter_val !== null && targets) {
  16312. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16313. const sv = new torch._C.SimpleValue(cur_elem);
  16314. const target_exprs = targets;
  16315. this.validateAssignLhsExpr(target_exprs, range);
  16316. if (target_exprs.length > 1) {
  16317. throw new python.Error('Not implemented.');
  16318. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16319. // target_exprs = ListExpr.create(range, [tl]);
  16320. }
  16321. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16322. }
  16323. emit_body();
  16324. this.popFrame();
  16325. guard.dispose();
  16326. }
  16327. loop_guard.dispose();
  16328. }
  16329. emitFor(...args) {
  16330. if (args.length === 1 && args[0] instanceof ast.For) {
  16331. const [stmt] = args;
  16332. const emit_body = () => this.emitStatements(stmt.body);
  16333. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16334. } else if (args.length === 4) {
  16335. const [targets, itrs, loc, emit_body] = args;
  16336. if (itrs instanceof ast.Tuple) {
  16337. throw new python.Error('List of iterables is not supported currently.');
  16338. }
  16339. const sv = this.emitSugaredExpr(itrs, 1);
  16340. const iterable = sv.iter(loc, this.method);
  16341. if (iterable.shouldEmitUnrolled()) {
  16342. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16343. } else {
  16344. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16345. }
  16346. } else {
  16347. throw new python.Error('Not implemented.');
  16348. }
  16349. }
  16350. emitWhile(stmt) {
  16351. const cond = stmt.test;
  16352. const emit_body = () => this.emitStatements(stmt.body);
  16353. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16354. }
  16355. emitIsInstance(obj, classinfo) {
  16356. const lhs_val = this.emitExpr(obj);
  16357. const lhs_types = [];
  16358. const rhs_types = [];
  16359. const gather_rhs = (expr) => {
  16360. if (expr instanceof ast.Tuple) {
  16361. for (const e of expr.elts) {
  16362. gather_rhs(e);
  16363. }
  16364. return;
  16365. }
  16366. const type = this._typeParser.parseTypeFromExpr(expr);
  16367. rhs_types.push(type);
  16368. };
  16369. lhs_types.push(lhs_val.type());
  16370. gather_rhs(classinfo);
  16371. torch._C.standardizeVectorForUnion(lhs_types);
  16372. torch._C.standardizeVectorForUnion(rhs_types);
  16373. let refinement = new torch._C.RefinementSet([], []);
  16374. let unified_true = null;
  16375. let unified_false = null;
  16376. const isinstance_types = [];
  16377. const not_isinstance_types = [];
  16378. let true_refinements = [];
  16379. let false_refinements = [];
  16380. let all_lhs_subtype_some_rhs = true;
  16381. for (const lhs_type of lhs_types) {
  16382. if (lhs_type === torch.AnyType.get()) {
  16383. isinstance_types.push(...rhs_types);
  16384. not_isinstance_types.push(torch.AnyType.get());
  16385. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16386. all_lhs_subtype_some_rhs = false;
  16387. }
  16388. break;
  16389. }
  16390. const get_smaller_type = (t1, t2) => {
  16391. if (t1.isSubtypeOf(t2)) {
  16392. return t1;
  16393. } else if (t2.isSubtypeOf(t1)) {
  16394. return t2;
  16395. }
  16396. return null;
  16397. };
  16398. let found_refinement = null;
  16399. for (const rhs_type of rhs_types) {
  16400. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16401. if (!maybe_smaller_type) {
  16402. continue;
  16403. } else if (maybe_smaller_type === lhs_type) {
  16404. found_refinement = lhs_type;
  16405. } else if (maybe_smaller_type === rhs_type) {
  16406. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16407. }
  16408. }
  16409. if (found_refinement) {
  16410. if (found_refinement === lhs_type) {
  16411. all_lhs_subtype_some_rhs &= true;
  16412. }
  16413. isinstance_types.push(found_refinement);
  16414. } else {
  16415. not_isinstance_types.push(lhs_type);
  16416. all_lhs_subtype_some_rhs = false;
  16417. }
  16418. }
  16419. if (isinstance_types.length > 0) {
  16420. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16421. }
  16422. if (obj instanceof ast.Name && unified_true) {
  16423. const ident = obj.id;
  16424. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16425. }
  16426. if (not_isinstance_types.length > 0) {
  16427. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16428. }
  16429. if (obj instanceof ast.Name && unified_false) {
  16430. const ident = obj.id;
  16431. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16432. }
  16433. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16434. const is_statically_false = isinstance_types.length === 0;
  16435. if (all_lhs_subtype_some_rhs) {
  16436. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16437. }
  16438. if (is_statically_false) {
  16439. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16440. }
  16441. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16442. return new torch._C.CondValue(result, refinement, null);
  16443. }
  16444. emitIf(stmt) {
  16445. const cond_value = this.emitCondExpr(stmt.test);
  16446. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16447. }
  16448. emitCondExpr(expr) {
  16449. /*
  16450. switch (expr.kind()) {
  16451. case TK_AND:
  16452. case TK_OR: {
  16453. const binop = BinOp(expr);
  16454. return emitShortCircuitLogical(
  16455. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16456. }
  16457. case TK_NOT: {
  16458. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16459. Value* result = emitBuiltinCall(
  16460. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16461. std::optional<bool> static_if;
  16462. if (v.staticIf()) {
  16463. static_if = !*v.staticIf();
  16464. }
  16465. return CondValue(result, v.refinements().Not(), static_if);
  16466. } break;
  16467. case TK_IS:
  16468. case TK_ISNOT: {
  16469. // meta programming on AST for is/is not cases and emit branches base on
  16470. const cond_op = BinOp(expr);
  16471. Value* lhs_val = emitExpr(cond_op.lhs());
  16472. Value* rhs_val = emitExpr(cond_op.rhs());
  16473. const lhs_none = canBeNone(lhs_val);
  16474. const rhs_none = canBeNone(rhs_val);
  16475. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16476. // AA, -> statically IS always holds, IS_NOT never holds
  16477. // AN , NA-> statically IS_NOT always holds, IS never holds
  16478. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16479. bool its_is = expr.kind() == TK_IS;
  16480. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16481. return CondValue(*graph, expr.range(), its_is, {});
  16482. } else if (
  16483. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16484. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16485. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16486. return CondValue(*graph, expr.range(), !its_is, {});
  16487. } else {
  16488. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16489. Value* cond_value = emitBuiltinCall(
  16490. expr.get()->range(),
  16491. *method.graph(),
  16492. kind,
  16493. {lhs_val, rhs_val},
  16494. {});
  16495. const refinements = RefinementSet(findIsNoneRefinements(
  16496. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16497. return CondValue(cond_value, refinements, null);
  16498. }
  16499. } break;
  16500. */
  16501. if (expr instanceof ast.UnaryOp) {
  16502. throw new python.Error('Not implemented.');
  16503. }
  16504. if (expr instanceof ast.Call) {
  16505. const apply = expr;
  16506. const callee = expr.func;
  16507. if (callee instanceof ast.Name) {
  16508. if (callee.id === 'isinstance') {
  16509. this.checkApplyNumInputs(apply, 2);
  16510. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16511. }
  16512. if (callee.id === 'hasattr') {
  16513. this.checkApplyNumInputs(apply, 2);
  16514. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16515. }
  16516. const sv = this.emitSugaredExpr(callee, 1);
  16517. if (sv instanceof torch._C.SpecialFormValue) {
  16518. if (sv.form() === 'prim::isinstance') {
  16519. this.checkApplyNumInputs(apply, 2);
  16520. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16521. }
  16522. }
  16523. }
  16524. }
  16525. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16526. let static_if = null;
  16527. const kind = expr_out.node().kind();
  16528. if (kind === 'aten::is_scripting') {
  16529. static_if = true;
  16530. } else if (kind === 'aten::has_torch_function') {
  16531. static_if = false;
  16532. }
  16533. const maybe_ivalue = torch._C.toIValue(expr_out);
  16534. if (maybe_ivalue) {
  16535. static_if = maybe_ivalue.toBool();
  16536. }
  16537. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16538. }
  16539. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16540. if (cond_value.staticIf() !== null) {
  16541. if (cond_value.staticIf()) {
  16542. this.insertRefinements(loc, cond_value.refinements());
  16543. this.emitStatements(trueBranch);
  16544. } else {
  16545. this.insertRefinements(loc, cond_value.refinements().Not());
  16546. this.emitStatements(falseBranch);
  16547. }
  16548. return;
  16549. }
  16550. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16551. n.addInput(cond_value.value());
  16552. const true_block = n.addBlock();
  16553. const false_block = n.addBlock();
  16554. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16555. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16556. const true_exits = this.exit_blocks.has(true_block);
  16557. const false_exits = this.exit_blocks.has(false_block);
  16558. if (true_exits && false_exits) {
  16559. this.exit_blocks.add(n.owningBlock());
  16560. }
  16561. const mutated_variables = new Set();
  16562. for (const v of save_true.definedVariables()) {
  16563. const insert = new torch._C.WithInsertPoint(false_block);
  16564. if (save_false.findInAnyFrame(v) || false_exits) {
  16565. mutated_variables.add(v);
  16566. } else {
  16567. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16568. }
  16569. insert.dispose();
  16570. }
  16571. for (const v of save_false.definedVariables()) {
  16572. const insert = new torch._C.WithInsertPoint(true_block);
  16573. if (save_true.findInAnyFrame(v) || true_exits) {
  16574. mutated_variables.add(v);
  16575. } else {
  16576. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16577. }
  16578. insert.dispose();
  16579. }
  16580. for (const x of mutated_variables) {
  16581. let tv = null;
  16582. let fv = null;
  16583. {
  16584. const insert = new torch._C.WithInsertPoint(true_block);
  16585. if (!true_exits) {
  16586. tv = save_true.getVar(x, loc);
  16587. }
  16588. insert.dispose();
  16589. }
  16590. {
  16591. const insert = new torch._C.WithInsertPoint(false_block);
  16592. if (!false_exits) {
  16593. fv = save_false.getVar(x, loc);
  16594. }
  16595. insert.dispose();
  16596. }
  16597. if (true_exits && false_exits) {
  16598. continue;
  16599. } else if (true_exits) {
  16600. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16601. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16602. } else if (false_exits) {
  16603. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16604. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16605. }
  16606. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16607. let full_type = null;
  16608. if (maybe_sugared_x) {
  16609. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16610. if (maybe_simple) {
  16611. full_type = maybe_simple.type();
  16612. }
  16613. }
  16614. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16615. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16616. if (!unified) {
  16617. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16618. throw new python.Error('Type mismatch.');
  16619. } else {
  16620. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16621. continue;
  16622. }
  16623. }
  16624. this.environment_stack.setType(x, unified);
  16625. }
  16626. }
  16627. emitSingleIfBranch(b, branch, refinements) {
  16628. this.pushFrame(b);
  16629. const guard = new torch._C.WithInsertPoint(b);
  16630. this.insertRefinements(branch, refinements);
  16631. this.emitStatements(branch);
  16632. const frame = this.popFrame();
  16633. guard.dispose();
  16634. return frame;
  16635. }
  16636. create(kind, loc, n_outputs) {
  16637. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16638. }
  16639. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16640. is_dict_constructor = is_dict_constructor || false;
  16641. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16642. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16643. if (!is_dict_constructor && candidate_types.length === 0) {
  16644. throw new python.Error("No matching types found in Union type annotation.");
  16645. } else if (candidate_types.length === 1) {
  16646. [refined_type_hint_ptr._] = candidate_types;
  16647. } else {
  16648. all_candidates._ = candidate_types;
  16649. }
  16650. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16651. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16652. }
  16653. if (is_dict_constructor) {
  16654. return;
  16655. }
  16656. if (all_candidates._.length === 0) {
  16657. if (type_match(refined_type_hint_ptr._)) {
  16658. do_if_match();
  16659. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16660. do_if_anytype();
  16661. } else {
  16662. throw new python.Error('Invalid annotation type.');
  16663. }
  16664. }
  16665. }
  16666. emitToBool(loc, v) {
  16667. let out = null;
  16668. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16669. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16670. if (!out) {
  16671. throw new python.Error('Could not cast value to bool.');
  16672. }
  16673. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16674. throw new python.Error('Expected a bool expression for condition.');
  16675. }
  16676. return out;
  16677. }
  16678. emitUnaryOp(tree, magicMethod, opSymbol) {
  16679. const inputs = [tree.operand];
  16680. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16681. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16682. if (val.node().kind() !== opSymbol) {
  16683. return val;
  16684. }
  16685. const maybe_out_stack = torch._C.runNodeIfInputsAreConstant(val.node());
  16686. if (!maybe_out_stack) {
  16687. return val;
  16688. }
  16689. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16690. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16691. }
  16692. emitAssignment(stmt) {
  16693. if (stmt instanceof ast.AnnAssign) {
  16694. return this.emitSingleAssignment(stmt);
  16695. }
  16696. if (stmt.targets.length === 1) {
  16697. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16698. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16699. for (const [key, value] of entries) {
  16700. assign[key] = value;
  16701. }
  16702. return this.emitSingleAssignment(assign);
  16703. }
  16704. if (stmt.targets.length <= 1) {
  16705. throw new python.Error('Invalid assignment.');
  16706. }
  16707. throw new python.Error('Not implemented.');
  16708. /*
  16709. const tmp_name = this.createTempName('$tmp_assign_');
  16710. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16711. const ident = new ast.Name(tmp_name);
  16712. for (const expr of lhs_list) {
  16713. const assign = new ast.Assign(targets, value, ctx);
  16714. this.emitSingleAssignment(Assign.create(stmt,
  16715. List<Expr>.create(expr.range(), [expr]),
  16716. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16717. Maybe<Expr>::create(stmt.range())));
  16718. }
  16719. */
  16720. }
  16721. emitSingleAssignment(stmt) {
  16722. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16723. const rhs = stmt.value;
  16724. const lhs = stmt.target;
  16725. if (lhs instanceof ast.Name) {
  16726. let type = null;
  16727. if (stmt.annotation) {
  16728. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16729. }
  16730. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16731. // BC HACK
  16732. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16733. } else if (lhs instanceof ast.Tuple) {
  16734. this.emitTupleAssign(lhs, rhs);
  16735. } else if (lhs instanceof ast.Attribute) {
  16736. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16737. } else {
  16738. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16739. }
  16740. }
  16741. emitSelectAssign(lhs, rhs, type, loc) {
  16742. if (!rhs) {
  16743. throw new python.Error('Expected RHS for assignment.');
  16744. }
  16745. let type_hint = null;
  16746. if (type) {
  16747. type_hint = this._typeParser.parseTypeFromExpr(type);
  16748. }
  16749. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16750. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16751. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16752. }
  16753. emitTupleAssign(...args) {
  16754. if (args.length === 2) {
  16755. const [tl, rhs] = args;
  16756. let n_binders = tl.elts.length;
  16757. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16758. if (starred_unpack) {
  16759. n_binders--;
  16760. }
  16761. const output = this.emitSugaredExpr(rhs, n_binders);
  16762. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16763. } else if (args.length === 5) {
  16764. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16765. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16766. if (outputs.length < n_binders) {
  16767. throw new python.Error('Not enough values to unpack.');
  16768. }
  16769. if (outputs.length > n_binders && !starred_unpack) {
  16770. throw new python.Error('Too many values to unpack.');
  16771. }
  16772. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16773. } else {
  16774. throw new python.Error('Not implemented.');
  16775. }
  16776. }
  16777. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16778. let i = 0;
  16779. for (const assignee of lhs_exprs) {
  16780. if (assignee instanceof ast.Subscript) {
  16781. throw new python.Error('Not implemented.');
  16782. /*
  16783. this.emitSubscriptAssign(
  16784. rhs_loc,
  16785. Subscript(assignee),
  16786. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16787. i++;
  16788. */
  16789. } else if (assignee instanceof ast.Name) {
  16790. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16791. i++;
  16792. } else if (assignee instanceof ast.Starred) {
  16793. throw new python.Error('Not implemented.');
  16794. /*
  16795. const var = Starred(assignee).expr();
  16796. if (var.kind() != TK_VAR) {
  16797. throw(
  16798. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16799. }
  16800. size_t n_matched = outputs.size() - n_binders;
  16801. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16802. const values = fmap(
  16803. outputs_ref.slice(i, n_matched),
  16804. [&](const std::shared_ptr<SugaredValue>& v) {
  16805. return v.asValue(assignee.range(), method);
  16806. });
  16807. const tup = graph.insertNode(graph.createTuple(values)).output();
  16808. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16809. i += n_matched;
  16810. */
  16811. } else if (assignee instanceof ast.Tuple) {
  16812. throw new python.Error('Not implemented.');
  16813. /*
  16814. // recursively emit tuple assignments on tuple literal input
  16815. TupleLiteral sub_tl = TupleLiteral(assignee);
  16816. size_t sub_n_binders = sub_tl.inputs().length;
  16817. bool sub_starred_unpack =
  16818. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16819. if (sub_starred_unpack)
  16820. sub_n_binders--;
  16821. emitTupleAssign(
  16822. sub_tl,
  16823. outputs.at(i),
  16824. rhs_loc,
  16825. sub_n_binders,
  16826. sub_starred_unpack);
  16827. i++;
  16828. */
  16829. } else if (assignee instanceof ast.Attribute) {
  16830. throw new python.Error('Not implemented.');
  16831. /*
  16832. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16833. i++;
  16834. */
  16835. } else {
  16836. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16837. }
  16838. }
  16839. }
  16840. emitReturn(stmt) {
  16841. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16842. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16843. if (declared_return_type) {
  16844. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16845. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16846. }
  16847. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16848. throw new python.Error(`Invalid return type.`);
  16849. }
  16850. } else {
  16851. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16852. if (!declared_return_type) {
  16853. declared_return_type = actual_return.type();
  16854. }
  16855. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16856. if (!merged_return_type) {
  16857. throw new python.Error(`Invalid return type.`);
  16858. }
  16859. declared_return_type = merged_return_type;
  16860. }
  16861. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16862. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16863. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16864. }
  16865. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16866. this.exit_blocks.add(this.environment_stack.block());
  16867. }
  16868. getNamedValues(trees, maybe_unpack) {
  16869. const values = [];
  16870. for (const tree of trees) {
  16871. if (maybe_unpack && tree instanceof ast.Starred) {
  16872. throw new python.Error('Starred argument not supported.');
  16873. } else {
  16874. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16875. }
  16876. }
  16877. return values;
  16878. }
  16879. getValues(trees, maybe_unpack) {
  16880. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16881. }
  16882. emitExpr(tree, type_hint) {
  16883. type_hint = type_hint || null;
  16884. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16885. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16886. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16887. }
  16888. return out_val;
  16889. }
  16890. emitSugaredExpr(tree, n_binders, type_hint) {
  16891. if (tree instanceof ast.Name) { // TK_VAR
  16892. return this.environment_stack.getSugaredVar(tree.id);
  16893. } else if (tree instanceof ast.Attribute) {
  16894. const sv = this.emitSugaredExpr(tree.value, 1);
  16895. return sv.attr(tree.range(), this.method, tree.attr);
  16896. } else if (tree instanceof ast.Call) { // TK_APPLY
  16897. return this.emitApplyExpr(tree, n_binders, type_hint);
  16898. } if (tree instanceof ast.Subscript) {
  16899. return this.emitSubscript(tree, type_hint);
  16900. }
  16901. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  16902. }
  16903. emitApplyExpr(apply, n_binders, type_hint) {
  16904. type_hint = type_hint || null;
  16905. const sv = this.emitSugaredExpr(apply.func, 1);
  16906. const loc = apply.func.range();
  16907. if (sv instanceof torch._C.SpecialFormValue) {
  16908. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  16909. }
  16910. const args = this.getNamedValues(apply.args, true);
  16911. const kwargs = this.emitAttributes(apply.keywords);
  16912. return sv.call(loc, this.method, args, kwargs, n_binders);
  16913. }
  16914. emitAttributes(attributes) {
  16915. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  16916. }
  16917. emitApplySpecialForm(form, apply, sv, type_hint) {
  16918. switch (form) {
  16919. case 'prim::fork': {
  16920. throw new python.Error('Not implemented.');
  16921. }
  16922. case 'prim::awaitable': {
  16923. throw new python.Error('Not implemented.');
  16924. }
  16925. case 'prim::annotate': {
  16926. this.checkApplyNumInputs(apply, 2);
  16927. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16928. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  16929. if (!expr.type().isSubtypeOf(type)) {
  16930. throw new python.Error('Invalid expression type.');
  16931. }
  16932. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  16933. const none = this.graph.createNone();
  16934. none.output().setType(type);
  16935. this.graph.insertNode(none);
  16936. expr = none.output();
  16937. }
  16938. return new torch._C.SimpleValue(expr);
  16939. }
  16940. case 'prim::unchecked_cast': {
  16941. this.checkApplyNumInputs(apply, 2);
  16942. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16943. let v = this.emitExpr(apply.args[1]);
  16944. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  16945. v = this.graph.insertUncheckedCast(v, type);
  16946. }
  16947. return new torch._C.SimpleValue(v);
  16948. }
  16949. case 'prim::GetAttr': {
  16950. this.checkApplyNumInputsRange(apply, 2, 3);
  16951. const obj = this.emitSugaredExpr(apply.args[0], 1);
  16952. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  16953. throw new python.Error('Invalid argument.');
  16954. }
  16955. const name = apply.args[1].value;
  16956. if (apply.args.length === 2) {
  16957. return obj.attr(apply, this.method, name);
  16958. } else if (obj.hasAttr(apply, this.method, name)) {
  16959. return obj.attr(apply, this.method, name);
  16960. }
  16961. return this.emitSugaredExpr(apply.inputs()[2], 1);
  16962. }
  16963. case 'prim::Uninitialized': {
  16964. this.checkApplyNumInputs(apply, 1);
  16965. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16966. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  16967. return new torch._C.SimpleValue(out.output());
  16968. }
  16969. case 'prim::TupleConstruct': {
  16970. throw new python.Error('Not implemented.');
  16971. }
  16972. case 'prim::isinstance': {
  16973. this.checkApplyNumInputs(apply, 2);
  16974. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  16975. return new torch._C.SimpleValue(result.value());
  16976. }
  16977. case 'prim::tolist': {
  16978. const value = apply.func.value;
  16979. const operand = this.emitSugaredExpr(value, 1);
  16980. if (!type_hint) {
  16981. throw new python.Error('Expected type hint for result of tolist().');
  16982. }
  16983. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  16984. }
  16985. case 'prim::HasAttr': {
  16986. throw new python.Error('Not implemented.');
  16987. }
  16988. case 'prim::CreateObject': {
  16989. if (apply.args.length !== 1) {
  16990. throw python.Error('Only one argument to __new__ allowed.');
  16991. }
  16992. const arg = this.emitSugaredExpr(apply.args[0], 1);
  16993. if (arg instanceof torch._C.ClassValue === false) {
  16994. throw python.Error('Expected class value as argument to __new__.');
  16995. }
  16996. const class_arg = arg;
  16997. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  16998. createNode.setSourceRange(apply.range());
  16999. return new torch._C.SimpleValue(createNode.output());
  17000. }
  17001. case 'prim::range': {
  17002. const input_vals = this.getValues(apply.args, true);
  17003. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  17004. }
  17005. case 'prim::enumerate': {
  17006. throw new python.Error('Not implemented.');
  17007. }
  17008. case 'prim::zip': {
  17009. throw new python.Error('Not implemented.');
  17010. }
  17011. case 'prim::list': {
  17012. throw new python.Error('Not implemented.');
  17013. }
  17014. case 'prim::dict': {
  17015. throw new python.Error('Not implemented.');
  17016. }
  17017. case 'aten::index': {
  17018. throw new python.Error('Not implemented.');
  17019. }
  17020. default: {
  17021. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  17022. }
  17023. }
  17024. }
  17025. emitSimpleExpr(tree, type_hint) {
  17026. if (tree instanceof ast.Constant) {
  17027. if (tree.value === true) {
  17028. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  17029. } else if (tree.value === false) {
  17030. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  17031. } else if (tree.value === null) {
  17032. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  17033. } else if (typeof tree.value === 'string') {
  17034. return this.emitStringLiteral(tree);
  17035. }
  17036. return this.emitConst(tree);
  17037. } else if (tree instanceof ast.List) {
  17038. return this.emitListLiteral(tree, type_hint);
  17039. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  17040. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  17041. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Constant) {
  17042. const c = tree.operand;
  17043. if (c.type === 'complex') {
  17044. return this.emitConst(new ast.Constant(new builtins.complex(-c.value.real, -c.value.imag), 'complex'));
  17045. }
  17046. return this.emitConst(new ast.Constant(-c.value, c.type));
  17047. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  17048. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  17049. } else if (tree instanceof ast.BinOp) {
  17050. return this.emitBinaryOp(tree);
  17051. } else if (tree instanceof ast.Dict) {
  17052. return this.emitDictLiteral(tree, type_hint);
  17053. } else if (tree instanceof ast.Tuple) {
  17054. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  17055. return this.graph.insertNode(this.graph.createTuple(values)).output();
  17056. }
  17057. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  17058. }
  17059. getNodeKind(kind /*, ninputs */) {
  17060. if (kind instanceof ast.Add) {
  17061. return 'aten::add';
  17062. } else if (kind instanceof ast.Sub) {
  17063. return 'aten::sub';
  17064. } else if (kind instanceof ast.Mult) {
  17065. return 'aten::mul';
  17066. }
  17067. /*
  17068. case TK_UNARY_MINUS: return 'aten::neg';
  17069. case TK_POW: return 'aten::pow';
  17070. case '@': return 'aten::matmul';
  17071. case TK_STARRED: return 'prim::Starred';
  17072. case '/': return 'aten::div';
  17073. case '%': return 'aten::remainder';
  17074. case TK_NE: return 'aten::ne';
  17075. case TK_EQ: return 'aten::eq';
  17076. case '<': return 'aten::lt';
  17077. case '>': return 'aten::gt';
  17078. case TK_LE: return 'aten::le';
  17079. case TK_GE: return 'aten::ge';
  17080. case TK_AND: return 'aten::__and__';
  17081. case TK_OR: return 'aten::__or__';
  17082. case TK_IS: return 'aten::__is__';
  17083. case TK_ISNOT: return 'aten::__isnot__';
  17084. case TK_NOT: return 'aten::__not__';
  17085. case TK_FLOOR_DIV: return 'aten::floordiv';
  17086. case TK_LSHIFT: return 'aten::__lshift__';
  17087. case TK_RSHIFT: return 'aten::__rshift__';
  17088. case '&': return 'aten::__and__';
  17089. case '|': return 'aten::__or__';
  17090. case '^': return 'aten::__xor__';
  17091. case TK_IN: return 'aten::__contains__';
  17092. */
  17093. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17094. }
  17095. getOperatorOverload(kind /*, ninputs */) {
  17096. if (kind instanceof ast.Add) {
  17097. return '__add__';
  17098. } else if (kind instanceof ast.Sub) {
  17099. return '__sub__';
  17100. } else if (kind instanceof ast.Mult) {
  17101. return '__mul__';
  17102. }
  17103. /*
  17104. case TK_UNARY_MINUS: return "__neg__";
  17105. case '~': return "__invert__";
  17106. case TK_POW: return "__pow__";
  17107. case '/': return "__truediv__";
  17108. case '%': return "__mod__";
  17109. case TK_NE: return "__ne__";
  17110. case TK_EQ: return "__eq__";
  17111. case '<': return "__lt__";
  17112. case '>': return "__gt__";
  17113. case TK_LE: return "__le__";
  17114. case TK_GE: return "__ge__";
  17115. case '&': return "__and__";
  17116. case '|': return "__or__";
  17117. case '^': return "__xor__";
  17118. case TK_IN: return "__contains__";
  17119. case TK_LSHIFT: return "__lshift__";
  17120. case TK_RSHIFT: return "__rshift__";
  17121. */
  17122. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17123. }
  17124. emitBinaryOp(tree) {
  17125. const inputs = [tree.left, tree.right];
  17126. const kind = this.getNodeKind(tree.op, inputs.length);
  17127. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17128. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17129. if (tree.op instanceof ast.In) {
  17130. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17131. throw new python.Error('Not implemented.');
  17132. }
  17133. if (named_values[0].type() instanceof torch.TupleType &&
  17134. named_values[1].type() instanceof torch.TupleType &&
  17135. kind === 'aten::add') {
  17136. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17137. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17138. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17139. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17140. }
  17141. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17142. }
  17143. emitDictLiteral(dl, type_hint) {
  17144. const key_trees = dl.keys;
  17145. const value_trees = dl.values;
  17146. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17147. const keys = [];
  17148. const values = [];
  17149. let rhs_value_type = null;
  17150. for (let i = 0; i < key_trees.length; i++) {
  17151. keys.push(this.emitExpr(key_trees[i]));
  17152. values.push(this.emitExpr(value_trees[i]));
  17153. if (i === 0) {
  17154. rhs_value_type = values[i].type();
  17155. } else {
  17156. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17157. throw new python.Error('Dict keys must contain only a single type.');
  17158. }
  17159. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17160. }
  17161. }
  17162. const refined_type_hint = { _: type_hint };
  17163. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17164. const all_candidates = { _: [] };
  17165. const default_refined_type_hint_setter = () => {
  17166. if (keys.length === 0) {
  17167. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17168. } else {
  17169. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17170. if (rhs_value_type instanceof torch.UnionType) {
  17171. throw new python.Error('Dict values consist of heterogeneous types.');
  17172. }
  17173. }
  17174. };
  17175. if (type_hint) {
  17176. const type_match = (t) => t instanceof torch.DictType;
  17177. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17178. if (all_candidates._.length > 0 && values.length === 0) {
  17179. throw new python.Error('Cannot assign an empty dict.');
  17180. }
  17181. } else {
  17182. default_refined_type_hint_setter();
  17183. }
  17184. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17185. if (values.length > 0) {
  17186. if (all_candidates._.length > 0) {
  17187. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17188. }
  17189. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17190. throw new python.Error('Type annotation does not match key type.');
  17191. }
  17192. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17193. throw new python.Error('Type annotation does not match value type.');
  17194. }
  17195. }
  17196. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17197. if (annotated_union_type) {
  17198. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17199. n.output().setType(annotated_union_type);
  17200. result = n;
  17201. }
  17202. return result.output();
  17203. }
  17204. emitStringLiteral(c) {
  17205. return torch._C.insertConstant(this.graph, c.value, c.range());
  17206. }
  17207. emitConst(c) {
  17208. if (c.type === 'int') {
  17209. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17210. } else if (c.type === 'complex') {
  17211. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17212. } else if (c.type === 'float') {
  17213. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17214. }
  17215. throw new python.Error(`Unsupported constant type.`);
  17216. }
  17217. emitListLiteral(ll, type_hint) {
  17218. type_hint = type_hint || null;
  17219. const values = this.getValues(ll.elts, true);
  17220. if (values.length === 0 && type_hint === null) {
  17221. throw new python.Error('Not implemented.');
  17222. }
  17223. let inferred_elem_type = torch.TensorType.get();
  17224. const refined_type_hint = { _: type_hint };
  17225. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17226. const all_candidates = { _: [] };
  17227. if (refined_type_hint._) {
  17228. const do_if_type_match = () => {
  17229. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17230. };
  17231. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17232. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17233. if (all_candidates._.length > 0 && values.len === 0) {
  17234. throw new python.Error('Cannot assign an empty list.');
  17235. }
  17236. }
  17237. if (values.length !== 0) {
  17238. const types = values.map((v) => v.type());
  17239. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17240. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17241. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17242. throw new python.Error('Not implemented.');
  17243. }
  17244. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17245. throw new python.Error('Not implemented.');
  17246. }
  17247. if (all_candidates._.length !== 0) {
  17248. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17249. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17250. }
  17251. if (!refined_type_hint._) {
  17252. inferred_elem_type = unified_elem_type;
  17253. }
  17254. }
  17255. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17256. if (annotated_union_type) {
  17257. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17258. n.output().setType(annotated_union_type);
  17259. result = n;
  17260. }
  17261. return result.output();
  17262. }
  17263. insertRefinements(loc, ref) {
  17264. for (const r of ref.activeRefinements()) {
  17265. const v = this.environment_stack.getVar(r.identifier(), loc);
  17266. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17267. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17268. }
  17269. }
  17270. shouldDeriveSetStateType(def, schema) {
  17271. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17272. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17273. if (!shouldInfer) {
  17274. return false;
  17275. }
  17276. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17277. throw new python.Error(`Invalid '__setstate' method.`);
  17278. }
  17279. return true;
  17280. }
  17281. checkApplyNumInputs(apply, expected_inputs) {
  17282. if (apply.args.length !== expected_inputs) {
  17283. throw new python.Error('Invalid number of arguments.');
  17284. }
  17285. if (apply.keywords.length > 0) {
  17286. throw new python.Error('Invalid number of keyword arguments.');
  17287. }
  17288. }
  17289. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17290. const position_arg_size = apply.args.length;
  17291. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17292. throw new python.Error('Invalid number of arguments.');
  17293. }
  17294. if (apply.keywords.length > 0) {
  17295. throw new python.Error('Invalid number of keyword arguments.');
  17296. }
  17297. }
  17298. validateAssignLhsExpr(lhs /*, r */) {
  17299. let num_normal_assign = 0;
  17300. let num_starred = 0;
  17301. for (const assignee of lhs) {
  17302. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17303. num_normal_assign++;
  17304. } else if (assignee instanceof ast.Starred) {
  17305. num_starred++;
  17306. } else {
  17307. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17308. }
  17309. }
  17310. if (num_starred > 1) {
  17311. throw new python.Error('Only one starred expression is allowed.');
  17312. }
  17313. if (num_starred > 0 && num_normal_assign === 0) {
  17314. throw new python.Error('Invalid starred expression.');
  17315. }
  17316. return num_starred;
  17317. }
  17318. createTempName(prefix) {
  17319. return `${prefix}${this._temp_name_count++}`;
  17320. }
  17321. handleMaybeNoReturn(def, block) {
  17322. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17323. if (this.exit_blocks.size === 0) {
  17324. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17325. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17326. }
  17327. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17328. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17329. b.dispose();
  17330. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17331. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17332. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17333. }
  17334. }
  17335. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17336. let adj_index = input_index;
  17337. const tuple_len = tuple_type.elements().length;
  17338. if (input_index < 0) {
  17339. adj_index = tuple_len + input_index;
  17340. }
  17341. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17342. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17343. }
  17344. return adj_index;
  17345. }
  17346. emitTupleIndex(loc, tuple_val, idx_val) {
  17347. const tuple_typ = tuple_val.type();
  17348. const elems = tuple_typ.elements();
  17349. let output_type = null;
  17350. if (idx_val.type() !== torch.IntType.get()) {
  17351. throw new python.Error('Tuple index must be an integer.');
  17352. }
  17353. const idx = torch._C.toIValue(idx_val);
  17354. if (idx) {
  17355. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17356. output_type = elems[adj_index];
  17357. } else {
  17358. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17359. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17360. }
  17361. [output_type] = elems;
  17362. }
  17363. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17364. }
  17365. getSliceInd(idx_val, loc) {
  17366. const ivalue = torch._C.toIValue(idx_val);
  17367. if (ivalue && ivalue.isInt()) {
  17368. return ivalue.toInt();
  17369. }
  17370. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17371. }
  17372. emitTupleSlice(loc, tuple_val, tuple_args) {
  17373. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17374. const tuple_len = tuple_type.elements().length;
  17375. const [beg_val, end_val, step] = tuple_args;
  17376. let step_size = 1;
  17377. if (step) {
  17378. const val = torch._C.toIValue(step.value(this.graph));
  17379. torch._C.TORCH_CHECK(val.isInt());
  17380. step_size = val.toInt();
  17381. }
  17382. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17383. if (beg_val) {
  17384. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17385. }
  17386. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17387. if (end_val) {
  17388. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17389. }
  17390. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17391. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17392. }
  17393. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17394. const args = [];
  17395. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17396. if (dim) {
  17397. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17398. args.emplace_back(new torch._C.NamedValue(dim));
  17399. } else {
  17400. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17401. }
  17402. if (sliceable.type() instanceof torch.TupleType) {
  17403. const tuple_args = [];
  17404. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17405. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17406. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17407. return this.emitTupleSlice(loc, args[0], tuple_args);
  17408. }
  17409. if (!step) {
  17410. step = this.graph.insertConstant(1, loc);
  17411. }
  17412. args.push(new torch._C.NamedValue(loc, 'start', start));
  17413. args.push(new torch._C.NamedValue(loc, 'end', end));
  17414. args.push(new torch._C.NamedValue(loc, 'step', step));
  17415. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17416. }
  17417. emitSlice(loc, input, dim, slice) {
  17418. let start = null;
  17419. let end = null;
  17420. let step = null;
  17421. if (slice.lower) {
  17422. start = this.emitExpr(slice.lower);
  17423. }
  17424. if (slice.upper) {
  17425. end = this.emitExpr(slice.upper);
  17426. }
  17427. if (slice.step) {
  17428. step = this.emitExpr(slice.step);
  17429. }
  17430. return this.emitSliceOp(loc, input, dim, start, end, step);
  17431. }
  17432. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17433. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17434. const slice_exp = subscript_exprs;
  17435. let maybe_dim = null;
  17436. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17437. maybe_dim = this.graph.insertConstant(0, loc);
  17438. }
  17439. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17440. }
  17441. emitSubscript(subscript, type_hint) {
  17442. type_hint = type_hint === undefined ? null : type_hint;
  17443. const sv = this.emitSugaredExpr(subscript.value, 1);
  17444. const subscript_exprs = subscript.slice;
  17445. const range = subscript.range();
  17446. const val_range = subscript.value;
  17447. if (subscript_exprs instanceof ast.Tuple) {
  17448. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17449. }
  17450. if (subscript_exprs instanceof ast.Slice) {
  17451. if (sv.kind() === 'module') {
  17452. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17453. const [slice] = subscript_exprs;
  17454. const tuple_args = [];
  17455. if (slice.start().present()) {
  17456. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17457. tuple_args.push(begin);
  17458. } else {
  17459. tuple_args.push(null);
  17460. }
  17461. if (slice.end().present()) {
  17462. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17463. tuple_args.push(end);
  17464. } else {
  17465. tuple_args.push(null);
  17466. }
  17467. if (slice.step().present()) {
  17468. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17469. tuple_args.push(step);
  17470. } else {
  17471. tuple_args.push(null);
  17472. }
  17473. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17474. return new torch._C.SimpleValue(tupleSliceValue);
  17475. }
  17476. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17477. }
  17478. const sliceable = sv.asValue(val_range, this.method);
  17479. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17480. if (subscript_sv instanceof torch._C.SliceValue) {
  17481. const slice_value = subscript_sv;
  17482. let dim = null;
  17483. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17484. dim = this.method.graph().insertConstant(0, val_range);
  17485. }
  17486. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17487. return new torch._C.SimpleValue(sliced);
  17488. }
  17489. const idx = subscript_sv.asValue(val_range, this.method);
  17490. if (sliceable.type() instanceof torch.TupleType) {
  17491. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17492. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17493. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17494. }
  17495. return sv.getitem(range, this.method, idx, type_hint);
  17496. }
  17497. });
  17498. this.registerType('torch.jit.CompilationUnit', class {
  17499. constructor() {
  17500. this._functions = new Map();
  17501. this._classes = new Map();
  17502. }
  17503. register_type(namedType) {
  17504. this._classes.set(namedType.annotation_str, namedType);
  17505. }
  17506. register_function(fn) {
  17507. const name = fn.qualname().qualifiedName();
  17508. torch._C.TORCH_CHECK(!this._functions.has(name));
  17509. this._functions.set(name, fn);
  17510. return fn;
  17511. }
  17512. define(...args) {
  17513. if (Array.isArray(args[1])) {
  17514. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17515. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17516. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17517. const functions = [];
  17518. const function_table = new Map();
  17519. const record_function = (fn) => {
  17520. function_table.set(fn.name(), fn);
  17521. functions.push(fn);
  17522. this.register_function(fn);
  17523. };
  17524. for (let i = 0; i < properties.length; i++) {
  17525. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17526. const getter_fn = property_fns.getGetter();
  17527. const setter_fn = property_fns.getSetter();
  17528. record_function(getter_fn);
  17529. if (setter_fn) {
  17530. record_function(setter_fn);
  17531. }
  17532. }
  17533. for (let i = 0; i < definitions.length; i++) {
  17534. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17535. record_function(fn);
  17536. }
  17537. for (const [name, fn] of function_table) {
  17538. if (name === '__init__') {
  17539. fn.ensure_defined();
  17540. }
  17541. }
  17542. for (const fn of functions) {
  17543. fn.ensure_defined();
  17544. }
  17545. return functions;
  17546. } else if (args[1] instanceof ast.FunctionDef) {
  17547. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17548. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17549. const creator = (method) => {
  17550. return new torch._C.to_ir(def, _resolver, self, method);
  17551. };
  17552. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17553. if (shouldMangle && this.find_function(name)) {
  17554. name = this.mangle(name);
  17555. }
  17556. const graph = new torch.Graph();
  17557. graph.set_op_version(operator_set_version);
  17558. const fn = new torch._C.GraphFunction(name, graph, creator);
  17559. fn.__ast__ = def; // remove
  17560. if (self) {
  17561. if (type === 'hook') {
  17562. self.getClassType().addForwardHook(fn);
  17563. } else if (type === 'prehook') {
  17564. self.getClassType().addPreHook(fn);
  17565. } else {
  17566. self.getClassType().addMethod(fn);
  17567. }
  17568. }
  17569. return fn;
  17570. }
  17571. throw new python.Error('Invalid arguments.');
  17572. }
  17573. get_type(name) {
  17574. return this._classes.get(name.qualifiedName());
  17575. }
  17576. get_class(name) {
  17577. return this.get_type(name);
  17578. }
  17579. find_function(name) {
  17580. const key = name.qualifiedName();
  17581. return this._functions.get(key);
  17582. }
  17583. });
  17584. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17585. const ctrl = new torch._C.ControlFlowLoadStores();
  17586. ctrl.run(graph);
  17587. const exit_vars = new torch._C.LoopContinuations();
  17588. exit_vars.run(graph);
  17589. torch._C.InlineLoopCondition(graph);
  17590. const erase_loads_stores = new torch._C.EraseLoadStores();
  17591. erase_loads_stores.run(graph);
  17592. torch._C.TransformExits(graph);
  17593. });
  17594. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17595. /*
  17596. LoopView loop(n);
  17597. if (loop.loopType() != LoopView::ModifiedLoop) {
  17598. return;
  17599. }
  17600. const g = n.owningGraph();
  17601. WithInsertPoint node_insert(n);
  17602. const zero = g.insertConstant(0);
  17603. const one = g.insertConstant(1);
  17604. const max_trip_count = loop.maxTripCount();
  17605. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17606. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17607. const inp_condition = toIValue(loop.inputCond());
  17608. if (inp_condition == null || inp_condition.toBool() == false) {
  17609. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17610. }
  17611. loop.replaceInputCondition(condition);
  17612. n.addOutput().setType(IntType::get());
  17613. WithInsertPoint loop_insert(loop.bodyBlock());
  17614. n.addInput(zero);
  17615. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17616. // unset unique name for jitter, its replacement does not have a name
  17617. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17618. const inc_iter = g.insert(aten::add, {new_iter, one});
  17619. loop.bodyBlock().registerOutput(inc_iter);
  17620. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17621. const loop_continue = loop.nextCond();
  17622. const new_condition =
  17623. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17624. loop.bodyBlock().eraseOutput(0);
  17625. loop.bodyBlock().insertOutput(0, new_condition);
  17626. */
  17627. });
  17628. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17629. for (const n of block.nodes()) {
  17630. for (const b of n.blocks()) {
  17631. torch._C.canonicalizeModifiedLoops(b);
  17632. }
  17633. if (n.kind() === 'prim::Loop') {
  17634. torch._C.canonicalizeModifiedLoop(n);
  17635. }
  17636. }
  17637. });
  17638. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17639. torch._C.canonicalizeModifiedLoops(graph.block());
  17640. });
  17641. this.registerType('torch._C.MiniEnvironment', class {
  17642. constructor(b, next) {
  17643. this.next = next || null;
  17644. this.table = new Map();
  17645. }
  17646. setVar(name, value) {
  17647. this.table.set(name, value);
  17648. }
  17649. definedVariables() {
  17650. const result = Array.from(this.table.keys());
  17651. return result.sort();
  17652. }
  17653. findInThisFrame(name) {
  17654. if (this.table.has(name)) {
  17655. return this.table.get(name);
  17656. }
  17657. return null;
  17658. }
  17659. findInAnyFrame(name) {
  17660. /* eslint-disable consistent-this */
  17661. const self = this;
  17662. /* eslint-enable consistent-this */
  17663. for (let runner = self; runner; runner = runner.next) {
  17664. const r = runner.findInThisFrame(name);
  17665. if (r) {
  17666. return r;
  17667. }
  17668. }
  17669. return null;
  17670. }
  17671. });
  17672. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17673. });
  17674. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17675. });
  17676. this.registerType('torch._C.ControlFlowLoadStores', class {
  17677. constructor() {
  17678. this.environment_stack = null;
  17679. }
  17680. pushFrame(b) {
  17681. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17682. }
  17683. popFrame() {
  17684. const old_frame = this.environment_stack;
  17685. this.environment_stack = this.environment_stack.next;
  17686. return old_frame;
  17687. }
  17688. addBlockInput(b, type, name) {
  17689. const g = b.owningGraph();
  17690. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17691. }
  17692. addBlockOutput(exit_block, type, name) {
  17693. const insert = new torch._C.WithInsertPoint(exit_block);
  17694. const g = exit_block.owningGraph();
  17695. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17696. exit_block.registerOutput(block_exit);
  17697. insert.dispose();
  17698. }
  17699. addNodeOutput(n, type, name) {
  17700. const out = n.addOutput().setType(type);
  17701. if (torch._C.meaningfulName(name)) {
  17702. out.setDebugName(name);
  17703. }
  17704. const g = n.owningGraph();
  17705. g.createStore(name, out).insertAfter(n);
  17706. }
  17707. addNodeInput(n, type, name) {
  17708. const g = n.owningGraph();
  17709. const inp = g.createLoad(name, type).insertBefore(n).output();
  17710. n.addInput(inp);
  17711. }
  17712. addIfLoadStores(n) {
  17713. const [true_block, false_block] = n.blocks();
  17714. const true_vars = this.addControlFlowLoadStores(true_block);
  17715. const false_vars = this.addControlFlowLoadStores(false_block);
  17716. const mutated_variables = new Set();
  17717. for (const v of true_vars.definedVariables()) {
  17718. if (false_vars.findInAnyFrame(v)) {
  17719. mutated_variables.add(v);
  17720. }
  17721. }
  17722. for (const v of false_vars.definedVariables()) {
  17723. if (true_vars.findInAnyFrame(v)) {
  17724. mutated_variables.add(v);
  17725. }
  17726. }
  17727. for (const x of mutated_variables) {
  17728. const true_type = true_vars.findInAnyFrame(x);
  17729. const false_type = false_vars.findInAnyFrame(x);
  17730. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17731. this.addBlockOutput(true_block, true_type, x);
  17732. this.addBlockOutput(false_block, false_type, x);
  17733. this.addNodeOutput(n, unified, x);
  17734. }
  17735. }
  17736. addLoopLoadStores(n) {
  17737. const [body_block] = n.blocks();
  17738. const loop_vars = this.addControlFlowLoadStores(body_block);
  17739. for (const name of loop_vars.definedVariables()) {
  17740. const parent_type = this.environment_stack.findInAnyFrame(name);
  17741. if (!parent_type) {
  17742. continue;
  17743. }
  17744. const block_type = loop_vars.findInThisFrame(name);
  17745. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17746. this.addNodeInput(n, parent_type, name);
  17747. this.addBlockInput(body_block, unified_type, name);
  17748. this.addBlockOutput(body_block, block_type, name);
  17749. this.addNodeOutput(n, unified_type, name);
  17750. }
  17751. }
  17752. addControlFlowLoadStores(block) {
  17753. this.pushFrame(block);
  17754. for (const n of block.nodes()) {
  17755. switch (n.kind()) {
  17756. case 'prim::If': {
  17757. this.addIfLoadStores(n);
  17758. break;
  17759. }
  17760. case 'prim::Loop': {
  17761. this.addLoopLoadStores(n);
  17762. break;
  17763. }
  17764. case 'prim::Closure': {
  17765. for (const b of n.blocks()) {
  17766. this.addControlFlowLoadStores(b);
  17767. }
  17768. break;
  17769. }
  17770. case 'prim::Store': {
  17771. this.environment_stack.setVar(n.s('name'), n.input().type());
  17772. break;
  17773. }
  17774. case 'prim::ComprehensionScope': {
  17775. this.addControlFlowLoadStores(n.blocks().at(0));
  17776. break;
  17777. }
  17778. default: {
  17779. break;
  17780. }
  17781. }
  17782. }
  17783. return this.popFrame();
  17784. }
  17785. run(graph) {
  17786. this.addControlFlowLoadStores(graph.block());
  17787. }
  17788. });
  17789. this.registerType('torch._C.LoopContinuations', class {
  17790. constructor() {
  17791. this._graph = null;
  17792. this._false_val = null;
  17793. this._curr_loop = null;
  17794. }
  17795. assignExitContinuations(block) {
  17796. for (const n of block.nodes()) {
  17797. switch (n.kind()) {
  17798. case 'prim::If': {
  17799. this.assignExitContinuations(n.blocks().at(0));
  17800. this.assignExitContinuations(n.blocks().at(1));
  17801. break;
  17802. }
  17803. case 'prim::Closure': {
  17804. const closure_block = new torch._C.LoopContinuations();
  17805. closure_block.run(n.blocks().at(0));
  17806. break;
  17807. }
  17808. case 'prim::Loop': {
  17809. const prev_loop = this._curr_loop;
  17810. this._curr_loop = n;
  17811. this.assignExitContinuations(n.blocks().at(0));
  17812. this._curr_loop = prev_loop;
  17813. break;
  17814. }
  17815. case 'prim::ContinueStmt': {
  17816. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17817. const header_block = loop_continuation.addBlock();
  17818. const [, pre_header] = this._curr_loop.blocks();
  17819. header_block.cloneFrom(pre_header, (v) => v);
  17820. this.InlineBlockBeforeNode(n, header_block);
  17821. loop_continuation.addInput(header_block.outputs()[0]);
  17822. loop_continuation.eraseBlock(0);
  17823. this.addLoopCarriedOutputs(loop_continuation);
  17824. n.destroy();
  17825. break;
  17826. }
  17827. case 'prim::BreakStmt': {
  17828. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17829. loop_exit.addInput(this._false_val);
  17830. this.addLoopCarriedOutputs(loop_exit);
  17831. n.destroy();
  17832. break;
  17833. }
  17834. default: {
  17835. break;
  17836. }
  17837. }
  17838. }
  17839. }
  17840. run(...args) {
  17841. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17842. const [graph] = args;
  17843. this.run(graph.block());
  17844. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17845. const [b] = args;
  17846. {
  17847. this._graph = b.owningGraph();
  17848. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17849. this._false_val = this._graph.insertConstant(false);
  17850. guard.dispose();
  17851. }
  17852. this.assignExitContinuations(b);
  17853. } else {
  17854. throw new python.Error('Not implemented.');
  17855. }
  17856. }
  17857. });
  17858. this.registerType('torch._C.LoopView', class {
  17859. constructor(node) {
  17860. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17861. this._node = node;
  17862. }
  17863. bodyBlock() {
  17864. return this._node.blocks().at(0);
  17865. }
  17866. nextCond() {
  17867. return this.bodyBlock().outputs()[0];
  17868. }
  17869. carriedOutputs() {
  17870. return this._node.outputs();
  17871. }
  17872. bodyCarriedInputs() {
  17873. return this.bodyBlock().inputs().slice(1);
  17874. }
  17875. bodyCarriedOutputs() {
  17876. return this.bodyBlock().outputs().slice(1);
  17877. }
  17878. });
  17879. this.registerType('torch._C.WithLoopStatus', class {
  17880. constructor(to_ir, new_status) {
  17881. this._to_ir = to_ir;
  17882. this._prev = this._to_ir._loop_status;
  17883. this._to_ir._loop_status = new_status;
  17884. }
  17885. dispose() {
  17886. this._to_ir._loop_status = this._prev;
  17887. }
  17888. });
  17889. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17890. for (const block_node of block.nodes()) {
  17891. block_node.moveBefore(before_node);
  17892. }
  17893. });
  17894. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  17895. if (args.length === 1 && args[0] instanceof torch.Block) {
  17896. const [block] = args;
  17897. for (const n of block.nodes()) {
  17898. for (const b of n.blocks()) {
  17899. torch._C.inlineLoopCondition(b);
  17900. }
  17901. if (n.kind() === 'prim::Loop') {
  17902. torch._C.inlineLoopCondition(n);
  17903. }
  17904. }
  17905. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  17906. const [n] = args;
  17907. const [body_block, pre_header] = n.blocks();
  17908. const temp_block = n.addBlock();
  17909. temp_block.cloneFrom(pre_header, (v) => v);
  17910. torch._C.InlineBlockBeforeNode(n, temp_block);
  17911. n.insertInput(1, temp_block.outputs()[0]);
  17912. n.eraseBlock(2);
  17913. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  17914. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  17915. n.eraseBlock(1);
  17916. } else {
  17917. throw new python.Error('Not implemented.');
  17918. }
  17919. });
  17920. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  17921. torch._C.inlineLoopCondition(graph.block());
  17922. });
  17923. this.registerType('torch._C.EraseLoadStores', class {
  17924. pushFrame(b) {
  17925. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  17926. }
  17927. popFrame() {
  17928. const old_frame = this.environment_stack;
  17929. this.environment_stack = this.environment_stack.next;
  17930. return old_frame;
  17931. }
  17932. eraseBlockLoadStores(block) {
  17933. this.pushFrame(block);
  17934. for (const n of block.nodes()) {
  17935. switch (n.kind()) {
  17936. case 'prim::Store': {
  17937. this.environment_stack.setVar(n.s('name'), n.input());
  17938. n.destroy();
  17939. break;
  17940. }
  17941. case 'prim::Load': {
  17942. const name = n.s('name');
  17943. const value = this.environment_stack.findInAnyFrame(name);
  17944. torch._C.TORCH_INTERNAL_ASSERT(value);
  17945. n.output().replaceAllUsesWith(value);
  17946. n.destroy();
  17947. break;
  17948. }
  17949. case 'prim::ComprehensionScope': {
  17950. const [body] = n.blocks();
  17951. this.eraseBlockLoadStores(body);
  17952. for (const body_node of body.nodes()) {
  17953. body_node.moveBefore(n);
  17954. }
  17955. n.destroy();
  17956. break;
  17957. }
  17958. default: {
  17959. for (const b of n.blocks()) {
  17960. this.eraseBlockLoadStores(b);
  17961. }
  17962. break;
  17963. }
  17964. }
  17965. }
  17966. this.popFrame();
  17967. }
  17968. run(graph) {
  17969. this.eraseBlockLoadStores(graph.block());
  17970. }
  17971. });
  17972. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  17973. });
  17974. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  17975. });
  17976. this.registerType('torch._C.ExitPair', class {
  17977. constructor(exit_v, exit_val_ref) {
  17978. const exit_vals = [];
  17979. for (const v of exit_val_ref) {
  17980. exit_vals.push(v);
  17981. }
  17982. if (exit_v.type() !== torch.BoolType.get()) {
  17983. throw new python.Error('Invalid exit value type.');
  17984. }
  17985. this.first = exit_v;
  17986. this.second = exit_vals;
  17987. }
  17988. hasExited() {
  17989. return this.first;
  17990. }
  17991. exitValues() {
  17992. return this.second;
  17993. }
  17994. });
  17995. this.registerType('torch._C.ExitTransformer', class {
  17996. constructor(graph) {
  17997. this._graph = graph;
  17998. this._target_block = null;
  17999. this._unit_values = new Map();
  18000. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  18001. this._true_val = this._graph.insertConstant(true);
  18002. this._false_val = this._graph.insertConstant(false);
  18003. this._throws_val = this.getUnitValue(torch.BoolType.get());
  18004. guard.dispose();
  18005. }
  18006. getUnitValue(type) {
  18007. const maybe_val = this._unit_values.get(type);
  18008. if (maybe_val) {
  18009. return maybe_val;
  18010. }
  18011. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  18012. this._unit_values.set(type, unit);
  18013. return unit;
  18014. }
  18015. transformReturnStmts() {
  18016. this._current_exit_kind = 'prim::ReturnStmt';
  18017. this.transformExits(this._graph.block());
  18018. }
  18019. transformLoopContinuations() {
  18020. this._current_exit_kind = 'prim::LoopContinuation';
  18021. this.transformExits(this._graph.block());
  18022. }
  18023. destroyNodeAfterExit(n) {
  18024. for (const output of n.outputs()) {
  18025. if (output.uses().length > 0) {
  18026. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  18027. }
  18028. }
  18029. n.destroy();
  18030. }
  18031. deleteAfterExitNodes(block, iter) {
  18032. const nodes = block.nodes();
  18033. if (iter === nodes.end()) {
  18034. return;
  18035. }
  18036. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  18037. for (const it of Array.from(nodes).reverse()) {
  18038. if (it === iter) {
  18039. break;
  18040. }
  18041. if (it !== block.return_node()) {
  18042. this.destroyNodeAfterExit(it);
  18043. }
  18044. }
  18045. this.destroyNodeAfterExit(iter);
  18046. insert.dispose();
  18047. }
  18048. updateTargetBlock(block) {
  18049. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  18050. this._target_block = block;
  18051. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  18052. this._target_block = block;
  18053. }
  18054. }
  18055. transformLoop(node) {
  18056. const loop = new torch._C.LoopView(node);
  18057. const body = loop.bodyBlock();
  18058. const exit_pair = this.transformExits(body);
  18059. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  18060. return this.constructWontExitPair();
  18061. }
  18062. const insert = new torch._C.WithInsertPoint(body);
  18063. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  18064. new_if.addInput(exit_pair.hasExited());
  18065. new_if.addBlock().registerOutput(this._false_val);
  18066. new_if.addBlock().registerOutput(loop.nextCond());
  18067. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  18068. loop.bodyBlock().eraseOutput(0);
  18069. loop.bodyBlock().insertOutput(0, new_condition);
  18070. node.addInput(this._false_val);
  18071. body.addInput().setType(torch.BoolType.get());
  18072. body.registerOutput(exit_pair.hasExited());
  18073. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  18074. for (const exit_value of exit_pair.exitValues()) {
  18075. const typ = exit_value.type();
  18076. node.addInput(this.getUnitValue(typ));
  18077. node.addOutput().setType(typ);
  18078. body.addInput().setType(typ);
  18079. body.registerOutput(exit_value);
  18080. }
  18081. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  18082. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  18083. insert.dispose();
  18084. return result;
  18085. }
  18086. calcIfExitStatus(then_status, else_status) {
  18087. if (then_status === 'THROWS') {
  18088. return else_status;
  18089. } else if (else_status === 'THROWS') {
  18090. return then_status;
  18091. }
  18092. if (then_status === 'WONT' && else_status === 'WONT') {
  18093. return 'WONT';
  18094. }
  18095. if (then_status === 'WILL' && else_status === 'WILL') {
  18096. return 'WILL';
  18097. }
  18098. return 'MIGHT';
  18099. }
  18100. transformIf(node) {
  18101. const [then_block, else_block] = node.blocks();
  18102. let then_pair = this.transformExits(then_block);
  18103. let else_pair = this.transformExits(else_block);
  18104. const then_status = this.getExitStatus(then_pair);
  18105. const else_status = this.getExitStatus(else_pair);
  18106. const if_status = this.calcIfExitStatus(then_status, else_status);
  18107. if (if_status === 'THROWS') {
  18108. return this.constructThrowsExitPair();
  18109. }
  18110. if (if_status === 'WONT') {
  18111. return this.constructWontExitPair();
  18112. }
  18113. if (then_status === 'WONT' || then_status === 'THROWS') {
  18114. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18115. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18116. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18117. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18118. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18119. }
  18120. let has_exited = null;
  18121. if (if_status === 'WILL') {
  18122. has_exited = this._true_val;
  18123. } else {
  18124. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18125. has_exited = node.outputs().at(node.outputs().length - 1);
  18126. }
  18127. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18128. const num_exit_vals = then_pair.exitValues().size();
  18129. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18130. return new torch._C.ExitPair(has_exited, exit_vals);
  18131. }
  18132. transformExits(block) {
  18133. const prev_target_block = this._target_block;
  18134. this.updateTargetBlock(block);
  18135. let exit_pair = this.constructWontExitPair();
  18136. for (const node of block.nodes()) {
  18137. const it = node.next;
  18138. switch (node.kind()) {
  18139. case 'prim::RaiseException': {
  18140. exit_pair = this.constructThrowsExitPair();
  18141. break;
  18142. }
  18143. case 'prim::ReturnStmt':
  18144. case 'prim::LoopContinuation': {
  18145. if (node.kind() === this._current_exit_kind) {
  18146. exit_pair = this.constructWillExitPair(node.inputs());
  18147. node.destroy();
  18148. }
  18149. break;
  18150. }
  18151. case 'prim::If': {
  18152. exit_pair = this.transformIf(node);
  18153. break;
  18154. }
  18155. case 'prim::With': {
  18156. exit_pair = this.transformWith(node);
  18157. break;
  18158. }
  18159. case 'prim::Closure': {
  18160. this.transformExits(node.blocks().at(0));
  18161. break;
  18162. }
  18163. case 'prim::Loop': {
  18164. exit_pair = this.transformLoop(node);
  18165. break;
  18166. }
  18167. default: {
  18168. break;
  18169. }
  18170. }
  18171. const status = this.getExitStatus(exit_pair);
  18172. if (status === 'WILL' || status === 'THROWS') {
  18173. this.deleteAfterExitNodes(block, it);
  18174. break;
  18175. }
  18176. if (status === 'MIGHT') {
  18177. throw new python.Error('Not implemented.');
  18178. // const nodes = block.nodes();
  18179. // if (node === nodes[nodes.length - 1]) {
  18180. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18181. // }
  18182. // break;
  18183. }
  18184. }
  18185. if (this._target_block === block) {
  18186. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18187. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18188. new_if.addBlock();
  18189. new_if.addBlock();
  18190. new_if.addInput(exit_pair.hasExited());
  18191. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18192. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18193. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18194. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18195. }
  18196. exit_pair = this.constructWontExitPair();
  18197. }
  18198. this._target_block = prev_target_block;
  18199. return exit_pair;
  18200. }
  18201. constructThrowsExitPair() {
  18202. return new torch._C.ExitPair(this._throws_val, []);
  18203. }
  18204. constructWontExitPair() {
  18205. return new torch._C.ExitPair(this._false_val, []);
  18206. }
  18207. constructWillExitPair(exit_val_ref) {
  18208. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18209. }
  18210. getExitStatus(exit_pair) {
  18211. const exit_v = exit_pair.hasExited();
  18212. if (exit_v === this._true_val) {
  18213. return 'WILL';
  18214. } else if (exit_v === this._false_val) {
  18215. return 'WONT';
  18216. } else if (exit_v === this._throws_val) {
  18217. return 'THROWS';
  18218. }
  18219. return 'MIGHT';
  18220. }
  18221. static owningNodeKind(block) {
  18222. if (block.owningNode()) {
  18223. return block.owningNode().kind();
  18224. }
  18225. return null;
  18226. }
  18227. static isGraphOrClosureBlock(block) {
  18228. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18229. }
  18230. static removeOutputs(b) {
  18231. while (b.outputs().length > 0) {
  18232. b.eraseOutput(0);
  18233. }
  18234. }
  18235. static registerBlockOutputs(b, outs) {
  18236. for (const out of outs) {
  18237. b.registerOutput(out);
  18238. }
  18239. }
  18240. static replaceBlockOutputs(b, outs) {
  18241. torch._C.ExitTransformer.removeOutputs(b);
  18242. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18243. }
  18244. });
  18245. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18246. });
  18247. this.registerFunction('torch._C.TransformExits', (graph) => {
  18248. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18249. const e_loop = new torch._C.ExitTransformer(graph);
  18250. e_loop.transformLoopContinuations();
  18251. const e_ret = new torch._C.ExitTransformer(graph);
  18252. e_ret.transformReturnStmts();
  18253. torch._C.inlineConsecutiveIfs(graph.block());
  18254. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18255. });
  18256. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18257. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18258. const args = iter.inputs();
  18259. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18260. newSub.replaceInput(0, args[1]);
  18261. newSub.replaceInput(1, args[0]);
  18262. iter.destroyCurrent();
  18263. return true;
  18264. }
  18265. return false;
  18266. });
  18267. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18268. });
  18269. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18270. const args = iter.inputs();
  18271. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18272. if (iter.kind() === 'aten::__is__') {
  18273. iter.replaceWithNewSymbol('aten::eq');
  18274. iter.destroyCurrent();
  18275. return true;
  18276. }
  18277. if (iter.kind() === 'aten::__isnot__') {
  18278. iter.replaceWithNewSymbol('aten::ne');
  18279. iter.destroyCurrent();
  18280. return true;
  18281. }
  18282. }
  18283. return false;
  18284. });
  18285. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18286. for (const it of block.nodes()) {
  18287. for (const sub of it.blocks()) {
  18288. torch._C.NormalizeOps(sub);
  18289. }
  18290. if (torch._C.normalizeRSub(it)) {
  18291. continue;
  18292. }
  18293. if (torch._C.normalizeOpAliases(it)) {
  18294. continue;
  18295. }
  18296. if (torch._C.normalizeIsBool(it)) {
  18297. continue;
  18298. }
  18299. }
  18300. });
  18301. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18302. return false;
  18303. });
  18304. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18305. /*
  18306. torch._C.liftClosures(to_clean);
  18307. torch._C.inlineForkedClosures(to_clean);
  18308. */
  18309. if (torch._C.getInlineEverythingMode()) {
  18310. torch._C.Inline(to_clean);
  18311. }
  18312. /*
  18313. torch._C.eraseListLiterals(to_clean);
  18314. */
  18315. torch._C.LowerSimpleTuples(to_clean);
  18316. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18317. torch._C.ConstantPooling(to_clean);
  18318. /*
  18319. torch._C.CanonicalizeOutputs(to_clean);
  18320. torch._C.AnnotateWarns(to_clean);
  18321. */
  18322. });
  18323. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18324. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18325. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18326. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18327. constructor(cpp_module) {
  18328. super();
  18329. this._initializing = true;
  18330. this._c = cpp_module;
  18331. }
  18332. static _construct(cpp_module, init_fn) {
  18333. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18334. init_fn(script_module);
  18335. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18336. return script_module;
  18337. }
  18338. static _finalize_scriptmodule(script_module) {
  18339. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18340. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18341. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18342. script_module._initializing = false;
  18343. }
  18344. get graph() {
  18345. // return this._c._get_method('forward').graph;
  18346. return this._c.graph;
  18347. }
  18348. get code_with_constants() {
  18349. // return this.forward.code_with_constants;
  18350. return this._c.code_with_constants;
  18351. }
  18352. __setattr__(name, value) {
  18353. if (this._initializing) {
  18354. super.__setattr__(name, value);
  18355. } else if (this._modules.has(name)) {
  18356. this._modules.set(name, value);
  18357. } else if (this._c.hasattr(name)) {
  18358. this._c.setattr(name, value);
  18359. } else {
  18360. //
  18361. }
  18362. }
  18363. __getattr__(name) {
  18364. if (this._initializing) {
  18365. return super.__getattr__(name);
  18366. }
  18367. if (this._modules.has(name)) {
  18368. return this._modules.get(name);
  18369. }
  18370. if (this._c.hasattr(name)) {
  18371. return this._c.getattr(name);
  18372. }
  18373. if (this._c._has_method(name)) {
  18374. //
  18375. }
  18376. return super.__getattr__(name);
  18377. }
  18378. });
  18379. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18380. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18381. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18382. torch.CompilationUnit = torch.jit.CompilationUnit;
  18383. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18384. torch._C.ScriptModule = torch.ScriptModule;
  18385. torch._C.ClassType = torch.ClassType;
  18386. this.registerType('torch._C.FlatBuffersLoader', class {
  18387. constructor(cu) {
  18388. this._cu = cu;
  18389. const torch = cu.execution.__import__('torch');
  18390. this._torch = torch;
  18391. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18392. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18393. this._ivalue_parsers = new Map();
  18394. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18395. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18396. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18397. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18398. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18399. }
  18400. parseModule(module) {
  18401. this._module = module;
  18402. this._all_functions = new Map();
  18403. this._all_ivalues = new Array(module.ivalues.length);
  18404. this._all_types = new Array(module.object_types.length);
  18405. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18406. for (let i = 0; i < mobile_ivalue_size; i++) {
  18407. this.parseAndPopulate(i, module.ivalues[i]);
  18408. }
  18409. const m = this._all_ivalues[module.state_obj];
  18410. for (const [name, value] of this._all_functions) {
  18411. const class_index = module.ivalues[name].val.class_type;
  18412. const class_type = this._all_types[class_index];
  18413. if (value) {
  18414. class_type.addMethod(value);
  18415. }
  18416. }
  18417. m._min_operator_version = module.operator_version;
  18418. m._bytecode_version = module.bytecode_version;
  18419. return m;
  18420. }
  18421. parseAndPopulate(i, ivalue) {
  18422. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18423. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18424. } else {
  18425. this._all_ivalues[i] = this.parseIValue(ivalue);
  18426. }
  18427. }
  18428. parseFunction(/* val */) {
  18429. return null;
  18430. }
  18431. parseIValue(ivalue) {
  18432. if (ivalue.val) {
  18433. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18434. return callback(ivalue);
  18435. }
  18436. return null;
  18437. }
  18438. parseTensor(ivalue) {
  18439. return this.parseTensorFromMetadata(ivalue.val);
  18440. }
  18441. parseTensorFromMetadata(metadata) {
  18442. if (metadata.quantized_schema) {
  18443. throw new torch.Error('Quantized schema not implemented.');
  18444. }
  18445. const index = metadata.storage_location_index;
  18446. const data = this._module.storage_data[index].data;
  18447. const dtype = this._dtypes.get(metadata.scalar_type);
  18448. const size = data.length / dtype.itemsize();
  18449. const storage = new torch.storage.TypedStorage(size, dtype);
  18450. storage._set_cdata(data);
  18451. const tensor = new torch.Tensor();
  18452. const shape = Array.from(metadata.sizes);
  18453. const stride = Array.from(metadata.strides);
  18454. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18455. return tensor;
  18456. }
  18457. parseObject(ivalue) {
  18458. const object = ivalue.val;
  18459. const obj_type = this._module.object_types[object.type_index];
  18460. const cls = this.getOrCreateClassTypeForObject(object);
  18461. switch (obj_type.type) {
  18462. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18463. const torch = this._torch;
  18464. const obj = torch.ScriptObject.create(cls);
  18465. for (let i = 0; i < object.attrs.length; i++) {
  18466. const attr_name = obj_type.attr_names[i];
  18467. const val = this._all_ivalues[object.attrs[i]];
  18468. obj.__setattr__(attr_name, val);
  18469. }
  18470. return obj;
  18471. }
  18472. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18473. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18474. default: {
  18475. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18476. }
  18477. }
  18478. }
  18479. getOrCreateClassTypeForObject(object) {
  18480. let cls = this._all_types[object.type_index];
  18481. const obj_type = this._module.object_types[object.type_index];
  18482. if (!cls) {
  18483. const name = obj_type.type_name;
  18484. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18485. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18486. if (!cls) {
  18487. const torch = this._torch;
  18488. cls = torch.ClassType.create(name, this._cu, true);
  18489. this._cu.register_type(cls);
  18490. }
  18491. } else {
  18492. // cls = c10::parseType(qn_str).cast<ClassType>();
  18493. }
  18494. this._all_types[object.type_index] = cls;
  18495. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18496. for (let i = 0; i < object.attrs.length; i++) {
  18497. // const val = this._all_ivalues[object.attrs[i]];
  18498. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18499. }
  18500. }
  18501. }
  18502. return cls;
  18503. }
  18504. });
  18505. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18506. constructor(export_module, flat_args_adapter) {
  18507. super();
  18508. const export_graph = copy.deepcopy(export_module.graph);
  18509. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18510. this.graph = torch.fx.Graph();
  18511. this.graph.owning_module = this;
  18512. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18513. this.flat_args_adapter = flat_args_adapter;
  18514. this.adapted = false;
  18515. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18516. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18517. }
  18518. });
  18519. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18520. constructor(input_specs, output_specs) {
  18521. this.input_specs = input_specs;
  18522. this.output_specs = output_specs;
  18523. }
  18524. get user_inputs() {
  18525. const user_inputs = [];
  18526. for (const s of this.input_specs) {
  18527. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18528. continue;
  18529. }
  18530. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18531. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18532. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18533. user_inputs.push(s.arg.name);
  18534. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18535. user_inputs.push(s.arg.value);
  18536. } else {
  18537. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18538. }
  18539. }
  18540. return user_inputs;
  18541. }
  18542. get user_outputs() {
  18543. const user_outputs = [];
  18544. for (const s of this.output_specs) {
  18545. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18546. continue;
  18547. }
  18548. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18549. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18550. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18551. user_outputs.push(s.arg.name);
  18552. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18553. user_outputs.push(s.arg.value);
  18554. } else {
  18555. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18556. }
  18557. }
  18558. return user_outputs;
  18559. }
  18560. get inputs_to_parameters() {
  18561. return new Map(this.input_specs
  18562. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18563. .map((s) => [s.arg.name, s.target]));
  18564. }
  18565. get inputs_to_buffers() {
  18566. return new Map(this.input_specs
  18567. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18568. .map((s) => [s.arg.name, s.target]));
  18569. }
  18570. get inputs_to_lifted_tensor_constants() {
  18571. return new Map(this.input_specs
  18572. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18573. .map((s) => [s.arg.name, s.target]));
  18574. }
  18575. });
  18576. torch.export.graph_signature.InputKind = {
  18577. USER_INPUT: 0,
  18578. PARAMETER: 1,
  18579. BUFFER: 2,
  18580. CONSTANT_TENSOR: 3,
  18581. CUSTOM_OBJ: 4,
  18582. TOKEN: 5
  18583. };
  18584. this.registerType('torch.export.graph_signature.InputSpec', class {
  18585. constructor(kind, arg, target, persistent) {
  18586. this.kind = kind;
  18587. this.arg = arg;
  18588. this.target = target;
  18589. this.persistent = persistent || null;
  18590. }
  18591. });
  18592. torch.export.graph_signature.OutputKind = {
  18593. USER_OUTPUT: 0,
  18594. LOSS_OUTPUT: 1,
  18595. BUFFER_MUTATION: 2,
  18596. GRADIENT_TO_PARAMETER: 3,
  18597. GRADIENT_TO_USER_INPUT: 4,
  18598. USER_INPUT_MUTATION: 5,
  18599. TOKEN: 6
  18600. };
  18601. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18602. constructor(kind, arg, target) {
  18603. this.kind = kind;
  18604. this.arg = arg;
  18605. this.target = target;
  18606. }
  18607. });
  18608. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18609. constructor(name, value) {
  18610. this.name = name;
  18611. this.value = value; // Union[int, float, bool, str, None]
  18612. }
  18613. });
  18614. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18615. constructor(name) {
  18616. this.name = name;
  18617. }
  18618. });
  18619. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18620. constructor(name) {
  18621. this.name = name;
  18622. }
  18623. });
  18624. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18625. constructor(name, class_fqn, fake_val) {
  18626. this.name = name;
  18627. this.class_fqn = class_fqn;
  18628. this.fake_val = fake_val;
  18629. }
  18630. });
  18631. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18632. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18633. // graph._codegen = torch.fx.graph.CodeGen()
  18634. this._graph_module = this._create_graph_module_for_export(root, graph);
  18635. if (root instanceof torch.fx.GraphModule) {
  18636. // this._graph_module.meta.update(root.meta);
  18637. }
  18638. this._graph_signature = graph_signature;
  18639. this._state_dict = state_dict;
  18640. this._range_constraints = range_constraints;
  18641. this._module_call_graph = module_call_graph;
  18642. this._example_inputs = example_inputs;
  18643. this._constants = tensor_constants || constants || {};
  18644. }
  18645. _create_graph_module_for_export(root, graph) {
  18646. let gm = null;
  18647. try {
  18648. gm = new torch.fx.GraphModule(root, graph);
  18649. } catch {
  18650. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18651. gm._graph = graph;
  18652. }
  18653. return gm;
  18654. }
  18655. get graph_module() {
  18656. return this._graph_module;
  18657. }
  18658. get graph() {
  18659. return this._graph_module.graph;
  18660. }
  18661. get graph_signature() {
  18662. return this._graph_signature;
  18663. }
  18664. get state_dict() {
  18665. return this._state_dict;
  18666. }
  18667. get constants() {
  18668. return this._constants;
  18669. }
  18670. });
  18671. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18672. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18673. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18674. return new torch.fx.graph_module.GraphModule(root, graph);
  18675. });
  18676. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18677. module = torch.export._remove_effect_tokens(module);
  18678. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18679. });
  18680. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18681. return new torch.fx.graph_module.GraphModule(root, graph);
  18682. });
  18683. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18684. constructor(exported_program, state_dict, constants, example_inputs) {
  18685. this.exported_program = exported_program;
  18686. this.state_dict = state_dict;
  18687. this.constants = constants;
  18688. this.example_inputs = example_inputs;
  18689. }
  18690. });
  18691. torch._export.serde.serialize._SYM_OPS = new Set([
  18692. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18693. operator.neg, operator.pos, operator.and_, operator.or_,
  18694. math.trunc, torch.sym_not,
  18695. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18696. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18697. operator.truediv, operator.and_
  18698. ]);
  18699. this.registerType('torch._export.serde.union._Union', class {
  18700. constructor(obj) {
  18701. if (obj.$type) {
  18702. this.type = obj.$type;
  18703. this[obj.$type] = obj.$value;
  18704. delete obj.$type;
  18705. delete obj.$value;
  18706. } else if (obj.type) {
  18707. this.type = obj.type;
  18708. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18709. this[obj.type] = Object.fromEntries(entries);
  18710. } else {
  18711. let entries = Object.entries(obj);
  18712. if (entries.length > 1) {
  18713. entries = entries.filter(([, value]) => value !== null);
  18714. }
  18715. if (entries.length !== 1) {
  18716. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18717. }
  18718. const [entry] = entries;
  18719. const [type, value] = entry;
  18720. this.type = type;
  18721. this[type] = value;
  18722. }
  18723. }
  18724. get value() {
  18725. return this[this.type];
  18726. }
  18727. });
  18728. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18729. constructor(obj) {
  18730. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18731. this.name = obj.name;
  18732. }
  18733. });
  18734. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18735. constructor(obj) {
  18736. super(obj);
  18737. switch (this.type) {
  18738. case 'as_int':
  18739. case 'as_ints':
  18740. case 'as_float':
  18741. case 'as_floats':
  18742. case 'as_bool':
  18743. case 'as_bools':
  18744. case 'as_string':
  18745. case 'as_strings':
  18746. case 'as_scalar_type':
  18747. case 'as_device':
  18748. case 'as_memory_format':
  18749. case 'as_layout':
  18750. break;
  18751. case 'as_none':
  18752. this.as_none = null;
  18753. break;
  18754. case 'as_tensor':
  18755. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18756. break;
  18757. case 'as_tensors':
  18758. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18759. break;
  18760. case 'as_graph':
  18761. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18762. break;
  18763. case 'as_sym_int':
  18764. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18765. break;
  18766. case 'as_sym_ints':
  18767. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18768. break;
  18769. case 'as_sym_bool':
  18770. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18771. break;
  18772. case 'as_sym_bools':
  18773. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18774. break;
  18775. case 'as_sym_float':
  18776. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18777. break;
  18778. case 'as_sym_floats':
  18779. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18780. break;
  18781. case 'as_optional_tensors':
  18782. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18783. break;
  18784. case 'as_custom_obj':
  18785. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18786. break;
  18787. // case 'as_graph': GraphArgument
  18788. default:
  18789. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18790. }
  18791. }
  18792. });
  18793. this.registerType('torch._export.serde.schema.Node', class {
  18794. constructor(obj) {
  18795. this.target = obj.target;
  18796. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18797. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18798. this.metadata = new Map(Object.entries(obj.metadata));
  18799. }
  18800. });
  18801. torch._export.serde.schema.ScalarType = {
  18802. UNKNOWN: 0,
  18803. BYTE: 1,
  18804. CHAR: 2,
  18805. SHORT: 3,
  18806. INT: 4,
  18807. LONG: 5,
  18808. HALF: 6,
  18809. FLOAT: 7,
  18810. DOUBLE: 8,
  18811. COMPLEXHALF: 9,
  18812. COMPLEXFLOAT: 10,
  18813. COMPLEXDOUBLE: 11,
  18814. BOOL: 12,
  18815. BFLOAT16: 13,
  18816. UINT16: 28,
  18817. FLOAT8E4M3FN: 29,
  18818. FLOAT8E5M2: 30,
  18819. FLOAT8E4M3FNUZ: 31,
  18820. FLOAT8E5M2FNUZ: 32,
  18821. };
  18822. torch._export.serde.schema.Layout = {
  18823. Unknown: 0,
  18824. SparseCoo: 1,
  18825. SparseCsr: 2,
  18826. SparseCsc: 3,
  18827. SparseBsr: 4,
  18828. SparseBsc: 5,
  18829. _mkldnn: 6,
  18830. Strided: 7
  18831. };
  18832. torch._export.serde.schema.MemoryFormat = {
  18833. Unknown: 0,
  18834. ContiguousFormat: 1,
  18835. ChannelsLast: 2,
  18836. ChannelsLast3d: 3,
  18837. PreserveFormat: 4,
  18838. };
  18839. this.registerType('torch._export.serde.schema.Device', class {
  18840. constructor(obj) {
  18841. Object.assign(this, { ...obj });
  18842. }
  18843. });
  18844. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18845. constructor(obj) {
  18846. obj = obj.meta || obj;
  18847. this.dtype = obj.dtype;
  18848. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18849. this.requires_grad = obj.requires_grad;
  18850. this.device = obj.device;
  18851. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18852. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18853. this.layout = obj.layout;
  18854. }
  18855. });
  18856. this.registerType('torch._export.serde.schema.Graph', class {
  18857. constructor(obj) {
  18858. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18859. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18860. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18861. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18862. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18863. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18864. this.is_single_tensor_return = obj.is_single_tensor_return;
  18865. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18866. if (obj.contants) {
  18867. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18868. // graph_signature -> input_specs -> tensor_constant
  18869. }
  18870. }
  18871. });
  18872. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18873. constructor(obj) {
  18874. Object.assign(this, { ...obj });
  18875. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18876. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18877. }
  18878. });
  18879. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18880. constructor(obj) {
  18881. Object.assign(this, { ...obj });
  18882. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18883. }
  18884. });
  18885. this.registerType('torch._export.serde.schema.GraphModule', class {
  18886. constructor(obj) {
  18887. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18888. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18889. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18890. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18891. }
  18892. });
  18893. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  18894. constructor(obj) {
  18895. Object.assign(this, { ...obj });
  18896. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  18897. }
  18898. });
  18899. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  18900. this.registerType('torch._export.serde.schema.SymExpr', class {
  18901. constructor(obj) {
  18902. this.expr_str = obj.expr_str;
  18903. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  18904. }
  18905. });
  18906. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  18907. constructor(obj) {
  18908. super(obj);
  18909. if (this.type === 'as_int') {
  18910. // continue
  18911. } else if (this.type === 'as_expr') {
  18912. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18913. } else {
  18914. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  18915. }
  18916. }
  18917. });
  18918. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  18919. constructor(obj) {
  18920. super(obj);
  18921. if (this.type === 'as_bool') {
  18922. // continue
  18923. } else if (this.type === 'as_expr') {
  18924. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18925. } else {
  18926. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  18927. }
  18928. }
  18929. });
  18930. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  18931. constructor(obj) {
  18932. super(obj);
  18933. Object.assign(this, { ...obj });
  18934. }
  18935. });
  18936. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  18937. constructor(obj) {
  18938. super(obj);
  18939. Object.assign(this, { ...obj });
  18940. }
  18941. });
  18942. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  18943. constructor(obj) {
  18944. super(obj);
  18945. Object.assign(this, { ...obj });
  18946. }
  18947. });
  18948. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  18949. constructor(obj) {
  18950. Object.assign(this, { ...obj });
  18951. }
  18952. });
  18953. this.registerType('torch._export.serde.schema.GraphSignature', class {
  18954. constructor(obj) {
  18955. this.input_specs = [];
  18956. if (Array.isArray(obj.input_specs)) {
  18957. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  18958. }
  18959. if (Array.isArray(obj.user_inputs)) {
  18960. for (const user_input of obj.user_inputs) {
  18961. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  18962. }
  18963. }
  18964. if (obj.inputs_to_parameters) {
  18965. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  18966. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  18967. }
  18968. }
  18969. this.output_specs = [];
  18970. if (Array.isArray(obj.output_specs)) {
  18971. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  18972. }
  18973. }
  18974. });
  18975. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  18976. constructor(obj) {
  18977. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18978. }
  18979. });
  18980. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  18981. constructor(obj) {
  18982. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18983. this.parameter_name = obj.parameter_name;
  18984. }
  18985. });
  18986. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  18987. constructor(obj) {
  18988. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18989. this.buffer_name = obj.buffer_name;
  18990. }
  18991. });
  18992. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  18993. constructor(obj) {
  18994. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18995. this.tensor_constant_name = obj.tensor_constant_name;
  18996. }
  18997. });
  18998. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  18999. constructor(obj) {
  19000. this.name = obj.name;
  19001. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  19002. }
  19003. });
  19004. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  19005. constructor(obj) {
  19006. super(obj);
  19007. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  19008. // continue
  19009. } else if (this.type === 'as_none') {
  19010. this.as_none = null;
  19011. } else {
  19012. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  19013. }
  19014. }
  19015. });
  19016. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  19017. constructor(obj) {
  19018. super(obj);
  19019. if (this.type === 'user_input') {
  19020. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  19021. } else if (this.type === 'parameter') {
  19022. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  19023. } else if (this.type === 'buffer') {
  19024. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  19025. } else if (this.type === 'tensor_constant') {
  19026. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  19027. } else if (this.type === 'constant_input') {
  19028. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  19029. } else {
  19030. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  19031. }
  19032. /*
  19033. custom_obj: InputToCustomObjSpec
  19034. token: InputTokenSpec
  19035. */
  19036. }
  19037. });
  19038. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  19039. constructor(obj) {
  19040. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19041. }
  19042. });
  19043. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  19044. constructor(obj) {
  19045. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19046. this.buffer_name = obj.buffer_name;
  19047. }
  19048. });
  19049. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  19050. constructor(obj) {
  19051. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19052. this.parameter_name = obj.parameter_name;
  19053. }
  19054. });
  19055. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  19056. constructor(obj) {
  19057. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19058. this.user_input_name = obj.user_input_name;
  19059. }
  19060. });
  19061. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  19062. constructor(obj) {
  19063. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19064. this.user_input_name = obj.user_input_name;
  19065. }
  19066. });
  19067. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  19068. constructor(obj) {
  19069. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  19070. }
  19071. });
  19072. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  19073. constructor(obj) {
  19074. super(obj);
  19075. if (this.type === 'user_output') {
  19076. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  19077. } else if (this.type === 'loss_output') {
  19078. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  19079. } else if (this.type === 'buffer_mutation') {
  19080. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  19081. } else if (this.type === 'gradient_to_parameter') {
  19082. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  19083. } else if (this.type === 'gradient_to_user_input') {
  19084. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  19085. } else if (this.type === 'user_input_mutation') {
  19086. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  19087. } else if (this.type === 'token') {
  19088. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  19089. }
  19090. }
  19091. });
  19092. this.registerType('torch._export.serde.schema.TensorArgument', class {
  19093. constructor(obj) {
  19094. this.name = obj.name;
  19095. }
  19096. });
  19097. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19098. constructor(obj) {
  19099. this.name = obj.name;
  19100. }
  19101. });
  19102. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19103. constructor(obj) {
  19104. this.name = obj.name;
  19105. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19106. }
  19107. });
  19108. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19109. constructor(obj) {
  19110. super(obj);
  19111. if (this.type === 'as_tensor') {
  19112. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19113. } else if (this.type === 'as_none') {
  19114. this.as_none = null;
  19115. } else {
  19116. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19117. }
  19118. }
  19119. });
  19120. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19121. const legacy_file = `data/weights/${model_name}.pt`;
  19122. if (f.has(legacy_file)) {
  19123. return f.get(legacy_file);
  19124. }
  19125. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19126. if (!f.has(weights_config_file)) {
  19127. return null;
  19128. }
  19129. const weights_config = f.get(weights_config_file);
  19130. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19131. const state_dict = new builtins.dict();
  19132. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19133. if (payload_meta.use_pickle) {
  19134. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19135. const weight_tensor = torch.load(weight_bytes);
  19136. state_dict.set(weight_fqn, weight_tensor);
  19137. } else {
  19138. const tensor_meta = payload_meta.tensor_meta;
  19139. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19140. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19141. const strides = tensor_meta.strides.map((s) => s.as_int);
  19142. const storage_offset = tensor_meta.storage_offset.as_int;
  19143. const weight_tensor = new torch.Tensor();
  19144. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19145. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19146. if (payload_meta.is_param) {
  19147. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19148. } else {
  19149. state_dict.set(weight_fqn, weight_tensor);
  19150. }
  19151. }
  19152. }
  19153. return state_dict;
  19154. });
  19155. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19156. const legacy_file = `data/constants/${model_name}.pt`;
  19157. if (f.has(legacy_file)) {
  19158. const entries = f.get(legacy_file);
  19159. return new builtins.dict(entries);
  19160. }
  19161. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19162. if (!f.has(constants_config_file)) {
  19163. return null;
  19164. }
  19165. const constants_config = f.get(constants_config_file);
  19166. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19167. const constants = new builtins.dict();
  19168. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19169. const path_name = payload_meta.path_name;
  19170. if (path_name.startsWith('tensor_')) {
  19171. if (payload_meta.use_pickle) {
  19172. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19173. const constant_tensor = torch.load(constant_bytes);
  19174. constants.set(constant_fqn, constant_tensor);
  19175. } else {
  19176. const tensor_meta = payload_meta.tensor_meta;
  19177. const tensor = constant_file_map.get(payload_meta.path_name);
  19178. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19179. const strides = tensor_meta.strides.map((s) => s.as_int);
  19180. const storage_offset = tensor_meta.storage_offset.as_int;
  19181. const constant_tensor = new torch.Tensor();
  19182. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19183. constants.set(constant_fqn, constant_tensor);
  19184. }
  19185. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19186. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19187. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19188. constants.set(constant_fqn, custom_obj);
  19189. }
  19190. }
  19191. return constants;
  19192. });
  19193. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19194. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19195. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19196. }
  19197. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19198. });
  19199. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19200. const file_map = new builtins.dict();
  19201. for (const payload_meta of Object.values(config.config)) {
  19202. if (payload_meta.use_pickle) {
  19203. continue;
  19204. }
  19205. if (file_map.has(payload_meta.path_name)) {
  19206. continue;
  19207. }
  19208. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19209. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19210. file_map.set(payload_meta.path_name, tensor);
  19211. }
  19212. return file_map;
  19213. });
  19214. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19215. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19216. const itemsize = dtype.itemsize();
  19217. const num_elements = tensor_bytes.length / itemsize;
  19218. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19219. storage._set_cdata(tensor_bytes);
  19220. const tensor = new torch.Tensor();
  19221. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19222. tensor.requires_grad = tensor_meta.requires_grad || false;
  19223. return tensor;
  19224. });
  19225. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19226. const exported_programs = new Map();
  19227. for (const name of f.keys()) {
  19228. const match = name.match(/^models\/([^/]+)\.json$/);
  19229. if (match) {
  19230. const [, model_name] = match;
  19231. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19232. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19233. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19234. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19235. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19236. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19237. exported_programs.set(model_name, exported_program);
  19238. }
  19239. }
  19240. return { exported_programs };
  19241. });
  19242. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19243. if (data === null) {
  19244. return data;
  19245. }
  19246. if (cls) {
  19247. return new cls(data);
  19248. }
  19249. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19250. });
  19251. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19252. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19253. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19254. });
  19255. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19256. constructor(expected_opset_version) {
  19257. this.expected_opset_version = expected_opset_version;
  19258. }
  19259. deserialize(exported_program, state_dict, constants, example_inputs) {
  19260. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19261. /*
  19262. symbol_name_to_range = {
  19263. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19264. for k, v in exported_program.range_constraints.items()
  19265. }
  19266. */
  19267. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19268. const res = deserializer.deserialize(
  19269. exported_program.graph_module,
  19270. state_dict,
  19271. constants,
  19272. example_inputs,
  19273. symbol_name_to_range);
  19274. const range_constraints = null;
  19275. /*
  19276. range_constraints = self.deserialize_range_constraints(
  19277. symbol_name_to_range, res.names_to_symbols,
  19278. )
  19279. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19280. self._validate_model_opset_version(model_opset_version)
  19281. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19282. */
  19283. return new torch.export.exported_program.ExportedProgram(
  19284. res.graph_module, res.graph_module.graph, res.signature,
  19285. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19286. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19287. res.constants);
  19288. // return upgrader.upgrade(exported_program)
  19289. }
  19290. });
  19291. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19292. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19293. return serialized;
  19294. }
  19295. if (serialized === null || serialized.length === 0) {
  19296. return new builtins.dict();
  19297. }
  19298. const artifact = torch.load(serialized);
  19299. return artifact;
  19300. });
  19301. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19302. constructor() {
  19303. this.serialized_name_to_node = new builtins.dict();
  19304. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19305. this.graph = new torch.fx.Graph();
  19306. this.module = new torch.nn.Module();
  19307. }
  19308. save_graph_module() {
  19309. const Context = class {
  19310. constructor(self) {
  19311. this.self = self;
  19312. }
  19313. __enter__() {
  19314. this.saved = [
  19315. this.self.graph,
  19316. this.self.module,
  19317. this.self.serialized_name_to_node,
  19318. this.self.serialized_name_to_meta,
  19319. this.self.unbacked_symbols,
  19320. ];
  19321. this.self.graph = new torch.fx.graph.Graph();
  19322. this.self.module = new torch.nn.modules.module.Module();
  19323. this.self.serialized_name_to_node = new builtins.dict();
  19324. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19325. this.self.unbacked_symbols = new Set();
  19326. }
  19327. __exit__(/* exc_type, exc_value, traceback */) {
  19328. const self = this.self;
  19329. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19330. }
  19331. };
  19332. return new Context(this);
  19333. }
  19334. deserialize_graph_output(output) {
  19335. if (output.type === 'as_tensor') {
  19336. return this.serialized_name_to_node.get(output.as_tensor.name);
  19337. } else if (output.type === 'as_sym_int') {
  19338. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19339. } else if (output.type === 'as_sym_bool') {
  19340. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19341. } else if (output.type === 'as_int') {
  19342. return this.serialized_name_to_node.get(output.as_int.as_name);
  19343. } else if (output.type === 'as_none') {
  19344. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19345. }
  19346. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19347. }
  19348. deserialize_graph(serialized_graph) {
  19349. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19350. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19351. this.serialized_name_to_meta.set(name, meta_val);
  19352. }
  19353. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19354. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19355. }
  19356. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19357. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19358. }
  19359. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19360. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19361. }
  19362. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19363. const input = serialized_graph.inputs[i];
  19364. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19365. const node_name = input.value.name;
  19366. const placeholder_node = this.graph.placeholder(node_name);
  19367. placeholder_node.name = node_name;
  19368. this.sync_fx_node(node_name, placeholder_node);
  19369. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19370. const node_name = this.signature.input_specs[i].arg.name;
  19371. const placeholder_node = this.graph.placeholder(node_name);
  19372. placeholder_node.meta.set('val', this.deserialize_input(input));
  19373. } else {
  19374. throw new python.Error(`Invalid input ${input.type}.`);
  19375. }
  19376. }
  19377. for (const serialized_node of serialized_graph.nodes) {
  19378. const target = this.deserialize_operator(serialized_node.target);
  19379. this.deserialize_node(serialized_node, target);
  19380. }
  19381. let outputs = [];
  19382. for (const output of serialized_graph.outputs) {
  19383. outputs.push(this.deserialize_graph_output(output));
  19384. }
  19385. if (serialized_graph.is_single_tensor_return) {
  19386. [outputs] = outputs;
  19387. } else {
  19388. outputs = new builtins.tuple(outputs);
  19389. }
  19390. const output_node = this.graph.output(outputs);
  19391. if (serialized_graph.is_single_tensor_return) {
  19392. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19393. } else {
  19394. /* output_node.meta['val'] = tuple(
  19395. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19396. for arg in output_node.args[0]
  19397. ) */
  19398. }
  19399. return self.graph;
  19400. }
  19401. deserialize_operator(serialized_target) {
  19402. let module = null;
  19403. let serialized_target_names = null;
  19404. if (serialized_target.startsWith('_operator')) {
  19405. module = operator;
  19406. serialized_target_names = serialized_target.split('.').slice(1);
  19407. } else if (serialized_target.startsWith('torch')) {
  19408. module = torch;
  19409. serialized_target_names = serialized_target.split('.').slice(1);
  19410. } else if (serialized_target.startsWith('#')) {
  19411. return self.deserialize_extension_operator(serialized_target);
  19412. } else {
  19413. return serialized_target;
  19414. }
  19415. let target = module;
  19416. for (const name of serialized_target_names) {
  19417. target = builtins.getattr(target, name);
  19418. if (!target) {
  19419. return serialized_target;
  19420. }
  19421. }
  19422. return target;
  19423. }
  19424. deserialize_node(serialized_node, target) {
  19425. let fx_node = null;
  19426. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19427. const name = serialized_node.outputs[0].value.as_name;
  19428. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19429. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19430. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19431. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19432. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19433. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19434. for (const x of [...args, ...kwargs.values()]) {
  19435. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19436. x.meta.update(metadata);
  19437. }
  19438. }
  19439. const name = serialized_node.outputs.length === 1 &&
  19440. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19441. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19442. serialized_node.outputs[0].as_tensor.name : null;
  19443. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19444. this.deserialize_outputs(serialized_node, fx_node);
  19445. fx_node.meta.update(metadata);
  19446. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19447. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19448. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19449. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19450. this.deserialize_outputs(serialized_node, fx_node);
  19451. } else if (typeof target === 'string') {
  19452. // Handle unresolved operators
  19453. execution.emit('resolve', target);
  19454. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19455. throw new python.Error(`Unsupported node target type '${target}'.`);
  19456. }
  19457. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19458. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19459. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19460. this.deserialize_outputs(serialized_node, fx_node);
  19461. } else {
  19462. throw new python.Error(`Unsupported node target type '${target}'.`);
  19463. }
  19464. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19465. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19466. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19467. }
  19468. }
  19469. deserialize_input_spec(i) {
  19470. if (i.type === 'user_input') {
  19471. return new torch.export.graph_signature.InputSpec(
  19472. torch.export.graph_signature.InputKind.USER_INPUT,
  19473. this.deserialize_argument_spec(i.user_input.arg),
  19474. null);
  19475. } else if (i.type === 'parameter') {
  19476. return new torch.export.graph_signature.InputSpec(
  19477. torch.export.graph_signature.InputKind.PARAMETER,
  19478. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19479. i.parameter.parameter_name,
  19480. );
  19481. } else if (i.type === 'buffer') {
  19482. return new torch.export.graph_signature.InputSpec(
  19483. torch.export.graph_signature.InputKind.BUFFER,
  19484. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19485. i.buffer.buffer_name,
  19486. i.buffer.persistent,
  19487. );
  19488. } else if (i.type === 'tensor_constant') {
  19489. return new torch.export.graph_signature.InputSpec(
  19490. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19491. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19492. i.tensor_constant.tensor_constant_name);
  19493. } else if (i.type === 'custom_obj') {
  19494. return new torch.export.graph_signature.InputSpec(
  19495. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19496. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19497. i.custom_obj.custom_obj_name);
  19498. } else if (i.type === 'token') {
  19499. return new torch.export.graph_signature.InputSpec(
  19500. torch.export.graph_signature.InputKind.TOKEN,
  19501. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19502. null);
  19503. } else if (i.type === 'constant_input') {
  19504. return new torch.export.graph_signature.InputSpec(
  19505. torch.export.graph_signature.InputKind.USER_INPUT,
  19506. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19507. null);
  19508. }
  19509. throw new python.Error(`Unknown input spec ${i}`);
  19510. }
  19511. deserialize_constant_input(inp) {
  19512. if (inp.type === 'as_int') {
  19513. return inp.as_int;
  19514. } else if (inp.type === 'as_float') {
  19515. return inp.as_float;
  19516. } else if (inp.type === 'as_string') {
  19517. return inp.as_string;
  19518. } else if (inp.type === 'as_bool') {
  19519. return inp.as_bool;
  19520. } else if (inp.type === 'as_none') {
  19521. return null;
  19522. }
  19523. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19524. }
  19525. deserialize_output_spec(o) {
  19526. if (o.type === 'user_output') {
  19527. return new torch.export.graph_signature.OutputSpec(
  19528. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19529. this.deserialize_argument_spec(o.user_output.arg),
  19530. null);
  19531. } else if (o.type === 'loss_output') {
  19532. return new torch.export.graph_signature.OutputSpec(
  19533. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19534. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19535. null);
  19536. } else if (o.type === 'buffer_mutation') {
  19537. return new torch.export.graph_signature.OutputSpec(
  19538. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19539. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19540. o.buffer_mutation.buffer_name);
  19541. } else if (o.type === 'gradient_to_parameter') {
  19542. return new torch.export.graph_signature.OutputSpec(
  19543. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19544. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19545. o.gradient_to_parameter.parameter_name);
  19546. } else if (o.type === 'gradient_to_user_input') {
  19547. return new torch.export.graph_signature.OutputSpec(
  19548. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19549. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19550. o.gradient_to_user_input.user_input_name);
  19551. } else if (o.type === 'user_input_mutation') {
  19552. return new torch.export.graph_signature.OutputSpec(
  19553. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19554. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19555. o.user_input_mutation.user_input_name);
  19556. } else if (o.type === 'token') {
  19557. return new torch.export.graph_signature.OutputSpec(
  19558. torch.export.graph_signature.OutputKind.TOKEN,
  19559. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19560. null);
  19561. }
  19562. throw new python.Error(`Unknown output spec ${o}.`);
  19563. }
  19564. deserialize_signature(sig) {
  19565. return new torch.export.graph_signature.ExportGraphSignature(
  19566. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19567. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19568. }
  19569. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19570. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19571. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19572. this.sympy_functions = new Map([
  19573. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19574. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19575. ['Where', torch.utils._sympy.functions.Where],
  19576. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19577. ['Mod', torch.utils._sympy.functions.Mod],
  19578. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19579. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19580. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19581. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19582. ['LShift', torch.utils._sympy.functions.LShift],
  19583. ['RShift', torch.utils._sympy.functions.RShift],
  19584. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19585. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19586. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19587. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19588. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19589. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19590. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19591. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19592. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19593. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19594. ['Identity', torch.utils._sympy.functions.Identity],
  19595. ]);
  19596. this.symbol_name_to_symbol = new Map();
  19597. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19598. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19599. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19600. /*
  19601. if symbol_name_to_range:
  19602. for k, vr in symbol_name_to_range.items():
  19603. lower = int(vr.lower)
  19604. if vr.upper >= 2: # max is >= 2, not sym bool range
  19605. lower = max(2, lower)
  19606. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19607. */
  19608. this.example_inputs = null;
  19609. if (example_inputs) {
  19610. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19611. }
  19612. this.deserialize_graph(serialized_graph_module.graph);
  19613. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19614. return {
  19615. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19616. signature: this.signature,
  19617. module_call_graph,
  19618. names_to_symbols: this.symbol_name_to_symbol,
  19619. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19620. constants: this.constants,
  19621. example_inputs: this.example_inputs,
  19622. };
  19623. }
  19624. sync_fx_node(name, fx_node) {
  19625. if (this.serialized_name_to_node.has(name)) {
  19626. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19627. }
  19628. this.serialized_name_to_node.set(name, fx_node);
  19629. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19630. }
  19631. deserialize_sym_op_inputs(inputs) {
  19632. return inputs.map((input) => this.deserialize_input(input.arg));
  19633. }
  19634. deserialize_inputs(target, serialized_node) {
  19635. const schema_args = this._get_schema_from_target(target).arguments;
  19636. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19637. const args = new builtins.list();
  19638. const kwargs = new builtins.dict();
  19639. for (const schema_arg of schema_args) {
  19640. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19641. if (is_positional) {
  19642. args.push(actual_args.get(schema_arg.name));
  19643. } else if (actual_args.has(schema_arg.name)) {
  19644. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19645. }
  19646. }
  19647. return [args, kwargs];
  19648. }
  19649. deserialize_hoo_inputs(inputs) {
  19650. const args = [];
  19651. const kwargs = new builtins.dict();
  19652. for (const input_ of inputs) {
  19653. if (input_.name === '') {
  19654. args.push(this.deserialize_input(input_.arg));
  19655. } else {
  19656. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19657. }
  19658. }
  19659. return [new builtins.tuple(args), kwargs];
  19660. }
  19661. deserialize_input(inp) {
  19662. const value = inp.value;
  19663. const typ_ = inp.type;
  19664. if (typ_ === 'as_none') {
  19665. return null;
  19666. } else if (typ_ === 'as_tensor') {
  19667. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19668. } else if (typ_ === 'as_scalar_type') {
  19669. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19670. } else if (typ_ === 'as_memory_format') {
  19671. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19672. } else if (typ_ === 'as_layout') {
  19673. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19674. } else if (typ_ === 'as_graph') {
  19675. const context = this.save_graph_module();
  19676. context.__enter__();
  19677. this.deserialize_graph(value.graph);
  19678. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19679. context.__exit__(null, null, null);
  19680. this.module.register_module(value.name, submodule);
  19681. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19682. } else if (typ_ === 'as_device') {
  19683. return this.deserialize_device(inp.as_device);
  19684. } else if (typ_ === 'as_int') {
  19685. return inp.as_int;
  19686. } else if (typ_ === 'as_float') {
  19687. return inp.as_float;
  19688. } else if (typ_ === 'as_bool') {
  19689. return inp.as_bool;
  19690. } else if (typ_ === 'as_string') {
  19691. return inp.as_string;
  19692. } else if (typ_ === 'as_sym_int') {
  19693. return this.deserialize_sym_argument(inp.as_sym_int);
  19694. } else if (typ_ === 'as_sym_float') {
  19695. return this.deserialize_sym_argument(inp.as_sym_float);
  19696. } else if (typ_ === 'as_sym_bool') {
  19697. return this.deserialize_sym_argument(inp.as_sym_bool);
  19698. } else if (Array.isArray(value)) {
  19699. if (value.length === 0) {
  19700. return [];
  19701. } else if (typ_ === 'as_tensors') {
  19702. const result = [];
  19703. for (const arg of value) {
  19704. result.push(this.serialized_name_to_node.get(arg.name));
  19705. }
  19706. return result;
  19707. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19708. return Array.from(value);
  19709. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19710. return value.map((arg) => this.deserialize_sym_argument(arg));
  19711. } else if (typ_ === 'as_optional_tensors') {
  19712. const deserialize_optional_tensor_args = (a) => {
  19713. if (a.type === 'as_none') {
  19714. return null;
  19715. } else if (a.type === 'as_tensor') {
  19716. return this.serialized_name_to_node.get(a.value.name);
  19717. }
  19718. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19719. };
  19720. return value.map((item) => deserialize_optional_tensor_args(item));
  19721. }
  19722. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19723. } else if (typ_ === 'as_custom_obj') {
  19724. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19725. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19726. }
  19727. return this.constants[inp.as_custom_obj.name];
  19728. } else if (typ_ === 'as_operator') {
  19729. return this.deserialize_operator(inp.as_operator);
  19730. }
  19731. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19732. }
  19733. deserialize_sym_argument(sym_arg) {
  19734. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19735. if (sym_arg.type === 'as_int') {
  19736. return sym_arg.as_int;
  19737. } else if (sym_arg.type === 'as_name') {
  19738. return this.serialized_name_to_node.get(sym_arg.as_name);
  19739. }
  19740. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19741. if (sym_arg.type === 'as_float') {
  19742. return sym_arg.as_float;
  19743. } else if (sym_arg.type === 'as_name') {
  19744. return this.serialized_name_to_node.get(sym_arg.as_name);
  19745. }
  19746. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19747. if (sym_arg.type === 'as_bool') {
  19748. return sym_arg.as_bool;
  19749. } else if (sym_arg.type === 'as_name') {
  19750. return this.serialized_name_to_node.get(sym_arg.as_name);
  19751. }
  19752. }
  19753. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19754. }
  19755. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19756. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19757. }
  19758. deserialize_outputs(serialized_node, fx_node) {
  19759. if (serialized_node.outputs.length === 0) {
  19760. return;
  19761. }
  19762. if (serialized_node.outputs.length === 1 &&
  19763. serialized_node.outputs[0].type === 'as_tensor') {
  19764. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19765. return;
  19766. } else if (serialized_node.outputs.length === 1 &&
  19767. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19768. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19769. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19770. return;
  19771. }
  19772. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19773. }
  19774. deserialize_multiple_outputs(serialized_node, fx_node) {
  19775. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19776. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19777. let name = '';
  19778. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19779. name = arg.name;
  19780. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19781. name = arg.as_name;
  19782. } else {
  19783. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19784. }
  19785. const individual_output = this.graph.create_node(
  19786. 'call_function',
  19787. operator.getitem,
  19788. new builtins.tuple([fx_node, idx]),
  19789. null,
  19790. name,
  19791. );
  19792. this.sync_fx_node(name, individual_output);
  19793. meta_val.push(this.serialized_name_to_meta.get(name));
  19794. individual_output.meta.update(deserialized_metadata);
  19795. };
  19796. const generate_getitems = (meta_val, fx_node, args) => {
  19797. for (let idx = 0; idx < args.length; idx++) {
  19798. let arg = args[idx];
  19799. if (arg instanceof torch._export.serde.schema.Argument) {
  19800. arg = arg.value;
  19801. }
  19802. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19803. generate_getitem(meta_val, fx_node, arg, idx);
  19804. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19805. const list_output = this.graph.create_node(
  19806. 'call_function',
  19807. operator.getitem,
  19808. (fx_node, idx),
  19809. );
  19810. meta_val.push([]);
  19811. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  19812. list_output.meta.update(deserialized_metadata);
  19813. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  19814. } else {
  19815. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19816. }
  19817. }
  19818. };
  19819. const meta_val = [];
  19820. if (serialized_node.outputs.length === 1) {
  19821. // assert isinstance(serialized_node.outputs[0].value, list)
  19822. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19823. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19824. } else {
  19825. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19826. }
  19827. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19828. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19829. }
  19830. deserialize_metadata(metadata) {
  19831. const ret = new builtins.dict();
  19832. const stack_trace = metadata.get('stack_trace');
  19833. if (stack_trace) {
  19834. ret.set('stack_trace', stack_trace);
  19835. }
  19836. const deserialize_meta_func = (serialized_target) => {
  19837. let module = null;
  19838. let serialized_target_names = [];
  19839. if (serialized_target.startsWith('torch.nn')) {
  19840. module = torch.nn;
  19841. serialized_target_names = serialized_target.split('.').slice(1);
  19842. } else if (serialized_target.startsWith('torch')) {
  19843. module = torch;
  19844. serialized_target_names = serialized_target.split('.').slice(1);
  19845. } else {
  19846. return this.deserialize_operator(serialized_target);
  19847. }
  19848. let target = module;
  19849. for (const name of serialized_target_names) {
  19850. if (!builtins.hasattr(target, name)) {
  19851. return serialized_target;
  19852. }
  19853. target = builtins.getattr(target, name);
  19854. }
  19855. return target;
  19856. };
  19857. const nn_module_stack_str = metadata.get('nn_module_stack');
  19858. if (nn_module_stack_str) {
  19859. const import_nn_module_stack = (key, path, ty) => {
  19860. return [key, [path, ty]];
  19861. };
  19862. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19863. ret.set('nn_module_stack', nn_module_stack);
  19864. }
  19865. const source_fn_st_str = metadata.get('source_fn_stack');
  19866. if (source_fn_st_str) {
  19867. const source_fn_st = [];
  19868. for (const source_fn_str of source_fn_st_str.split(';')) {
  19869. const [name, target_str] = source_fn_str.split(',');
  19870. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19871. }
  19872. ret.set('source_fn_stack', source_fn_st);
  19873. }
  19874. const torch_fn = metadata.get('torch_fn');
  19875. if (torch_fn) {
  19876. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19877. }
  19878. const custom_str = metadata.get('custom');
  19879. if (custom_str) {
  19880. ret.set('custom', JSON.parse(custom_str));
  19881. }
  19882. return ret;
  19883. }
  19884. deserialize_argument_spec(x) {
  19885. if (x.type === 'as_tensor') {
  19886. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19887. } else if (x.type === 'as_sym_int') {
  19888. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19889. } else if (x.type === 'as_custom_obj') {
  19890. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19891. }
  19892. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19893. }
  19894. deserialize_tensor_meta(tensor_meta) {
  19895. try {
  19896. this.fake_tensor_mode.__enter__();
  19897. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  19898. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  19899. const device = this.deserialize_device(tensor_meta.device);
  19900. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19901. return torch.empty_strided(sizes, strides, dtype, null, device);
  19902. } finally {
  19903. this.fake_tensor_mode.__exit__(null, null, null);
  19904. }
  19905. }
  19906. deserialize_script_obj_meta(script_obj_meta) {
  19907. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  19908. }
  19909. _parse_sym_expr(expr_str, hint) {
  19910. const _process_sym_expr = (sym, hint) => {
  19911. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  19912. return sym;
  19913. }
  19914. expr_str = sym.__str__();
  19915. for (const arg of sym.args) {
  19916. this._parse_sym_expr(arg);
  19917. }
  19918. if (this.symbol_name_to_symbol.has(expr_str)) {
  19919. sym = this.symbol_name_to_symbol.get(expr_str);
  19920. } else {
  19921. this.symbol_name_to_symbol.set(expr_str, sym);
  19922. if (builtins.isinstance(sym, sympy.core.symbol.Symbol) && torch.fx.experimental.symbolic_shapes.symbol_is_type(sym, [torch.utils._sympy.symbol.SymT.UNBACKED_INT, torch.utils._sympy.symbol.SymT.UNBACKED_FLOAT])) {
  19923. this.unbacked_symbols.add(sym);
  19924. }
  19925. }
  19926. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  19927. this.shape_env.add_var_to_val(sym, hint);
  19928. }
  19929. const vr = this.symbol_name_to_range.get(expr_str);
  19930. if (vr) {
  19931. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  19932. }
  19933. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  19934. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  19935. }
  19936. return sym;
  19937. };
  19938. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  19939. const expr = sympy.core.sympify.sympify(expr_str, locals);
  19940. return _process_sym_expr(expr, hint);
  19941. }
  19942. deserialize_sym_int(s) {
  19943. const val = s.value;
  19944. let hint = null;
  19945. if (s.type === 'as_expr') {
  19946. if (val.hint === null) {
  19947. hint = null;
  19948. } else {
  19949. // assert val.hint.type == "as_int"
  19950. hint = val.hint.value;
  19951. }
  19952. const sym = this._parse_sym_expr(val.expr_str, hint);
  19953. return this.shape_env.create_symintnode(sym, hint);
  19954. } else if (s.type === 'as_int') {
  19955. // assert type(val) is int
  19956. return val;
  19957. }
  19958. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  19959. }
  19960. deserialize_sym_bool(s) {
  19961. const val = s.value;
  19962. let hint = null;
  19963. if (s.type === 'as_expr') {
  19964. if (val.hint === null) {
  19965. hint = null;
  19966. } else {
  19967. // assert val.hint.type == "as_bool"
  19968. hint = val.hint.value;
  19969. }
  19970. const sym = this._parse_sym_expr(val.expr_str, hint);
  19971. return this.shape_env.create_symboolnode(sym, hint);
  19972. } else if (s.type === 'as_bool') {
  19973. // assert type(val) is bool
  19974. return val;
  19975. }
  19976. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  19977. }
  19978. deserialize_device(d) {
  19979. if (d.index === null) {
  19980. return new torch.device(d.type);
  19981. }
  19982. return new torch.device(d.type, d.index);
  19983. }
  19984. _get_schema_from_target(target) {
  19985. if (target instanceof torch._ops.OpOverload) {
  19986. return target._schema;
  19987. }
  19988. throw new python.Error(`Unsupported schema '${target.name}'.`);
  19989. }
  19990. _is_single_tensor_return(target) {
  19991. const schema = this._get_schema_from_target(target);
  19992. const returns = schema.returns;
  19993. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  19994. }
  19995. });
  19996. this.registerType('torch._export.verifier.Verifier', class {});
  19997. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  19998. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  19999. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  20000. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  20001. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  20002. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  20003. constructor(mod, dynamo_ctx) {
  20004. builtins.object.__setattr__(self, '_orig_mod', mod);
  20005. // this._super_module_initialized = false;
  20006. super();
  20007. // this._super_module_initialized = true;
  20008. this._orig_mod = mod;
  20009. this.dynamo_ctx = dynamo_ctx;
  20010. // this._initialize();
  20011. this.training = this._orig_mod.training;
  20012. }
  20013. });
  20014. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  20015. this.registerType('torch._dynamo.hooks.Hooks', class {});
  20016. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  20017. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  20018. this.registerType('torch._TorchCompileInductorWrapper', class {});
  20019. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  20020. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  20021. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  20022. const module = new types.ModuleType(name);
  20023. execution.register('sys').modules.set(name, module);
  20024. const context = new python.Execution.Context(module, null);
  20025. execution.exec(meta.get('module_src'), context);
  20026. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  20027. const state = meta.get('state');
  20028. if (state) {
  20029. if (obj.__setstate__) {
  20030. obj.__setstate__(state);
  20031. } else {
  20032. for (const [key, value] of state) {
  20033. obj[key] = value;
  20034. }
  20035. }
  20036. }
  20037. return obj;
  20038. });
  20039. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  20040. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  20041. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  20042. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  20043. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  20044. this.registerType('torch.device', class {
  20045. constructor(type, index) {
  20046. this.type = type;
  20047. this.index = index ? index : null;
  20048. }
  20049. __str__() {
  20050. return this.index === null ? this.type : `${this.type}:${this.index}`;
  20051. }
  20052. toString() {
  20053. const index = this.index === null ? '' : `, index=${this.index}`;
  20054. return `device(type='${this.type}'${index})`;
  20055. }
  20056. });
  20057. this.registerType('torch.memory_format', class {
  20058. constructor(name) {
  20059. this.name = name;
  20060. }
  20061. __str__() {
  20062. return `torch.${this.name}`;
  20063. }
  20064. toString() {
  20065. return this.__str__();
  20066. }
  20067. });
  20068. this.registerType('torch.dtype', class {
  20069. constructor(scalar_type, name, itemsize) {
  20070. this._scalar_type = scalar_type;
  20071. this._name = name;
  20072. this._itemsize = itemsize;
  20073. }
  20074. scalar_type() {
  20075. return this._scalar_type;
  20076. }
  20077. itemsize() {
  20078. return this._itemsize;
  20079. }
  20080. __reduce__() {
  20081. return this._name;
  20082. }
  20083. __str__() {
  20084. return `torch.${this._name}`;
  20085. }
  20086. toString() {
  20087. return this.__str__();
  20088. }
  20089. });
  20090. this.registerType('torch.layout', class {
  20091. constructor(name) {
  20092. this._name = name;
  20093. }
  20094. __str__() {
  20095. return `torch.${this._name}`;
  20096. }
  20097. toString() {
  20098. return this.__str__();
  20099. }
  20100. });
  20101. this.registerType('torch.qscheme', class {
  20102. constructor(name) {
  20103. this._name = name;
  20104. }
  20105. __str__() {
  20106. return this._name;
  20107. }
  20108. toString() {
  20109. return this.__str__();
  20110. }
  20111. });
  20112. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20113. __setstate__(state) {
  20114. [this.hooks_dict_ref, this.id] = state;
  20115. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20116. }
  20117. });
  20118. this.registerType('torch.storage._StorageBase', class {
  20119. constructor(size, dtype) {
  20120. this._size = size;
  20121. this._dtype = dtype;
  20122. this._device = null;
  20123. }
  20124. get device() {
  20125. return this._device;
  20126. }
  20127. get dtype() {
  20128. return this._dtype;
  20129. }
  20130. element_size() {
  20131. return this._dtype.element_size;
  20132. }
  20133. size() {
  20134. return this._size;
  20135. }
  20136. get data() {
  20137. return this._cdata;
  20138. }
  20139. _set_cdata(data) {
  20140. const length = this.size() * this.dtype.itemsize();
  20141. if (length !== data.length) {
  20142. throw new python.Error('Typed storage data size mismatch.');
  20143. }
  20144. this._cdata = data;
  20145. }
  20146. _set_from_file(unpickler) {
  20147. const buffer = unpickler.read(8);
  20148. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20149. if (size !== this.size()) {
  20150. throw new python.Error('Typed storage size mismatch.');
  20151. }
  20152. const itemsize = this.dtype.itemsize();
  20153. const data = unpickler.stream(itemsize * size);
  20154. this._set_cdata(data);
  20155. }
  20156. static _new_with_file(unpickler) {
  20157. const buffer = unpickler.read(8);
  20158. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20159. const storage = new this(size);
  20160. const itemsize = storage.dtype.itemsize();
  20161. const data = unpickler.stream(itemsize * size);
  20162. storage._set_cdata(data);
  20163. return storage;
  20164. }
  20165. });
  20166. this.registerType('torch.storage.UntypedStorage', class {
  20167. constructor(size) {
  20168. this._size = size;
  20169. }
  20170. _set_cdata(data) {
  20171. if (this._size !== data.length) {
  20172. throw new python.Error('Untyped storage data size mismatch.');
  20173. }
  20174. this._cdata = data;
  20175. }
  20176. });
  20177. this.registerType('torch.storage.TypedStorage', class {
  20178. constructor(...args) {
  20179. if (args.length === 0) {
  20180. this._size = 0;
  20181. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20182. [this._size] = args;
  20183. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20184. if (args[3] instanceof torch.device) {
  20185. [this._size, this.dtype, , this._device] = args;
  20186. } else {
  20187. [this._size, this.dtype] = args;
  20188. }
  20189. } else {
  20190. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20191. }
  20192. }
  20193. get device() {
  20194. return this._device;
  20195. }
  20196. get dtype() {
  20197. return this._dtype;
  20198. }
  20199. set dtype(value) {
  20200. this._dtype = value;
  20201. }
  20202. element_size() {
  20203. return this._dtype.element_size;
  20204. }
  20205. size() {
  20206. return this._size;
  20207. }
  20208. get data() {
  20209. return this._cdata;
  20210. }
  20211. _set_cdata(data) {
  20212. const length = this.size() * this.dtype.itemsize();
  20213. if (length !== data.length) {
  20214. throw new python.Error('Storage data size mismatch.');
  20215. }
  20216. this._cdata = data;
  20217. }
  20218. _set_from_file(unpickler) {
  20219. const buffer = unpickler.read(8);
  20220. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20221. if (size !== this.size()) {
  20222. throw new python.Error('Storage size mismatch.');
  20223. }
  20224. const itemsize = this.dtype.itemsize();
  20225. const data = unpickler.stream(itemsize * size);
  20226. this._set_cdata(data);
  20227. }
  20228. static _new_with_file(unpickler) {
  20229. const buffer = unpickler.read(8);
  20230. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20231. const storage = new this(size);
  20232. const itemsize = storage.dtype.itemsize();
  20233. const data = unpickler.stream(itemsize * size);
  20234. storage._set_cdata(data);
  20235. return storage;
  20236. }
  20237. });
  20238. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20239. });
  20240. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20241. constructor(...args) {
  20242. // eslint-disable-next-line no-constructor-return
  20243. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20244. }
  20245. });
  20246. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20247. constructor(...args) {
  20248. // eslint-disable-next-line no-constructor-return
  20249. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20250. }
  20251. });
  20252. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20253. constructor(...args) {
  20254. // eslint-disable-next-line no-constructor-return
  20255. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20256. }
  20257. });
  20258. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20259. constructor(...args) {
  20260. // eslint-disable-next-line no-constructor-return
  20261. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20262. }
  20263. });
  20264. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20265. constructor(...args) {
  20266. // eslint-disable-next-line no-constructor-return
  20267. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20268. }
  20269. });
  20270. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20271. constructor(...args) {
  20272. // eslint-disable-next-line no-constructor-return
  20273. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20274. }
  20275. });
  20276. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20277. constructor(...args) {
  20278. // eslint-disable-next-line no-constructor-return
  20279. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20280. }
  20281. });
  20282. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20283. constructor(...args) {
  20284. // eslint-disable-next-line no-constructor-return
  20285. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20286. }
  20287. });
  20288. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20289. constructor(...args) {
  20290. // eslint-disable-next-line no-constructor-return
  20291. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20292. }
  20293. });
  20294. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20295. constructor(...args) {
  20296. // eslint-disable-next-line no-constructor-return
  20297. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20298. }
  20299. });
  20300. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20301. constructor(...args) {
  20302. // eslint-disable-next-line no-constructor-return
  20303. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20304. }
  20305. });
  20306. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20307. constructor(...args) {
  20308. // eslint-disable-next-line no-constructor-return
  20309. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20310. }
  20311. });
  20312. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20313. constructor(...args) {
  20314. // eslint-disable-next-line no-constructor-return
  20315. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20316. }
  20317. });
  20318. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20319. constructor(...args) {
  20320. // eslint-disable-next-line no-constructor-return
  20321. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20322. }
  20323. });
  20324. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20325. constructor(...args) {
  20326. // eslint-disable-next-line no-constructor-return
  20327. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20328. }
  20329. });
  20330. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20331. constructor(...args) {
  20332. // eslint-disable-next-line no-constructor-return
  20333. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20334. }
  20335. });
  20336. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20337. constructor(...args) {
  20338. // eslint-disable-next-line no-constructor-return
  20339. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20340. }
  20341. });
  20342. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20343. constructor(...args) {
  20344. // eslint-disable-next-line no-constructor-return
  20345. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20346. }
  20347. });
  20348. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20349. constructor(...args) {
  20350. // eslint-disable-next-line
  20351. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20352. }
  20353. });
  20354. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20355. constructor(...args) {
  20356. // eslint-disable-next-line no-constructor-return
  20357. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20358. }
  20359. });
  20360. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20361. constructor(...args) {
  20362. // eslint-disable-next-line no-constructor-return
  20363. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20364. }
  20365. });
  20366. this.registerType('torch.Size', class extends Array {
  20367. constructor(size) {
  20368. super(size.length);
  20369. for (let i = 0; i < size.length; i++) {
  20370. this[i] = size[i];
  20371. }
  20372. }
  20373. __len__() {
  20374. return this.length;
  20375. }
  20376. });
  20377. this.registerType('torch._C.TensorMeta', class {
  20378. });
  20379. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20380. });
  20381. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20382. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20383. super();
  20384. if (storage) {
  20385. this._storage = storage;
  20386. }
  20387. if (shape !== null && shape !== undefined) {
  20388. this._shape = shape;
  20389. }
  20390. if (dtype) {
  20391. this._dtype = dtype;
  20392. }
  20393. this._layout = layout || torch.strided;
  20394. if (device) {
  20395. this._device = device;
  20396. }
  20397. if (requires_grad !== undefined) {
  20398. this.requires_grad = requires_grad;
  20399. }
  20400. }
  20401. clone() {
  20402. const tensor = new torch.Tensor(this._storage, this._shape, this._dtype, this._layout, this._device, this.requires_grad);
  20403. tensor._storage_offset = this._storage_offset;
  20404. tensor._stride = this._stride;
  20405. tensor._values = this._values;
  20406. tensor._indices = this._indices;
  20407. tensor.__quantized__ = this.__quantized__;
  20408. tensor.__nested__ = this.__nested__;
  20409. tensor.data = this.data;
  20410. tensor._backward_hooks = this._backward_hooks;
  20411. return tensor;
  20412. }
  20413. get device() {
  20414. if (this._device !== undefined) {
  20415. return this._device;
  20416. }
  20417. return this.storage().device;
  20418. }
  20419. get dtype() {
  20420. if (this._dtype !== undefined) {
  20421. return this._dtype;
  20422. }
  20423. if (this._layout === torch.sparse_coo) {
  20424. return this._values.dtype;
  20425. }
  20426. return this.storage().dtype;
  20427. }
  20428. get shape() {
  20429. return this._shape;
  20430. }
  20431. get layout() {
  20432. return this._layout;
  20433. }
  20434. get values() {
  20435. if (this._layout === torch.sparse_coo) {
  20436. return this._values;
  20437. }
  20438. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20439. }
  20440. get indices() {
  20441. if (this._layout === torch.sparse_coo) {
  20442. return this._indices;
  20443. }
  20444. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20445. }
  20446. get is_quantized() {
  20447. return this.__quantized__ === true;
  20448. }
  20449. get is_nested() {
  20450. return this.__nested__ === true;
  20451. }
  20452. get is_sparse() {
  20453. return this.layout !== torch.strided;
  20454. }
  20455. size() {
  20456. return this._shape;
  20457. }
  20458. storage() {
  20459. return this._storage;
  20460. }
  20461. storage_offset() {
  20462. return this._storage_offset;
  20463. }
  20464. stride() {
  20465. return this._stride;
  20466. }
  20467. resize_(shape) {
  20468. this._shape = shape;
  20469. }
  20470. __len__() {
  20471. return this._shape[0];
  20472. }
  20473. __setstate__(state) {
  20474. switch (state.length) {
  20475. case 3:
  20476. break;
  20477. case 4:
  20478. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20479. break;
  20480. case 5:
  20481. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20482. break;
  20483. default:
  20484. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20485. }
  20486. }
  20487. set_(source, storage_offset, size, stride) {
  20488. this._storage = source;
  20489. this._storage_offset = storage_offset;
  20490. this._shape = size;
  20491. this._stride = stride;
  20492. }
  20493. __bool__() {
  20494. return true;
  20495. }
  20496. __int__() {
  20497. const storage = this.storage();
  20498. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20499. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20500. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20501. return view.getBigInt64(0, true);
  20502. }
  20503. return NaN;
  20504. }
  20505. __float__() {
  20506. const storage = this.storage();
  20507. if (storage && storage.dtype.__reduce__() === 'float32') {
  20508. if (storage.size() !== undefined && storage.data.length === 4) {
  20509. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20510. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20511. return view.getFloat32(0, true);
  20512. }
  20513. }
  20514. return NaN;
  20515. }
  20516. __str__() {
  20517. return 'tensor(...)';
  20518. }
  20519. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20520. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20521. t.__setstate__([null, storage_offset, size, stride]);
  20522. return t;
  20523. }
  20524. });
  20525. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20526. constructor(data, requires_grad) {
  20527. super();
  20528. this.data = data || new torch.Tensor([]);
  20529. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20530. }
  20531. });
  20532. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20533. });
  20534. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20535. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20536. super();
  20537. this.allow_fallback_kernels = allow_fallback_kernels;
  20538. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20539. this.shape_env = shape_env;
  20540. this.enter_stack = [];
  20541. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20542. }
  20543. __enter__() {
  20544. const prev_only_lift_cpu_tensors = null;
  20545. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20546. if (this === maybe_prev_fake_mode) {
  20547. torch._C._set_dispatch_mode(this);
  20548. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20549. } else {
  20550. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20551. return super.__enter__();
  20552. }
  20553. return this;
  20554. }
  20555. __exit__(exc_type, exc_value, traceback) {
  20556. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20557. if (live) {
  20558. super.__exit__(exc_type, exc_value, traceback);
  20559. if (maybe_prev_fake_mode !== null) {
  20560. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20561. }
  20562. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20563. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20564. }
  20565. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20566. }
  20567. }
  20568. });
  20569. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20570. constructor(requires_grad /*, device, dtype */) {
  20571. super(undefined, requires_grad);
  20572. }
  20573. });
  20574. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20575. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20576. constructor(...args) {
  20577. // eslint-disable-next-line no-constructor-return
  20578. return new torch.Tensor(...args);
  20579. }
  20580. });
  20581. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20582. constructor(...args) {
  20583. // eslint-disable-next-line no-constructor-return
  20584. return new torch.Tensor(...args);
  20585. }
  20586. });
  20587. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20588. constructor(...args) {
  20589. // eslint-disable-next-line no-constructor-return
  20590. return new torch.Tensor(...args);
  20591. }
  20592. });
  20593. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20594. constructor(...args) {
  20595. // eslint-disable-next-line no-constructor-return
  20596. return new torch.Tensor(...args);
  20597. }
  20598. });
  20599. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20600. constructor(...args) {
  20601. // eslint-disable-next-line no-constructor-return
  20602. return new torch.Tensor(...args);
  20603. }
  20604. });
  20605. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20606. constructor(...args) {
  20607. // eslint-disable-next-line no-constructor-return
  20608. return new torch.Tensor(...args);
  20609. }
  20610. });
  20611. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20612. constructor(...args) {
  20613. // eslint-disable-next-line no-constructor-return
  20614. return new torch.Tensor(...args);
  20615. }
  20616. });
  20617. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20618. constructor(...args) {
  20619. // eslint-disable-next-line no-constructor-return
  20620. return new torch.Tensor(...args);
  20621. }
  20622. });
  20623. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20624. constructor(...args) {
  20625. // eslint-disable-next-line no-constructor-return
  20626. return new torch.Tensor(...args);
  20627. }
  20628. });
  20629. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20630. constructor(...args) {
  20631. // eslint-disable-next-line no-constructor-return
  20632. return new torch.Tensor(...args);
  20633. }
  20634. });
  20635. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20636. constructor(...args) {
  20637. // eslint-disable-next-line no-constructor-return
  20638. return new torch.Tensor(...args);
  20639. }
  20640. });
  20641. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20642. constructor(...args) {
  20643. // eslint-disable-next-line no-constructor-return
  20644. return new torch.Tensor(...args);
  20645. }
  20646. });
  20647. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20648. constructor(...args) {
  20649. // eslint-disable-next-line no-constructor-return
  20650. return new torch.Tensor(...args);
  20651. }
  20652. });
  20653. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20654. constructor(...args) {
  20655. // eslint-disable-next-line no-constructor-return
  20656. return new torch.Tensor(...args);
  20657. }
  20658. });
  20659. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20660. constructor(...args) {
  20661. // eslint-disable-next-line no-constructor-return
  20662. return new torch.Tensor(...args);
  20663. }
  20664. });
  20665. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20666. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20667. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20668. constructor(...args) {
  20669. // eslint-disable-next-line no-constructor-return
  20670. return new torch.Tensor(...args);
  20671. }
  20672. });
  20673. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20674. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20675. constructor(...args) {
  20676. // eslint-disable-next-line no-constructor-return
  20677. return new torch.Tensor(...args);
  20678. }
  20679. });
  20680. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20681. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20682. constructor(...args) {
  20683. // eslint-disable-next-line no-constructor-return
  20684. return new torch.Tensor(...args);
  20685. }
  20686. });
  20687. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20688. this.registerType('torchao.dtypes.utils.Layout', class {});
  20689. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20690. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20691. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20692. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20693. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20694. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20695. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20696. this.registerType('torch.SymBool', class {
  20697. constructor(node) {
  20698. this.node = node;
  20699. }
  20700. });
  20701. this.registerType('torch.SymInt', class {
  20702. constructor(node) {
  20703. this.node = node;
  20704. }
  20705. toString() {
  20706. return this.node.__str__();
  20707. }
  20708. });
  20709. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20710. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20711. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20712. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20713. /* eslint-disable no-multi-assign */
  20714. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20715. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20716. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20717. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20718. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20719. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20720. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20721. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20722. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20723. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20724. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20725. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20726. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20727. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20728. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20729. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20730. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20731. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20732. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20733. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20734. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20735. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20736. torch.bits8 = new torch.dtype(21, 'bits8');
  20737. torch.bits16 = new torch.dtype(22, 'bits16');
  20738. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20739. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20740. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20741. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20742. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  20743. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  20744. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  20745. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20746. ['uint8', 'BYTE'],
  20747. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20748. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20749. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20750. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20751. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20752. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20753. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20754. torch.channels_last = new torch.memory_format('channels_last');
  20755. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20756. torch.preserve_format = new torch.memory_format('preserve_format');
  20757. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20758. ['contiguous_format', 'ContiguousFormat'],
  20759. ['channels_last', 'ChannelsLast'],
  20760. ['channels_last_3d', 'ChannelsLast3d'],
  20761. ['preserve_format', 'PreserveFormat']
  20762. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20763. /* eslint-enable no-multi-assign */
  20764. torch.strided = new torch.layout('strided');
  20765. torch.sparse_coo = new torch.layout('sparse_coo');
  20766. torch.sparse_csr = new torch.layout('sparse_csr');
  20767. torch.sparse_csc = new torch.layout('sparse_csc');
  20768. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20769. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20770. torch._mkldnn = new torch.layout('_mkldnn');
  20771. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20772. ['sparse_coo', 'SparseCoo'],
  20773. ['sparse_csr', 'SparseCsr'],
  20774. ['sparse_csc', 'SparseCsc'],
  20775. ['sparse_bsr', 'SparseBsr'],
  20776. ['sparse_bsc', 'SparseBsc'],
  20777. ['_mkldnn', '_mkldnn'],
  20778. ['strided', 'Strided'],
  20779. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20780. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20781. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20782. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20783. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20784. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20785. torch.inf = this.register('math').inf;
  20786. this.registerFunction('fastcore.basics._using_attr');
  20787. this.registerFunction('fastcore.imports.noop');
  20788. this.registerType('fastcore.basics.fastuple', class {});
  20789. this.registerType('fastcore.basics.GetAttr', class {});
  20790. this.registerType('fastcore.dispatch._TypeDict', class {});
  20791. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20792. this.registerType('fastcore.foundation.L', class {});
  20793. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20794. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20795. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20796. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20797. this.registerType('fastai.basic_train.Learner', class {});
  20798. this.registerType('fastai.basic_train.Recorder', class {});
  20799. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20800. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20801. return self.invoke(cls, [tensor]);
  20802. });
  20803. this.registerFunction('fastai.torch_core.trainable_params');
  20804. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20805. const tensor = self.invoke(type, [func(...args)]);
  20806. Object.assign(tensor, dict);
  20807. return tensor;
  20808. });
  20809. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20810. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20811. constructor(x) {
  20812. super();
  20813. Object.assign(this, x);
  20814. }
  20815. });
  20816. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20817. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20818. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20819. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20820. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20821. this.registerFunction('fastai.torch_core.uniform');
  20822. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20823. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20824. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20825. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20826. this.registerFunction('fastai.callback.hook._hook_inner');
  20827. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20828. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20829. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20830. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20831. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20832. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20833. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20834. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20835. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20836. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20837. this.registerType('fastai.data.core.Datasets', class {});
  20838. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20839. this.registerType('fastai.data.core.FilteredBase', class {});
  20840. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20841. this.registerType('fastai.data.core.TfmdLists', class {});
  20842. this.registerType('fastai.data.load._FakeLoader', class {});
  20843. this.registerFunction('fastai.data.load._wif');
  20844. this.registerType('fastai.data.transforms.Categorize', class {});
  20845. this.registerType('fastai.data.transforms.Category', class {});
  20846. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20847. this.registerType('fastai.data.transforms.ColReader', class {});
  20848. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20849. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20850. this.registerType('fastai.data.transforms.Normalize', class {});
  20851. this.registerType('fastai.data.transforms.parent_label', class {});
  20852. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20853. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20854. this.registerType('fastai.data.transforms.ToTensor', class {});
  20855. this.registerType('fastai.data_block.CategoryList', class {});
  20856. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20857. this.registerType('fastai.imports.noop', class {});
  20858. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20859. this.registerType('fastai.layers.ConvLayer', class {});
  20860. this.registerType('fastai.layers.Embedding', class {});
  20861. this.registerType('fastai.layers.Flatten', class {});
  20862. this.registerType('fastai.layers.FlattenedLoss', class {});
  20863. this.registerType('fastai.layers.LinBnDrop', class {});
  20864. this.registerType('fastai.layers.MergeLayer', class {});
  20865. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20866. this.registerType('fastai.layers.ResBlock', class {});
  20867. this.registerType('fastai.layers.SelfAttention', class {});
  20868. this.registerType('fastai.layers.SigmoidRange', class {});
  20869. this.registerType('fastai.layers.TimeDistributed', class {});
  20870. this.registerType('fastai.layers.ToTensorBase', class {});
  20871. this.registerType('fastai.learner._ConstantFunc', class {});
  20872. this.registerType('fastai.learner.Metric', class {});
  20873. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20874. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20875. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20876. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20877. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20878. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20879. this.registerType('fastai.learner.Recorder', class {});
  20880. this.registerType('fastai.losses.BaseLoss', class {});
  20881. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20882. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20883. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20884. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20885. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20886. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20887. this.registerType('fastai.metrics.Dice', class {});
  20888. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20889. this.registerFunction('fastai.metrics._rmse');
  20890. this.registerFunction('fastai.metrics.accuracy');
  20891. this.registerFunction('fastai.metrics.accuracy_multi');
  20892. this.registerFunction('fastai.metrics.foreground_acc');
  20893. this.registerFunction('fastai.metrics.mse');
  20894. this.registerFunction('fastai.metrics.error_rate');
  20895. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  20896. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  20897. this.registerFunction('fastai.optimizer.Adam');
  20898. this.registerFunction('fastai.optimizer.adam_step');
  20899. this.registerFunction('fastai.optimizer.average_grad');
  20900. this.registerFunction('fastai.optimizer.average_sqr_grad');
  20901. this.registerFunction('fastai.optimizer.RAdam');
  20902. this.registerFunction('fastai.optimizer.step_stat');
  20903. this.registerFunction('fastai.optimizer.weight_decay');
  20904. this.registerType('fastai.tabular.core.Categorify', class {});
  20905. this.registerType('fastai.tabular.core.FillMissing', class {});
  20906. this.registerType('fastai.tabular.core.FillStrategy', class {});
  20907. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  20908. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  20909. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  20910. this.registerType('fastai.tabular.core.Tabular', class {});
  20911. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  20912. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  20913. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  20914. this.registerType('fastai.tabular.model.TabularModel', class {});
  20915. this.registerFunction('fastai.vision.augment.aug_transforms');
  20916. this.registerFunction('fastai.vision.augment.dihedral_mat');
  20917. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  20918. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  20919. this.registerType('fastai.vision.augment._WarpCoord', class {});
  20920. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  20921. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  20922. this.registerType('fastai.vision.augment.Brightness', class {});
  20923. this.registerType('fastai.vision.augment.flip_mat', class {});
  20924. this.registerType('fastai.vision.augment.Flip', class {});
  20925. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  20926. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  20927. this.registerType('fastai.vision.augment.Resize', class {});
  20928. this.registerType('fastai.vision.augment.rotate_mat', class {});
  20929. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  20930. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  20931. this.registerType('fastai.vision.augment.zoom_mat', class {});
  20932. this.registerType('fastai.vision.core.PILImage', class {});
  20933. this.registerType('fastai.vision.core.PILMask', class {});
  20934. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  20935. this.registerType('fastai.vision.data.ImageList', class {});
  20936. this.registerType('fastai.vision.data.ImageItemList', class {});
  20937. this.registerType('fastai.vision.image.Image', class {});
  20938. this.registerType('fastai.vision.image.RandTransform', class {});
  20939. this.registerType('fastai.vision.image.TfmCrop', class {});
  20940. this.registerFunction('fastai.vision.learner._resnet_split');
  20941. this.registerFunction('fastai.vision.learner.default_split');
  20942. this.registerFunction('fastai.vision.learner.default_split');
  20943. this.registerType('fastai.vision.learner.TimmBody', class {});
  20944. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  20945. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  20946. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  20947. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  20948. this.registerFunction('fastai.vision.transform._crop_pad');
  20949. }
  20950. exec(code , context) {
  20951. const ast = this.ast;
  20952. const program = ast.parse(code, '', null, null);
  20953. if (!program) {
  20954. throw new python.Error("Module '?' parse error.");
  20955. }
  20956. this.block(program.body, context);
  20957. }
  20958. debug(/* file */) {
  20959. }
  20960. source(file) {
  20961. if (this._sources.has(file)) {
  20962. return this._sources.get(file);
  20963. }
  20964. return null;
  20965. }
  20966. read(file) {
  20967. const buffer = this.source(file);
  20968. if (buffer) {
  20969. const debug = this.debug(file);
  20970. return this.parse(file, buffer, debug);
  20971. }
  20972. return null;
  20973. }
  20974. parse(filename, buffer, debug) {
  20975. const ast = this.ast;
  20976. const source = this._utf8Decoder.decode(buffer);
  20977. const program = ast.parse(source, filename, null, debug);
  20978. if (!program) {
  20979. throw new python.Error(`Module '${filename}' parse error.`);
  20980. }
  20981. return program;
  20982. }
  20983. import(name, current, level) {
  20984. if (level) {
  20985. let bits = current.split('.');
  20986. if (bits.length < level) {
  20987. throw new python.Error('Invalid relative import beyond top-level package.');
  20988. }
  20989. bits = bits.slice(0, bits.length - level);
  20990. const base = bits.join('.');
  20991. name = name ? [base, name].join('.') : base;
  20992. }
  20993. const index = name.lastIndexOf('.');
  20994. let parent = null;
  20995. let child = null;
  20996. if (index > 0) {
  20997. parent = name.substring(0, index);
  20998. child = name.substring(index + 1);
  20999. this.import(parent);
  21000. }
  21001. if (!this._modules.has(name)) {
  21002. const module = this._registry.get(name) || new this.builtins.module(name);
  21003. module.__package__ = name;
  21004. this._modules.set(name, module);
  21005. const path = name.split('.').join('/');
  21006. module.__path__ = [path];
  21007. const file = `${path}.py`;
  21008. const program = this.read(file);
  21009. if (program) {
  21010. module.__file__ = file;
  21011. for (const [name, value] of Object.entries(this.builtins)) {
  21012. switch (name) {
  21013. case '__class__':
  21014. case '__package__':
  21015. case '__module__':
  21016. case '__name__':
  21017. case '__path__':
  21018. case '__file__':
  21019. break;
  21020. default:
  21021. module[name] = value;
  21022. break;
  21023. }
  21024. }
  21025. const context = new python.Execution.Context(module, null);
  21026. if (name !== 'builtins') {
  21027. context.set('__builtins__', this._modules.get('builtins'));
  21028. }
  21029. this.block(program.body, context);
  21030. }
  21031. if (parent) {
  21032. const parent_module = this._modules.get(parent);
  21033. parent_module[child] = module;
  21034. }
  21035. }
  21036. return this._modules.get(name);
  21037. }
  21038. __import__(name, globals, locals, fromlist, level) {
  21039. let module = null;
  21040. level = level || 0;
  21041. if (level === 0) {
  21042. module = this.import(name);
  21043. } else {
  21044. globals = globals || {};
  21045. let current = globals.__package__;
  21046. if (!current) {
  21047. const spec = globals.__spec__;
  21048. if (spec) {
  21049. current = spec.parent;
  21050. } else {
  21051. const name = globals.__name__;
  21052. const bits = name.split('.');
  21053. bits.pop();
  21054. current = bits.join('.');
  21055. }
  21056. }
  21057. module = this.import(name, current, level);
  21058. }
  21059. if (!fromlist) {
  21060. if (level === 0) {
  21061. return this.import(name.split('.')[0]);
  21062. } else if (name) {
  21063. throw new python.Error(`Unsupported relative import '${name}'.`);
  21064. // cut_off = len(name) - len(name.partition('.')[0])
  21065. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  21066. }
  21067. } else if (module.__path__) {
  21068. const handle_fromlist = (module, fromlist, recursive) => {
  21069. for (const name of fromlist) {
  21070. if (name === '*') {
  21071. if (!recursive && module.__all__) {
  21072. handle_fromlist(module, module.__all__, true);
  21073. }
  21074. } else if (!module[name]) {
  21075. this.import(`${module.__name__}.${name}`);
  21076. }
  21077. }
  21078. return module;
  21079. };
  21080. handle_fromlist(module, fromlist);
  21081. }
  21082. return module;
  21083. }
  21084. module(name) {
  21085. return this._modules.get(name);
  21086. }
  21087. resolve(name) {
  21088. const index = name.lastIndexOf('.');
  21089. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  21090. const moduleName = index === -1 ? '' : name.substring(0, index);
  21091. const module = this.import(moduleName);
  21092. let type = module ? module[memberName] : null;
  21093. if (!type) {
  21094. if (!this._unresolved.has(name)) {
  21095. const moduleName = name.split('.').shift();
  21096. if (this._registry.has(moduleName) && moduleName !== '__main__' && moduleName !== '__torch__') {
  21097. this.emit('resolve', name);
  21098. }
  21099. const type = this._createType(name, class {});
  21100. this._unresolved.set(name, type);
  21101. }
  21102. type = this._unresolved.get(name);
  21103. }
  21104. return type;
  21105. }
  21106. invoke(target, args) {
  21107. const builtins = this.builtins;
  21108. if (typeof target === 'string') {
  21109. target = this.resolve(target);
  21110. }
  21111. if (target) {
  21112. if (target.__class__ === builtins.type) {
  21113. if (target.prototype && target.prototype.__class__ === target) {
  21114. return Reflect.construct(target, args);
  21115. }
  21116. const obj = Object.create(target);
  21117. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21118. obj.__init__(...args);
  21119. }
  21120. return obj;
  21121. } else if (target.__class__ === builtins.function) {
  21122. if (target.__call__) {
  21123. return target.__call__(args);
  21124. }
  21125. return target(...args);
  21126. }
  21127. }
  21128. throw new python.Error('Unsupported invoke target.');
  21129. }
  21130. call(target, name, args, keywords, context) {
  21131. const builtins = this.builtins;
  21132. const callTarget = this.target(target, context);
  21133. const callArguments = args.map((arg) => this.expression(arg, context));
  21134. if (!callTarget || (name !== null && !callTarget[name])) {
  21135. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21136. name = null;
  21137. callArguments.shift();
  21138. } else {
  21139. const targetName = `${this.identifier(target)}.${name}`;
  21140. throw new python.Error(`Unknown function '${targetName}'.`);
  21141. }
  21142. }
  21143. const func = name ? callTarget[name] : callTarget;
  21144. if (func.__class__ === builtins.type) {
  21145. if (func.prototype && func.prototype.__class__ === func) {
  21146. return Reflect.construct(func, callArguments);
  21147. }
  21148. const obj = Object.create(func);
  21149. obj.__class__ = func;
  21150. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21151. obj.__init__(...args);
  21152. }
  21153. return obj;
  21154. }
  21155. if (func.__class__ === builtins.function) {
  21156. if (func.__call__) {
  21157. return func.__call__(callArguments);
  21158. }
  21159. }
  21160. if (func.__class__ === builtins.method) {
  21161. if (func.__call__) {
  21162. return func.__call__([callTarget].concat(callArguments));
  21163. }
  21164. }
  21165. if (typeof func === 'function') {
  21166. return func.apply(callTarget, callArguments);
  21167. }
  21168. throw new python.Error('Unsupported call expression.');
  21169. }
  21170. apply(method, args, context) {
  21171. const locals = Array.prototype.slice.call(args);
  21172. context = new python.Execution.Context(context.globals, {});
  21173. args = method.args.posonlyargs.concat(method.args.args);
  21174. const default_pos = args.length - method.args.defaults.length;
  21175. for (let i = 0; i < method.args.args.length; i++) {
  21176. const arg = method.args.args[i];
  21177. let value = null;
  21178. if (locals.length > 0) {
  21179. value = locals.shift();
  21180. } else if (i >= default_pos) {
  21181. value = this.expression(method.args.defaults[i - default_pos], context);
  21182. } else {
  21183. throw new python.Error('Missing required positional argument.');
  21184. }
  21185. context.set(arg.arg, value);
  21186. }
  21187. return this.block(method.body, context);
  21188. }
  21189. block(statements, context) {
  21190. statements = Array.prototype.slice.call(statements);
  21191. while (statements.length > 0) {
  21192. const stmt = statements.shift();
  21193. const value = this.statement(stmt, context);
  21194. if (value !== undefined) {
  21195. return value;
  21196. }
  21197. }
  21198. return undefined;
  21199. }
  21200. statement(stmt, context) {
  21201. const ast = this.ast;
  21202. const builtins = this.builtins;
  21203. if (stmt instanceof ast.Pass) {
  21204. // pass
  21205. } else if (stmt instanceof ast.Constant) {
  21206. // pass
  21207. } else if (stmt instanceof ast.Return) {
  21208. return this.expression(stmt.value, context);
  21209. } else if (stmt instanceof ast.FunctionDef) {
  21210. const module = context.get('__name__');
  21211. /* eslint-disable consistent-this */
  21212. const self = this;
  21213. /* eslint-enable consistent-this */
  21214. const parent = context.get('__class__');
  21215. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21216. const func = {
  21217. __class__: type,
  21218. __globals__: context,
  21219. __module__: module,
  21220. __name__: stmt.name,
  21221. __code__: stmt,
  21222. __call__(args) {
  21223. return self.apply(this.__code__, args, this.__globals__);
  21224. }
  21225. };
  21226. context.set(stmt.name, func);
  21227. } else if (stmt instanceof ast.ClassDef) {
  21228. const bases = stmt.bases.map((base) => this.base(base, context));
  21229. if (bases.length > 1) {
  21230. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21231. }
  21232. const base = bases.length === 1 ? bases[0] : null;
  21233. const name = `${context.get('__name__')}.${stmt.name}`;
  21234. const value = this._createType(name, base ? class extends base {} : class {});
  21235. value.__bases__ = bases;
  21236. context.set(stmt.name, value);
  21237. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21238. } else if (stmt instanceof ast.AnnAssign) {
  21239. const target = this.identifier(stmt.target, context);
  21240. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21241. } else if (stmt instanceof ast.Assign) {
  21242. this.expression(stmt, context);
  21243. } else if (stmt instanceof ast.If) {
  21244. const test = this.expression(stmt.test, context);
  21245. if (test === true || test) {
  21246. const value = this.block(stmt.body, context);
  21247. if (value !== undefined) {
  21248. return value;
  21249. }
  21250. } else if (test === false) {
  21251. if (stmt.orelse) {
  21252. const value = this.block(stmt.orelse, context);
  21253. if (value !== undefined) {
  21254. return value;
  21255. }
  21256. }
  21257. } else {
  21258. throw new python.Error('Unsupported condition.');
  21259. }
  21260. } else if (stmt instanceof ast.For) {
  21261. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21262. const range = this.expression(stmt.iter, context);
  21263. const variable = stmt.target;
  21264. for (const current of range) {
  21265. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21266. const value = this.block(stmt.body.statements, context);
  21267. if (value !== undefined) {
  21268. return value;
  21269. }
  21270. }
  21271. } else {
  21272. throw new python.Error("Unsupported 'for' statement.");
  21273. }
  21274. } else if (stmt instanceof ast.While) {
  21275. const test = this.expression(stmt.test, context);
  21276. if (test) {
  21277. const value = this.block(stmt.body.statements, context);
  21278. if (value !== undefined) {
  21279. return value;
  21280. }
  21281. }
  21282. } else if (stmt instanceof ast.With) {
  21283. const items = [];
  21284. for (const item of stmt.items) {
  21285. items.push(this.expression(item.context_expr, context));
  21286. }
  21287. for (const item of items) {
  21288. if (item.__enter__ && item.__enter__.__call__) {
  21289. item.__enter__.__call__([item]);
  21290. }
  21291. }
  21292. const value = this.block(stmt.body, context);
  21293. for (const item of items) {
  21294. if (item.__exit__ && item.__exit__.__call__) {
  21295. item.__exit__.__call__([item]);
  21296. }
  21297. }
  21298. if (value !== undefined) {
  21299. return value;
  21300. }
  21301. } else if (stmt instanceof ast.Expr) {
  21302. this.expression(stmt.value, context);
  21303. } else if (stmt instanceof ast.Import) {
  21304. for (const alias of stmt.names) {
  21305. let module = this.__import__(alias.name, context);
  21306. if (alias.asname) {
  21307. const bits = alias.name.split('.').reverse();
  21308. bits.pop();
  21309. while (bits.length > 0) {
  21310. module = module[bits.pop()];
  21311. }
  21312. context.set(alias.asname, module);
  21313. } else {
  21314. context.set(alias.name.split('.')[0], module);
  21315. }
  21316. }
  21317. } else if (stmt instanceof ast.ImportFrom) {
  21318. const fromlist = stmt.names.map((name) => name.name);
  21319. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21320. for (const entry of stmt.names) {
  21321. const name = entry.name;
  21322. const asname = entry.asname ? entry.asname : null;
  21323. if (!module[name]) {
  21324. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21325. }
  21326. context.set(asname ? asname : name, module[name]);
  21327. }
  21328. } else {
  21329. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21330. }
  21331. return undefined;
  21332. }
  21333. expression(expr, context) {
  21334. const ast = this.ast;
  21335. const builtins = this.builtins;
  21336. const typing = this.typing;
  21337. const self = context.get('self');
  21338. switch (expr.__class__.__name__) {
  21339. case 'Assign': {
  21340. const [target] = expr.targets;
  21341. if (target instanceof ast.Name) {
  21342. const value = this.expression(expr.value, context);
  21343. context.set(target.id, value);
  21344. return undefined;
  21345. } else if (target instanceof ast.Subscript) {
  21346. if (target.value instanceof ast.Name &&
  21347. target.slice instanceof ast.List &&
  21348. target.slice.elts.length === 1) {
  21349. const index = this.expression(target.slice.elts[0], context);
  21350. const id = target.value.id;
  21351. if (id === '__annotations__') {
  21352. context.set(id, context.get(id) || {});
  21353. }
  21354. const obj = context.get(id);
  21355. const value = this.expression(expr.value, context);
  21356. if (obj instanceof Map) {
  21357. obj.set(index, value);
  21358. } else {
  21359. obj[index] = value;
  21360. }
  21361. return undefined;
  21362. }
  21363. } else if (target instanceof ast.Attribute) {
  21364. const obj = this.expression(target.value, context);
  21365. const value = this.expression(expr.value, context);
  21366. obj[target.attr] = value;
  21367. return undefined;
  21368. } else if (target instanceof ast.Tuple) {
  21369. context.target.push(target.elts);
  21370. const value = this.expression(expr.value, context);
  21371. context.target.pop();
  21372. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21373. if (target.elts.length < value.length) {
  21374. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21375. }
  21376. if (target.elts.length > value.length) {
  21377. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21378. }
  21379. for (let i = 0; i < value.length; i++) {
  21380. context.set(target.elts[i].id, value[i]);
  21381. }
  21382. return undefined;
  21383. }
  21384. }
  21385. break;
  21386. }
  21387. case 'List': {
  21388. return expr.elts.map((expr) => this.expression(expr, context));
  21389. }
  21390. case 'Constant': {
  21391. return expr.value;
  21392. }
  21393. case 'Subscript': {
  21394. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21395. const id = expr.value.id;
  21396. if (context.get(id)) {
  21397. const index = this.expression(expr.slice, context);
  21398. const target = context.get(id);
  21399. if (target instanceof Map) {
  21400. return target.get(index);
  21401. }
  21402. return target[index < 0 ? target.length + index : index];
  21403. }
  21404. }
  21405. const value = this.expression(expr.value, context);
  21406. if (value && expr.slice instanceof ast.List &&
  21407. (value.__class__ === typing._TupleType ||
  21408. value.__class__ === typing._SpecialGenericAlias ||
  21409. value.__class__ === typing._SpecialForm)) {
  21410. const type = { ...value };
  21411. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21412. return type;
  21413. }
  21414. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21415. const index = this.expression(expr.slice.elts[0], context);
  21416. if (value instanceof Map) {
  21417. return value.get(index);
  21418. }
  21419. return value[index < 0 ? value.length + index : index];
  21420. }
  21421. break;
  21422. }
  21423. case 'Attribute': {
  21424. const value = this.target(expr.value, context);
  21425. return value[expr.attr];
  21426. }
  21427. case 'Call': {
  21428. const func = expr.func;
  21429. if (func instanceof ast.Attribute) {
  21430. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21431. }
  21432. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21433. }
  21434. case 'Name': {
  21435. const id = expr.id;
  21436. if (id === 'self') {
  21437. return self;
  21438. }
  21439. const type = (value) => {
  21440. return value &&
  21441. (value.__class__ === builtins.type ||
  21442. value.__class__ === typing._TupleType ||
  21443. value.__class__ === typing._SpecialGenericAlias ||
  21444. value.__class__ === typing._SpecialForm);
  21445. };
  21446. const builtin = builtins[id];
  21447. if (type(builtin)) {
  21448. return builtin;
  21449. }
  21450. const value = context.get(id);
  21451. if (value === undefined) {
  21452. const value = typing[id];
  21453. if (type(value)) {
  21454. return value;
  21455. }
  21456. }
  21457. return value;
  21458. }
  21459. case 'Tuple': {
  21460. return expr.elts.map((expr) => this.expression(expr, context));
  21461. }
  21462. case 'Dict': {
  21463. const dict = {};
  21464. for (let i = 0; i < expr.keys.length; i++) {
  21465. const key = this.expression(expr.keys[i], context);
  21466. const value = this.expression(expr.values[i], context);
  21467. dict[key] = value;
  21468. }
  21469. return dict;
  21470. }
  21471. case 'UnaryOp': {
  21472. if (expr.op instanceof ast.USub) {
  21473. return -this.expression(expr.operand, context);
  21474. }
  21475. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21476. }
  21477. case 'binary': {
  21478. switch (expr.op) {
  21479. case '==': {
  21480. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21481. }
  21482. default: {
  21483. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21484. }
  21485. }
  21486. }
  21487. default: {
  21488. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21489. }
  21490. }
  21491. return undefined;
  21492. }
  21493. base(expr, context) {
  21494. return this.expression(expr, context);
  21495. }
  21496. identifier(expr) {
  21497. const ast = this.ast;
  21498. if (expr instanceof ast.Name) {
  21499. return expr.id;
  21500. }
  21501. if (expr instanceof ast.Attribute) {
  21502. return `${this.identifier(expr.value)}.${expr.attr}`;
  21503. }
  21504. return null;
  21505. }
  21506. target(expr, context) {
  21507. const ast = this.ast;
  21508. let current = expr;
  21509. let path = [];
  21510. for (;;) {
  21511. if (current instanceof ast.Attribute) {
  21512. path.push(current.attr);
  21513. current = current.value;
  21514. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21515. path.push(current.id);
  21516. break;
  21517. } else {
  21518. path = null;
  21519. break;
  21520. }
  21521. }
  21522. if (path) {
  21523. let target = null;
  21524. for (let i = path.length - 1; i >= 0; i--) {
  21525. const name = path[i];
  21526. if (target) {
  21527. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21528. } else {
  21529. target = context.get(name);
  21530. }
  21531. if (!target) {
  21532. break;
  21533. }
  21534. }
  21535. if (!target) {
  21536. path.reverse();
  21537. const name = path.join('.');
  21538. const file = `${path.join('/')}.py`;
  21539. if (this._sources.has(file)) {
  21540. target = this.import(name);
  21541. } else {
  21542. target = this.resolve(name);
  21543. }
  21544. }
  21545. return target;
  21546. }
  21547. return this.expression(expr, context);
  21548. }
  21549. add(name, source) {
  21550. this._sources.set(name, source);
  21551. }
  21552. on(event, listener) {
  21553. const value = this._events.get(event) || [];
  21554. value.push(listener);
  21555. this._events.set(event, value);
  21556. }
  21557. emit(event, ...args) {
  21558. if (this._events.has(event)) {
  21559. for (const callback of this._events.get(event)) {
  21560. callback(this, ...args);
  21561. }
  21562. }
  21563. }
  21564. register(name, value) {
  21565. if (!this._registry.has(name)) {
  21566. value = value || new (this._registry.get('builtins').module)(name);
  21567. this._registry.set(name, value);
  21568. let current = name;
  21569. for (;;) {
  21570. const index = current.lastIndexOf('.');
  21571. if (index === -1) {
  21572. break;
  21573. }
  21574. const child = current.substring(index + 1);
  21575. current = current.substring(0, index);
  21576. if (!value.__module__) {
  21577. value.__module__ = current;
  21578. }
  21579. const parent = this.register(current);
  21580. parent[child] = value;
  21581. value = parent;
  21582. }
  21583. }
  21584. return this._registry.get(name);
  21585. }
  21586. registerFunction(name, value) {
  21587. const builtins = this.builtins;
  21588. const index = name.lastIndexOf('.');
  21589. if (!value) {
  21590. value = () => {
  21591. throw new python.Error(`'${name}' is not implemented.`);
  21592. };
  21593. }
  21594. value.__class__ = builtins.function;
  21595. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21596. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21597. const module = this.register(value.__module__);
  21598. if (module[name]) {
  21599. throw new python.Error(`Function '${name}' is already registered.`);
  21600. }
  21601. module[value.__name__] = value;
  21602. return value;
  21603. }
  21604. registerOperator(name, value) {
  21605. this._operators.set(name, value);
  21606. }
  21607. _createType(name, value) {
  21608. const builtins = this.builtins;
  21609. const index = name.lastIndexOf('.');
  21610. value.__class__ = builtins.type;
  21611. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21612. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21613. value.prototype.__class__ = value;
  21614. return value;
  21615. }
  21616. registerType(name, value) {
  21617. value = this._createType(name, value);
  21618. const parts = name.split('.');
  21619. const memberName = parts.pop();
  21620. const moduleName = parts.join('.');
  21621. const module = this.register(moduleName);
  21622. if (module[memberName]) {
  21623. throw new python.Error(`Class '${memberName}' is already registered.`);
  21624. }
  21625. module[memberName] = value;
  21626. return value;
  21627. }
  21628. };
  21629. python.Execution.Context = class {
  21630. constructor(globals, locals) {
  21631. this.globals = globals;
  21632. this.locals = locals;
  21633. }
  21634. set(name, value) {
  21635. if (this.locals) {
  21636. this.locals[name] = value;
  21637. } else {
  21638. this.globals[name] = value;
  21639. }
  21640. }
  21641. get(name) {
  21642. if (this.locals && name in this.locals) {
  21643. return this.locals[name];
  21644. }
  21645. if (name in this.globals) {
  21646. return this.globals[name];
  21647. }
  21648. return undefined;
  21649. }
  21650. get target() {
  21651. this._target = this._target || [];
  21652. return this._target;
  21653. }
  21654. };
  21655. python.BinaryReader = class {
  21656. constructor(buffer) {
  21657. this._buffer = buffer;
  21658. this._length = buffer.length;
  21659. this._position = 0;
  21660. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21661. this._utf8Decoder = new TextDecoder('utf-8');
  21662. this._asciiDecoder = new TextDecoder('ascii');
  21663. }
  21664. get position() {
  21665. return this._position;
  21666. }
  21667. get length() {
  21668. return this._length;
  21669. }
  21670. seek(position) {
  21671. this._position = position >= 0 ? position : this._length + position;
  21672. if (this._position > this._buffer.length) {
  21673. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21674. }
  21675. }
  21676. skip(offset) {
  21677. this._position += offset;
  21678. if (this._position > this._buffer.length) {
  21679. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21680. }
  21681. }
  21682. stream(length) {
  21683. const buffer = this.read(length);
  21684. return new python.BinaryReader(buffer);
  21685. }
  21686. peek(length) {
  21687. const position = this._position;
  21688. length = length === undefined ? this._length - this._position : length;
  21689. this.skip(length);
  21690. const end = this._position;
  21691. this.skip(-length);
  21692. if (position === 0 && length === this._length) {
  21693. return this._buffer;
  21694. }
  21695. return this._buffer.subarray(position, end);
  21696. }
  21697. read(length) {
  21698. const position = this._position;
  21699. length = length === undefined ? this._length - this._position : length;
  21700. this.skip(length);
  21701. if (position === 0 && length === this._length) {
  21702. return this._buffer;
  21703. }
  21704. return this._buffer.subarray(position, this._position);
  21705. }
  21706. byte() {
  21707. const position = this._position;
  21708. this.skip(1);
  21709. return this._view.getUint8(position);
  21710. }
  21711. uint16() {
  21712. const position = this._position;
  21713. this.skip(2);
  21714. return this._view.getUint16(position, true);
  21715. }
  21716. int32() {
  21717. const position = this._position;
  21718. this.skip(4);
  21719. return this._view.getInt32(position, true);
  21720. }
  21721. uint32() {
  21722. const position = this._position;
  21723. this.skip(4);
  21724. return this._view.getUint32(position, true);
  21725. }
  21726. int64() {
  21727. const position = this._position;
  21728. this.skip(8);
  21729. return this._view.getBigInt64(position, true);
  21730. }
  21731. float64() {
  21732. const position = this._position;
  21733. this.skip(8);
  21734. return this._view.getFloat64(position, false);
  21735. }
  21736. string(size, encoding) {
  21737. const data = this.read(size);
  21738. return (encoding === 'utf-8') ?
  21739. this._utf8Decoder.decode(data) :
  21740. this._asciiDecoder.decode(data);
  21741. }
  21742. line() {
  21743. const index = this._buffer.indexOf(0x0A, this._position);
  21744. if (index === -1) {
  21745. throw new python.Error('Could not find end of line.');
  21746. }
  21747. const size = index - this._position;
  21748. const text = this.string(size, 'ascii');
  21749. this.skip(1);
  21750. return text;
  21751. }
  21752. };
  21753. python.StreamReader = class {
  21754. constructor(stream) {
  21755. this._stream = stream;
  21756. this._length = stream.length;
  21757. this._position = 0;
  21758. this._utf8Decoder = new TextDecoder('utf-8');
  21759. this._asciiDecoder = new TextDecoder('ascii');
  21760. }
  21761. get position() {
  21762. return this._position;
  21763. }
  21764. get length() {
  21765. return this._length;
  21766. }
  21767. seek(position) {
  21768. this._stream.seek(position);
  21769. this._position = this._stream.position;
  21770. }
  21771. skip(offset) {
  21772. this._position += offset;
  21773. if (this._position > this._length) {
  21774. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21775. }
  21776. }
  21777. stream(length) {
  21778. this._stream.seek(this._position);
  21779. this.skip(length);
  21780. return this._stream.stream(length);
  21781. }
  21782. peek(length) {
  21783. this._stream.seek(this._position);
  21784. return this._stream.peek(length);
  21785. }
  21786. read(length) {
  21787. this._stream.seek(this._position);
  21788. this.skip(length);
  21789. return this._stream.read(length);
  21790. }
  21791. byte() {
  21792. const position = this._fill(1);
  21793. return this._view.getUint8(position);
  21794. }
  21795. uint16() {
  21796. const position = this._fill(2);
  21797. return this._view.getUint16(position, true);
  21798. }
  21799. int32() {
  21800. const position = this._fill(4);
  21801. return this._view.getInt32(position, true);
  21802. }
  21803. uint32() {
  21804. const position = this._fill(4);
  21805. return this._view.getUint32(position, true);
  21806. }
  21807. int64() {
  21808. const position = this._fill(8);
  21809. return this._view.getBigInt64(position, true);
  21810. }
  21811. float64() {
  21812. const position = this._fill(8);
  21813. return this._view.getFloat64(position, false);
  21814. }
  21815. string(size, encoding) {
  21816. const data = this.read(size);
  21817. return (encoding === 'utf-8') ?
  21818. this._utf8Decoder.decode(data) :
  21819. this._asciiDecoder.decode(data);
  21820. }
  21821. line() {
  21822. let position = this._fill(0);
  21823. let index = this._buffer.indexOf(0x0A, position);
  21824. if (index === -1) {
  21825. const size = Math.min(0x20000000, this._stream.length - this._position);
  21826. this._fill(size);
  21827. this.skip(-size);
  21828. position = this._fill(0);
  21829. index = this._buffer.indexOf(0x0A, position);
  21830. if (index === -1) {
  21831. throw new python.Error('Could not find end of line.');
  21832. }
  21833. }
  21834. const size = index - position;
  21835. const text = this.string(size, 'ascii');
  21836. this.skip(1);
  21837. return text;
  21838. }
  21839. _fill(length) {
  21840. if (this._position + length > this._length) {
  21841. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21842. }
  21843. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21844. this._offset = this._position;
  21845. this._stream.seek(this._offset);
  21846. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21847. this._buffer = this._stream.read(size);
  21848. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21849. }
  21850. const position = this._position;
  21851. this._position += length;
  21852. return position - this._offset;
  21853. }
  21854. };
  21855. python.Error = class extends Error {
  21856. constructor(message) {
  21857. super(message);
  21858. this.name = 'Python Error';
  21859. }
  21860. };
  21861. export const Execution = python.Execution;