python.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925
  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. });
  2401. this.registerType('builtins.NoneType', class {});
  2402. this.registerType('builtins.object', class {
  2403. static __new__(cls, ...args) {
  2404. return execution.invoke(cls, args);
  2405. }
  2406. static __setattr__(obj, name, value) {
  2407. builtins.setattr(obj, name, value);
  2408. }
  2409. });
  2410. this.registerType('builtins.tuple', class extends Array {
  2411. constructor(items) {
  2412. super(items ? items.length : 0);
  2413. if (items) {
  2414. for (let i = 0; i < items.length; i++) {
  2415. this[i] = items[i];
  2416. }
  2417. }
  2418. }
  2419. });
  2420. this.registerType('builtins.staticmethod', class {});
  2421. this.registerType('builtins.Warning', class {});
  2422. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2423. this.registerType('builtins.BaseException', class {});
  2424. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2425. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2426. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2427. this.registerFunction('builtins.print', () => {});
  2428. this.registerFunction('builtins.unicode');
  2429. builtins.Ellipsis = new builtins.ellipsis();
  2430. this.registerType('typing._Final', class {});
  2431. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2432. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2433. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2434. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2435. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2436. this.registerType('typing._CallableType', class {});
  2437. this.registerFunction('typing.cast');
  2438. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2439. typing.Callable = Reflect.construct(typing._CallableType, []);
  2440. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2441. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2442. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2443. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2444. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2445. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2446. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2447. this.registerType('enum.Enum', class {
  2448. // __reduce_ex__(proto) {
  2449. // return self.__class__, (self._value_, )
  2450. // }
  2451. });
  2452. this.registerFunction('operator.add');
  2453. this.registerFunction('operator.and_');
  2454. this.registerFunction('operator.and_');
  2455. this.registerFunction('operator.eq');
  2456. this.registerFunction('operator.floordiv');
  2457. this.registerFunction('operator.ge');
  2458. this.registerFunction('operator.getitem');
  2459. this.registerFunction('operator.gt');
  2460. this.registerFunction('operator.le');
  2461. this.registerFunction('operator.lt');
  2462. this.registerFunction('operator.mod');
  2463. this.registerFunction('operator.mul');
  2464. this.registerFunction('operator.ne');
  2465. this.registerFunction('operator.neg');
  2466. this.registerFunction('operator.or_');
  2467. this.registerFunction('operator.pos');
  2468. this.registerFunction('operator.pow');
  2469. this.registerFunction('operator.sub');
  2470. this.registerFunction('operator.truediv');
  2471. this.registerFunction('sys.path.append', () => {});
  2472. this.registerFunction('sys.path.insert', () => {});
  2473. this.registerType('argparse.Namespace', class {
  2474. constructor(args) {
  2475. this.args = args;
  2476. }
  2477. });
  2478. this.registerType('catboost._catboost._CatBoost', class {
  2479. _deserialize_model(/* serialized_model_str */) {
  2480. }
  2481. });
  2482. this.registerType('catboost.core._CatBoostBase', class {
  2483. constructor() {
  2484. this._object = new catboost._catboost._CatBoost();
  2485. }
  2486. __setstate__(state) {
  2487. for (const [key, value] of state) {
  2488. if (key === '__model') {
  2489. this._load_from_string(value);
  2490. continue;
  2491. }
  2492. this[key] = value;
  2493. }
  2494. }
  2495. _load_from_string(dump_model_str) {
  2496. this._deserialize_model(dump_model_str);
  2497. }
  2498. _deserialize_model(dump_model_str) {
  2499. this._object._deserialize_model(dump_model_str);
  2500. }
  2501. });
  2502. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2503. load_model(/* blob */) {
  2504. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2505. // this._load_from_string(blob);
  2506. }
  2507. });
  2508. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2509. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2510. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2511. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2512. catboost.CatBoost = catboost.core.CatBoost;
  2513. this.registerType('collections.deque', class extends Array {
  2514. constructor(iterable) {
  2515. super();
  2516. if (Array.isArray(iterable)) {
  2517. for (const value of iterable) {
  2518. this.push(value);
  2519. }
  2520. }
  2521. }
  2522. });
  2523. this.registerType('collections.OrderedDict', class extends dict {});
  2524. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2525. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2526. this.registerType('cuml.internals.array.CumlArray', class {});
  2527. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2528. this.registerType('cuml.raft.common.handle.Handle', class {
  2529. __setstate__(state) {
  2530. this._handle = state;
  2531. }
  2532. });
  2533. this.registerType('cuml.svm.svr.SVR', class {});
  2534. this.registerType('datetime.date', class {});
  2535. this.registerType('datetime.datetime', class extends datetime.date {});
  2536. this.registerType('datetime.timedelta', class {});
  2537. this.registerType('datetime.tzinfo', class {});
  2538. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2539. this.registerType('dnnlib.tflib.network.Network', class {});
  2540. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2541. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2542. constructor(dict) {
  2543. Object.assign(this, dict);
  2544. }
  2545. });
  2546. this.registerType('haiku._src.data_structures.frozendict', class {
  2547. constructor(obj) {
  2548. Object.assign(this, obj);
  2549. }
  2550. });
  2551. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2552. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2553. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2554. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2555. this.registerType('io.BytesIO', class {
  2556. constructor(buf, mode) {
  2557. this.mode = mode || 'r';
  2558. this._buf = this.mode === 'w' ? null : buf;
  2559. this._point = 0;
  2560. }
  2561. seek(offset) {
  2562. if (this._buf.seek) {
  2563. this._buf.seek(offset);
  2564. }
  2565. this._point = offset;
  2566. }
  2567. read(size, stream) {
  2568. if (this._buf.stream && stream) {
  2569. return this._buf.stream(size);
  2570. }
  2571. if (this._buf.peek) {
  2572. return this._buf.read(size);
  2573. }
  2574. if (this._buf instanceof Uint8Array) {
  2575. const start = this._point;
  2576. this._point = size === undefined ? this._buf.length : start + size;
  2577. return this._buf.subarray(start, this._point);
  2578. }
  2579. throw new python.Error('Unsupported buffer type.');
  2580. }
  2581. write(data) {
  2582. const src = this._buf || new Uint8Array();
  2583. const end = this._point + data.length;
  2584. const size = Math.max(src.length, end);
  2585. this._buf = new Uint8Array(size);
  2586. this._buf.set(src, 0);
  2587. this._buf.set(data, this._point);
  2588. this._point = end;
  2589. }
  2590. getbuffer() {
  2591. return new builtins.memoryview(this._buf);
  2592. }
  2593. });
  2594. this.registerType('io.StringIO', class {
  2595. constructor() {
  2596. this._buf = [];
  2597. }
  2598. write(text) {
  2599. this._buf.push(text);
  2600. }
  2601. toString() {
  2602. return this._buf.join('');
  2603. }
  2604. });
  2605. this.registerType('numpy.dtype', class {
  2606. constructor(obj, align, copy) {
  2607. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2608. this.kind = 'V';
  2609. this.byteorder = '|';
  2610. this.itemsize = obj.itemsize;
  2611. this.names = obj.names;
  2612. this.fields = new Map();
  2613. for (let i = 0; i < obj.names.length; i++) {
  2614. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2615. }
  2616. return;
  2617. }
  2618. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2619. this.byteorder = obj.substring(0, 1);
  2620. obj = obj.substring(1);
  2621. } else {
  2622. this.byteorder = '=';
  2623. }
  2624. switch (obj) {
  2625. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2626. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2627. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2628. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2629. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2630. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2631. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2632. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2633. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2634. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2635. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2636. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2637. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2638. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2639. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2640. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2641. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2642. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2643. default:
  2644. if (obj.startsWith('V')) {
  2645. this.itemsize = parseInt(obj.substring(1), 10);
  2646. this.kind = 'V';
  2647. } else if (obj.startsWith('O')) {
  2648. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2649. this.kind = 'O';
  2650. } else if (obj.startsWith('S')) {
  2651. this.itemsize = parseInt(obj.substring(1), 10);
  2652. this.kind = 'S';
  2653. } else if (obj.startsWith('U')) { // Unicode string
  2654. this.kind = 'U';
  2655. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2656. } else if (obj.startsWith('T')) {
  2657. this.kind = 'T';
  2658. this.itemsize = parseInt(obj.substring(1), 10);
  2659. } else {
  2660. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2661. }
  2662. break;
  2663. }
  2664. if (align) {
  2665. this.align = align;
  2666. }
  2667. if (copy) {
  2668. this.copy = copy;
  2669. }
  2670. }
  2671. get str() {
  2672. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2673. }
  2674. get name() {
  2675. switch (this.kind) {
  2676. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2677. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2678. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2679. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2680. case 'M': return 'datetime64';
  2681. case 'm': return 'timedelta64';
  2682. case 'b': return 'bool';
  2683. default: return this.__name__;
  2684. }
  2685. }
  2686. __setstate__(state) {
  2687. switch (state.length) {
  2688. case 8:
  2689. [
  2690. this.version, this.byteorder, this.subarray, this.names,
  2691. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2692. ] = state;
  2693. break;
  2694. case 9:
  2695. [
  2696. this.version, this.byteorder, this.subarray, this.names,
  2697. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2698. this.metadata
  2699. ] = state;
  2700. break;
  2701. default:
  2702. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2703. }
  2704. }
  2705. get __name__() {
  2706. switch (this.kind) {
  2707. case 'b':
  2708. switch (this.itemsize) {
  2709. case 1: return 'boolean';
  2710. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2711. }
  2712. case 'i':
  2713. switch (this.itemsize) {
  2714. case 1: return 'int8';
  2715. case 2: return 'int16';
  2716. case 4: return 'int32';
  2717. case 8: return 'int64';
  2718. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2719. }
  2720. case 'u':
  2721. switch (this.itemsize) {
  2722. case 1: return 'uint8';
  2723. case 2: return 'uint16';
  2724. case 4: return 'uint32';
  2725. case 8: return 'uint64';
  2726. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2727. }
  2728. case 'f':
  2729. switch (this.itemsize) {
  2730. case 1: return 'float8e5m2';
  2731. case 2: return 'float16';
  2732. case 4: return 'float32';
  2733. case 8: return 'float64';
  2734. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2735. }
  2736. case 'c':
  2737. switch (this.itemsize) {
  2738. case 8: return 'complex<float32>';
  2739. case 16: return 'complex<float64>';
  2740. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2741. }
  2742. case 'S':
  2743. case 'T':
  2744. return 'string';
  2745. case 'U':
  2746. return 'string';
  2747. case 'M':
  2748. return 'datetime';
  2749. case 'm':
  2750. return 'timedelta';
  2751. case 'O':
  2752. return 'object';
  2753. case 'V':
  2754. return 'void';
  2755. default:
  2756. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2757. }
  2758. }
  2759. });
  2760. this.registerType('numpy.generic', class {});
  2761. this.registerType('numpy.inexact', class {});
  2762. this.registerType('numpy.flexible', class extends numpy.generic {});
  2763. this.registerType('numpy.void', class extends numpy.flexible {});
  2764. this.registerType('numpy.bool_', class extends numpy.generic {});
  2765. this.registerType('numpy.number', class extends numpy.generic {});
  2766. this.registerType('numpy.integer', class extends numpy.number {});
  2767. this.registerType('numpy.floating', class extends numpy.inexact {});
  2768. this.registerType('numpy.float16', class extends numpy.floating {});
  2769. this.registerType('numpy.float32', class extends numpy.floating {});
  2770. this.registerType('numpy.float64', class extends numpy.floating {});
  2771. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2772. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2773. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2774. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2775. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2776. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2777. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2778. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2779. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2780. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2781. this.registerType('numpy.datetime64', class extends numpy.generic {
  2782. constructor(...args) {
  2783. super();
  2784. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2785. [this.buffer] = args;
  2786. }
  2787. }
  2788. toString() {
  2789. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2790. const value = view.getBigInt64(0, true);
  2791. if (value === -9223372036854775808n) {
  2792. return 'NaT';
  2793. }
  2794. const date = new Date(Number(value / 1000000n));
  2795. return date.toISOString().slice(0, -1);
  2796. }
  2797. });
  2798. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2799. constructor() {
  2800. super('|T16');
  2801. }
  2802. });
  2803. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2804. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2805. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2806. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2807. this.registerType('gensim.models.fasttext.FastText', class {});
  2808. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2809. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2810. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2811. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2812. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2813. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2814. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2815. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2816. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2817. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2818. this.registerFunction('gensim.models.phrases.original_scorer');
  2819. this.registerType('gensim.models.phrases.Phraser', class {});
  2820. this.registerType('gensim.models.phrases.Phrases', class {});
  2821. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2822. this.registerType('gensim.models.word2vec.Vocab', class {});
  2823. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2824. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2825. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2826. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2827. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2828. throw new builtins.AttributeError('This method should be called on a class object.');
  2829. });
  2830. this.registerFunction('gensim.utils.identity');
  2831. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2832. constructor(obj) {
  2833. Object.assign(this, obj);
  2834. }
  2835. });
  2836. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2837. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2838. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2839. __read__(unpickler) {
  2840. if (this.dtype.__name__ === 'object') {
  2841. return unpickler.load();
  2842. }
  2843. if (this.numpy_array_alignment_bytes) {
  2844. const [size] = unpickler.read(1);
  2845. unpickler.read(size);
  2846. }
  2847. if (this.order === 'F') {
  2848. throw new python.Error('Fortran order not implemented.');
  2849. }
  2850. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2851. this.data = unpickler.read(size);
  2852. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2853. }
  2854. });
  2855. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2856. __setstate__(state) {
  2857. this.subclass = state.get('subclass');
  2858. this.filename = state.get('state');
  2859. this.allow_mmap = state.get('allow_mmap');
  2860. }
  2861. __read__(/* unpickler */) {
  2862. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2863. }
  2864. });
  2865. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2866. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2867. this.registerType('keras.engine.sequential.Sequential', class {});
  2868. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2869. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2870. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2871. this.registerType('lasagne.layers.input.InputLayer', class {});
  2872. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2873. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2874. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2875. this.registerType('lightgbm.basic.Booster', class {
  2876. constructor() {
  2877. this.average_output = false;
  2878. this.models = [];
  2879. this.loaded_parameter = '';
  2880. }
  2881. __setstate__(state) {
  2882. const model_str = state.get('_handle', state.get('handle', null));
  2883. if (model_str) {
  2884. this.LoadModelFromString(model_str);
  2885. return;
  2886. }
  2887. for (const [key, value] of state) {
  2888. this[key] = value;
  2889. }
  2890. }
  2891. LoadModelFromString(model_str) {
  2892. const lines = model_str.split('\n');
  2893. const signature = lines.shift() || '?';
  2894. if (signature.trim() !== 'tree') {
  2895. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2896. }
  2897. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2898. const key_vals = new Map();
  2899. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2900. const cur_line = lines.shift().trim();
  2901. if (cur_line.length > 0) {
  2902. const strs = cur_line.split('=');
  2903. if (strs.length === 1) {
  2904. key_vals.set(strs[0], '');
  2905. } else if (strs.length === 2) {
  2906. key_vals.set(strs[0], strs[1]);
  2907. } else if (strs.length > 2) {
  2908. if (strs[0] === "feature_names") {
  2909. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2910. } else if (strs[0] === 'monotone_constraints') {
  2911. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2912. } else {
  2913. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2914. }
  2915. }
  2916. }
  2917. }
  2918. const atoi = (key, value) => {
  2919. if (key_vals.has(key)) {
  2920. return parseInt(key_vals.get(key), 10);
  2921. }
  2922. if (value !== undefined) {
  2923. return value;
  2924. }
  2925. throw new python.Error(`Model file does not specify ${key}.`);
  2926. };
  2927. const list = (key, size) => {
  2928. if (key_vals.has(key)) {
  2929. const value = key_vals.get(key).split(' ');
  2930. if (value.length !== size) {
  2931. throw new python.Error(`Wrong size of ${key}.`);
  2932. }
  2933. return value;
  2934. }
  2935. throw new python.Error(`Model file does not contain ${key}.`);
  2936. };
  2937. this.version = key_vals.get('version') || '';
  2938. this.num_class = atoi('num_class');
  2939. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2940. this.label_index = atoi('label_index');
  2941. this.max_feature_idx = atoi('max_feature_idx');
  2942. if (key_vals.has('average_output')) {
  2943. this.average_output = true;
  2944. }
  2945. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2946. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2947. if (key_vals.has('monotone_constraints')) {
  2948. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2949. }
  2950. if (key_vals.has('objective')) {
  2951. this.objective = key_vals.get('objective');
  2952. }
  2953. let tree = null;
  2954. while (lines.length > 0) {
  2955. const text = lines.shift();
  2956. const line = text.trim();
  2957. if (line.length === 0) {
  2958. continue;
  2959. }
  2960. if (line.startsWith('Tree=')) {
  2961. tree = { index: parseInt(line.split('=').pop(), 10) };
  2962. this.models.push(tree);
  2963. continue;
  2964. }
  2965. if (line === 'end of trees') {
  2966. break;
  2967. }
  2968. const param = line.split('=');
  2969. if (param.length !== 2) {
  2970. throw new python.Error(`Invalid property '${line}'.`);
  2971. }
  2972. const name = param[0].trim();
  2973. const value = param[1].trim();
  2974. tree[name] = value;
  2975. }
  2976. const ss = [];
  2977. let is_inparameter = false;
  2978. while (lines.length > 0) {
  2979. const text = lines.shift();
  2980. const line = text.trim();
  2981. if (line === 'parameters:') {
  2982. is_inparameter = true;
  2983. continue;
  2984. } else if (line === 'end of parameters') {
  2985. break;
  2986. } else if (is_inparameter) {
  2987. ss.push(line);
  2988. }
  2989. }
  2990. if (ss.length > 0) {
  2991. this.loaded_parameter = ss.join('\n');
  2992. }
  2993. }
  2994. });
  2995. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2996. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  2997. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  2998. this.registerFunction('megengine.functional.nn.relu', () => {});
  2999. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3000. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3001. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3002. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3003. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3004. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3005. this.registerFunction('megengine.functional.tensor.full', () => {});
  3006. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3007. this.registerFunction('megengine.functional.tensor.split', () => {});
  3008. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3009. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3010. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3011. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3012. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3013. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3014. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3015. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3016. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3017. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3018. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3019. this.registerType('megengine.distributed.group.Group', class {});
  3020. this.registerType('megengine.module.activation.ReLU', class {});
  3021. this.registerType('megengine.module.activation.Softmax', class {});
  3022. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3023. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3024. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3025. this.registerType('megengine.module.conv.Conv2d', class {});
  3026. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3027. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3028. this.registerType('megengine.module.dropout.Dropout', class {});
  3029. this.registerType('megengine.module.identity.Identity', class {});
  3030. this.registerType('megengine.module.linear.Linear', class {});
  3031. this.registerType('megengine.module.module.Module', class {});
  3032. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3033. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3034. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3035. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3036. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3037. this.registerType('megengine.module.qat.concat.Concat', class {});
  3038. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3039. this.registerType('megengine.module.sequential.Sequential', class {});
  3040. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3041. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3042. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3043. this.registerType('megengine.quantization.utils.QParams', class {});
  3044. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3045. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3046. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3047. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3048. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3049. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3050. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3051. this.registerType('megengine.traced_module.expr.Apply', class {});
  3052. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3053. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3054. this.registerType('megengine.traced_module.expr.Constant', class {});
  3055. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3056. this.registerType('megengine.traced_module.expr.Input', class {});
  3057. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3058. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3059. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3060. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3061. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3062. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3063. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3064. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3065. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3066. this.registerType('megengine.tensor.Parameter', class {
  3067. constructor(data, dtype, device) {
  3068. this.data = data;
  3069. this.dtype = dtype;
  3070. this.device = device;
  3071. }
  3072. });
  3073. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3074. toString() {
  3075. let content = '';
  3076. for (const child of this.children_defs) {
  3077. content += `${child},`;
  3078. }
  3079. if (typeof this.type === "string") {
  3080. return `${this.type.split(".").slice(-1)}(${content})`;
  3081. }
  3082. return `${this.type.__name__}(${content})`;
  3083. }
  3084. });
  3085. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3086. toString() {
  3087. let content = '';
  3088. if (this.const_val === null) {
  3089. content += '[';
  3090. } else {
  3091. content += this.const_val;
  3092. }
  3093. for (const t of Object.values(this.type)) {
  3094. content += t.__name__;
  3095. }
  3096. content += ']';
  3097. return content;
  3098. }
  3099. });
  3100. this.registerType('megengine.tensor.Tensor', class {
  3101. constructor(data, dtype, device) {
  3102. this.data = data;
  3103. this.dtype = dtype;
  3104. this.device = device;
  3105. }
  3106. });
  3107. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3108. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3109. this.name = name;
  3110. this.cname = cname;
  3111. this.np_dtype = np_dtype;
  3112. this.qmin = qmin;
  3113. this.qmax = qmax;
  3114. this.is_signed = is_signed;
  3115. }
  3116. });
  3117. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3118. this.registerType('nolearn.lasagne.base.Layers', class {});
  3119. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3120. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3121. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3122. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3123. this.registerType('numpy.ndarray', class {
  3124. constructor(shape, dtype, buffer, offset, strides, order) {
  3125. this.shape = shape;
  3126. this.dtype = dtype;
  3127. this.data = buffer === undefined ? null : buffer;
  3128. this.offset = offset === undefined ? 0 : offset;
  3129. this._strides = strides === undefined ? null : strides;
  3130. this.order = order === undefined ? null : order;
  3131. this.flags = {};
  3132. this._read();
  3133. }
  3134. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3135. return new cls(shape, dtype, buffer, offset, strides, order);
  3136. }
  3137. __setstate__(state) {
  3138. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3139. this._read();
  3140. }
  3141. flatten() {
  3142. const size = this.shape.reduce((a, b) => a * b, 1);
  3143. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3144. value.flags = this.flags;
  3145. return value;
  3146. }
  3147. reshape(shape, order) {
  3148. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3149. }
  3150. tobytes() {
  3151. return this.data;
  3152. }
  3153. tolist() {
  3154. if (this.shape.length < 0 || this.shape.length > 1) {
  3155. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3156. }
  3157. const size = this.shape.reduce((a, b) => a * b, 1);
  3158. const list = new Array(size);
  3159. switch (this.dtype.kind) {
  3160. case 'U': {
  3161. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3162. const itemsize = this.dtype.itemsize >> 2;
  3163. let offset = 0;
  3164. for (let i = 0; i < size; i++) {
  3165. const buffer = data.subarray(offset, offset + itemsize);
  3166. const index = buffer.indexOf(0);
  3167. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3168. offset += itemsize;
  3169. }
  3170. return list;
  3171. }
  3172. case 'S': {
  3173. const data = this.data;
  3174. const itemsize = this.dtype.itemsize;
  3175. const decoder = new TextDecoder('utf-8');
  3176. let offset = 0;
  3177. for (let i = 0; i < size; i++) {
  3178. const buffer = data.subarray(offset, offset + itemsize);
  3179. const index = buffer.indexOf(0);
  3180. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3181. offset += itemsize;
  3182. }
  3183. return list;
  3184. }
  3185. case 'V': {
  3186. const itemsize = this.dtype.itemsize;
  3187. let offset = 0;
  3188. for (let i = 0; i < size; i++) {
  3189. list[i] = this.data.slice(offset, offset + itemsize);
  3190. offset += itemsize;
  3191. }
  3192. return list;
  3193. }
  3194. case 'M': {
  3195. const itemsize = this.dtype.itemsize;
  3196. let offset = 0;
  3197. for (let i = 0; i < size; i++) {
  3198. const buffer = this.data.slice(offset, offset + itemsize);
  3199. list[i] = new numpy.datetime64(buffer);
  3200. offset += itemsize;
  3201. }
  3202. return list;
  3203. }
  3204. case 'T': {
  3205. return this.data;
  3206. }
  3207. case 'O': {
  3208. return this.data;
  3209. }
  3210. default: {
  3211. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3212. }
  3213. }
  3214. }
  3215. get itemsize() {
  3216. return this.dtype.itemsize;
  3217. }
  3218. get size() {
  3219. return (this.shape || []).reduce((a, b) => a * b, 1);
  3220. }
  3221. get strides() {
  3222. if (!this._strides) {
  3223. const shape = this.shape;
  3224. const strides = new Array(shape.length);
  3225. let stride = this.itemsize;
  3226. for (let i = shape.length - 1; i >= 0; i--) {
  3227. strides[i] = stride;
  3228. stride *= shape[i];
  3229. }
  3230. return strides;
  3231. }
  3232. return this._strides;
  3233. }
  3234. _read() {
  3235. if (this.data) {
  3236. const length = this.dtype.itemsize * this.size;
  3237. if (typeof this.data === 'string') {
  3238. this.data = this._unescape(this.data, length);
  3239. if (this.data.length !== length) {
  3240. throw new python.Error('Invalid string array data size.');
  3241. }
  3242. } else if (this.data.length !== length) {
  3243. // throw new python.Error('Invalid array data size.');
  3244. }
  3245. }
  3246. }
  3247. _unescape(token, size) {
  3248. const length = token.length;
  3249. const a = new Uint8Array(length);
  3250. if (size && size === length) {
  3251. for (let p = 0; p < size; p++) {
  3252. a[p] = token.charCodeAt(p);
  3253. }
  3254. return a;
  3255. }
  3256. let i = 0;
  3257. let o = 0;
  3258. while (i < length) {
  3259. let c = token.charCodeAt(i++);
  3260. if (c !== 0x5C || i >= length) {
  3261. a[o++] = c;
  3262. } else {
  3263. c = token.charCodeAt(i++);
  3264. switch (c) {
  3265. case 0x27: a[o++] = 0x27; break; // '
  3266. case 0x5C: a[o++] = 0x5C; break; // \\
  3267. case 0x22: a[o++] = 0x22; break; // "
  3268. case 0x72: a[o++] = 0x0D; break; // \r
  3269. case 0x6E: a[o++] = 0x0A; break; // \n
  3270. case 0x74: a[o++] = 0x09; break; // \t
  3271. case 0x62: a[o++] = 0x08; break; // \b
  3272. case 0x58: // x
  3273. case 0x78: { // X
  3274. const xsi = i - 1;
  3275. const xso = o;
  3276. for (let xi = 0; xi < 2; xi++) {
  3277. if (i >= length) {
  3278. i = xsi;
  3279. o = xso;
  3280. a[o] = 0x5c;
  3281. break;
  3282. }
  3283. let c = token.charCodeAt(i++);
  3284. if (c >= 65 && c <= 70) {
  3285. c -= 55;
  3286. } else if (c >= 97 && c <= 102) {
  3287. c -= 87;
  3288. } else if (c >= 48 && c <= 57) {
  3289. c -= 48;
  3290. } else {
  3291. c = -1;
  3292. }
  3293. if (c === -1) {
  3294. i = xsi;
  3295. o = xso;
  3296. a[o] = 0x5c;
  3297. break;
  3298. }
  3299. a[o] = a[o] << 4 | c;
  3300. }
  3301. o++;
  3302. break;
  3303. }
  3304. default:
  3305. if (c < 48 || c > 57) { // 0-9
  3306. a[o++] = 0x5c;
  3307. a[o++] = c;
  3308. } else {
  3309. i--;
  3310. const osi = i;
  3311. const oso = o;
  3312. for (let oi = 0; oi < 3; oi++) {
  3313. if (i >= length) {
  3314. i = osi;
  3315. o = oso;
  3316. a[o] = 0x5c;
  3317. break;
  3318. }
  3319. const od = token.charCodeAt(i++);
  3320. if (od < 48 || od > 57) {
  3321. i = osi;
  3322. o = oso;
  3323. a[o] = 0x5c;
  3324. break;
  3325. }
  3326. a[o] = a[o] << 3 | od - 48;
  3327. }
  3328. o++;
  3329. }
  3330. break;
  3331. }
  3332. }
  3333. }
  3334. return a.slice(0, o);
  3335. }
  3336. });
  3337. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3338. static __new__(/* subtype, data, dtype, copy */) {
  3339. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3340. }
  3341. });
  3342. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3343. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3344. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3345. super(data.shape, data.dtype, data.data);
  3346. }
  3347. });
  3348. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3349. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3350. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3351. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3352. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3353. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3354. __setstate__(state) {
  3355. [this._dtype, this._ndarray] = state;
  3356. Object.assign(this, Object.fromEntries(state[2]));
  3357. }
  3358. });
  3359. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3360. __setstate__(state) {
  3361. [this._dtype, this._ndarray] = state;
  3362. Object.assign(this, Object.fromEntries(state[2]));
  3363. }
  3364. });
  3365. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3366. __setstate__(state) {
  3367. [this._dtype, this._ndarray] = state;
  3368. Object.assign(this, Object.fromEntries(state[2]));
  3369. }
  3370. });
  3371. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3372. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3373. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3374. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3375. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3376. this.registerType('pandas.core.generic.Flags', class {});
  3377. this.registerType('pandas.core.generic.NDFrame', class {
  3378. constructor(data) {
  3379. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3380. this._metadata = [];
  3381. builtins.object.__setattr__(self, "_mgr", data);
  3382. builtins.object.__setattr__(self, "_attrs", {});
  3383. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3384. }
  3385. __setstate__(state) {
  3386. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3387. this._mgr = state;
  3388. } else if (state instanceof builtins.dict) {
  3389. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3390. state.__setitem__('_mgr', state.pop('_data'));
  3391. }
  3392. const typ = state.get('_typ');
  3393. if (typ) {
  3394. let attrs = state.get('_attrs', new builtins.dict());
  3395. if (!attrs) {
  3396. attrs = new builtins.dict();
  3397. }
  3398. builtins.object.__setattr__(this, '_attrs', attrs);
  3399. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3400. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3401. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3402. for (const k of meta) {
  3403. if (state.__contains__(k) && k !== '_flags') {
  3404. const v = state.__getitem__(k);
  3405. builtins.object.__setattr__(this, k, v);
  3406. }
  3407. }
  3408. for (const [k, v] of state) {
  3409. if (!meta.has(k)) {
  3410. builtins.object.__setattr__(this, k, v);
  3411. }
  3412. }
  3413. } else {
  3414. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3415. }
  3416. } else if (state.size === 2) {
  3417. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3418. }
  3419. }
  3420. });
  3421. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3422. });
  3423. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3424. return new cls(d);
  3425. });
  3426. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3427. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3428. this.registerType('pandas.core.indexes.base.Index', class {});
  3429. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3430. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3431. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3432. this.registerType('pandas.core.index.Int64Index', class {});
  3433. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3434. });
  3435. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3436. });
  3437. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3438. return pandas.core.internals.blocks.NumpyBlock;
  3439. });
  3440. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3441. return values;
  3442. });
  3443. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3444. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3445. return new klass(values, ndim, placement, refs);
  3446. });
  3447. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3448. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3449. this.registerType('pandas.core.series.Series', class {});
  3450. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3451. const obj = new cls();
  3452. if (state && obj.__setstate__) {
  3453. obj.__setstate__(state);
  3454. }
  3455. return obj;
  3456. });
  3457. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3458. const obj = new cls();
  3459. if (state && obj.__setstate__) {
  3460. obj.__setstate__(state);
  3461. }
  3462. return obj;
  3463. });
  3464. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3465. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3466. // if not isinstance(placement, BlockPlacement):
  3467. // placement = BlockPlacement(placement)
  3468. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3469. });
  3470. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3471. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3472. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3473. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3474. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3475. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3476. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3477. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3478. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3479. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3480. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3481. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3482. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3483. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3484. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3485. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3486. this.registerType('pathlib.Path', class {});
  3487. this.registerType('pathlib._local.PosixPath', class {});
  3488. this.registerType('pathlib._local.WindowsPath', class {});
  3489. const pathlib = this.register('pathlib');
  3490. pathlib.PosixPath = pathlib._local.PosixPath;
  3491. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3492. this.registerType('shap._serializable.Serializable', class {});
  3493. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3494. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3495. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3496. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3497. this.registerType('sklearn._loss.link.BaseLink', class {});
  3498. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3499. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3500. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3501. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3502. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3503. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3504. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3505. this.registerType('sklearn._loss.link.Interval', class {});
  3506. this.registerType('sklearn._loss.link.LogitLink', class {});
  3507. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3508. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3509. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3510. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3511. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3512. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3513. this.registerType('sklearn.base.BaseEstimator', class {});
  3514. this.registerType('sklearn.base.TransformerMixin', class {});
  3515. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3516. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3517. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3518. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3519. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3520. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3521. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3522. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3523. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3524. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3525. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3526. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3527. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3528. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3529. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3530. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3531. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3532. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3533. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3534. this.registerType('sklearn.decomposition.PCA', class {});
  3535. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3536. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3537. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3538. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3539. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3540. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3541. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3542. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3543. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3544. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3545. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3546. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3547. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3548. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3549. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3550. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3551. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3552. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3553. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3554. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3555. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3556. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3557. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3558. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3559. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3560. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3561. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3562. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3563. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3564. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3565. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3566. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3567. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3568. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3569. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3570. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3571. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3572. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3573. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3574. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3575. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3576. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3577. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3578. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3579. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3580. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3581. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3582. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3583. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3584. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3585. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3586. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3587. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3588. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3589. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3590. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3591. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3592. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3593. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3594. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3595. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3596. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3597. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3598. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3599. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3600. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3601. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3602. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3603. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3604. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3605. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3606. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3607. this.registerType('sklearn.impute.SimpleImputer', class {});
  3608. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3609. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3610. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3611. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3612. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3613. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3614. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3615. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3616. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3617. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3618. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3619. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3620. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3621. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3622. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3623. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3624. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3625. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3626. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3627. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3628. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3629. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3630. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3631. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3632. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3633. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3634. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3635. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3636. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3637. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3638. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3639. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3640. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3641. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3642. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3643. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3644. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3645. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3646. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3647. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3648. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3649. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3650. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3651. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3652. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3653. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3654. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3655. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3656. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3657. this.registerType('sklearn.model_selection._split.KFold', class {});
  3658. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3659. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3660. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3661. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3662. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3663. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3664. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3665. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3666. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3667. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3668. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3669. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3670. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3671. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3672. return obj.__new__(obj);
  3673. });
  3674. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3675. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3676. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3677. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3678. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3679. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3680. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3681. return obj.__new__(obj);
  3682. });
  3683. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3684. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3685. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3686. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3687. return obj.__new__(obj);
  3688. });
  3689. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3690. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3691. return obj.__new__(obj);
  3692. });
  3693. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3694. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3695. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3696. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3697. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3698. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3699. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3700. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3701. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3702. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3703. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3704. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3705. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3706. this.registerType('sklearn.pipeline.Pipeline', class {});
  3707. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3708. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3709. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3710. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3711. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3712. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3713. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3714. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3715. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3716. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3717. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3718. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3719. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3720. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3721. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3722. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3723. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3724. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3725. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3726. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3727. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3728. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3729. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3730. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3731. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3732. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3733. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3734. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3735. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3736. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3737. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3738. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3739. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3740. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3741. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3742. this.registerType('sklearn.svm._classes.SVC', class {});
  3743. this.registerType('sklearn.svm._classes.SVR', class {});
  3744. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3745. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3746. this.registerType('sklearn.svm.classes.SVC', class {});
  3747. this.registerType('sklearn.svm.classes.SVR', class {});
  3748. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3749. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3750. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3751. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3752. this.registerType('sklearn.tree._tree.Tree', class {
  3753. constructor(n_features, n_classes, n_outputs) {
  3754. this.n_features = n_features;
  3755. this.n_classes = n_classes;
  3756. this.n_outputs = n_outputs;
  3757. }
  3758. __setstate__(state) {
  3759. this.max_depth = state.get('max_depth');
  3760. this.node_count = state.get('node_count');
  3761. this.nodes = state.get('nodes');
  3762. this.values = state.get('values');
  3763. }
  3764. });
  3765. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3766. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3767. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3768. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3769. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3770. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3771. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3772. this.registerType('pickle.Unpickler', class {
  3773. constructor(data) {
  3774. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3775. this.persistent_load = () => {
  3776. throw new python.Error('Unsupported persistent id.');
  3777. };
  3778. }
  3779. load() {
  3780. const reader = this._reader;
  3781. const marker = [];
  3782. let stack = [];
  3783. const memo = {};
  3784. let size = 0;
  3785. while (reader.position < reader.length) {
  3786. const opcode = reader.byte();
  3787. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3788. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3789. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3790. switch (opcode) {
  3791. case 128: { // PROTO
  3792. const version = reader.byte();
  3793. if (version > 5) {
  3794. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3795. }
  3796. break;
  3797. }
  3798. case 99: { // GLOBAL 'c'
  3799. const module = reader.line();
  3800. const name = reader.line();
  3801. stack.push(this.find_class(module, name));
  3802. break;
  3803. }
  3804. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3805. const name = stack.pop();
  3806. const module = stack.pop();
  3807. stack.push(this.find_class(module, name));
  3808. break;
  3809. }
  3810. case 111: { // OBJ 'o'
  3811. const args = stack;
  3812. const cls = args.pop();
  3813. stack = marker.pop();
  3814. const obj = this._instantiate(cls, args);
  3815. stack.push(obj);
  3816. break;
  3817. }
  3818. case 112 : { // PUT 'p'
  3819. const index = parseInt(reader.line(), 10);
  3820. if (stack.length === 0) {
  3821. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3822. }
  3823. memo[index] = stack[stack.length - 1];
  3824. size++;
  3825. break;
  3826. }
  3827. case 103: { // GET 'g'
  3828. const index = parseInt(reader.line(), 10);
  3829. if (index in memo === false) {
  3830. throw new python.Error(`Memo value not found at index '${index}'.`);
  3831. }
  3832. stack.push(memo[index]);
  3833. break;
  3834. }
  3835. case 48: // POP '0'
  3836. stack.pop();
  3837. break;
  3838. case 49: // POP_MARK '1'
  3839. stack = marker.pop();
  3840. break;
  3841. case 50: // DUP '2'
  3842. if (stack.length === 0) {
  3843. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3844. }
  3845. stack.push(stack[stack.length - 1]);
  3846. break;
  3847. case 80: // PERSID 'P'
  3848. stack.push(this.persistent_load(reader.line()));
  3849. break;
  3850. case 81: // BINPERSID 'Q'
  3851. stack.push(this.persistent_load(stack.pop()));
  3852. break;
  3853. case 82: { // REDUCE 'R'
  3854. const args = stack.pop();
  3855. const func = stack.pop();
  3856. stack.push(this._reduce(func, args));
  3857. break;
  3858. }
  3859. case 129: { // NEWOBJ
  3860. const args = stack.pop();
  3861. const cls = stack.pop();
  3862. const obj = this._newobj(cls, args);
  3863. stack.push(obj);
  3864. break;
  3865. }
  3866. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3867. const kwargs = stack.pop();
  3868. const args = stack.pop();
  3869. const cls = stack.pop();
  3870. if (Object.entries(kwargs).length > 0) {
  3871. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3872. }
  3873. const obj = this._newobj(cls, args);
  3874. stack.push(obj);
  3875. break;
  3876. }
  3877. case 104: { // BINGET 'h'
  3878. const index = reader.byte();
  3879. if (index in memo === false) {
  3880. throw new python.Error(`Memo value not found at index '${index}'.`);
  3881. }
  3882. stack.push(memo[index]);
  3883. break;
  3884. }
  3885. case 105: { // INST 'i'
  3886. const module = reader.line();
  3887. const name = reader.line();
  3888. const args = stack;
  3889. const cls = `${module}.${name}`;
  3890. stack = marker.pop();
  3891. // cls = this.find_class(module, name)
  3892. const obj = this._instantiate(cls, args);
  3893. stack.push(obj);
  3894. break;
  3895. }
  3896. case 106: { // LONG_BINGET 'j'
  3897. const index = reader.uint32();
  3898. if (index in memo === false) {
  3899. throw new python.Error(`Memo value not found at index '${index}'.`);
  3900. }
  3901. stack.push(memo[index]);
  3902. break;
  3903. }
  3904. case 113: // BINPUT 'q'
  3905. if (stack.length === 0) {
  3906. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3907. }
  3908. memo[reader.byte()] = stack[stack.length - 1];
  3909. size++;
  3910. break;
  3911. case 114: // LONG_BINPUT 'r'
  3912. if (stack.length === 0) {
  3913. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3914. }
  3915. memo[reader.uint32()] = stack[stack.length - 1];
  3916. size++;
  3917. break;
  3918. case 74: // BININT 'J'
  3919. stack.push(reader.int32());
  3920. break;
  3921. case 75: // BININT1 'K'
  3922. stack.push(reader.byte());
  3923. break;
  3924. case 76: // LONG 'L'
  3925. stack.push(parseInt(reader.line(), 10));
  3926. break;
  3927. case 77: // BININT2 'M'
  3928. stack.push(reader.uint16());
  3929. break;
  3930. case 66: // BINBYTES 'B' (Protocol 3)
  3931. stack.push(reader.read(reader.int32()));
  3932. break;
  3933. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3934. stack.push(reader.read(reader.byte()));
  3935. break;
  3936. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3937. stack.push(reader.read(reader.int64().toNumber()));
  3938. break;
  3939. case 70: // FLOAT 'F'
  3940. stack.push(parseFloat(reader.line()));
  3941. break;
  3942. case 71: // BINFLOAT 'G'
  3943. stack.push(reader.float64());
  3944. break;
  3945. case 73: { // INT 'I'
  3946. const value = reader.line();
  3947. if (value === '01') {
  3948. stack.push(true);
  3949. } else if (value === '00') {
  3950. stack.push(false);
  3951. } else {
  3952. stack.push(parseInt(value, 10));
  3953. }
  3954. break;
  3955. }
  3956. case 93: // EMPTY_LIST ']'
  3957. stack.push(new builtins.list());
  3958. break;
  3959. case 41: // EMPTY_TUPLE ')'
  3960. stack.push([]);
  3961. break;
  3962. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3963. stack.push([]);
  3964. break;
  3965. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3966. const items = stack;
  3967. stack = marker.pop();
  3968. const obj = stack[stack.length - 1];
  3969. for (let i = 0; i < items.length; i++) {
  3970. obj.push(items[i]);
  3971. }
  3972. break;
  3973. }
  3974. case 145: { // FROZENSET '\x91' (Protocol 4)
  3975. const items = stack;
  3976. stack = marker.pop();
  3977. stack.push(items);
  3978. break;
  3979. }
  3980. case 100: { // DICT 'd'
  3981. const items = stack;
  3982. stack = marker.pop();
  3983. const dict = new builtins.dict();
  3984. for (let i = 0; i < items.length; i += 2) {
  3985. dict.__setitem__(items[i], items[i + 1]);
  3986. }
  3987. stack.push(dict);
  3988. break;
  3989. }
  3990. case 108: { // LIST 'l'
  3991. const items = stack;
  3992. stack = marker.pop();
  3993. stack.push(items);
  3994. break;
  3995. }
  3996. case 116: { // TUPLE 't'
  3997. const items = stack;
  3998. stack = marker.pop();
  3999. stack.push(items);
  4000. break;
  4001. }
  4002. case 133: { // TUPLE1 // '\x85'
  4003. stack.push([stack.pop()]);
  4004. break;
  4005. }
  4006. case 134: { // TUPLE2 '\x86'
  4007. const b = stack.pop();
  4008. const a = stack.pop();
  4009. stack.push([a, b]);
  4010. break;
  4011. }
  4012. case 135: { // TUPLE3 '\x87'
  4013. const c = stack.pop();
  4014. const b = stack.pop();
  4015. const a = stack.pop();
  4016. stack.push([a, b, c]);
  4017. break;
  4018. }
  4019. case 115: { // SETITEM 's'
  4020. const value = stack.pop();
  4021. const key = stack.pop();
  4022. const obj = stack[stack.length - 1];
  4023. if (obj.__setitem__) {
  4024. obj.__setitem__(key, value);
  4025. } else {
  4026. obj[key] = value;
  4027. }
  4028. break;
  4029. }
  4030. case 117: { // SETITEMS 'u'
  4031. const items = stack;
  4032. stack = marker.pop();
  4033. const obj = stack[stack.length - 1];
  4034. if (obj.__setitem__) {
  4035. for (let i = 0; i < items.length; i += 2) {
  4036. obj.__setitem__(items[i], items[i + 1]);
  4037. }
  4038. } else {
  4039. for (let i = 0; i < items.length; i += 2) {
  4040. obj[items[i]] = items[i + 1];
  4041. }
  4042. }
  4043. break;
  4044. }
  4045. case 125: // EMPTY_DICT '}'
  4046. stack.push(new builtins.dict());
  4047. break;
  4048. case 97: { // APPEND 'a'
  4049. const append = stack.pop();
  4050. stack[stack.length - 1].push(append);
  4051. break;
  4052. }
  4053. case 101: { // APPENDS 'e'
  4054. const appends = stack;
  4055. stack = marker.pop();
  4056. const list = stack[stack.length - 1];
  4057. list.push(...appends);
  4058. break;
  4059. }
  4060. case 83: { // STRING 'S'
  4061. const str = reader.line();
  4062. stack.push(str.substring(1, str.length - 1));
  4063. break;
  4064. }
  4065. case 84: // BINSTRING 'T'
  4066. stack.push(reader.string(reader.uint32()));
  4067. break;
  4068. case 85 : // SHORT_BINSTRING 'U'
  4069. stack.push(reader.string(reader.byte()));
  4070. break;
  4071. case 86: // UNICODE 'V'
  4072. stack.push(reader.line());
  4073. break;
  4074. case 88: // BINUNICODE 'X
  4075. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4076. break;
  4077. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4078. stack.push(reader.string(reader.byte(), 'utf-8'));
  4079. break;
  4080. case 98: { // BUILD 'b'
  4081. const state = stack.pop();
  4082. let obj = stack.pop();
  4083. if (obj.__setstate__) {
  4084. if (obj.__setstate__.__call__) {
  4085. obj.__setstate__.__call__([obj, state]);
  4086. } else {
  4087. obj.__setstate__(state);
  4088. }
  4089. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4090. obj.__state__ = state;
  4091. } else if (obj instanceof Map && state instanceof Map) {
  4092. for (const [key, value] of state) {
  4093. obj.set(key, value);
  4094. }
  4095. } else if (obj instanceof Map) {
  4096. /* eslint-disable guard-for-in */
  4097. for (const key in state) {
  4098. obj.set(key, state[key]);
  4099. }
  4100. /* eslint-enable guard-for-in */
  4101. } else if (state instanceof Map) {
  4102. for (const [key, value] of state) {
  4103. obj[key] = value;
  4104. }
  4105. } else {
  4106. Object.assign(obj, state);
  4107. }
  4108. if (obj.__read__) {
  4109. obj = obj.__read__(this);
  4110. }
  4111. stack.push(obj);
  4112. break;
  4113. }
  4114. case 40: // MARK '('
  4115. marker.push(stack);
  4116. stack = [];
  4117. break;
  4118. case 136: // NEWTRUE '\x88'
  4119. stack.push(true);
  4120. break;
  4121. case 137: // NEWFALSE '\x89'
  4122. stack.push(false);
  4123. break;
  4124. case 138: { // LONG1 '\x8a'
  4125. const data = reader.read(reader.byte());
  4126. let number = 0;
  4127. switch (data.length) {
  4128. case 0: number = 0; break;
  4129. case 1: [number] = data; break;
  4130. case 2: number = data[1] << 8 | data[0]; break;
  4131. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4132. case 4: number = (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0; break;
  4133. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4134. default: number = Array.prototype.slice.call(data, 0); break;
  4135. }
  4136. stack.push(number);
  4137. break;
  4138. }
  4139. case 139: // LONG4 '\x8b'
  4140. // decode LONG4
  4141. stack.push(reader.read(reader.uint32()));
  4142. break;
  4143. case 148: // MEMOIZE '\x94' (Protocol 4)
  4144. memo[size++] = stack[stack.length - 1];
  4145. break;
  4146. case 149: // FRAME '\x95' (Protocol 4)
  4147. reader.read(8);
  4148. break;
  4149. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4150. stack.push(reader.read(reader.int64().toNumber()));
  4151. break;
  4152. }
  4153. case 78: // NONE 'N'
  4154. stack.push(null);
  4155. break;
  4156. case 46: // STOP '.'
  4157. return stack.pop();
  4158. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4159. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4160. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4161. default:
  4162. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4163. }
  4164. }
  4165. throw new python.Error('Unexpected end of file.');
  4166. }
  4167. find_class(module, name) {
  4168. execution.__import__(module);
  4169. return execution.resolve(`${module}.${name}`);
  4170. }
  4171. _instantiate(cls, args) {
  4172. return execution.invoke(cls, args);
  4173. }
  4174. _newobj(cls, args) {
  4175. // cls.__new__(cls, args)
  4176. return execution.invoke(cls, args);
  4177. }
  4178. _reduce(func, args) {
  4179. return execution.invoke(func, args);
  4180. }
  4181. read(size) {
  4182. return this._reader.read(size);
  4183. }
  4184. stream(size) {
  4185. return this._reader.stream(size);
  4186. }
  4187. });
  4188. this.registerType('random.Random', class {});
  4189. this.registerType('re.Pattern', class {
  4190. constructor(pattern, flags) {
  4191. this.pattern = pattern;
  4192. this.flags = flags;
  4193. }
  4194. });
  4195. this.registerType('spacy._ml.PrecomputableAffine', class {
  4196. __setstate__(state) {
  4197. Object.assign(this, new pickle.Unpickler(state).load());
  4198. }
  4199. });
  4200. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4201. __setstate__(state) {
  4202. Object.assign(this, new pickle.Unpickler(state).load());
  4203. }
  4204. });
  4205. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4206. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4207. this.registerType('theano.compile.function_module.Function', class {});
  4208. this.registerType('theano.compile.function_module.Supervisor', class {});
  4209. this.registerType('theano.compile.io.In', class {});
  4210. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4211. this.registerType('theano.compile.mode.Mode', class {});
  4212. this.registerType('theano.compile.ops.OutputGuard', class {});
  4213. this.registerType('theano.compile.ops.Shape', class {});
  4214. this.registerType('theano.compile.ops.Shape_i', class {});
  4215. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4216. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4217. this.registerType('theano.gof.graph.Apply', class {});
  4218. this.registerType('theano.gof.link.Container', class {});
  4219. this.registerType('theano.gof.opt._metadict', class {});
  4220. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4221. this.registerType('theano.gof.opt.MergeFeature', class {});
  4222. this.registerType('theano.gof.optdb.Query', class {});
  4223. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4224. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4225. this.registerType('theano.gof.utils.scratchpad', class {});
  4226. this.registerType('theano.misc.ordered_set.Link', class {});
  4227. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4228. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4229. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4230. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4231. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4232. this.registerType('theano.scalar.basic.Abs', class {});
  4233. this.registerType('theano.scalar.basic.Add', class {});
  4234. this.registerType('theano.scalar.basic.Cast', class {});
  4235. this.registerType('theano.scalar.basic.Composite', class {});
  4236. this.registerType('theano.scalar.basic.EQ', class {});
  4237. this.registerType('theano.scalar.basic.GE', class {});
  4238. this.registerType('theano.scalar.basic.Identity', class {});
  4239. this.registerType('theano.scalar.basic.IntDiv', class {});
  4240. this.registerType('theano.scalar.basic.Inv', class {});
  4241. this.registerType('theano.scalar.basic.LE', class {});
  4242. this.registerType('theano.scalar.basic.LT', class {});
  4243. this.registerType('theano.scalar.basic.Mul', class {});
  4244. this.registerType('theano.scalar.basic.Neg', class {});
  4245. this.registerType('theano.scalar.basic.Pow', class {});
  4246. this.registerType('theano.scalar.basic.Scalar', class {});
  4247. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4248. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4249. this.registerType('theano.scalar.basic.Second', class {});
  4250. this.registerType('theano.scalar.basic.Sgn', class {});
  4251. this.registerType('theano.scalar.basic.specific_out', class {});
  4252. this.registerType('theano.scalar.basic.Sub', class {});
  4253. this.registerType('theano.scalar.basic.Switch', class {});
  4254. this.registerType('theano.scalar.basic.Tanh', class {});
  4255. this.registerType('theano.scalar.basic.transfer_type', class {});
  4256. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4257. this.registerType('theano.tensor.basic.Alloc', class {});
  4258. this.registerType('theano.tensor.basic.Dot', class {});
  4259. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4260. this.registerType('theano.tensor.basic.Reshape', class {});
  4261. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4262. this.registerType('theano.tensor.blas.Dot22', class {});
  4263. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4264. this.registerType('theano.tensor.blas.Gemm', class {});
  4265. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4266. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4267. this.registerType('theano.tensor.elemwise.Sum', class {});
  4268. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4269. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4270. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4271. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4272. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4273. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4274. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4275. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4276. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4277. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4278. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4279. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4280. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4281. this.registerType('theano.tensor.opt.MakeVector', class {});
  4282. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4283. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4284. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4285. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4286. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4287. this.registerType('theano.tensor.type.TensorType', class {});
  4288. this.registerType('theano.tensor.var.TensorConstant', class {});
  4289. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4290. this.registerType('theano.tensor.var.TensorVariable', class {});
  4291. this.registerType('thinc.describe.Biases', class {});
  4292. this.registerType('thinc.describe.Dimension', class {});
  4293. this.registerType('thinc.describe.Gradient', class {});
  4294. this.registerType('thinc.describe.Weights', class {});
  4295. this.registerType('thinc.describe.Synapses', class {});
  4296. this.registerType('thinc.neural._classes.affine.Affine', class {
  4297. __setstate__(state) {
  4298. Object.assign(this, new pickle.Unpickler(state).load());
  4299. }
  4300. });
  4301. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4302. __setstate__(state) {
  4303. Object.assign(this, new pickle.Unpickler(state).load());
  4304. }
  4305. });
  4306. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4307. __setstate__(state) {
  4308. Object.assign(this, new pickle.Unpickler(state).load());
  4309. }
  4310. });
  4311. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4312. __setstate__(state) {
  4313. Object.assign(this, new pickle.Unpickler(state).load());
  4314. }
  4315. });
  4316. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4317. __setstate__(state) {
  4318. Object.assign(this, new pickle.Unpickler(state).load());
  4319. }
  4320. });
  4321. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4322. __setstate__(state) {
  4323. Object.assign(this, new pickle.Unpickler(state).load());
  4324. }
  4325. });
  4326. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4327. __setstate__(state) {
  4328. Object.assign(this, new pickle.Unpickler(state).load());
  4329. }
  4330. });
  4331. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4332. __setstate__(state) {
  4333. Object.assign(this, new pickle.Unpickler(state).load());
  4334. }
  4335. });
  4336. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4337. __setstate__(state) {
  4338. Object.assign(this, new pickle.Unpickler(state).load());
  4339. }
  4340. });
  4341. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4342. __setstate__(state) {
  4343. Object.assign(this, new pickle.Unpickler(state).load());
  4344. }
  4345. });
  4346. this.registerType('thinc.neural.mem.Memory', class {
  4347. });
  4348. this.registerType('thinc.neural.ops.NumpyOps', class {
  4349. });
  4350. this.registerType('__main__.BYOLState', class {
  4351. constructor(dict) {
  4352. Object.assign(this, dict);
  4353. }
  4354. });
  4355. const types = this.register('types');
  4356. this.registerType('types.GenericAlias', class {});
  4357. this.registerType('types.SimpleNamespace', class {});
  4358. this.registerType('types.BuiltinFunctionType', class {});
  4359. this.registerType('types.BuiltinMethodType', class {});
  4360. this.registerFunction('types.resolve_bases', (bases) => {
  4361. return bases;
  4362. });
  4363. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4364. if (kwds) {
  4365. kwds = new builtins.dict(kwds);
  4366. } else {
  4367. kwds = new builtins.dict();
  4368. }
  4369. let meta = null;
  4370. if (kwds.__contains__('metaclass')) {
  4371. meta = kwds.pop('metaclass');
  4372. } else if (bases && bases.length > 0) {
  4373. meta = builtins.type(bases[0]);
  4374. } else {
  4375. meta = builtins.type;
  4376. }
  4377. if (meta instanceof builtins.type) {
  4378. meta = types._calculate_meta(meta, bases);
  4379. }
  4380. let ns = null;
  4381. if (builtins.hasattr(meta, '__prepare__')) {
  4382. // ns = meta.__prepare__(name, bases, **kwds)
  4383. } else {
  4384. ns = new builtins.dict();
  4385. }
  4386. return [meta, ns, kwds];
  4387. });
  4388. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4389. const winner = meta;
  4390. return winner;
  4391. });
  4392. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4393. const resolved_bases = types.resolve_bases(bases);
  4394. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4395. if (exec_body) {
  4396. exec_body(ns);
  4397. }
  4398. return new meta(name, resolved_bases, ns);
  4399. });
  4400. types.ObjectType = builtins.object;
  4401. types.ModuleType = builtins.module;
  4402. types.MethodType = builtins.method;
  4403. types.FunctionType = builtins.function;
  4404. types.TypeType = builtins.type;
  4405. types.CodeType = builtins.code;
  4406. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4407. this.registerType('xgboost.core.Booster', class {
  4408. load_model(fname) {
  4409. if (fname instanceof Uint8Array) {
  4410. // XGBoosterLoadModel()
  4411. } else {
  4412. // XGBoosterUnserializeFromBuffer(handle) {
  4413. }
  4414. }
  4415. __setstate__(state) {
  4416. const handle = state.get('handle');
  4417. if (handle) {
  4418. this.handle = handle;
  4419. // XGBoosterLoadModelFromBuffer()
  4420. }
  4421. }
  4422. });
  4423. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4424. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4425. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4426. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4427. return new builtins.bytearray(obj, encoding);
  4428. });
  4429. this.registerType('builtins.bytearray', class extends Uint8Array {
  4430. constructor(source, encoding /*, errors */) {
  4431. source = builtins.bytes.__encode__(source, encoding);
  4432. super(Number.isInteger(source) ? source : source.length);
  4433. if (Array.isArray(source)) {
  4434. for (let i = 0; i < source.length; i++) {
  4435. this[i] = source;
  4436. }
  4437. } else if (source instanceof Uint8Array) {
  4438. this.set(source, 0);
  4439. } else if (typeof source === 'string') {
  4440. for (let i = 0; i < source.length; i++) {
  4441. this[i] = source.charCodeAt(i);
  4442. }
  4443. }
  4444. }
  4445. static __encode__(source, encoding) {
  4446. if (source === undefined) {
  4447. return 0;
  4448. }
  4449. if (Number.isInteger(source)) {
  4450. return source;
  4451. }
  4452. if (Array.isArray(source) || source instanceof Uint8Array) {
  4453. return source;
  4454. }
  4455. if (typeof source === 'string') {
  4456. switch (encoding) {
  4457. case 'latin1':
  4458. case 'latin-1':
  4459. return source;
  4460. case 'utf8':
  4461. case 'utf-8':
  4462. return new TextEncoder('utf-8').encode(source);
  4463. case undefined:
  4464. throw new python.Error('Unsupported string argument without an encoding.');
  4465. default:
  4466. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4467. }
  4468. }
  4469. throw new python.Error('Unsupported source.');
  4470. }
  4471. });
  4472. this.registerType('builtins.bytes', class extends Uint8Array {
  4473. constructor(source, encoding /*, errors */) {
  4474. source = builtins.bytes.__encode__(source, encoding);
  4475. super(Number.isInteger(source) ? source : source.length);
  4476. if (Array.isArray(source)) {
  4477. for (let i = 0; i < source.length; i++) {
  4478. this[i] = source;
  4479. }
  4480. } else if (source instanceof Uint8Array) {
  4481. this.set(source, 0);
  4482. } else if (typeof source === 'string') {
  4483. for (let i = 0; i < source.length; i++) {
  4484. this[i] = source.charCodeAt(i);
  4485. }
  4486. }
  4487. }
  4488. static __encode__(source, encoding) {
  4489. if (source === undefined) {
  4490. return 0;
  4491. }
  4492. if (Number.isInteger(source)) {
  4493. return source;
  4494. }
  4495. if (Array.isArray(source) || source instanceof Uint8Array) {
  4496. return source;
  4497. }
  4498. if (typeof source === 'string') {
  4499. switch (encoding) {
  4500. case 'latin1':
  4501. case 'latin-1':
  4502. return source;
  4503. case 'utf8':
  4504. case 'utf-8':
  4505. return new TextEncoder('utf-8').encode(source);
  4506. case undefined:
  4507. throw new python.Error('Unsupported string argument without an encoding.');
  4508. default:
  4509. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4510. }
  4511. }
  4512. throw new python.Error('Unsupported source.');
  4513. }
  4514. });
  4515. this.registerType('builtins.memoryview', class {
  4516. constructor(buf) {
  4517. this._buf = buf;
  4518. }
  4519. get nbytes() {
  4520. return this._buf.length;
  4521. }
  4522. });
  4523. this.registerType('builtins.frozenset', class extends Set {
  4524. constructor(iterable) {
  4525. super();
  4526. if (iterable) {
  4527. for (const item of iterable) {
  4528. this.add(item);
  4529. }
  4530. }
  4531. }
  4532. });
  4533. this.registerFunction('builtins.exec');
  4534. this.registerFunction('builtins.issubclass', (obj, type) => {
  4535. const name = `${type.__module__}.${type.__name__}`;
  4536. if (obj.__module__ && obj.__name__) {
  4537. if (name === `${obj.__module__}.${obj.__name__}`) {
  4538. return true;
  4539. }
  4540. }
  4541. if (obj.__bases__) {
  4542. for (const base of obj.__bases__) {
  4543. if (builtins.issubclass(base, type)) {
  4544. return true;
  4545. }
  4546. }
  4547. }
  4548. return false;
  4549. });
  4550. this.registerFunction('builtins.isinstance', (obj, type) => {
  4551. if (obj && type && obj instanceof type) {
  4552. return true;
  4553. }
  4554. if (obj && obj.__class__) {
  4555. return builtins.issubclass(obj.__class__, type);
  4556. }
  4557. return false;
  4558. });
  4559. this.registerFunction('builtins.hasattr', (obj, name) => {
  4560. if (obj instanceof Map && obj.__contains__) {
  4561. return obj.__contains__(name);
  4562. }
  4563. return Object.prototype.hasOwnProperty.call(obj, name);
  4564. });
  4565. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4566. if (obj && obj.__getattr__) {
  4567. return obj.__getattr__(name);
  4568. }
  4569. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4570. return obj[name];
  4571. }
  4572. return defaultValue;
  4573. });
  4574. this.registerFunction('builtins.len', (obj) => {
  4575. return obj.length;
  4576. });
  4577. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4578. if (obj && obj.__setattr__) {
  4579. obj.__setattr__(name, value);
  4580. } else {
  4581. obj[name] = value;
  4582. }
  4583. });
  4584. this.registerType('builtins.set', class extends Set {
  4585. __contains__(item) {
  4586. return this.has(item);
  4587. }
  4588. update(iterable) {
  4589. for (const item of iterable) {
  4590. this.add(item);
  4591. }
  4592. }
  4593. });
  4594. this.registerType('builtins.slice', class {
  4595. constructor(start, stop, step) {
  4596. this.start = start;
  4597. this.stop = stop;
  4598. this.step = step;
  4599. }
  4600. });
  4601. this.registerFunction('builtins.hash');
  4602. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4603. return name;
  4604. });
  4605. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4606. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4607. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4608. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4609. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4610. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4611. cell.cell_contents = value;
  4612. }
  4613. return cell;
  4614. });
  4615. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4616. // globals["__builtins__"] = __builtins__
  4617. return new types.FunctionType(code, globals, name, argdefs, closure);
  4618. });
  4619. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4620. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4621. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4622. if (class_tracker_id) {
  4623. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4624. }
  4625. return class_def;
  4626. });
  4627. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4628. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4629. const kwds = { 'metaclass': type_constructor };
  4630. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4631. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4632. });
  4633. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4634. return new builtins.cell();
  4635. });
  4636. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4637. [state] = state;
  4638. let registry = null;
  4639. for (const [attrname, attr] of state.items()) {
  4640. if (attrname === '_abc_impl') {
  4641. registry = attr;
  4642. } else {
  4643. builtins.setattr(obj, attrname, attr);
  4644. }
  4645. }
  4646. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4647. obj.__firstlineno__ = state.get('__firstlineno__');
  4648. }
  4649. if (registry) {
  4650. for (const subclass of registry) {
  4651. obj.register(subclass);
  4652. }
  4653. }
  4654. return obj;
  4655. });
  4656. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4657. const [, slotstate] = state;
  4658. [state] = state;
  4659. // obj.__dict__.update(state)
  4660. /* const obj_globals = */ slotstate.pop('__globals__');
  4661. const obj_closure = slotstate.pop('__closure__');
  4662. slotstate.pop('_cloudpickle_submodules');
  4663. if (obj.__globals__) {
  4664. // obj.__globals__.update(obj_globals);
  4665. // obj.__globals__.__builtins__ = __builtins__;
  4666. }
  4667. if (obj_closure) {
  4668. // let value = null;
  4669. for (let i = 0; i < obj_closure.length; i++) {
  4670. // const cell = obj_closure[i];
  4671. try {
  4672. // value = cell.cell_contents;
  4673. } catch {
  4674. // cell is empty
  4675. }
  4676. // obj.__closure__[i].cell_contents = value;
  4677. }
  4678. }
  4679. for (const [k, v] of slotstate.items()) {
  4680. builtins.setattr(obj, k, v);
  4681. }
  4682. });
  4683. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4684. execution.__import__(name);
  4685. return sys.modules.get(name);
  4686. });
  4687. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4688. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4689. const ray = this.register('ray');
  4690. this.register('ray.cloudpickle.cloudpickle');
  4691. this.register('ray.cloudpickle.cloudpickle_fast');
  4692. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4693. ray.cloudpickle.cloudpickle._fill_function = cloudpickle.cloudpickle._fill_function;
  4694. ray.cloudpickle.cloudpickle._make_cell = cloudpickle.cloudpickle._make_cell;
  4695. ray.cloudpickle.cloudpickle._make_function = cloudpickle.cloudpickle._make_function;
  4696. ray.cloudpickle.cloudpickle._make_skel_func = cloudpickle.cloudpickle._make_skel_func;
  4697. ray.cloudpickle.cloudpickle._make_skeleton_class = cloudpickle.cloudpickle._make_skeleton_class;
  4698. ray.cloudpickle.cloudpickle._make_empty_cell = cloudpickle.cloudpickle._make_empty_cell;
  4699. ray.cloudpickle.cloudpickle._empty_cell_value = cloudpickle.cloudpickle._empty_cell_value;
  4700. ray.cloudpickle.cloudpickle._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4701. ray.cloudpickle.cloudpickle._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4702. ray.cloudpickle.cloudpickle._lookup_class_or_track = cloudpickle.cloudpickle._lookup_class_or_track;
  4703. ray.cloudpickle.cloudpickle_fast._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4704. ray.cloudpickle.cloudpickle_fast._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4705. this.registerType('ray.rllib.algorithms.ppo.ppo.PPO', class {});
  4706. this.registerType('ray.rllib.algorithms.ppo.ppo.PPOConfig', class {});
  4707. this.registerType('ray.rllib.algorithms.algorithm_config.AlgorithmConfig', class {});
  4708. this.registerFunction('ray.rllib.algorithms.algorithm_config.AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN');
  4709. this.registerType('ray.rllib.algorithms.algorithm_config.TorchCompileWhatToCompile', class {});
  4710. this.registerType('ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector', class {});
  4711. this.registerType('ray.rllib.callbacks.callbacks.RLlibCallback', class {});
  4712. this.registerType('ray.rllib.core.learner.learner.TorchCompileWhatToCompile', class {});
  4713. this.registerType('ray.rllib.policy.policy.PolicySpec', class {});
  4714. this.registerType('ray.rllib.policy.sample_batch.SampleBatch', class {});
  4715. this.registerType('ray.rllib.utils.metrics.stats.mean.MeanStats', class {});
  4716. this.registerType('ray.rllib.utils.metrics.stats.ema.EmaStats', class {});
  4717. this.registerType('ray.rllib.utils.metrics.stats.min.MinStats', class {});
  4718. this.registerType('ray.rllib.utils.metrics.stats.max.MaxStats', class {});
  4719. this.registerType('ray.rllib.utils.metrics.stats.sum.SumStats', class {});
  4720. this.registerType('ray.rllib.utils.metrics.stats.lifetime_sum.LifetimeSumStats', class {});
  4721. this.registerType('ray.rllib.utils.metrics.stats.percentiles.PercentilesStats', class {});
  4722. this.registerType('ray.rllib.utils.metrics.stats.item.ItemStats', class {});
  4723. this.registerType('ray.rllib.utils.metrics.stats.item_series.ItemSeriesStats', class {});
  4724. this.registerType('collections.Counter', class {});
  4725. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4726. return {};
  4727. });
  4728. this.registerFunction('copy.deepcopy');
  4729. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4730. // copyreg._reconstructor in Python 3
  4731. if (base === '__builtin__.object' || base === builtins.object) {
  4732. return self.invoke(cls, []);
  4733. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4734. const obj = self.invoke(cls, []);
  4735. for (let i = 0; i < state.length; i++) {
  4736. obj[i] = state[i];
  4737. }
  4738. return obj;
  4739. }
  4740. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4741. });
  4742. this.registerFunction('copy.deepcopy', (/* x */) => {
  4743. throw new python.Error('Unsupported copy.deepcopy().');
  4744. });
  4745. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4746. const array = f(...args);
  4747. if (array.__setstate__) {
  4748. array.__setstate__(state);
  4749. }
  4750. if (npdict) {
  4751. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4752. }
  4753. return array;
  4754. });
  4755. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4756. return function() {
  4757. };
  4758. });
  4759. this.registerFunction('dill._dill._create_code', (args) => {
  4760. return self.invoke('types.CodeType', [args]);
  4761. });
  4762. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4763. return function() {
  4764. };
  4765. });
  4766. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4767. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4768. if (obj) {
  4769. return obj;
  4770. }
  4771. return undefined;
  4772. });
  4773. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4774. const [name, bases, dict] = args;
  4775. const type = class extends bases[0] {};
  4776. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4777. return self.registerType(identifier, Object.assign(type, dict));
  4778. });
  4779. this.registerFunction('dill._dill._eval_repr');
  4780. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4781. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4782. return self[name];
  4783. }
  4784. return undefined;
  4785. });
  4786. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4787. try {
  4788. if (import_name.startsWith('__runtime__.')) {
  4789. return execution.module(import_name);
  4790. } else if (import_name.indexOf('.') === -1) {
  4791. return execution.__import__(import_name);
  4792. }
  4793. return execution.resolve(import_name);
  4794. } catch (error) {
  4795. if (safe) {
  4796. return null;
  4797. }
  4798. throw error;
  4799. }
  4800. });
  4801. this.registerFunction('dill._dill._load_type', (name) => {
  4802. const _dill = self.register('dill._dill');
  4803. if (!_dill._reverse_typemap) {
  4804. _dill._reverse_typemap = new Map();
  4805. for (const name of ['__builtin__', 'types']) {
  4806. const module = self.register(name);
  4807. for (const [name, obj] of Object.entries(module)) {
  4808. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4809. _dill._reverse_typemap.set(name, obj);
  4810. }
  4811. }
  4812. }
  4813. _dill._reverse_typemap.set('PartialType', functools.partial);
  4814. _dill._reverse_typemap.set('CellType', builtins.cell);
  4815. }
  4816. if (!_dill._reverse_typemap.has(name)) {
  4817. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4818. }
  4819. return _dill._reverse_typemap.get(name);
  4820. });
  4821. this.registerFunction('dill._dill.loads');
  4822. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4823. const np_value = fun(...args);
  4824. np_value.__setstate__(arr_state);
  4825. const jnp_value = jax.device_put(np_value);
  4826. jnp_value.aval = jnp_value.aval.update(aval_state);
  4827. return jnp_value;
  4828. });
  4829. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4830. this.registerFunction('jax.device_put', (x) => {
  4831. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4832. return new jax.Array(aval, x.data);
  4833. });
  4834. this.registerType('jax._src.core.AbstractValue', class {});
  4835. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4836. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4837. constructor(shape, dtype, weak_type) {
  4838. super();
  4839. this.shape = shape;
  4840. this.dtype = dtype;
  4841. this.weak_type = weak_type || false;
  4842. }
  4843. update(dict) {
  4844. const shape = dict.get('shape') || this.shape;
  4845. const dtype = dict.get('dtype') || this.dtype;
  4846. const weak_type = dict.get('weak_type') || this.weak_type;
  4847. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4848. }
  4849. });
  4850. this.registerType('jax.Array', class {
  4851. constructor(aval, data) {
  4852. this.aval = aval;
  4853. this.data = data;
  4854. }
  4855. get dtype() {
  4856. return this.aval.dtype;
  4857. }
  4858. get shape() {
  4859. return this.aval.shape;
  4860. }
  4861. tobytes() {
  4862. return this.data;
  4863. }
  4864. });
  4865. jax.numpy.ndarray = jax.Array;
  4866. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4867. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4868. });
  4869. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4870. this.registerFunction('lasagne.nonlinearities.rectify');
  4871. this.registerFunction('lasagne.nonlinearities.softmax');
  4872. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4873. this.registerFunction('lasagne.updates.nesterov_momentum');
  4874. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4875. const BinaryReader = class {
  4876. constructor(buffer, ext_hook) {
  4877. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4878. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4879. this._buffer = buffer;
  4880. this._position = 0;
  4881. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4882. this._ext_hook = ext_hook;
  4883. }
  4884. value() {
  4885. const c = this._view.getUint8(this.skip(1));
  4886. if (c >= 0xe0) {
  4887. return c - 0x100;
  4888. }
  4889. if (c < 0xC0) {
  4890. if (c < 0x80) {
  4891. return c;
  4892. }
  4893. if (c < 0x90) {
  4894. return this.map(c - 0x80);
  4895. }
  4896. if (c < 0xa0) {
  4897. return this.array(c - 0x90);
  4898. }
  4899. return this.string(c - 0xa0);
  4900. }
  4901. switch (c) {
  4902. case 0xC0: return null;
  4903. case 0xC2: return false;
  4904. case 0xC3: return true;
  4905. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4906. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4907. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4908. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4909. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4910. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4911. case 0xCA: return this._view.getFloat32(this.skip(4));
  4912. case 0xCB: return this._view.getFloat64(this.skip(8));
  4913. case 0xCC: return this._view.getUint8(this.skip(1));
  4914. case 0xCD: return this._view.getUint16(this.skip(2));
  4915. case 0xCE: return this._view.getUint32(this.skip(4));
  4916. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4917. case 0xD0: return this._view.getInt8(this.skip(1));
  4918. case 0xD1: return this._view.getInt16(this.skip(2));
  4919. case 0xD2: return this._view.getInt32(this.skip(4));
  4920. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4921. case 0xD4: return this.extension(1);
  4922. case 0xD5: return this.extension(2);
  4923. case 0xD6: return this.extension(4);
  4924. case 0xD7: return this.extension(8);
  4925. case 0xD8: return this.extension(16);
  4926. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4927. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4928. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4929. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4930. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4931. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4932. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4933. default: throw new python.Error(`Invalid code '${c}'.`);
  4934. }
  4935. }
  4936. map(size) {
  4937. const map = {};
  4938. for (let i = 0; i < size; i++) {
  4939. const key = this.value();
  4940. const value = this.value();
  4941. map[key] = value;
  4942. }
  4943. return map;
  4944. }
  4945. array(size) {
  4946. const array = new Array(size);
  4947. for (let i = 0; i < size; i++) {
  4948. array[i] = this.value();
  4949. }
  4950. return array;
  4951. }
  4952. extension(size) {
  4953. const code = this._view.getUint8(this.skip(1));
  4954. const data = this.read(size);
  4955. return this._ext_hook(code, data);
  4956. }
  4957. skip(offset) {
  4958. const position = this._position;
  4959. this._position += offset;
  4960. if (this._position > this._buffer.length) {
  4961. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4962. }
  4963. return position;
  4964. }
  4965. read(size) {
  4966. const data = this._buffer.subarray(this._position, this._position + size);
  4967. this._position += size;
  4968. return data;
  4969. }
  4970. string(size) {
  4971. const buffer = this.read(size);
  4972. this._decoder = this._decoder || new TextDecoder('utf8');
  4973. return this._decoder.decode(buffer);
  4974. }
  4975. };
  4976. return new BinaryReader(packed, ext_hook).value();
  4977. });
  4978. this.registerFunction('nolearn.lasagne.base.objective');
  4979. this.registerFunction('numpy.core._DType_reconstruct');
  4980. this.registerFunction('numpy.core._ufunc_reconstruct');
  4981. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4982. return numpy.ndarray.__new__(subtype, shape, dtype);
  4983. });
  4984. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4985. const shape = [buf.length / dtype.itemsize];
  4986. return new numpy.ndarray(shape, dtype, buf);
  4987. });
  4988. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  4989. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  4990. });
  4991. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4992. return new numpy.dtypes.StringDType();
  4993. });
  4994. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4995. let data = rawData;
  4996. if (typeof rawData === 'string' || rawData instanceof String) {
  4997. data = new Uint8Array(rawData.length);
  4998. for (let i = 0; i < rawData.length; i++) {
  4999. data[i] = rawData.charCodeAt(i);
  5000. }
  5001. }
  5002. switch (dtype.kind) {
  5003. case 'b': {
  5004. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5005. switch (dtype.itemsize) {
  5006. case 1: return view.getInt8(0) ? true : false;
  5007. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  5008. }
  5009. }
  5010. case 'f': {
  5011. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5012. switch (dtype.itemsize) {
  5013. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  5014. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  5015. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  5016. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  5017. }
  5018. }
  5019. case 'i': {
  5020. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5021. switch (dtype.itemsize) {
  5022. case 1: return view.getInt8(0);
  5023. case 2: return view.getInt16(0, dtype.byteorder === '<');
  5024. case 4: return view.getInt32(0, dtype.byteorder === '<');
  5025. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  5026. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  5027. }
  5028. }
  5029. case 'u': {
  5030. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5031. switch (dtype.itemsize) {
  5032. case 1: return view.getUint8(0);
  5033. case 2: return view.getUint16(0, dtype.byteorder === '<');
  5034. case 4: return view.getUint32(0, dtype.byteorder === '<');
  5035. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5036. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5037. }
  5038. }
  5039. case 'U': {
  5040. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5041. const list = [];
  5042. for (let i = 0; i < dtype.itemsize; i += 4) {
  5043. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5044. }
  5045. return list.join('');
  5046. }
  5047. default: {
  5048. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5049. }
  5050. }
  5051. });
  5052. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5053. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5054. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5055. this.registerFunction('numpy.core._multiarray_umath.greater');
  5056. this.registerFunction('numpy.core._multiarray_umath.less');
  5057. this.registerFunction('numpy.core._multiarray_umath.log');
  5058. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5059. let data = rawData;
  5060. if (typeof rawData === 'string') {
  5061. data = new Uint8Array(rawData.length);
  5062. for (let i = 0; i < rawData.length; i++) {
  5063. data[i] = rawData.charCodeAt(i);
  5064. }
  5065. }
  5066. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5067. switch (dtype.__name__) {
  5068. case 'uint8':
  5069. return dataView.getUint8(0);
  5070. case 'float32':
  5071. return dataView.getFloat32(0, true);
  5072. case 'float64':
  5073. return dataView.getFloat64(0, true);
  5074. case 'int8':
  5075. return dataView.getInt8(0, true);
  5076. case 'int16':
  5077. return dataView.getInt16(0, true);
  5078. case 'int32':
  5079. return dataView.getInt32(0, true);
  5080. case 'int64':
  5081. return dataView.getBigInt64(0, true);
  5082. default:
  5083. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5084. }
  5085. });
  5086. this.registerFunction('numpy.core._multiarray_umath.sin');
  5087. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5088. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5089. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5090. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5091. this.register('numpy.core.numeric', numpy._core.numeric);
  5092. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5093. this.registerFunction('numpy.load', (file) => {
  5094. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5095. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5096. if (!file.read(6).every((v, i) => v === signature[i])) {
  5097. throw new python.Error('Invalid signature.');
  5098. }
  5099. const version = file.read(2);
  5100. const [major, minor] = version;
  5101. if (major > 3) {
  5102. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5103. }
  5104. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5105. let data = null;
  5106. switch (dtype.byteorder) {
  5107. case '|': {
  5108. data = file.read();
  5109. if (dtype.kind === 'O') {
  5110. const unpickler = new pickle.Unpickler(data);
  5111. return unpickler.load();
  5112. }
  5113. break;
  5114. }
  5115. case '>':
  5116. case '<': {
  5117. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5118. const stream = file.getbuffer().nbytes > 0x1000000;
  5119. data = file.read(dtype.itemsize * count, stream);
  5120. break;
  5121. }
  5122. default: {
  5123. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5124. }
  5125. }
  5126. if (fortran_order) {
  5127. data = null;
  5128. }
  5129. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5130. });
  5131. this.registerFunction('numpy.save', (file, arr) => {
  5132. const descr = arr.dtype.str;
  5133. if (descr[0] !== '<' && descr[0] !== '>') {
  5134. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5135. }
  5136. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5137. throw new python.Error(`Unsupported data type '${descr}'.`);
  5138. }
  5139. let shape = '';
  5140. switch (arr.shape.length) {
  5141. case 0: shape = '()'; break;
  5142. case 1: shape = `(${arr.shape[0]},)`; break;
  5143. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5144. }
  5145. const properties = [
  5146. `'descr': '${descr}'`,
  5147. "'fortran_order': False",
  5148. `'shape': ${shape}`
  5149. ];
  5150. let header = `{ ${properties.join(', ')} }`;
  5151. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5152. const encoder = new TextEncoder('ascii');
  5153. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5154. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5155. file.write(encoder.encode(header));
  5156. file.write(arr.tobytes());
  5157. });
  5158. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5159. const buffer = new Uint8Array([0, 0, 0, 0]);
  5160. const [major] = version;
  5161. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5162. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5163. let header = file.read(header_length);
  5164. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5165. header = decoder.decode(header).trim();
  5166. try {
  5167. header = ast.literal_eval(header);
  5168. } catch {
  5169. if (major <= 2) {
  5170. header = numpy.lib._format_impl._filter_header(header);
  5171. header = ast.literal_eval(header);
  5172. }
  5173. }
  5174. if (header.descr === undefined) {
  5175. throw new python.Error("Invalid 'descr'.");
  5176. }
  5177. if (!Array.isArray(header.shape)) {
  5178. throw new python.Error("Invalid 'shape'.");
  5179. }
  5180. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5181. return [header.shape, header.fortran_order, dtype];
  5182. });
  5183. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5184. if (typeof descr === 'string') {
  5185. return new numpy.dtype(descr);
  5186. } else if (descr instanceof builtins.tuple) {
  5187. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5188. return new numpy.dtype([dt, descr[1]]);
  5189. }
  5190. const titles = [];
  5191. const names = [];
  5192. const formats = [];
  5193. const offsets = [];
  5194. let offset = 0;
  5195. for (const field of descr) {
  5196. let name = null;
  5197. let dt = null;
  5198. let descr_str = null;
  5199. let shape = null;
  5200. let title = null;
  5201. if (field.length === 2) {
  5202. [name, descr_str] = field;
  5203. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5204. } else {
  5205. [name, descr_str, shape] = field;
  5206. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5207. }
  5208. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5209. if (!is_pad) {
  5210. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5211. titles.push(title);
  5212. names.push(name);
  5213. formats.push(dt);
  5214. offsets.push(offset);
  5215. }
  5216. offset += dt.itemsize;
  5217. }
  5218. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5219. });
  5220. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5221. const tokens = [];
  5222. const tokenizer = new ast._Tokenizer(s, '');
  5223. while (!tokenizer.match('eof')) {
  5224. const token = tokenizer.read();
  5225. if (token.type === 'int') {
  5226. const next = tokenizer.peek();
  5227. if (next.type === 'id' && next.value === 'L') {
  5228. tokenizer.read();
  5229. }
  5230. }
  5231. tokens.push(token.value);
  5232. }
  5233. return tokens.join('');
  5234. });
  5235. this.registerFunction('numpy.amin');
  5236. this.registerFunction('numpy.amax');
  5237. this.registerFunction('numpy.std');
  5238. this.registerFunction('numpy.asarray', (a, dtype) => {
  5239. const encode = (context, data, dim) => {
  5240. const size = context.shape[dim];
  5241. const littleendian = context.littleendian;
  5242. if (dim === context.shape.length - 1) {
  5243. for (let i = 0; i < size; i++) {
  5244. switch (context.dtype) {
  5245. case 'f2':
  5246. context.view.setFloat16(context.position, data[i], littleendian);
  5247. break;
  5248. case 'f4':
  5249. context.view.setFloat32(context.position, data[i], littleendian);
  5250. break;
  5251. case 'f8':
  5252. context.view.setFloat64(context.position, data[i], littleendian);
  5253. break;
  5254. case 'i1':
  5255. context.view.setInt8(context.position, data[i], littleendian);
  5256. break;
  5257. case 'i2':
  5258. context.view.setInt16(context.position, data[i], littleendian);
  5259. break;
  5260. case 'i4':
  5261. context.view.setInt32(context.position, data[i], littleendian);
  5262. break;
  5263. case 'i8':
  5264. context.view.setBigInt64(context.position, typeof data[i] === 'number' ? BigInt(data[i]) : data[i], littleendian);
  5265. break;
  5266. case 'u1':
  5267. context.view.setUint8(context.position, data[i], littleendian);
  5268. break;
  5269. case 'u2':
  5270. context.view.setUint16(context.position, data[i], littleendian);
  5271. break;
  5272. case 'u4':
  5273. context.view.setUint32(context.position, data[i], littleendian);
  5274. break;
  5275. case 'u8':
  5276. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5277. break;
  5278. case 'c8':
  5279. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5280. break;
  5281. case 'c16':
  5282. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5283. break;
  5284. case 'b1':
  5285. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5286. break;
  5287. default:
  5288. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5289. }
  5290. context.position += context.itemsize;
  5291. }
  5292. } else {
  5293. for (let j = 0; j < size; j++) {
  5294. encode(context, data[j], dim + 1);
  5295. }
  5296. }
  5297. };
  5298. const array_size = (value) => {
  5299. if (value.every((item) => Array.isArray(item))) {
  5300. const dims = value.map((item) => array_size(item));
  5301. const [dim] = dims;
  5302. for (let i = 1; i < dims.length; i++) {
  5303. if (dim.length === dims[i].length) {
  5304. if (!dims[i].every((value, i) => value === dim[i])) {
  5305. throw new python.Error('Invalid array shape.');
  5306. }
  5307. }
  5308. }
  5309. return [value.length].concat(dim);
  5310. }
  5311. return [value.length];
  5312. };
  5313. const shape = Array.isArray(a) ? array_size(a) : [];
  5314. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5315. const context = {
  5316. position: 0,
  5317. itemsize: dtype.itemsize,
  5318. dtype: dtype.str.substring(1),
  5319. littleendian: dtype.str[0],
  5320. shape,
  5321. data: new Uint8Array(size)
  5322. };
  5323. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5324. encode(context, a, 0);
  5325. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5326. });
  5327. this.registerFunction('numpy.max');
  5328. this.registerFunction('numpy.mean');
  5329. this.registerFunction('numpy.min');
  5330. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5331. const data = self.invoke(baseclass, [baseshape, basetype]);
  5332. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5333. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5334. return self.invoke(subtype, [data, mask, basetype]);
  5335. });
  5336. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5337. return {};
  5338. });
  5339. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5340. return {};
  5341. });
  5342. this.registerType('numpy.random.bit_generator.BitGenerator', class {
  5343. __setstate__(state) {
  5344. if (state instanceof Map || !Array.isArray(state)) {
  5345. this.state = state;
  5346. } else {
  5347. [this.state, this._seed_seq] = state;
  5348. }
  5349. }
  5350. });
  5351. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5352. __setstate__(state) {
  5353. [this.entropy, this.n_children_spawned, this.pool, this.pool_size, this.spawn_key] = state;
  5354. }
  5355. });
  5356. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5357. const obj = new cls();
  5358. if (state) {
  5359. obj.__setstate__(state);
  5360. }
  5361. return obj;
  5362. });
  5363. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5364. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5365. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5366. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5367. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5368. numpy.random._pickle.BitGenerators = {
  5369. 'MT19937': numpy.random._mt19937.MT19937,
  5370. 'PCG64': numpy.random._pcg64.PCG64,
  5371. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5372. 'Philox': numpy.random._philox.Philox,
  5373. 'SFC64': numpy.random._sfc64.SFC64,
  5374. };
  5375. this.registerType('numpy.random._generator.Generator', class {
  5376. constructor(bit_generator) {
  5377. this.bit_generator = bit_generator;
  5378. }
  5379. });
  5380. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5381. bit_generator = bit_generator || 'MT19937';
  5382. let bit_gen_class = null;
  5383. if (builtins.isinstance(bit_generator, builtins.type)) {
  5384. bit_gen_class = bit_generator;
  5385. } else {
  5386. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5387. }
  5388. if (bit_gen_class) {
  5389. return new bit_gen_class();
  5390. }
  5391. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5392. });
  5393. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5394. if (bit_generator_name instanceof numpy.random.bit_generator.BitGenerator) {
  5395. return new numpy.random._generator.Generator(bit_generator_name);
  5396. }
  5397. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5398. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5399. });
  5400. this.registerFunction('numpy.reshape');
  5401. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5402. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5403. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5404. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5405. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5406. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5407. this.registerFunction('sklearn.metrics._classification.f1_score');
  5408. this.registerFunction('sklearn.metrics._classification.log_loss');
  5409. this.registerFunction('sklearn.metrics._classification.precision_score');
  5410. this.registerFunction('sklearn.metrics._classification.recall_score');
  5411. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5412. return obj.__new__(obj);
  5413. });
  5414. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5415. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5416. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5417. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5418. this.registerFunction('sklearn.metrics._regression.r2_score');
  5419. sklearn.metrics.regression = sklearn.metrics._regression;
  5420. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5421. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5422. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5423. this.registerFunction('re._compile', (pattern, flags) => {
  5424. return self.invoke('re.Pattern', [pattern, flags]);
  5425. });
  5426. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5427. return function() {
  5428. return self.invoke(`types.${args[0]}`, args);
  5429. };
  5430. });
  5431. this.registerType('sympy.printing.defaults.Printable', class {});
  5432. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5433. constructor(...args) {
  5434. super();
  5435. this._args = args;
  5436. }
  5437. get args() {
  5438. return this._args;
  5439. }
  5440. });
  5441. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5442. });
  5443. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5444. });
  5445. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5446. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5447. __str__() {
  5448. return this._args.map((a) => a.__str__()).join('**');
  5449. }
  5450. });
  5451. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5452. __str__() {
  5453. return this._args.map((a) => a.__str__()).join(' + ');
  5454. }
  5455. });
  5456. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5457. __str__() {
  5458. return this._args.map((a) => a.__str__()).join('*');
  5459. }
  5460. });
  5461. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5462. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5463. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5464. constructor(value) {
  5465. super();
  5466. this.value = value;
  5467. this.is_Integer = true;
  5468. }
  5469. __int__() {
  5470. return this.value;
  5471. }
  5472. __str__() {
  5473. return this.value.toString();
  5474. }
  5475. });
  5476. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5477. constructor(name) {
  5478. super();
  5479. this.name = name;
  5480. }
  5481. __int__() {
  5482. throw new python.Error('Cannot convert symbols to int.');
  5483. }
  5484. __str__() {
  5485. return this.name;
  5486. }
  5487. });
  5488. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5489. constructor(lhs, rhs, op) {
  5490. super();
  5491. this._args = [lhs, rhs];
  5492. this._op = op;
  5493. }
  5494. __str__() {
  5495. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5496. }
  5497. });
  5498. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5499. });
  5500. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5501. });
  5502. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5503. constructor(lhs, rhs) {
  5504. super(lhs, rhs, '>=');
  5505. }
  5506. });
  5507. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5508. });
  5509. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5510. constructor(lhs, rhs) {
  5511. super(lhs, rhs, '<=');
  5512. }
  5513. });
  5514. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5515. constructor(lhs, rhs) {
  5516. super(lhs, rhs, '<');
  5517. }
  5518. });
  5519. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5520. constructor(lhs, rhs) {
  5521. super(lhs, rhs, '>');
  5522. }
  5523. });
  5524. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5525. constructor(lhs, rhs) {
  5526. super(lhs, rhs, '==');
  5527. }
  5528. });
  5529. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5530. });
  5531. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5532. __str__() {
  5533. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5534. }
  5535. });
  5536. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5537. if (a instanceof sympy.core.expr.Expr) {
  5538. return a;
  5539. }
  5540. const p = ast.parse(a);
  5541. const sympify = (node) => {
  5542. if (node instanceof ast.Call) {
  5543. switch (node.func.id) {
  5544. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5545. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5546. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5547. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5548. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5549. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5550. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5551. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5552. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5553. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5554. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5555. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5556. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5557. }
  5558. }
  5559. if (node instanceof ast.Name) {
  5560. return new sympy.core.symbol.Symbol(node.id);
  5561. }
  5562. if (node instanceof ast.Constant) {
  5563. if (node.type === 'int') {
  5564. return new sympy.core.numbers.Integer(node.value);
  5565. }
  5566. }
  5567. if (node instanceof ast.BinOp) {
  5568. if (node.op instanceof ast.Mult) {
  5569. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5570. }
  5571. if (node.op instanceof ast.Pow) {
  5572. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5573. }
  5574. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5575. }
  5576. if (node instanceof ast.Compare) {
  5577. const left = sympify(node.left);
  5578. const right = sympify(node.comparators[0]);
  5579. const [op] = node.ops;
  5580. if (op instanceof ast.Gt) {
  5581. return new sympy.core.relational.StrictGreaterThan(left, right);
  5582. }
  5583. if (op instanceof ast.GtE) {
  5584. return new sympy.core.relational.GreaterThan(left, right);
  5585. }
  5586. if (op instanceof ast.Lt) {
  5587. return new sympy.core.relational.StrictLessThan(left, right);
  5588. }
  5589. if (op instanceof ast.LtE) {
  5590. return new sympy.core.relational.LessThan(left, right);
  5591. }
  5592. if (op instanceof ast.Eq) {
  5593. return new sympy.core.relational.Equality(left, right);
  5594. }
  5595. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5596. }
  5597. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5598. };
  5599. return sympify(p.body[0].value);
  5600. });
  5601. this.registerFunction('theano.scalar.basic.same_out');
  5602. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5603. this.registerFunction('theano.scalar.basic.upcast_out');
  5604. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5605. this.registerFunction('theano.tensor.nnet.conv2d');
  5606. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5607. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5608. this.registerType('torch.nn.modules.module.Module', class {
  5609. constructor() {
  5610. this._modules = new collections.OrderedDict();
  5611. this._parameters = new collections.OrderedDict();
  5612. this._buffers = new collections.OrderedDict();
  5613. }
  5614. __setattr__(name, value) {
  5615. if (value instanceof torch.nn.modules.module.Module) {
  5616. this._modules.set(name, value);
  5617. } else {
  5618. this[name] = value;
  5619. }
  5620. }
  5621. __getattr__(name) {
  5622. if (this._modules.has(name)) {
  5623. return this._modules.get(name);
  5624. }
  5625. return this[name];
  5626. }
  5627. __delattr__(name) {
  5628. if (this._modules.has(name)) {
  5629. this._modules.delete(name);
  5630. }
  5631. }
  5632. children() {
  5633. return this._modules.values();
  5634. }
  5635. named_modules(memo, prefix, remove_duplicate) {
  5636. memo = memo || new Set();
  5637. prefix = prefix || '';
  5638. const modules = new builtins.dict();
  5639. if (!memo.has(this)) {
  5640. if (remove_duplicate) {
  5641. memo.add(this);
  5642. }
  5643. modules.set(prefix, this);
  5644. for (const [name, module] of this._modules.items()) {
  5645. if (module && module.named_modules) {
  5646. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5647. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5648. modules.set(k, v);
  5649. }
  5650. }
  5651. }
  5652. }
  5653. return modules;
  5654. }
  5655. named_children() {
  5656. return this._modules;
  5657. }
  5658. parameters() {
  5659. return this._parameters.values();
  5660. }
  5661. named_parameters(recurse) {
  5662. if (recurse) {
  5663. throw new python.Error('Named parameters with recurse not implemented.');
  5664. }
  5665. return this._parameters;
  5666. }
  5667. buffers() {
  5668. return this._buffers.values();
  5669. }
  5670. named_buffers(recurse) {
  5671. if (recurse) {
  5672. throw new python.Error('Named parameters with recurse not implemented.');
  5673. }
  5674. return this._buffers;
  5675. }
  5676. _get_name() {
  5677. return this.__class__.__name__;
  5678. }
  5679. add_module(name, module) {
  5680. this._modules.set(name, module);
  5681. }
  5682. register_module(name, module) {
  5683. this.add_module(name, module);
  5684. }
  5685. });
  5686. torch.nn.Module = torch.nn.modules.module.Module;
  5687. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5688. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5689. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5690. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5691. this.registerType('torch._C.SchemaParser', class {
  5692. constructor(str, allow_typevars) {
  5693. this.L = new torch._C.Lexer(str);
  5694. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5695. }
  5696. parseName() {
  5697. const L = this.L;
  5698. let name = L.expect('id').text();
  5699. if (L.nextIf(':')) {
  5700. L.expect(':');
  5701. name = `${name}::${L.expect('ident').text()}`;
  5702. }
  5703. let overload_name = '';
  5704. if (L.nextIf('.')) {
  5705. overload_name = L.expect('ident').text();
  5706. }
  5707. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5708. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5709. return new torch._C.OperatorName(name, overload_name);
  5710. }
  5711. parseDeclaration() {
  5712. const L = this.L;
  5713. const name = this.parseName();
  5714. if (L.cur().kind !== '(') {
  5715. return name;
  5716. }
  5717. throw new python.Error('Not implemented.');
  5718. }
  5719. parseExactlyOneDeclaration() {
  5720. // const L = this.L;
  5721. const result = this.parseDeclaration();
  5722. // L.nextIf(TK_NEWLINE);
  5723. // L.expect(TK_EOF);
  5724. return result;
  5725. }
  5726. parseArgument(idx, is_return, kwarg_only) {
  5727. const L = this.L;
  5728. const type_parser = this.type_parser;
  5729. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5730. let N = null;
  5731. if (L.nextIf('[')) {
  5732. fake_type = torch.ListType.create(fake_type);
  5733. real_type = torch.ListType.create(real_type);
  5734. if (L.cur().kind === '#') {
  5735. N = Number(L.cur().text());
  5736. L.next();
  5737. }
  5738. L.expect(']');
  5739. let container = type_parser.parseAliasAnnotation();
  5740. if (alias_info) {
  5741. if (!container) {
  5742. container = new torch._C.AliasInfo();
  5743. container.is_write = alias_info.is_write;
  5744. }
  5745. container.addContainedType(alias_info);
  5746. }
  5747. alias_info = container;
  5748. if (L.nextIf('?')) {
  5749. fake_type = torch.OptionalType.create(fake_type);
  5750. real_type = torch.OptionalType.create(real_type);
  5751. }
  5752. }
  5753. let name = null;
  5754. /* eslint-disable no-undef-init */
  5755. let default_value = undefined;
  5756. /* eslint-enable no-undef-init */
  5757. if (is_return) {
  5758. kwarg_only = false;
  5759. if (L.cur().kind === 'id') {
  5760. name = L.next().text();
  5761. } else {
  5762. name = '';
  5763. }
  5764. } else {
  5765. name = L.expect('id').text();
  5766. if (L.nextIf('=')) {
  5767. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5768. }
  5769. }
  5770. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5771. }
  5772. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5773. // auto range = L.cur().range;
  5774. const L = this.L;
  5775. const range = null;
  5776. switch (kind) {
  5777. case torch._C.TypeKind.StringType:
  5778. case torch._C.TypeKind.OptionalType:
  5779. case torch._C.TypeKind.NumberType:
  5780. case torch._C.TypeKind.IntType:
  5781. case torch._C.TypeKind.BoolType:
  5782. case torch._C.TypeKind.FloatType:
  5783. case torch._C.TypeKind.ComplexType:
  5784. return this.parseSingleConstant(arg_type, kind, real_type);
  5785. case torch._C.TypeKind.ListType: {
  5786. const elem_type = arg_type.containedType(0);
  5787. const real_elem_type = real_type.containedType(0);
  5788. if (L.cur().kind === 'id') {
  5789. return this.parseTensorDefault(range);
  5790. } else if (arg_N && L.cur().kind !== '[') {
  5791. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5792. const repeated = Array(arg_N).fill(v);
  5793. // std::vector<IValue> repeated(arg_N, v);
  5794. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5795. }
  5796. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5797. }
  5798. case torch._C.TypeKind.DynamicType:
  5799. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5800. default:
  5801. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5802. }
  5803. }
  5804. parseSingleConstant(type, kind, real_type) {
  5805. const L = this.L;
  5806. if (kind === torch._C.TypeKind.DynamicType) {
  5807. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5808. }
  5809. // const auto& str2dtype = c10::getStringToDtypeMap();
  5810. if (L.cur().kind === 'id') {
  5811. if (L.cur().text() === 'True') {
  5812. L.next();
  5813. return new torch._C.IValue(true);
  5814. }
  5815. if (L.cur().text() === 'False') {
  5816. L.next();
  5817. return new torch._C.IValue(false);
  5818. }
  5819. if (L.cur().text() === 'None') {
  5820. L.next();
  5821. return new torch._C.IValue();
  5822. }
  5823. } else if (L.cur().kind === 'string') {
  5824. const token = L.next();
  5825. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5826. } else if (L.cur().kind === '#') {
  5827. let n = '';
  5828. if (L.nextIf('-')) {
  5829. n = `-${L.expect('#').text()}`; // # .text();
  5830. } else {
  5831. n = L.expect('#').text(); // # .text();
  5832. }
  5833. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5834. throw new Error("Complex type not implemented.");
  5835. /*
  5836. const imag = std::stod(n.substr(0, n.size() - 1));
  5837. return c10::complex<double>(0, imag);
  5838. */
  5839. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5840. const v = parseFloat(n);
  5841. return new torch._C.IValue(v, 'Double');
  5842. } else {
  5843. const v = parseInt(n, 10);
  5844. return new torch._C.IValue(v, 'Int');
  5845. }
  5846. }
  5847. throw new python.Error('Not implemented.');
  5848. /*
  5849. switch (L.cur().kind) {
  5850. case TK_TRUE:
  5851. L.next();
  5852. return true;
  5853. case TK_FALSE:
  5854. L.next();
  5855. return false;
  5856. case TK_NONE:
  5857. L.next();
  5858. return IValue();
  5859. case TK_STRINGLITERAL: {
  5860. const token = L.next();
  5861. return parseStringLiteral(token.range, token.text());
  5862. }
  5863. case TK_IDENT: {
  5864. const tok = L.next();
  5865. const text_view = tok.text_view();
  5866. // NB: float/complex/long are here for BC purposes. Other dtypes
  5867. // are handled via str2dtype.
  5868. // Please don't add more cases to this if-else block.
  5869. if ("float" == text_view) {
  5870. return static_cast<int64_t>("at::kFloat");
  5871. } else if ("complex" == text_view) {
  5872. return static_cast<int64_t>("at::kComplexFloat");
  5873. } else if ("long" == text_view) {
  5874. return static_cast<int64_t>("at::kLong");
  5875. } else if ("strided" == text_view) {
  5876. return static_cast<int64_t>("at::kStrided");
  5877. } else if ("Mean" == text_view) {
  5878. return static_cast<int64_t>("at::Reduction::Mean");
  5879. } else if ("contiguous_format" == text_view) {
  5880. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5881. } else {
  5882. const text = tok.text();
  5883. if (isPossiblyOptionalScalarType(real_type) &&
  5884. str2dtype.count(text) > 0) {
  5885. return static_cast<int64_t>(str2dtype.at(text));
  5886. } else {
  5887. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5888. }
  5889. }
  5890. }
  5891. default: {
  5892. let n;
  5893. if (L.nextIf('-')) {
  5894. n = "-" + L.expect(TK_NUMBER).text();
  5895. }
  5896. else {
  5897. n = L.expect(TK_NUMBER).text();
  5898. }
  5899. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5900. throw new python.Error('Complex type not implemented.');
  5901. const imag = std::stod(n.substr(0, n.size() - 1));
  5902. return c10::complex<double>(0, imag);
  5903. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5904. throw new python.Error('Float type not implemented.');
  5905. return std::stod(n);
  5906. } else {
  5907. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5908. int64_t v = std::stoll(n);
  5909. return v;
  5910. }
  5911. }
  5912. }
  5913. */
  5914. }
  5915. parseConstantList(type, kind, real_type) {
  5916. const L = this.L;
  5917. const tok = L.expect('[');
  5918. const vs = [];
  5919. if (L.cur().kind !== ']') {
  5920. do {
  5921. vs.push(this.parseSingleConstant(type, kind, real_type));
  5922. } while (L.nextIf(','));
  5923. }
  5924. L.expect(']');
  5925. return this.convertToList(type, kind, tok.range, vs);
  5926. }
  5927. convertToList(type, kind, range, vs) {
  5928. switch (kind) {
  5929. case torch._C.TypeKind.ComplexType:
  5930. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5931. case torch._C.TypeKind.FloatType:
  5932. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5933. case torch._C.TypeKind.IntType:
  5934. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5935. case torch._C.TypeKind.BoolType:
  5936. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5937. case torch._C.TypeKindDynamicType:
  5938. return this.convertToList(type.dynamicKind(), range, vs);
  5939. default:
  5940. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5941. throw new python.Error('lists are only supported for float, int and complex types');
  5942. }
  5943. }
  5944. });
  5945. this.registerType('torch.FunctionSchema', class {
  5946. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5947. const index = name.indexOf('(');
  5948. if (index === -1) {
  5949. this._name = name;
  5950. this._overload_name = overload_name || '';
  5951. this._arguments = args || [];
  5952. this._returns = returns || [];
  5953. this._is_vararg = is_vararg || false;
  5954. this._is_varret = is_varret || false;
  5955. } else {
  5956. const value = name.substring(0, index).trim();
  5957. const dot = value.indexOf('.');
  5958. if (dot === -1) {
  5959. this._name = value;
  5960. this._overload_name = '';
  5961. } else {
  5962. this._name = value.substring(0, dot);
  5963. this._overload_name = value.substring(dot + 1, value.length);
  5964. }
  5965. this._buffer = name.substring(index, name.length);
  5966. }
  5967. }
  5968. static parse(schema) {
  5969. return new torch.FunctionSchema(schema);
  5970. }
  5971. get name() {
  5972. return this._name;
  5973. }
  5974. get overload_name() {
  5975. return this._overload_name;
  5976. }
  5977. get arguments() {
  5978. this._parse();
  5979. return this._arguments;
  5980. }
  5981. get returns() {
  5982. this._parse();
  5983. return this._returns;
  5984. }
  5985. get is_vararg() {
  5986. this._parse();
  5987. return this._is_vararg;
  5988. }
  5989. get is_varret() {
  5990. this._parse();
  5991. return this._is_varret;
  5992. }
  5993. argumentIndexWithName(name) {
  5994. const index = this.arguments.findIndex((arg) => arg.name === name);
  5995. return index === -1 ? null : index;
  5996. }
  5997. _parse() {
  5998. if (this._buffer) {
  5999. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  6000. const L = parser.L;
  6001. this._arguments = [];
  6002. this._is_vararg = false;
  6003. this._kwarg_only = false;
  6004. let idx = 0;
  6005. L.expect('(');
  6006. if (!L.nextIf(')')) {
  6007. while (true) {
  6008. if (this._is_vararg) {
  6009. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  6010. }
  6011. if (L.nextIf('*')) {
  6012. this._kwarg_only = true;
  6013. } else if (L.nextIf('...')) {
  6014. this._is_vararg = true;
  6015. } else {
  6016. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  6017. this._arguments.push(argument);
  6018. }
  6019. if (!L.nextIf(',')) {
  6020. break;
  6021. }
  6022. }
  6023. L.expect(')');
  6024. }
  6025. L.expect('->');
  6026. this._returns = [];
  6027. this._is_varret = false;
  6028. if (L.nextIf('...')) {
  6029. this._is_varret = true;
  6030. } else if (L.nextIf('(')) {
  6031. if (!L.nextIf(')')) {
  6032. while (true) {
  6033. if (this._is_varret) {
  6034. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6035. }
  6036. if (L.nextIf('...')) {
  6037. this._is_varret = true;
  6038. } else {
  6039. const argument = parser.parseArgument(idx++, true, false);
  6040. this._returns.push(argument);
  6041. }
  6042. if (!L.nextIf(',')) {
  6043. break;
  6044. }
  6045. }
  6046. L.expect(')');
  6047. }
  6048. } else {
  6049. this._returns.push(parser.parseArgument(0, true, false));
  6050. }
  6051. delete this._buffer;
  6052. }
  6053. }
  6054. __str__() {
  6055. const list = [this.name];
  6056. const overload_name = this.overload_name;
  6057. if (overload_name !== '' && overload_name !== 'default') {
  6058. list.push(`.${this.overload_name}`);
  6059. }
  6060. list.push('(');
  6061. let first = true;
  6062. let kwarg_only = false;
  6063. for (const argument of this.arguments) {
  6064. if (!first) {
  6065. list.push(', ');
  6066. }
  6067. if (argument.kwarg_only && !kwarg_only) {
  6068. list.push('*, ');
  6069. kwarg_only = true;
  6070. }
  6071. first = false;
  6072. list.push(argument.str());
  6073. }
  6074. if (this.is_vararg) {
  6075. if (!first) {
  6076. list.push(', ');
  6077. }
  6078. first = true;
  6079. list.push('...');
  6080. }
  6081. list.push(') -> ');
  6082. const returns = this.returns;
  6083. const braces = !this.is_varret &&
  6084. (returns.length !== 1 ||
  6085. returns[0].name ||
  6086. returns[0].real_type instanceof torch.TupleType ||
  6087. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6088. if (braces) {
  6089. list.push('(');
  6090. }
  6091. first = true;
  6092. for (const argument of this.returns) {
  6093. if (!first) {
  6094. list.push(', ');
  6095. }
  6096. first = false;
  6097. list.push(argument.str());
  6098. }
  6099. if (this.is_varret) {
  6100. if (!first) {
  6101. list.push(', ');
  6102. }
  6103. first = true;
  6104. list.push('...');
  6105. }
  6106. if (braces) {
  6107. list.push(')');
  6108. }
  6109. return list.join('');
  6110. }
  6111. aliasAnalysis() {
  6112. return this._alias_kind || 'CONSERVATIVE';
  6113. }
  6114. setAliasAnalysis(v) {
  6115. this._alias_kind = v;
  6116. }
  6117. hasAnyAliasInfo() {
  6118. for (const arg of this.arguments) {
  6119. if (arg.alias_info !== null) {
  6120. return true;
  6121. }
  6122. }
  6123. for (const ret of this.returns) {
  6124. if (ret.alias_info !== null) {
  6125. return true;
  6126. }
  6127. }
  6128. return false;
  6129. }
  6130. is_mutable() {
  6131. return this.arguments.some((arg) => {
  6132. const aliasInfo = arg.alias_info;
  6133. return aliasInfo && aliasInfo.is_write;
  6134. });
  6135. }
  6136. });
  6137. this.registerType('torch._C.SchemaInfo', class {
  6138. constructor(schema) {
  6139. this._schema = schema;
  6140. this._alias_maps_current = false;
  6141. this._has_init = false;
  6142. }
  6143. is_nondeterministic() {
  6144. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6145. //
  6146. }
  6147. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6148. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6149. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6150. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6151. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6152. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6153. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6154. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6155. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6156. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6157. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6158. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6159. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6160. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6161. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6162. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6163. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6164. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6165. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6166. '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',
  6167. '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',
  6168. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6169. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6170. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6171. ]);
  6172. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6173. return true;
  6174. }
  6175. /*
  6176. const auto& op = c10::Dispatcher::singleton().findOp(
  6177. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6178. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6179. */
  6180. return false;
  6181. }
  6182. });
  6183. this.registerType('torch._C.OperatorRegistry', class {
  6184. constructor() {
  6185. this.to_register = [];
  6186. this.operators = new Map();
  6187. }
  6188. registerPendingOperators() {
  6189. for (const op of this.to_register) {
  6190. const sym = op.schema().name;
  6191. if (!this.operators.has(sym)) {
  6192. this.operators.set(sym, []);
  6193. }
  6194. this.operators.get(sym).push(op);
  6195. }
  6196. this.to_register = [];
  6197. }
  6198. registerOperator(op) {
  6199. this.to_register.push(op);
  6200. }
  6201. getOperators(name) {
  6202. this.registerPendingOperators();
  6203. if (this.operators.has(name)) {
  6204. return this.operators.get(name);
  6205. }
  6206. return [];
  6207. }
  6208. });
  6209. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6210. return torch._C.getRegistry().getOperators(name);
  6211. });
  6212. this.registerType('torch._C.Operator', class {
  6213. constructor(schema) {
  6214. this._schema = schema;
  6215. }
  6216. schema() {
  6217. return this._schema;
  6218. }
  6219. getOperation(/* node */) {
  6220. return null;
  6221. }
  6222. aliasAnalysisKind() {
  6223. const schemaRef = this.schema();
  6224. const alias_analysis = schemaRef.aliasAnalysis();
  6225. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6226. return alias_analysis;
  6227. }
  6228. });
  6229. this.registerFunction('torch._C.getRegistry', () => {
  6230. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6231. return torch._C.r;
  6232. });
  6233. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6234. const operations = torch._C.getAllOperatorsFor(op_name);
  6235. for (const op of operations) {
  6236. if (op.schema().overload_name === overload_name) {
  6237. return op.schema();
  6238. }
  6239. }
  6240. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6241. });
  6242. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6243. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6244. });
  6245. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6246. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6247. if (sortedOps.length === 0) {
  6248. return [null, null];
  6249. }
  6250. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6251. return [{}, overload_names];
  6252. });
  6253. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6254. const operations = torch._C.getAllOperatorsFor(op_name);
  6255. for (const op of operations) {
  6256. if (op.schema().overload_name === overload_name) {
  6257. return [{}, {}, null];
  6258. }
  6259. }
  6260. return null;
  6261. });
  6262. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6263. return null;
  6264. });
  6265. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6266. });
  6267. this.registerType('torch._C.MatchedSchema', class {
  6268. constructor(inputs, return_types, return_field_names, schema_name) {
  6269. this.inputs = inputs;
  6270. this.return_types = return_types;
  6271. this.register_field_names = return_field_names;
  6272. this.schema_name = schema_name;
  6273. }
  6274. });
  6275. this.registerType('torch._C.Self', class {
  6276. });
  6277. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6278. return nvs.map((v) => v.value(g));
  6279. });
  6280. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6281. constructor(classType) {
  6282. super();
  6283. this._classType = classType;
  6284. }
  6285. makeSugared(v) {
  6286. v.setType(this._classType);
  6287. return new torch._C.SimpleValue(v);
  6288. }
  6289. getClassType() {
  6290. return this._classType;
  6291. }
  6292. });
  6293. this.registerType('torch._C.Function', class {
  6294. isGraphFunction() {
  6295. return false;
  6296. }
  6297. name() {
  6298. return this.qualname().name();
  6299. }
  6300. });
  6301. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6302. constructor(qualname, schema) {
  6303. super();
  6304. this._name = qualname;
  6305. this._schema = schema;
  6306. }
  6307. qualname() {
  6308. return this._name;
  6309. }
  6310. getSchema() {
  6311. return this._schema;
  6312. }
  6313. ensure_defined() {
  6314. }
  6315. });
  6316. this.registerType('torch._C.DeadCodeEliminator', class {
  6317. constructor(...args) {
  6318. this._aliasDb = null;
  6319. this._useAliasDb = false;
  6320. this._memo = new Map();
  6321. this._marked = new Set();
  6322. this._liveValues = new Set();
  6323. this._deleteCallback = () => {};
  6324. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6325. [this._graph, this._sideEffectPolicy] = args;
  6326. this._useAliasDb = true;
  6327. } else {
  6328. [this._sideEffectPolicy] = args;
  6329. }
  6330. }
  6331. run(block, recurse) {
  6332. this.eliminateDeadForkInputs(block, recurse);
  6333. this.mark(block.return_node());
  6334. this.mark(block);
  6335. this._deleteCallback(this._liveValues);
  6336. this.sweep(block, recurse);
  6337. }
  6338. setDeleteCallback(deleteCallback) {
  6339. this._deleteCallback = deleteCallback;
  6340. }
  6341. eliminateDeadForkInputs(block, recurse) {
  6342. for (const node of block.nodes()) {
  6343. if (recurse) {
  6344. for (const sb of node.blocks()) {
  6345. this.eliminateDeadForkInputs(sb, recurse);
  6346. }
  6347. }
  6348. if (node.kind() !== 'prim::fork') {
  6349. continue;
  6350. }
  6351. const g = node.g("Subgraph");
  6352. for (let i = 0; i < g.inputs().length; i++) {
  6353. if (!g.inputs()[i].hasUses()) {
  6354. g.eraseInput(i);
  6355. node.removeInput(i);
  6356. }
  6357. }
  6358. }
  6359. }
  6360. markReturnNode(node) {
  6361. if (this._marked.has(node)) {
  6362. return false;
  6363. }
  6364. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6365. const outerNode = node.owningBlock().owningNode();
  6366. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6367. return this.mark(node);
  6368. }
  6369. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6370. const loop = new torch._C.LoopView(outerNode);
  6371. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6372. if (outerNode.kind() === 'onnx::Loop') {
  6373. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6374. continue;
  6375. }
  6376. const innerInput = loop.bodyCarriedInputs()[i];
  6377. const innerOutput = loop.bodyCarriedOutputs()[i];
  6378. const outerOutput = loop.carriedOutputs()[i];
  6379. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6380. this._liveValues.add(innerOutput);
  6381. }
  6382. }
  6383. this._liveValues.add(loop.nextCond());
  6384. } else {
  6385. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6386. for (let i = 0; i < outerNode.outputs().length; i++) {
  6387. const innerOutput = node.inputs()[i];
  6388. const outerOutput = outerNode.outputs()[i];
  6389. if (!this._liveValues.has(outerOutput)) {
  6390. this._liveValues.add(innerOutput);
  6391. }
  6392. }
  6393. }
  6394. this._marked.add(node);
  6395. return true;
  6396. }
  6397. markLoop(node) {
  6398. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6399. let marked = false;
  6400. let anyMarked = false;
  6401. do {
  6402. marked = this.mark(node.blocks().at(0));
  6403. anyMarked = anyMarked || marked;
  6404. } while (marked);
  6405. return anyMarked;
  6406. }
  6407. mark(...args) {
  6408. if (args.length === 1 && args[0] instanceof torch.Block) {
  6409. const [block] = args;
  6410. let anyMarked = false;
  6411. for (const node of block.nodes()) {
  6412. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6413. const marked = this.mark(node);
  6414. anyMarked = anyMarked || marked;
  6415. }
  6416. }
  6417. const marked = this.markReturnNode(block.return_node());
  6418. anyMarked = anyMarked || marked;
  6419. for (const node of block.nodes()) {
  6420. if (node.kind() === 'prim::Loop') {
  6421. const marked = this.markLoop(node);
  6422. anyMarked = anyMarked || marked;
  6423. } else {
  6424. for (const subBlock of node.blocks()) {
  6425. const marked = this.mark(subBlock);
  6426. anyMarked = anyMarked || marked;
  6427. }
  6428. }
  6429. const marked = this.markIfLive(node);
  6430. anyMarked = anyMarked || marked;
  6431. }
  6432. return anyMarked;
  6433. }
  6434. if (args.length === 1 && args[0] instanceof torch.Node) {
  6435. const [node] = args;
  6436. if (this._marked.has(node)) {
  6437. return false;
  6438. }
  6439. this._marked.add(node);
  6440. let curNode = node;
  6441. while (curNode && curNode.owningBlock()) {
  6442. this.mark(curNode);
  6443. curNode = curNode.owningBlock().owningNode();
  6444. }
  6445. for (const input of node.inputs()) {
  6446. if (!this._liveValues.has(input)) {
  6447. this._liveValues.add(input);
  6448. }
  6449. }
  6450. return true;
  6451. }
  6452. throw new python.Error('Not implemented.');
  6453. }
  6454. markIfLive(node) {
  6455. for (const output of node.outputs()) {
  6456. if (this._liveValues.has(output)) {
  6457. return this.mark(node);
  6458. }
  6459. }
  6460. if (this._useAliasDb) {
  6461. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6462. return this.mark(node);
  6463. }
  6464. }
  6465. return false;
  6466. }
  6467. sweep(block, recurse) {
  6468. const nodes = Array.from(block.nodes()).reverse();
  6469. for (const node of nodes) {
  6470. this.removeDeadBlockOutputs(node);
  6471. this.removeDeadLoopOutputs(node);
  6472. if (recurse) {
  6473. for (const block of node.blocks()) {
  6474. this.sweep(block, true);
  6475. }
  6476. }
  6477. if (!this._marked.has(node) && !node.hasUses()) {
  6478. node.destroy();
  6479. }
  6480. }
  6481. }
  6482. hasUntrackedMutation(node) {
  6483. if (!this._useAliasDb) {
  6484. if (node.kind() === 'prim::SetAttr') {
  6485. return true;
  6486. }
  6487. const schema = node.maybeSchema();
  6488. return schema && schema.is_mutable();
  6489. }
  6490. return this.getOrCreateAliasDb().writesToWildcard(node);
  6491. }
  6492. hasSideEffects(node) {
  6493. const it = this._memo.get(node);
  6494. if (it) {
  6495. return it;
  6496. }
  6497. const has_side_effects = node.hasSideEffects() ||
  6498. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6499. this.hasUntrackedMutation(node);
  6500. this._memo.set(node, has_side_effects);
  6501. return has_side_effects;
  6502. }
  6503. removeDeadBlockOutputs(node) {
  6504. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6505. return;
  6506. }
  6507. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6508. const i = i_1 - 1;
  6509. if (!node.outputs()[i].hasUses()) {
  6510. node.eraseOutput(i);
  6511. for (const b of node.blocks()) {
  6512. b.eraseOutput(i);
  6513. }
  6514. }
  6515. }
  6516. }
  6517. removeDeadLoopOutputs() {
  6518. }
  6519. getOrCreateAliasDb() {
  6520. if (!this._aliasDb) {
  6521. this._aliasDb = new torch._C.AliasDb(this._graph);
  6522. }
  6523. return this._aliasDb;
  6524. }
  6525. });
  6526. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6527. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6528. const [graph] = args;
  6529. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6530. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6531. worker.run(graph.block(), /*recurse=*/true);
  6532. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6533. const [block] = args;
  6534. const recurse = false;
  6535. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6536. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6537. worker.run(block, recurse);
  6538. } else {
  6539. throw new python.Error('Not implemented.');
  6540. }
  6541. });
  6542. this.registerFunction('torch._C.removeTupleNodes', () => {
  6543. });
  6544. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6545. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6546. const [graph] = args;
  6547. torch._C.LowerSimpleTuples(graph.block());
  6548. torch._C.EliminateDeadCode(graph);
  6549. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6550. const [block] = args;
  6551. for (const n of block.nodes()) {
  6552. torch._C.removeTupleNodes(n, false);
  6553. for (const b of n.blocks()) {
  6554. torch._C.LowerSimpleTuples(b);
  6555. }
  6556. }
  6557. } else {
  6558. throw new python.Error('Not implemented.');
  6559. }
  6560. });
  6561. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6562. torch._C.AT_ASSERT(lhs !== null);
  6563. torch._C.AT_ASSERT(rhs !== null);
  6564. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6565. return false;
  6566. }
  6567. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6568. return true;
  6569. }
  6570. const lnames = lhs.attributeNames();
  6571. const rnames = rhs.attributeNames();
  6572. lnames.sort();
  6573. rnames.sort();
  6574. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6575. return false;
  6576. }
  6577. for (const name of lnames) {
  6578. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6579. return false;
  6580. }
  6581. const kind = lhs.kindOf(name);
  6582. switch (kind) {
  6583. case 'i':
  6584. case 'f':
  6585. case 's':
  6586. case 't': {
  6587. if (lhs[kind](name) !== rhs[kind](name)) {
  6588. return false;
  6589. }
  6590. break;
  6591. }
  6592. case 'c': {
  6593. const lc = lhs.c(name);
  6594. const rc = rhs.c(name);
  6595. if (lc.real !== rc.real || lc.imag !== rc.imag) {
  6596. return false;
  6597. }
  6598. break;
  6599. }
  6600. case 'ival': {
  6601. if (lhs[kind](name) !== rhs[kind](name)) {
  6602. return false;
  6603. }
  6604. break;
  6605. }
  6606. default: {
  6607. throw new python.Error('Not implemented.');
  6608. }
  6609. }
  6610. }
  6611. return true;
  6612. });
  6613. this.registerFunction('torch._C.get_hash', (...args) => {
  6614. let hash = 0;
  6615. for (const value of args) {
  6616. if (typeof value === 'number') {
  6617. hash += (value | 0);
  6618. } else if (typeof value === 'string') {
  6619. hash += (value.length | 0);
  6620. } else if (Array.isArray(value)) {
  6621. for (const item of value) {
  6622. hash += torch._C.get_hash(item);
  6623. }
  6624. } else if (value instanceof builtins.complex) {
  6625. hash += (value.real | 0) + (value.imag | 0);
  6626. }
  6627. }
  6628. return hash;
  6629. });
  6630. this.registerFunction('torch._C.HashNode', (k) => {
  6631. torch._C.AT_ASSERT(k !== null);
  6632. let constant_hash = 0;
  6633. if (k.kind() === 'prim::Constant') {
  6634. const type = k.output().type();
  6635. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6636. constant_hash = k.i('value');
  6637. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6638. constant_hash = k.f('value');
  6639. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6640. constant_hash = k.c('value');
  6641. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6642. constant_hash = k.i('value');
  6643. }
  6644. }
  6645. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6646. });
  6647. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6648. if (lhs === null && rhs === null) {
  6649. return true;
  6650. }
  6651. if (lhs === null || rhs === null) {
  6652. return false;
  6653. }
  6654. if (lhs.kind() !== rhs.kind()) {
  6655. return false;
  6656. }
  6657. const lhs_outputs = lhs.outputs();
  6658. const rhs_outputs = rhs.outputs();
  6659. if (lhs_outputs.length !== rhs_outputs.length) {
  6660. return false;
  6661. }
  6662. for (let i = 0; i < lhs_outputs.length; i++) {
  6663. const lt = lhs_outputs[i].type();
  6664. const rt = rhs_outputs[i].type();
  6665. if (!lt.equals(rt)) {
  6666. return false;
  6667. }
  6668. }
  6669. const lhs_inputs = lhs.inputs();
  6670. const rhs_inputs = rhs.inputs();
  6671. if (lhs_inputs.length !== rhs_inputs.length) {
  6672. return false;
  6673. }
  6674. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6675. return false;
  6676. }
  6677. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6678. return false;
  6679. }
  6680. if (lhs.blocks().length !== rhs.blocks().length) {
  6681. return false;
  6682. }
  6683. for (let i = 0; i < lhs.blocks().length; i++) {
  6684. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6685. return false;
  6686. }
  6687. }
  6688. return true;
  6689. });
  6690. this.registerType('torch._C.NodeSet', class {
  6691. constructor() {
  6692. this._nodes = new Map();
  6693. }
  6694. insert(n) {
  6695. const key = torch._C.HashNode(n);
  6696. if (this._nodes.has(key)) {
  6697. this._nodes.get(key).push(n);
  6698. } else {
  6699. this._nodes.set(key, [n]);
  6700. }
  6701. }
  6702. get(n) {
  6703. const key = torch._C.HashNode(n);
  6704. if (this._nodes.has(key)) {
  6705. const nodes = this._nodes.get(key);
  6706. for (const node of nodes) {
  6707. if (torch._C.EqualNode(node, n)) {
  6708. return node;
  6709. }
  6710. }
  6711. }
  6712. return null;
  6713. }
  6714. has(n) {
  6715. return this.get(n) !== null;
  6716. }
  6717. });
  6718. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6719. const ty = stack.pop().type();
  6720. for (const candidate of types) {
  6721. if (ty.isSubtypeOf(candidate)) {
  6722. stack.push(new torch._C.IValue(true, 'Bool'));
  6723. stack.push(true);
  6724. return;
  6725. }
  6726. }
  6727. stack.push(new torch._C.IValue(false, 'Bool'));
  6728. });
  6729. this.registerType('torch._C.Tuple', class {
  6730. constructor(elements) {
  6731. this._elements = elements;
  6732. }
  6733. static create(elements) {
  6734. return new torch._C.Tuple(elements);
  6735. }
  6736. elements() {
  6737. return this._elements;
  6738. }
  6739. });
  6740. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6741. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6742. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6743. const tuple = torch._C.Tuple.create(elems.reverse());
  6744. stack.push(new torch._C.IValue(tuple));
  6745. });
  6746. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6747. let stack = [];
  6748. for (const input of n.inputs()) {
  6749. const ival = torch._C.toIValue(input);
  6750. if (ival) {
  6751. stack.push(ival);
  6752. } else {
  6753. return null;
  6754. }
  6755. }
  6756. switch (n.kind()) {
  6757. case 'prim::ListUnpack': {
  6758. if (stack.back().toList().size() !== n.outputs().length) {
  6759. return null;
  6760. }
  6761. torch._C.listUnpack(stack, n.outputs().length);
  6762. break;
  6763. }
  6764. case 'prim::TupleConstruct': {
  6765. const tt = n.output().type().expect(torch.TupleType);
  6766. if (tt.name()) {
  6767. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6768. } else {
  6769. torch._C.tupleConstruct(stack, n.inputs().length);
  6770. }
  6771. break;
  6772. }
  6773. case 'prim::ListConstruct': {
  6774. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6775. break;
  6776. }
  6777. case 'prim::DictConstruct': {
  6778. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6779. break;
  6780. }
  6781. case 'prim::CreateObject': {
  6782. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6783. break;
  6784. }
  6785. case 'prim::GetAttr': {
  6786. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6787. torch._C.push(stack, attr);
  6788. break;
  6789. }
  6790. case 'prim::isinstance': {
  6791. torch._C.isinstance(stack, n.tys('types'));
  6792. break;
  6793. }
  6794. default: {
  6795. const maybe_schema = n.maybeSchema();
  6796. if (maybe_schema && maybe_schema.is_vararg) {
  6797. return null;
  6798. }
  6799. // try
  6800. // {
  6801. // const op = n.getOperation();
  6802. // op(stack);
  6803. const [module, name] = n.kind().split('::');
  6804. const obj = torch.ops[module];
  6805. if (!obj) {
  6806. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6807. }
  6808. const fn = torch.ops[module].__getattr__(name);
  6809. if (!fn || !fn.__call__) {
  6810. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6811. }
  6812. const args = stack.map((v) => v.value);
  6813. const result = fn.__call__(...args);
  6814. if (result === undefined) {
  6815. stack = [];
  6816. } else if (result instanceof torch._C.IValue) {
  6817. stack = [result];
  6818. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6819. stack = result;
  6820. } else {
  6821. stack = [new torch._C.IValue(result)];
  6822. }
  6823. // } catch {
  6824. // stack = [];
  6825. // return null;
  6826. // }
  6827. break;
  6828. }
  6829. }
  6830. for (const v of stack) {
  6831. if (v.isTensor()) {
  6832. const t = v.toTensor();
  6833. if (t.defined() && t.requires_grad()) {
  6834. return null;
  6835. }
  6836. }
  6837. if (ignore_custom_classes) {
  6838. if (v.isCustomClass()) {
  6839. return null;
  6840. }
  6841. }
  6842. if (v.isCustomClass()) {
  6843. if (v.toObject().is_weak_compilation_ref()) {
  6844. continue;
  6845. }
  6846. if (!db) {
  6847. continue;
  6848. }
  6849. const n_non_const = n;
  6850. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6851. continue;
  6852. }
  6853. const obj = v.toObject();
  6854. obj.unsafe_make_weak_compilation_ref();
  6855. }
  6856. if (v.isObject()) {
  6857. if (!v.toObject().is_weak_compilation_ref()) {
  6858. return null;
  6859. }
  6860. }
  6861. }
  6862. return stack;
  6863. });
  6864. this.registerType('torch._C.ConstantPropagator', class {
  6865. constructor(graph, aliasing_types, ignore_custom_classes) {
  6866. this._made_change = false;
  6867. this._graph = graph;
  6868. this._aliasing_types = aliasing_types;
  6869. this._ignore_custom_classes = ignore_custom_classes;
  6870. }
  6871. static NoAliasDb(graph) {
  6872. return new torch._C.ConstantPropagator(graph, false, false);
  6873. }
  6874. run() {
  6875. this.ConstantPropagation(this._graph.block());
  6876. return this._made_change;
  6877. }
  6878. propagateNode(n) {
  6879. let outputs = [];
  6880. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6881. if (outputs_opt) {
  6882. outputs = outputs_opt;
  6883. const graph = n.owningGraph();
  6884. const guard = new torch._C.WithInsertPoint(n);
  6885. for (let i = 0; i < outputs.length; i++) {
  6886. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6887. if (new_output) {
  6888. this._made_change = true;
  6889. if (outputs[i].isNone()) {
  6890. new_output.setType(n.outputs()[i].type());
  6891. }
  6892. n.outputs()[i].replaceAllUsesWith(new_output);
  6893. }
  6894. }
  6895. guard.dispose();
  6896. }
  6897. }
  6898. removeLoopNode(n) {
  6899. const loop_input_offset = 2;
  6900. for (let i = 0; i < n.outputs().length; i++) {
  6901. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6902. }
  6903. this._made_change = true;
  6904. n.destroy();
  6905. }
  6906. loopWillNotRun(node) {
  6907. const [trip_count, start_cond] = node.inputs();
  6908. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6909. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6910. const loop_might_run = cond_val && iter_len > 0;
  6911. return !loop_might_run;
  6912. }
  6913. inlineIfBody(body) {
  6914. const n = body.owningNode();
  6915. for (const body_node of body.nodes()) {
  6916. body_node.moveBefore(n);
  6917. }
  6918. for (let i = 0; i < n.outputs().length; i++) {
  6919. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6920. }
  6921. n.destroy();
  6922. }
  6923. inlineIf(n) {
  6924. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6925. torch._C.AT_ASSERT(input_bool !== null);
  6926. const block_index = input_bool ? 0 : 1;
  6927. this.ConstantPropagation(n.blocks().at(block_index));
  6928. this.inlineIfBody(n.blocks().at(block_index));
  6929. this._made_change = true;
  6930. }
  6931. replaceAndRemoveIfOutput(n, i, replacement) {
  6932. n.outputs()[i].replaceAllUsesWith(replacement);
  6933. n.eraseOutput(i);
  6934. n.blocks().at(0).eraseOutput(i);
  6935. n.blocks().at(1).eraseOutput(i);
  6936. }
  6937. removeExtraIfOutputs(n) {
  6938. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6939. const [true_block, false_block] = n.blocks();
  6940. const graph = n.owningGraph();
  6941. const initial_outputs = true_block.outputs().length;
  6942. const guard = new torch._C.WithInsertPoint(n);
  6943. for (let i = 0; i < true_block.outputs().length;) {
  6944. const t_out = true_block.outputs()[i];
  6945. const f_out = false_block.outputs()[i];
  6946. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6947. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6948. continue;
  6949. }
  6950. const maybe_const = torch._C.toIValue(t_out);
  6951. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6952. const new_const = graph.insertConstant(maybe_const);
  6953. this.replaceAndRemoveIfOutput(n, i, new_const);
  6954. continue;
  6955. }
  6956. i++;
  6957. }
  6958. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6959. guard.dispose();
  6960. }
  6961. removeExtraLoopOutputs(node) {
  6962. const initial_outputs = node.outputs().length;
  6963. const [loop_body] = node.blocks();
  6964. const loop_input_offset = 2;
  6965. const loop_body_offset = 1;
  6966. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6967. const i = i_1 - 1;
  6968. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6969. const node_input = node.inputs()[loop_input_offset + i];
  6970. node.outputs().at(i).replaceAllUsesWith(node_input);
  6971. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6972. node.eraseOutput(i);
  6973. node.removeInput(loop_input_offset + i);
  6974. loop_body.eraseInput(loop_body_offset + i);
  6975. loop_body.eraseOutput(loop_body_offset + i);
  6976. }
  6977. }
  6978. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6979. }
  6980. noMutableValues(values) {
  6981. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6982. }
  6983. getOrCreateAliasDb() {
  6984. if (!this._aliasDb) {
  6985. this._aliasDb = new torch._C.AliasDb(this._graph);
  6986. }
  6987. return this._aliasDb;
  6988. }
  6989. supportedNode(n) {
  6990. torch._C.skip_list = torch._C.skip_list || new Set([
  6991. 'prim::If',
  6992. 'prim::Loop',
  6993. 'prim::Closure',
  6994. 'prim::Constant',
  6995. 'prim::AutogradZero',
  6996. 'prim::Uninitialized',
  6997. 'prim::Guard',
  6998. 'prim::profile',
  6999. 'prim::profile_ivalue',
  7000. 'prim::unchecked_unwrap_optional',
  7001. 'prim::awaitable',
  7002. 'aten::dequantize'
  7003. ]);
  7004. let no_mutation = false;
  7005. if (this._aliasing_types) {
  7006. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  7007. } else {
  7008. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  7009. }
  7010. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  7011. }
  7012. ConstantPropagation(...args) {
  7013. if (args[0] instanceof torch.Graph) {
  7014. throw new python.Error('Not implemented.');
  7015. } else if (args[0] instanceof torch.Block) {
  7016. const [block] = args;
  7017. for (const n of block.nodes()) {
  7018. this.ConstantPropagation(n);
  7019. }
  7020. } else if (args[0] instanceof torch.Node) {
  7021. const [n] = args;
  7022. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  7023. if (n.kind() === 'prim::If') {
  7024. if (constant_inputs) {
  7025. this.inlineIf(n);
  7026. } else {
  7027. this.ConstantPropagation(n.blocks());
  7028. this.removeExtraIfOutputs(n);
  7029. }
  7030. } else if (n.kind() === 'prim::Loop') {
  7031. if (this.loopWillNotRun(n)) {
  7032. this.removeLoopNode(n);
  7033. } else {
  7034. this.ConstantPropagation(n.blocks());
  7035. this.removeExtraLoopOutputs(n);
  7036. }
  7037. } else if (constant_inputs && this.supportedNode(n)) {
  7038. this.propagateNode(n);
  7039. } else {
  7040. this.ConstantPropagation(n.blocks()); // not implemented
  7041. }
  7042. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7043. const [blocks] = args;
  7044. for (const block of blocks) {
  7045. this.ConstantPropagation(block);
  7046. }
  7047. } else {
  7048. throw new python.Error('Not implemented.');
  7049. }
  7050. }
  7051. });
  7052. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7053. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7054. const made_change = cp.run();
  7055. if (made_change) {
  7056. torch._C.EliminateDeadCode(graph);
  7057. }
  7058. return made_change;
  7059. });
  7060. this.registerType('torch._C.MutableTypePtrHelper', class {
  7061. constructor(mutable_type_cache) {
  7062. this._mutable_type_cache = mutable_type_cache;
  7063. }
  7064. mapTypeToAliasTypeSet(type) {
  7065. if (this._mutable_type_cache) {
  7066. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7067. if (result) {
  7068. return result;
  7069. }
  7070. }
  7071. return this.mapTypeToAliasTypeSetImpl(type);
  7072. }
  7073. mapTypeToAliasTypeSetImpl(type) {
  7074. if (type instanceof torch.ListType ||
  7075. type instanceof torch.DictType ||
  7076. type instanceof torch.ClassType ||
  7077. type instanceof torch.TensorType) {
  7078. return [torch._C.unshapedType(type)];
  7079. }
  7080. if (type instanceof torch.UnionType) {
  7081. const mutable_types = [];
  7082. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7083. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7084. if (maybe_inner_types) {
  7085. mutable_types.push(...maybe_inner_types);
  7086. }
  7087. }
  7088. if (mutable_types.length === 0) {
  7089. return null;
  7090. }
  7091. return mutable_types;
  7092. }
  7093. if (type instanceof torch.OptionalType) {
  7094. const inner = type.getElementType();
  7095. return this.mapTypeToAliasTypeSet(inner);
  7096. }
  7097. if (type instanceof torch.AnyType) {
  7098. return [torch._C.AliasTypeSet([type])];
  7099. }
  7100. if (type instanceof torch.FutureType) {
  7101. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7102. if (maybe_mut_types) {
  7103. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7104. }
  7105. return null;
  7106. }
  7107. if (type instanceof torch.AwaitType) {
  7108. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7109. if (maybe_mut_types) {
  7110. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7111. }
  7112. return null;
  7113. }
  7114. if (type instanceof torch.TupleType) {
  7115. const mutable_types = [];
  7116. for (const inner of type.elements()) {
  7117. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7118. if (maybe_inner_types) {
  7119. mutable_types.push(...maybe_inner_types);
  7120. }
  7121. }
  7122. if (mutable_types.length === 0) {
  7123. return null;
  7124. }
  7125. return [[torch.TupleType.create(mutable_types)]];
  7126. }
  7127. return null;
  7128. }
  7129. });
  7130. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7131. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7132. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7133. return true;
  7134. }
  7135. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7136. if (mutable_type_cache) {
  7137. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7138. }
  7139. return helper.mapTypeToAliasTypeSet(type) !== null;
  7140. });
  7141. this.registerType('torch._C.AliasDb', class {
  7142. constructor() {
  7143. this._writeIndex = new Map();
  7144. }
  7145. static isMutableType(...args) {
  7146. if (args[0] instanceof torch.Type) {
  7147. const [type] = args;
  7148. return torch._C.isMutableTypeImpl(type, null);
  7149. }
  7150. if (args[0] instanceof torch.Value) {
  7151. const [value] = args;
  7152. return torch._C.AliasDb.isMutableType(value.type());
  7153. }
  7154. throw new python.Error('Not implemented.');
  7155. }
  7156. writesToAlias(/* n, vs */) {
  7157. /*
  7158. const writtenTo = this.getWrites(n);
  7159. if (writtenTo.length === 0) {
  7160. return false;
  7161. }
  7162. MemoryLocations locs;
  7163. for (const v of vs) {
  7164. const it = elementMap_.find(v);
  7165. if (it != elementMap_.end()) {
  7166. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7167. if (writtenTo.intersects(vlocs)) {
  7168. return true;
  7169. }
  7170. }
  7171. }
  7172. */
  7173. return false;
  7174. }
  7175. writesToWildcard(n) {
  7176. if (!this._writeIndex.has(n)) {
  7177. return false;
  7178. }
  7179. const writes = this._writeIndex.get(n);
  7180. for (const pr of this._wildcardIndex) {
  7181. const [, wildcardElement] = pr;
  7182. if (writes.test(wildcardElement.index)) {
  7183. return true;
  7184. }
  7185. }
  7186. return false;
  7187. }
  7188. safeToChangeAliasingRelationship(a, b) {
  7189. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7190. return false;
  7191. }
  7192. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7193. }
  7194. });
  7195. this.registerFunction('torch._C.hasWriters', () => {
  7196. });
  7197. this.registerFunction('torch._C.escapesScope', () => {
  7198. });
  7199. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7200. constructor(graph) {
  7201. this._current = graph.block().nodes().front();
  7202. }
  7203. next() {
  7204. return null;
  7205. }
  7206. });
  7207. this.registerType('torch._C.ConcatCombiner', class {
  7208. constructor(graph) {
  7209. this._graph = graph;
  7210. this._aliasDb = new torch._C.AliasDb(graph);
  7211. this._combinable_concats = [];
  7212. }
  7213. collectOptimizableConcats() {
  7214. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7215. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7216. if (node.kind() === 'aten::cat') {
  7217. this.handleConcat(node);
  7218. }
  7219. }
  7220. }
  7221. combineConcats() {
  7222. if (this._combinable_concats.length === 0) {
  7223. return false;
  7224. }
  7225. const list_construct_inputs = this.getListConstructInputs();
  7226. for (const node_and_new_list of list_construct_inputs) {
  7227. const [node, inputs] = node_and_new_list;
  7228. const new_list_construct = this.createListConstruct(inputs);
  7229. const old_list_construct = node.input(0).node();
  7230. new_list_construct.output().setType(old_list_construct.output().type());
  7231. new_list_construct.insertBefore(node);
  7232. old_list_construct.replaceAllUsesWith(new_list_construct);
  7233. }
  7234. return true;
  7235. }
  7236. run() {
  7237. this.collectOptimizableConcats();
  7238. const changed = this.combineConcats();
  7239. if (changed) {
  7240. torch._C.EliminateDeadCode(this._graph);
  7241. }
  7242. return changed;
  7243. }
  7244. });
  7245. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7246. const changed = new torch._C.ConcatCombiner(graph).run();
  7247. return changed;
  7248. });
  7249. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7250. constructor(graph, disable_shape_peepholes) {
  7251. this._graph = graph;
  7252. this._shape_peepholes = !disable_shape_peepholes;
  7253. }
  7254. run() {
  7255. let changed = this.optimizeBlock(this._graph.block());
  7256. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7257. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7258. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7259. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7260. changed = changed || torch._C.CombineConcats(this._graph);
  7261. return changed;
  7262. }
  7263. optimizeBlock(block) {
  7264. let changed = false;
  7265. for (const node of block.nodes()) {
  7266. for (const sub_block of node.blocks()) {
  7267. changed = changed || this.optimizeBlock(sub_block);
  7268. }
  7269. if (node.kind() !== 'prim::Constant') {
  7270. const guard = new torch._C.WithInsertPoint(node);
  7271. for (const output of node.outputs()) {
  7272. if (output.type() instanceof torch.NoneType) {
  7273. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7274. changed = true;
  7275. }
  7276. }
  7277. guard.dispose();
  7278. }
  7279. if (node.kind() === 'prim::If') {
  7280. // throw new python.Error('Not implemented.');
  7281. /*
  7282. const n = new torch._C.IfView(node);
  7283. // this handles redundant short circuits like "x and True" or "x or
  7284. // False"
  7285. for (const auto i : c10::irange(n.outputs().length)) {
  7286. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7287. continue;
  7288. }
  7289. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7290. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7291. if (true_val && !false_val) {
  7292. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7293. changed = true;
  7294. }
  7295. }
  7296. for (let i = 0; i < n.outputs().length; ++i) {
  7297. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7298. const output_optional = n.outputs()[i].type();
  7299. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7300. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7301. if (unif) {
  7302. n.outputs()[i].setType(unif);
  7303. changed = true;
  7304. }
  7305. }
  7306. }
  7307. */
  7308. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7309. torch._C.AT_ASSERT(node.inputs().length === 2);
  7310. for (const check_none_index of [0, 1]) {
  7311. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7312. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7313. if (input_must_be_none && other_must_not_be_none) {
  7314. const guard = new torch._C.WithInsertPoint(node);
  7315. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7316. node.output().replaceAllUsesWith(output);
  7317. changed = true;
  7318. guard.dispose();
  7319. }
  7320. }
  7321. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7322. throw new python.Error('Not implemented.');
  7323. /*
  7324. // we are unwrapping an input that can't be None, remove the unwrap
  7325. const input = node.input();
  7326. if (input.mustNotBeNone()) {
  7327. node.output().replaceAllUsesWith(node.input());
  7328. changed = true;
  7329. }
  7330. */
  7331. } else if (node.kind() === 'prim::unchecked_cast') {
  7332. const input_type = torch._C.unshapedType(node.input().type());
  7333. const output_type = torch._C.unshapedType(node.output().type());
  7334. if (input_type.isSubtypeOf(output_type)) {
  7335. node.output().replaceAllUsesWith(node.input());
  7336. changed = true;
  7337. }
  7338. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7339. node.output().replaceAllUsesWith(node.input());
  7340. changed = true;
  7341. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7342. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7343. continue;
  7344. }
  7345. const inp_type = node.inputs()[0].type();
  7346. const immut_type = (type) => {
  7347. const kind = type.kind();
  7348. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7349. return handled_immutable_types.has(kind);
  7350. };
  7351. let non_throwing_type = false;
  7352. if (inp_type instanceof torch.ListType) {
  7353. non_throwing_type = immut_type(inp_type.getElementType());
  7354. } else if (inp_type instanceof torch.DictType) {
  7355. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7356. } else {
  7357. non_throwing_type = immut_type(inp_type);
  7358. }
  7359. if (non_throwing_type) {
  7360. const guard = new torch._C.WithInsertPoint(node);
  7361. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7362. changed = true;
  7363. guard.dispose();
  7364. }
  7365. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7366. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7367. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7368. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7369. }
  7370. }
  7371. return changed;
  7372. }
  7373. });
  7374. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7375. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7376. const changed = peephole.run();
  7377. if (changed) {
  7378. torch._C.EliminateDeadCode(graph.block());
  7379. }
  7380. return changed;
  7381. });
  7382. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7383. if (!cond) {
  7384. throw new python.Error('Assertion failed.');
  7385. }
  7386. });
  7387. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7388. if (!cond) {
  7389. throw new python.Error('Assertion failed.');
  7390. }
  7391. });
  7392. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7393. if (!cond) {
  7394. throw new python.Error('Assertion failed.');
  7395. }
  7396. });
  7397. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7398. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7399. for (let next_node = it.next(); next_node !== null;) {
  7400. const node = next_node;
  7401. next_node = it.next();
  7402. if (node.kind() === 'prim::EmptyListLiteral') {
  7403. if (node.hasUses()) {
  7404. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7405. }
  7406. const li = graph.createList(torch.TensorType.get(), []);
  7407. li.insertBefore(node);
  7408. node.replaceAllUsesWith(li);
  7409. }
  7410. node.destroy();
  7411. }
  7412. });
  7413. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7414. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7415. const [graph] = args;
  7416. const aliasDb = new torch._C.AliasDb(graph);
  7417. const constants = new torch._C.NodeSet();
  7418. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7419. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7420. const [block, constants, aliasDb] = args;
  7421. for (const node of block.nodes()) {
  7422. if (node.blocks().length > 0) {
  7423. for (const block of node.blocks()) {
  7424. torch._C.ConstantPooling(block, constants, aliasDb);
  7425. }
  7426. continue;
  7427. }
  7428. if (node.kind() !== 'prim::Constant') {
  7429. continue;
  7430. }
  7431. if (constants.has(node)) {
  7432. const existing = constants.get(node);
  7433. const old_ivalue = torch._C.toIValue(existing.output());
  7434. const new_ivalue = torch._C.toIValue(node.output());
  7435. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7436. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7437. continue;
  7438. }
  7439. node.replaceAllUsesWith(existing);
  7440. node.destroy();
  7441. continue;
  7442. } else {
  7443. constants.insert(node);
  7444. }
  7445. const [first_node] = node.owningGraph().block().nodes();
  7446. if (node !== first_node) {
  7447. node.moveBefore(first_node);
  7448. }
  7449. }
  7450. } else {
  7451. throw new python.Error('Not implemented.');
  7452. }
  7453. });
  7454. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7455. /*
  7456. const autocast_stack = [];
  7457. let incompatible_amp = null;
  7458. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7459. for (const node of block.nodes()) {
  7460. switch (node.kind()) {
  7461. case 'prim::CallFunction':
  7462. if (current_state() === initial_state) {
  7463. if (current_state()) {
  7464. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7465. }
  7466. break;
  7467. }
  7468. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7469. incompatible_amp = true;
  7470. break;
  7471. case 'prim::CallMethod':
  7472. if (current_state() === initial_state) {
  7473. if (current_state()) {
  7474. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7475. }
  7476. break;
  7477. }
  7478. if (node.input(0).type() instanceof torch.ClassType) {
  7479. const class_type = node.input(0).type();
  7480. const name = node.s('name');
  7481. const fn = class_type.getMethod(name);
  7482. if (!fn.isGraphFunction()) {
  7483. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7484. incompatible_amp = true;
  7485. }
  7486. } else {
  7487. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7488. incompatible_amp = true;
  7489. }
  7490. break;
  7491. case 'prim::Enter': {
  7492. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7493. if (autocast_scope) {
  7494. if (node.hasUses()) {
  7495. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7496. }
  7497. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7498. incompatible_amp = false;
  7499. autocast_stack.push(autocast_scope);
  7500. }
  7501. break;
  7502. }
  7503. case 'prim::Exit': {
  7504. if (torch._C.isAutocastNode(node.input(0))) {
  7505. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7506. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7507. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7508. incompatible_amp = false;
  7509. autocast_stack.pop();
  7510. }
  7511. break;
  7512. }
  7513. case 'aten::is_autocast_enabled': {
  7514. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7515. break;
  7516. }
  7517. case 'aten::is_autocast_cpu_enabled': {
  7518. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7519. break;
  7520. }
  7521. case 'aten::_convolution':
  7522. case 'aten::conv1d':
  7523. case 'aten::conv2d':
  7524. case 'aten::conv3d':
  7525. case 'aten::conv_tbc':
  7526. case 'aten::conv_transpose1d':
  7527. case 'aten::convolution':
  7528. case 'aten::cudnn_convolution':
  7529. case 'aten::cudnn_convolution_transpose':
  7530. case 'aten::prelu':
  7531. case 'aten::addmm':
  7532. case 'aten::addmv':
  7533. case 'aten::addr':
  7534. case 'aten::matmul':
  7535. case 'aten::mm':
  7536. case 'aten::mv':
  7537. case 'aten::linear':
  7538. case 'aten::addbmm':
  7539. case 'aten::baddbmm':
  7540. case 'aten::bmm':
  7541. case 'aten::chain_matmul':
  7542. case 'aten::_thnn_fused_lstm_cell':
  7543. case 'aten::_thnn_fused_gru_cell':
  7544. case 'aten::lstm_cell':
  7545. case 'aten::gru_cell':
  7546. case 'aten::rnn_tanh_cell':
  7547. case 'aten::rnn_relu_cell': {
  7548. if (!node.schema().is_mutable()) {
  7549. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7550. }
  7551. break;
  7552. }
  7553. case 'aten::native_layer_norm':
  7554. case 'aten::acos':
  7555. case 'aten::asin':
  7556. case 'aten::cosh':
  7557. case 'aten::erfinv':
  7558. case 'aten::exp':
  7559. case 'aten::expm1':
  7560. case 'aten::log':
  7561. case 'aten::log10':
  7562. case 'aten::log2':
  7563. case 'aten::log1p':
  7564. case 'aten::reciprocal':
  7565. case 'aten::rsqrt':
  7566. case 'aten::sinh':
  7567. case 'aten::tan':
  7568. case 'aten::pow':
  7569. case 'aten::softplus':
  7570. case 'aten::gelu':
  7571. case 'aten::layer_norm':
  7572. case 'aten::group_norm':
  7573. case 'aten::frobenius_norm':
  7574. case 'aten::nuclear_norm':
  7575. case 'aten::cosine_similarity':
  7576. case 'aten::cosine_embedding_loss':
  7577. case 'aten::nll_loss':
  7578. case 'aten::nll_loss2d':
  7579. case 'aten::hinge_embedding_loss':
  7580. case 'aten::kl_div':
  7581. case 'aten::l1_loss':
  7582. case 'aten::smooth_l1_loss':
  7583. case 'aten::mse_loss':
  7584. case 'aten::margin_ranking_loss':
  7585. case 'aten::multilabel_margin_loss':
  7586. case 'aten::soft_margin_loss':
  7587. case 'aten::triplet_margin_loss':
  7588. case 'aten::multi_margin_loss':
  7589. case 'aten::binary_cross_entropy_with_logits':
  7590. case 'aten::dist':
  7591. case 'aten::pdist':
  7592. case 'aten::cdist':
  7593. case 'aten::renorm':
  7594. case 'aten::logsumexp': {
  7595. if (!node.schema().is_mutable()) {
  7596. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7597. }
  7598. break;
  7599. }
  7600. case 'aten::prod':
  7601. case 'aten::log_softmax':
  7602. case 'aten::cumprod':
  7603. case 'aten::cumsum':
  7604. case 'aten::sum': {
  7605. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7606. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7607. }
  7608. break;
  7609. }
  7610. case 'aten::softmax': {
  7611. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7612. const context = current_state();
  7613. context.cpu_enabled = false;
  7614. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7615. }
  7616. break;
  7617. }
  7618. case 'aten::addcdiv':
  7619. case 'aten::addcmul':
  7620. case 'aten::atan2':
  7621. case 'aten::bilinear':
  7622. case 'aten::cat':
  7623. case 'aten::cross':
  7624. case 'aten::dot':
  7625. case 'aten::equal':
  7626. case 'aten::index_put':
  7627. case 'aten::stack':
  7628. case 'aten::tensordot':
  7629. case 'aten::add':
  7630. case 'aten::sub':
  7631. case 'aten::mul':
  7632. case 'aten::div': {
  7633. if (!node.schema().is_mutable()) {
  7634. torch._C.castInputsToWidestType(node, current_state());
  7635. }
  7636. break;
  7637. }
  7638. case 'aten::binary_cross_entropy': {
  7639. if (current_state()) {
  7640. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7641. }
  7642. break;
  7643. }
  7644. default: {
  7645. break;
  7646. }
  7647. }
  7648. for (const sub_block of node.blocks()) {
  7649. torch._C.handleBlock(sub_block, current_state());
  7650. }
  7651. }
  7652. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7653. */
  7654. });
  7655. this.registerFunction('torch._C.autocastEnabled', () => {
  7656. return true;
  7657. });
  7658. this.registerFunction('torch._C.Autocast', (graph) => {
  7659. if (torch._C.autocastEnabled()) {
  7660. const init = null;
  7661. /* AutocastContext init = {
  7662. at::autocast::is_autocast_enabled(at::kCUDA),
  7663. at::autocast::is_autocast_enabled(at::kCPU),
  7664. at::autocast::get_autocast_dtype(at::kCUDA),
  7665. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7666. torch._C.handleBlock(graph.block(), init);
  7667. }
  7668. });
  7669. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7670. disable_autocast = disable_autocast || false;
  7671. torch._C.Inline(graph);
  7672. torch._C.PeepholeOptimize(graph, true);
  7673. torch._C.ConstantPropagationImmutableTypes(graph);
  7674. if (!disable_autocast) {
  7675. torch._C.Autocast(graph);
  7676. }
  7677. torch._C.ConstantPooling(graph);
  7678. });
  7679. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7680. constructor(name, graph, function_creator, executor_execution_mode) {
  7681. super();
  7682. this._name = name;
  7683. this._graph = graph;
  7684. this._executor_execution_mode = executor_execution_mode || null;
  7685. this._function_creator = function_creator;
  7686. this._force_no_amp = false;
  7687. }
  7688. isGraphFunction() {
  7689. return true;
  7690. }
  7691. qualname() {
  7692. return this._name;
  7693. }
  7694. graph() {
  7695. return this._graph;
  7696. }
  7697. optimized_graph() {
  7698. const graph_ref = this._graph.copy();
  7699. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7700. return graph_ref;
  7701. }
  7702. ensure_defined() {
  7703. if (this._function_creator) {
  7704. const creator = this._function_creator;
  7705. this._function_creator = () => {
  7706. throw new python.Error('Recursive method call.');
  7707. };
  7708. creator(this);
  7709. this._function_creator = null;
  7710. }
  7711. this.check_single_output();
  7712. }
  7713. check_single_output() {
  7714. if (this.graph().outputs().length !== 1) {
  7715. throw new python.Error('Graph must have a single output.');
  7716. }
  7717. }
  7718. getSchema() {
  7719. this._schema = this._schema || this.defaultSchemaFor(this);
  7720. return this._schema;
  7721. }
  7722. setSchema(schema) {
  7723. this._schema = schema;
  7724. }
  7725. num_inputs() {
  7726. return this.graph().inputs().length;
  7727. }
  7728. unshapedType(type) {
  7729. if (type.isSubtypeOf(torch.TensorType.get())) {
  7730. return torch.TensorType.get();
  7731. }
  7732. const contained = type.containedTypes();
  7733. if (contained.length === 0) {
  7734. return type;
  7735. }
  7736. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7737. }
  7738. defaultSchemaFor(fn) {
  7739. const args = [];
  7740. const returns = [];
  7741. const g = fn.graph();
  7742. const num_inputs = fn.num_inputs();
  7743. for (let i = 0; i < num_inputs; i++) {
  7744. const v = g.inputs()[i];
  7745. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7746. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7747. args.push(argument);
  7748. }
  7749. const num_outputs = g.outputs().length;
  7750. for (let i = 0; i < num_outputs; i++) {
  7751. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7752. returns.push(argument);
  7753. }
  7754. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7755. }
  7756. });
  7757. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7758. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7759. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7760. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7761. __str__() {
  7762. return this._args.map((a) => a.__str__()).join('//');
  7763. }
  7764. });
  7765. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7766. this.registerType('torch.utils._sympy.functions.Where', class {});
  7767. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7768. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7769. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7770. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7771. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7772. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7773. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7774. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7775. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7776. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7777. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7778. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7779. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7780. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7781. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7782. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7783. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7784. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7785. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7786. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7787. static extract() {
  7788. }
  7789. });
  7790. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7791. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7792. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7793. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7794. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7795. this.registerType('torch.utils.data.dataset.Subset', class {});
  7796. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7797. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7798. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7799. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7800. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7801. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7802. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7803. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7804. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7805. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7806. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7807. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7808. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7809. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7810. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7811. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7812. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7813. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7814. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7815. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7816. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7817. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7818. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7819. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7820. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7821. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7822. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7823. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7824. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7825. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7826. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7827. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7828. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7829. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7830. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7831. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7832. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7833. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7834. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7835. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7836. this.registerType('torch._C._LegacyVariableBase', class {});
  7837. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7838. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7839. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7840. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7841. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7842. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7843. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7844. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7845. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7846. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7847. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7848. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7849. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7850. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7851. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7852. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7853. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7854. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7855. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7856. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7857. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7858. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7859. this.registerType('torch.distributions.beta.Beta', class {});
  7860. this.registerType('torch.distributions.binomial.Binomial', class {});
  7861. this.registerType('torch.distributions.categorical.Categorical', class {});
  7862. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7863. this.registerType('torch.distributions.constraints._Interval', class {});
  7864. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7865. this.registerType('torch.distributions.constraints._Real', class {});
  7866. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7867. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7868. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7869. this.registerType('torch.distributions.normal.Normal', class {});
  7870. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7871. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7872. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7873. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7874. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7875. this.registerType('torch.distributions.uniform.Uniform', class {});
  7876. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7877. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7878. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7879. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7880. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7881. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7882. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7883. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7884. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7885. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7886. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7887. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7888. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7889. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7890. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7891. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7892. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7893. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7894. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7895. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7896. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7897. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7898. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7899. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7900. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7901. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7902. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7903. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7904. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7905. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7906. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7907. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7908. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7913. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7915. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7916. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7917. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7918. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7920. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7921. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7922. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7923. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7924. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7925. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7926. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7927. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7928. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7929. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7930. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7931. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7932. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7933. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7934. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7935. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7936. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7937. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7938. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7939. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7940. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7941. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7942. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7943. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7944. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7945. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7946. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7947. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7948. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7949. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7950. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7951. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7952. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7953. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7954. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7955. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7956. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7957. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7958. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7959. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7960. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7961. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7962. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7963. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7964. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7965. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7966. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7967. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7968. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7969. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7970. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7971. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7972. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7973. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7974. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7975. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7976. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7977. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7978. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7979. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7980. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7981. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7982. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7983. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7984. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7985. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7986. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7987. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  7988. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7989. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  7990. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  7991. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  7992. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  7993. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  7994. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  7995. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  7996. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  7997. this.registerType('torch.nn.modules.module.PatchForward', class {});
  7998. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  7999. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  8000. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  8001. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  8002. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  8003. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  8004. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8005. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8006. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8007. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  8008. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8009. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8010. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8011. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  8012. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  8013. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  8014. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  8015. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  8016. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  8017. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  8018. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  8019. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  8020. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  8021. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8022. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8023. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8024. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  8025. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  8026. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  8027. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  8028. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8029. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8030. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8031. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8032. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8033. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8034. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8035. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8036. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8037. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8038. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8039. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8040. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8041. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8042. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8043. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8044. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8045. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8046. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8047. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8048. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8049. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8050. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8051. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8052. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8053. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8054. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8055. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8056. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8057. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8058. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8059. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8060. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8061. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8062. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8063. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8064. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8065. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8066. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8067. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8068. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8069. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8070. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8071. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8072. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8073. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8074. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8075. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8076. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8077. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8078. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8079. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8080. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8081. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8082. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8083. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8084. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8085. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8086. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8087. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8088. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8089. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8090. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8091. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8092. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8093. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8094. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8095. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8096. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8097. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8098. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8099. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8100. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8101. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8102. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8103. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8104. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8105. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8106. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8107. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8108. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8109. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8110. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8111. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8112. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8113. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8114. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8115. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8116. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8117. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8118. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8119. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8120. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8121. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8122. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8123. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8124. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8125. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8126. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8127. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8128. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8129. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8130. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8131. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8132. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8133. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8134. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8135. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8136. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8137. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8138. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8139. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8140. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8141. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8142. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8143. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8144. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8145. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8146. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8147. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8148. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8149. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8150. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8151. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8152. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8153. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8154. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8155. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8156. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8157. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8158. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8159. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8160. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8161. this.registerType('torch.optim.adamw.AdamW', class {});
  8162. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8163. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8164. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8165. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8166. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8167. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8168. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8169. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8170. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8171. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8172. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8173. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8174. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8175. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8176. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8177. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8178. this.registerType('torch.optim.sgd.SGD', class {});
  8179. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8180. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8181. torch.optim.RAdam = torch.optim.radam.RAdam;
  8182. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8183. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8184. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8185. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8186. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8187. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8188. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8189. this.registerFunction('torch.quantization.observer._with_args');
  8190. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8191. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8192. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8193. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8194. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8195. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8196. __enter__() {
  8197. return this;
  8198. }
  8199. __exit__(/* exc_type, exc_value, traceback */) {
  8200. }
  8201. });
  8202. this.registerFunction('torch.utils._pytree.tree_map');
  8203. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8204. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8205. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8206. this._expr = expr;
  8207. this.shape_env = shape_env;
  8208. this.pytype = pytype;
  8209. this._optimized_summation = optimized_summation;
  8210. this._hint = hint;
  8211. this.constant = constant;
  8212. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8213. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8214. }
  8215. __str__() {
  8216. return this._expr.__str__();
  8217. }
  8218. });
  8219. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8220. constructor() {
  8221. this.var_to_val = new Map();
  8222. this.var_to_stack = new Map();
  8223. }
  8224. add_var_to_val(expr, val) {
  8225. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8226. }
  8227. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8228. }
  8229. create_symintnode(sym, hint, source) {
  8230. let out = null;
  8231. let fx_node = null;
  8232. if (this._translation_validation_enabled && source !== null) {
  8233. throw new python.Error('Not implemented.');
  8234. } else {
  8235. fx_node = null;
  8236. }
  8237. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8238. out = builtins.int(sym);
  8239. if (hint !== null && out !== hint) {
  8240. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8241. }
  8242. } else {
  8243. // if free_unbacked_symbols(sym):
  8244. // hint = None
  8245. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8246. }
  8247. return out;
  8248. }
  8249. create_symboolnode(sym) {
  8250. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8251. }
  8252. });
  8253. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8254. /*
  8255. assert isinstance(sym, sympy.Symbol)
  8256. const name_str = sym.name.toLowerCase();
  8257. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8258. return name_str.startsWith(prefix_str[prefix])
  8259. }
  8260. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8261. */
  8262. return false;
  8263. });
  8264. this.registerType('torch.fx.proxy.TracerBase', class {
  8265. constructor() {
  8266. this.traced_func_name = 'forward';
  8267. }
  8268. });
  8269. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8270. trace(root /*, concrete_args */) {
  8271. let fn = null;
  8272. if (root instanceof torch.nn.Module) {
  8273. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8274. this.root = root;
  8275. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8276. this.root_module_name = root._get_name();
  8277. this.submodule_paths = new builtins.dict(root.named_modules());
  8278. } else {
  8279. this.root = new torch.nn.Module();
  8280. fn = root;
  8281. }
  8282. const tracer_cls = builtins.getattr(this, '__class__', null);
  8283. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8284. if (builtins.hasattr(this, '__code__')) {
  8285. const code = fn.__code__;
  8286. this.graph._co_fields = {
  8287. co_name: code.co_name,
  8288. co_filename: code.co_filename,
  8289. co_firstlineno: code.co_firstlineno,
  8290. };
  8291. }
  8292. return this.graph;
  8293. }
  8294. is_leaf_module(m /*, module_qualified_name */) {
  8295. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8296. }
  8297. });
  8298. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8299. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8300. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8301. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8302. return new graph_module_cls(...args);
  8303. });
  8304. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8305. let tracer_cls = body.get('_tracer_cls');
  8306. if (!tracer_cls) {
  8307. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8308. }
  8309. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8310. const cls_tracer = tracer_cls;
  8311. const KeepModules = class extends cls_tracer {
  8312. is_leaf_module() {
  8313. return true;
  8314. }
  8315. };
  8316. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8317. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8318. const graph = new KeepModules().trace(com, tracer_extras);
  8319. graph._tracer_cls = tracer_cls;
  8320. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8321. for (const [k, v] of body.items()) {
  8322. if (!builtins.hasattr(gm, k)) {
  8323. builtins.setattr(gm, k, v);
  8324. }
  8325. }
  8326. return gm;
  8327. });
  8328. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8329. globals = { ...globals };
  8330. const context = new python.Execution.Context(globals, null);
  8331. execution.exec(src, context);
  8332. const forward_fn = globals.forward;
  8333. delete globals.forward;
  8334. return forward_fn;
  8335. });
  8336. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8337. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8338. let fn_src = null;
  8339. if (body.has('_code')) {
  8340. fn_src = body.get('_code');
  8341. } else if (body.has('code')) {
  8342. fn_src = body.get('code');
  8343. } else {
  8344. fn_src = body._code || body.code;
  8345. }
  8346. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8347. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8348. });
  8349. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8350. const forward = importer.import_module(generated_module_name).forward;
  8351. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8352. });
  8353. this.registerType('torch.fx.graph.CodeGen', class {});
  8354. this.registerType('torch.fx.graph._Namespace', class {
  8355. constructor() {
  8356. this._obj_to_name = new Map();
  8357. this._unassociated_names = new Set();
  8358. this._used_names = new Set();
  8359. this._base_count = {};
  8360. }
  8361. create_name(candidate, obj) {
  8362. if (obj && this._obj_to_name.has(obj)) {
  8363. return self._obj_to_name.get(obj);
  8364. }
  8365. candidate = candidate || '_unnamed';
  8366. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8367. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8368. const match = candidate.match(/(.*)_(\d+)$"/);
  8369. let base = candidate;
  8370. let num = null;
  8371. if (match) {
  8372. [, base] = match;
  8373. num = parseInt(match[2], 10);
  8374. }
  8375. candidate = num ? `${base}_${num}` : base;
  8376. if (!num) {
  8377. num = this._base_count[base] || 0;
  8378. }
  8379. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8380. num += 1;
  8381. candidate = `${base}_${num}`;
  8382. }
  8383. this._used_names.add(candidate);
  8384. this._base_count[base] = num;
  8385. if (obj) {
  8386. this._obj_to_name[obj] = candidate;
  8387. } else {
  8388. this._unassociated_names.add(candidate);
  8389. }
  8390. return candidate;
  8391. }
  8392. _is_illegal_name(/* name, obj */) {
  8393. /*
  8394. if name in keyword.kwlist:
  8395. return True
  8396. if name in builtins.__dict__:
  8397. return obj is not builtins.__dict__[name]
  8398. if name in _custom_builtins:
  8399. return obj is not _custom_builtins[name].obj
  8400. */
  8401. return false;
  8402. }
  8403. associate_name_with_obj() {
  8404. }
  8405. });
  8406. this.registerType('torch.fx.node.Node', class {
  8407. constructor(graph, name, op, target, args, kwargs, return_type) {
  8408. this.graph = graph;
  8409. this.name = name;
  8410. this.op = op;
  8411. this.target = target;
  8412. this._input_nodes = new builtins.dict();
  8413. this.__update_args_kwargs(args, kwargs);
  8414. this.users = new builtins.dict();
  8415. this.type = return_type;
  8416. this._prev = this;
  8417. this._next = this;
  8418. this._erased = false;
  8419. this._repr_fn = null;
  8420. this.meta = new builtins.dict();
  8421. }
  8422. get args() {
  8423. return this._args;
  8424. }
  8425. get kwargs() {
  8426. return this._kwargs;
  8427. }
  8428. get next() {
  8429. return this._next;
  8430. }
  8431. prepend(x) {
  8432. x._remove_from_list();
  8433. const p = this._prev;
  8434. [p._next, x._prev] = [x, p];
  8435. [x._next, this._prev] = [this, x];
  8436. }
  8437. _remove_from_list() {
  8438. const [p, n] = [this._prev, this._next];
  8439. [p._next, n._prev] = [n, p];
  8440. }
  8441. __update_args_kwargs(new_args, new_kwargs) {
  8442. const update_users_and_input_nodes = (n) => {
  8443. if (n instanceof torch.fx.node.Node) {
  8444. this._input_nodes.setdefault(n);
  8445. n.users.setdefault(this);
  8446. }
  8447. return n;
  8448. };
  8449. const map_aggregate = (a, fn) => {
  8450. if (a instanceof builtins.tuple) {
  8451. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8452. if (!builtins.hasattr(a, '_fields')) {
  8453. return t;
  8454. }
  8455. throw new python.Error('Not implemented.');
  8456. // return type(a)(*t);
  8457. } else if (Array.isArray(a)) {
  8458. return a.map((elem) => map_aggregate(elem, fn));
  8459. } else if (a instanceof builtins.dict) {
  8460. const rv = new builtins.dict();
  8461. for (const [k, v] of a) {
  8462. rv.__setitem__(k, map_aggregate(v, fn));
  8463. }
  8464. return rv;
  8465. } else if (a instanceof builtins.slice) {
  8466. throw new python.Error('Not implemented.');
  8467. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8468. }
  8469. return fn(a);
  8470. };
  8471. for (const old_use of this._input_nodes.keys()) {
  8472. old_use.users.pop(this);
  8473. }
  8474. // object.__setattr__(self, "_input_nodes", {})
  8475. this._input_nodes = new builtins.dict();
  8476. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8477. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8478. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8479. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8480. }
  8481. });
  8482. torch.fx.Node = torch.fx.node.Node;
  8483. torch.fx.graph.Node = torch.fx.node.Node;
  8484. this.registerType('torch.fx.graph.Graph', class {
  8485. constructor(owning_module, tracer_cls, tracer_extras) {
  8486. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8487. this._used_names = new Map();
  8488. this._len = 0;
  8489. this._graph_namespace = new torch.fx.graph._Namespace();
  8490. this._owning_module = owning_module;
  8491. this._tracer_cls = tracer_cls;
  8492. this._tracer_extras = tracer_extras;
  8493. // this._codegen = CodeGen()
  8494. // this._co_fields = {}
  8495. }
  8496. get nodes() {
  8497. const array = new Array(this._len);
  8498. let node = this._root.next;
  8499. for (let i = 0; node !== this._root; i++) {
  8500. array[i] = node;
  8501. node = node.next;
  8502. }
  8503. return array;
  8504. }
  8505. placeholder(name, type_expr /*, default_value */) {
  8506. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8507. const kwargs = new builtins.dict();
  8508. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8509. }
  8510. create_node(op, target, args, kwargs, name, type_expr) {
  8511. args = args || new builtins.tuple();
  8512. kwargs = kwargs || new builtins.dict();
  8513. const candidate = name || this._target_to_str(target);
  8514. name = this._graph_namespace.create_name(candidate, null);
  8515. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8516. this._graph_namespace.associate_name_with_obj(name, n);
  8517. this._insert(n);
  8518. this._len += 1;
  8519. return n;
  8520. }
  8521. _insert(n) {
  8522. this._root.prepend(n);
  8523. }
  8524. output(result, type_expr) {
  8525. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8526. }
  8527. _target_to_str(target) {
  8528. if (typeof target === 'string') {
  8529. if (target.startsWith('__') && target.endsWith('__')) {
  8530. target = target.substring(2, target.length - 2);
  8531. }
  8532. } else {
  8533. target = target.__name__;
  8534. }
  8535. return this._snake_case(target);
  8536. }
  8537. _snake_case(s) {
  8538. const chars = [];
  8539. let prev_lower = false;
  8540. for (const c of s) {
  8541. const x = c.toLowerCase();
  8542. if (prev_lower && x !== c) {
  8543. chars.push('_');
  8544. } else {
  8545. prev_lower = true;
  8546. }
  8547. chars.push(x);
  8548. }
  8549. return chars.join('');
  8550. }
  8551. });
  8552. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8553. constructor(body) {
  8554. super();
  8555. for (const [k, v] of body.items()) {
  8556. builtins.setattr(this, k, v);
  8557. }
  8558. }
  8559. });
  8560. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8561. const parts = target.split('.');
  8562. const field = parts.pop();
  8563. for (const item of parts) {
  8564. const f = builtins.getattr(from_module, item);
  8565. let t = builtins.getattr(to_module, item, null);
  8566. if (f === t) {
  8567. return;
  8568. }
  8569. if (t === null) {
  8570. t = new torch.nn.modules.module.Module();
  8571. builtins.setattr(to_module, item, t);
  8572. }
  8573. from_module = f;
  8574. to_module = t;
  8575. }
  8576. const orig = builtins.getattr(from_module, field);
  8577. builtins.setattr(to_module, field, orig);
  8578. });
  8579. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8580. constructor(root, graph, class_name) {
  8581. super();
  8582. this.__class__.__name__ = class_name || 'GraphModule';
  8583. this.graph = graph;
  8584. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8585. for (const node of graph.nodes) {
  8586. if (node.op === 'get_attr' || node.op === 'call_module') {
  8587. torch.fx.graph_module._copy_attr(root, this, node.target);
  8588. }
  8589. }
  8590. }
  8591. }
  8592. });
  8593. torch.fx.Graph = torch.fx.graph.Graph;
  8594. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8595. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8596. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8597. return fn_or_name;
  8598. });
  8599. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8600. this.registerFunction('torchvision.datasets.folder.default_loader');
  8601. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8602. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8603. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8604. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8605. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8606. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8607. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8608. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8609. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8610. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8611. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8612. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8613. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8614. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8615. this.registerType('torchvision.ops.misc.Permute', class {});
  8616. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8617. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8618. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8619. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8620. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8621. this.registerType('torchvision.models._api.Weights', class {});
  8622. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8623. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8624. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8625. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8626. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8627. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8628. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8629. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8630. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8631. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8632. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8633. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8634. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8635. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8636. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8637. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8638. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8639. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8640. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8641. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8642. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8643. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8644. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8645. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8646. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8647. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8648. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8649. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8650. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8651. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8652. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8653. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8654. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8655. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8656. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8657. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8658. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8659. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8660. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8661. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8662. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8663. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8664. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8665. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8666. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8667. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8668. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8669. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8670. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8671. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8672. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8673. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8674. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8675. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8676. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8677. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8678. this.registerType('torchvision.models.googlenet.Inception', class {});
  8679. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8680. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8681. this.registerType('torchvision.models.inception.Inception3', class {});
  8682. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8683. this.registerType('torchvision.models.inception.InceptionA', class {});
  8684. this.registerType('torchvision.models.inception.InceptionB', class {});
  8685. this.registerType('torchvision.models.inception.InceptionC', class {});
  8686. this.registerType('torchvision.models.inception.InceptionD', class {});
  8687. this.registerType('torchvision.models.inception.InceptionE', class {});
  8688. this.registerFunction('torchvision.models.inception.inception_v3');
  8689. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8690. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8691. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8692. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8693. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8694. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8695. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8696. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8697. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8698. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8699. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8700. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8701. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8702. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8703. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8704. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8705. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8706. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8707. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8708. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8709. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8710. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8711. this.registerType('torchvision.models.regnet.RegNet', class {});
  8712. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8713. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8714. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8715. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8716. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8717. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8718. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8719. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8720. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8721. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8722. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8723. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8724. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8725. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8726. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8727. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8728. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8729. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8730. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8731. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8732. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8733. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8734. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8735. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8736. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8737. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8738. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8739. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8740. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8741. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8742. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8743. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8744. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8745. this.registerType('torchvision.models.resnet.ResNet', class {});
  8746. this.registerType('torchvision.models.vgg.VGG', class {});
  8747. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8748. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8749. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8750. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8751. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8752. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8753. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8754. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8755. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8756. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8757. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8758. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8759. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8760. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8761. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8762. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8763. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8764. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8765. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8766. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8767. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8768. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8769. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8770. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8771. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8772. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8773. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8774. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8775. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8776. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8777. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8778. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8779. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8780. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8781. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8782. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8783. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8784. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8785. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8786. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8787. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8788. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8789. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8790. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8791. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8792. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8793. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8794. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8795. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8796. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8797. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8798. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8799. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8800. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8801. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8802. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8803. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8804. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8805. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8806. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8807. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8808. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8809. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8810. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8811. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8812. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8813. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8814. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8815. this.registerFunction('torchvision.ops.boxes.box_iou');
  8816. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8817. this.registerFunction('builtins.annotate', (type, value) => {
  8818. if (type === builtins.int) {
  8819. return Number.isInteger(value) ? value : NaN;
  8820. }
  8821. if (type === builtins.float) {
  8822. return typeof value === 'number' ? value : NaN;
  8823. }
  8824. if (type === builtins.number) {
  8825. // if (pytorch.Utility.isTensor(value)) {
  8826. // value.resize_([]);
  8827. // }
  8828. }
  8829. return value;
  8830. });
  8831. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8832. return undefined;
  8833. });
  8834. this.registerFunction('builtins.range', (start, stop, step) => {
  8835. if (stop === undefined && step === undefined) {
  8836. if (Number.isInteger(start)) {
  8837. return Array(start).keys();
  8838. }
  8839. if (isNaN(start)) {
  8840. return [];
  8841. }
  8842. }
  8843. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8844. });
  8845. this.registerFunction('math.trunc');
  8846. builtins.xrange = builtins.range;
  8847. this.registerFunction('torch._C._nn.gelu');
  8848. this.registerFunction('torch._C._nn.avg_pool2d');
  8849. this.registerFunction('torch._C._nn.avg_pool3d');
  8850. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8851. this.registerFunction('torch._C._nn.softplus');
  8852. this.registerFunction('torch._native_multi_head_attention');
  8853. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8854. if (layout === torch.sparse_coo) {
  8855. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8856. }
  8857. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8858. });
  8859. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8860. return device;
  8861. });
  8862. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8863. device = torch._utils._get_restore_location(device);
  8864. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8865. });
  8866. this.registerFunction('torch.from_numpy', (obj) => {
  8867. const dtypes = new Map([
  8868. ['<f2', torch.float16],
  8869. ['<f4', torch.float32],
  8870. ['<f8', torch.float64],
  8871. ['<i2', torch.int16],
  8872. ['<i4', torch.int32],
  8873. ['<i8', torch.int64],
  8874. ]);
  8875. if (!dtypes.has(obj.dtype.str)) {
  8876. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8877. }
  8878. const dtype = dtypes.get(obj.dtype.str);
  8879. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8880. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8881. storage._set_cdata(obj.data);
  8882. const tensor = new torch.Tensor();
  8883. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8884. return tensor;
  8885. });
  8886. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8887. const tensor = torch.from_numpy(data);
  8888. // tensor = tensor.to(dtype, device)
  8889. tensor.requires_grad = requires_grad;
  8890. return tensor;
  8891. });
  8892. this.registerFunction('torch._utils._rebuild_device_tensor_from_cpu_tensor', (data, dtype, device, requires_grad) => {
  8893. data = data.clone();
  8894. data.requires_grad = requires_grad;
  8895. return data;
  8896. });
  8897. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  8898. const tensor = self.invoke('torch.Tensor', []);
  8899. tensor._layout = torch.sparse_coo;
  8900. tensor._indices = indices;
  8901. tensor._values = values;
  8902. tensor._shape = size;
  8903. return tensor;
  8904. });
  8905. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  8906. torch._C._set_tensor_metadata(tensor, metadata);
  8907. });
  8908. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  8909. return tensor;
  8910. });
  8911. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  8912. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  8913. });
  8914. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  8915. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  8916. const [, storage_type, , ,size] = storage;
  8917. storage = new storage_type(size);
  8918. }
  8919. const tensor = new torch.Tensor();
  8920. tensor.__setstate__([storage, storage_offset, size, stride]);
  8921. return tensor;
  8922. });
  8923. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  8924. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  8925. tensor.requires_grad = requires_grad;
  8926. if (metadata) {
  8927. torch._utils.set_tensor_metadata(tensor, metadata);
  8928. }
  8929. tensor.backward_hooks = backward_hooks;
  8930. return tensor;
  8931. });
  8932. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  8933. const t = new torch.Tensor(null, null, dtype);
  8934. t.set_(storage, storage_offset, size, stride);
  8935. if (metadata) {
  8936. torch._utils.set_tensor_metadata(t, metadata);
  8937. }
  8938. t._backward_hooks = backward_hooks;
  8939. return torch._utils._restore_device_fake_mode(t);
  8940. });
  8941. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  8942. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8943. param.backward_hooks = backward_hooks;
  8944. return param;
  8945. });
  8946. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  8947. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8948. param.backward_hooks = backward_hooks;
  8949. torch._utils._set_obj_state(param, state);
  8950. return param;
  8951. });
  8952. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  8953. const _set_obj_state = (obj, state) => {
  8954. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  8955. if (dict_state) {
  8956. for (const [k, v] of Object.entries(dict_state)) {
  8957. builtins.setattr(obj, k, v);
  8958. }
  8959. }
  8960. if (slots_state) {
  8961. for (const [k, v] of Object.entries(slots_state)) {
  8962. builtins.setattr(obj, k, v);
  8963. }
  8964. }
  8965. };
  8966. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8967. param._backward_hooks = backward_hooks;
  8968. _set_obj_state(param, state);
  8969. return param;
  8970. });
  8971. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  8972. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  8973. tensor.quantizer_params = quantizer_params;
  8974. return tensor;
  8975. });
  8976. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  8977. let dict_state = state;
  8978. let slots_state = null;
  8979. if (state instanceof self.builtins.tuple) {
  8980. if (state.length !== 2) {
  8981. throw new python.Error(`Invalid serialized state: '${state}'.`);
  8982. }
  8983. [dict_state, slots_state] = state;
  8984. }
  8985. if (dict_state) {
  8986. for (const [name, value] of Object.entries(dict_state)) {
  8987. builtins.setattr(obj, name, value);
  8988. }
  8989. }
  8990. if (slots_state) {
  8991. for (const [name, value] of Object.entries(slots_state)) {
  8992. builtins.setattr(obj, name, value);
  8993. }
  8994. }
  8995. return obj;
  8996. });
  8997. this.registerFunction('torch._set_item', (dict, key, value) => {
  8998. dict[key] = value;
  8999. });
  9000. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  9001. let ret = func(...args);
  9002. if (ret.__class__ !== new_type) {
  9003. // ret = ret.as_subclass(new_type);
  9004. }
  9005. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  9006. if (setstate === torch.Tensor.__setstate__) {
  9007. ret = torch._utils._set_obj_state(ret, state);
  9008. } else {
  9009. ret.__setstate__(state);
  9010. }
  9011. return ret;
  9012. });
  9013. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  9014. if (step === 0) {
  9015. throw new python.Error('range() arg 3 must not be zero');
  9016. }
  9017. if (step > 0 && lo < hi) {
  9018. return 1 + (hi - 1 - lo) / step;
  9019. } else if (step < 0 && lo > hi) {
  9020. return 1 + (lo - 1 - hi) / (0 - step);
  9021. }
  9022. return 0;
  9023. });
  9024. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  9025. this.registerOperator('aten::_unwrap_optional', (value) => {
  9026. return value;
  9027. });
  9028. this.registerFunction('torch.get_default_dtype', () => {
  9029. torch._default_type = torch._default_type || torch.float32;
  9030. return torch._default_type;
  9031. });
  9032. this.registerFunction('torch.set_default_dtype', (value) => {
  9033. torch._default_type = value;
  9034. });
  9035. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9036. return value || torch.get_default_dtype();
  9037. });
  9038. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9039. const shape = size;
  9040. dtype = torch._prims_common.dtype_or_default(dtype);
  9041. let storage = null;
  9042. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9043. const size = shape.reduce((a, b) => a * b, 1);
  9044. storage = new torch.storage.TypedStorage(size, dtype);
  9045. }
  9046. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9047. tensor.__setstate__([storage, 0, shape, stride]);
  9048. return tensor;
  9049. });
  9050. this.registerFunction('torch.all', (input) => {
  9051. if (Array.isArray(input) && input.length === 0) {
  9052. return true;
  9053. }
  9054. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9055. });
  9056. this.registerFunction('torch.append', (list, value) => {
  9057. list.push(value);
  9058. return value;
  9059. });
  9060. this.registerFunction('torch.clear', (value) => {
  9061. if (value instanceof torch.Value) {
  9062. throw new python.Error('Invalid value.');
  9063. }
  9064. if (Object(value) === value) {
  9065. for (const key of Object.keys(value)) {
  9066. delete value[key];
  9067. }
  9068. }
  9069. });
  9070. this.registerFunction('torch.dict', (args) => {
  9071. const obj = {};
  9072. if (args) {
  9073. if (Array.isArray(args)) {
  9074. for (const [key, value] of args) {
  9075. obj[key] = value;
  9076. }
  9077. } else {
  9078. throw new python.Error("'torch.dict' arguments not supported.");
  9079. }
  9080. }
  9081. return obj;
  9082. });
  9083. this.registerOperator('aten::cosine_similarity', () => {
  9084. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9085. });
  9086. this.registerOperator('aten::extend', (list, value) => {
  9087. list.push(...value);
  9088. });
  9089. this.registerOperator('aten::insert', (list, index, value) => {
  9090. list.splice(index, 0, value);
  9091. return value;
  9092. });
  9093. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9094. return value.replace(oldvalue, newvalue);
  9095. });
  9096. this.registerOperator('aten::add', (a, b) => {
  9097. if ((typeof a === 'number' || a instanceof Number) && (typeof b === 'number' || b instanceof Number)) {
  9098. return a + b;
  9099. }
  9100. if (typeof a === 'number' && b instanceof builtins.complex) {
  9101. return new builtins.complex(a + b.real, b.imag);
  9102. }
  9103. if (a instanceof builtins.complex && typeof b === 'number') {
  9104. return new builtins.complex(a.real + b, a.imag);
  9105. }
  9106. if (a instanceof builtins.complex && b instanceof builtins.complex) {
  9107. return new builtins.complex(a.real + b.real, a.imag + b.imag);
  9108. }
  9109. if (Array.isArray(a) && Array.isArray(b)) {
  9110. return a.concat(b);
  9111. }
  9112. if (typeof a === 'string' && typeof b === 'string') {
  9113. return a + b;
  9114. }
  9115. throw new python.Error('Unsupported aten::add expression type.');
  9116. });
  9117. this.registerOperator('aten::log', (x) => {
  9118. if (typeof x === 'number' || x instanceof Number) {
  9119. return Math.log(x);
  9120. }
  9121. throw new python.Error('Unsupported aten::log expression type.');
  9122. });
  9123. this.registerOperator('aten::dim', (tensor) => {
  9124. if (tensor && tensor.size) {
  9125. const size = tensor.size();
  9126. if (size) {
  9127. return size.length;
  9128. }
  9129. }
  9130. return NaN;
  9131. });
  9132. this.registerOperator('aten::numel', (tensor) => {
  9133. if (tensor && tensor.size) {
  9134. const size = tensor.size();
  9135. if (size) {
  9136. return size.reduce((a, b) => a * b, 1);
  9137. }
  9138. }
  9139. return NaN;
  9140. });
  9141. this.registerOperator('aten::eq', (left, right) => {
  9142. if (typeof left === 'string' && typeof right === 'string') {
  9143. return left === right;
  9144. }
  9145. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9146. if (isNaN(left) && isNaN(right)) {
  9147. return true;
  9148. }
  9149. return left === right;
  9150. }
  9151. if (left === undefined || right === undefined) {
  9152. return true;
  9153. }
  9154. if (Array.isArray(left) && Array.isArray(right)) {
  9155. return left.length === right.length && left.every((item, index) => item === right[index]);
  9156. }
  9157. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9158. });
  9159. this.registerOperator('aten::floor', (value) => {
  9160. return Math.floor(value);
  9161. });
  9162. this.registerOperator('aten::ceil', (value) => {
  9163. return Math.ceil(value);
  9164. });
  9165. this.registerOperator('aten::floordiv', (left, right) => {
  9166. return Math.floor(left / right);
  9167. });
  9168. this.registerOperator('aten::format', (...args) => {
  9169. const list = args.shift().split(/({}D?)/);
  9170. return list.map((text) => {
  9171. if (text === '{}' || text === '{}D') {
  9172. const arg = args.shift();
  9173. if (Array.isArray(arg)) {
  9174. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9175. }
  9176. return arg ? arg.toString() : '?';
  9177. }
  9178. return text;
  9179. }).join('');
  9180. });
  9181. this.registerOperator('aten::strip', (self, chars) => {
  9182. chars = chars || '\\n\\t\\f\\v';
  9183. const regex = new RegExp(`[${chars}]`, 'g');
  9184. return self.replace(regex, '');
  9185. });
  9186. this.registerOperator('aten::gt', (left, right) => {
  9187. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9188. if (!isNaN(left) && !isNaN(right)) {
  9189. return left > right;
  9190. }
  9191. }
  9192. if (isNaN(left) && !isNaN(right)) {
  9193. return true;
  9194. }
  9195. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9196. });
  9197. this.registerOperator('aten::ge', (left, right) => {
  9198. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9199. if (!isNaN(left) && !isNaN(right)) {
  9200. return left > right;
  9201. }
  9202. }
  9203. if (isNaN(left) && !isNaN(right)) {
  9204. return true;
  9205. }
  9206. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9207. });
  9208. this.registerOperator('aten::is_floating_point', (tensor) => {
  9209. const type = tensor.dtype.scalar_type();
  9210. return (type === 5 || type === 6 || type === 7);
  9211. });
  9212. this.registerOperator('aten::is_grad_enabled', () => {
  9213. return false;
  9214. });
  9215. this.registerOperator('aten::is_autocast_enabled', () => {
  9216. return false;
  9217. });
  9218. this.registerOperator('aten::isfinite');
  9219. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9220. });
  9221. this.registerFunction('torch.serialization._get_layout', (name) => {
  9222. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9223. return value instanceof torch.layout ? value : null;
  9224. });
  9225. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9226. return torch.load(b);
  9227. });
  9228. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9229. return data;
  9230. });
  9231. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9232. return data;
  9233. });
  9234. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9235. return data;
  9236. });
  9237. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9238. return data;
  9239. });
  9240. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9241. return self.builtins.CONSTANTS[`c${data}`];
  9242. });
  9243. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9244. return value;
  9245. });
  9246. this.registerOperator('aten::keys', (dict) => {
  9247. return Object.keys(dict);
  9248. });
  9249. this.registerOperator('aten::len', (value) => {
  9250. if (Array.isArray(value)) {
  9251. return value.length;
  9252. }
  9253. if (value && value.shape && value.__len__) {
  9254. return value.__len__();
  9255. }
  9256. return NaN;
  9257. });
  9258. this.registerOperator('aten::le', (left, right) => {
  9259. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9260. if (isNaN(left) || isNaN(right)) {
  9261. return false;
  9262. }
  9263. return left <= right;
  9264. }
  9265. if (left === undefined || right === undefined) {
  9266. return true;
  9267. }
  9268. throw new python.Error("Unsupported 'torch.le' expression type.");
  9269. });
  9270. this.registerOperator('aten::list', (args) => {
  9271. return args;
  9272. });
  9273. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9274. return size;
  9275. });
  9276. this.registerType('torch.PyTorchFileReader', class {
  9277. constructor(entries) {
  9278. let prefix = 0;
  9279. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9280. for (let set = new Set(); set && paths.length > 0;) {
  9281. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9282. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9283. prefix += set ? set.keys().next().value.length + 1 : 0;
  9284. }
  9285. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9286. this._version = 0;
  9287. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  9288. if (stream) {
  9289. const decoder = new TextDecoder('utf-8');
  9290. const buffer = stream.peek();
  9291. const text = decoder.decode(buffer);
  9292. this._version = Number(text.split('\n').shift().trim());
  9293. }
  9294. }
  9295. has_record(name) {
  9296. return this._records.has(name);
  9297. }
  9298. get_record(name) {
  9299. return this._records.get(name);
  9300. }
  9301. get_all_records() {
  9302. return Array.from(this._records.keys());
  9303. }
  9304. version() {
  9305. return this._version;
  9306. }
  9307. });
  9308. this.registerFunction('torch.load', (f) => {
  9309. const legacy_load = (entries) => {
  9310. const deserialized_objects = {};
  9311. if (entries.has('storages')) {
  9312. const data = entries.get('storages');
  9313. const unpickler = new pickle.Unpickler(data);
  9314. const num_storages = unpickler.load();
  9315. for (let i = 0; i < num_storages; i++) {
  9316. const args = unpickler.load();
  9317. const [key, , storage_type] = args;
  9318. const obj = storage_type._new_with_file(unpickler);
  9319. deserialized_objects[key] = obj;
  9320. }
  9321. /*
  9322. let storage_views = unpickler.load();
  9323. for target_cdata, root_cdata, offset, size in storage_views:
  9324. root = deserialized_objects[root_cdata]
  9325. deserialized_objects[target_cdata] = root[offset:offset + size]
  9326. */
  9327. }
  9328. if (entries.has('tensors')) {
  9329. const data = entries.get('tensors');
  9330. const unpickler = new pickle.Unpickler(data);
  9331. const num_tensors = unpickler.load();
  9332. const int32 = (unpickler) => {
  9333. const buffer = unpickler.read(4);
  9334. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9335. };
  9336. const int64 = (unpickler) => {
  9337. const buffer = unpickler.read(8);
  9338. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9339. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9340. }
  9341. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9342. };
  9343. for (let i = 0; i < num_tensors; i++) {
  9344. const args = unpickler.load();
  9345. const [key, storage_id] = args;
  9346. const storage = deserialized_objects[storage_id];
  9347. const ndim = int32(unpickler);
  9348. unpickler.read(4);
  9349. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9350. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9351. const storage_offset = int64(unpickler);
  9352. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9353. deserialized_objects[key] = tensor;
  9354. }
  9355. }
  9356. const data = entries.get('pickle');
  9357. const unpickler = new pickle.Unpickler(data);
  9358. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9359. return unpickler.load();
  9360. };
  9361. const _legacy_load = () => {
  9362. const unpickler = new pickle.Unpickler(f);
  9363. unpickler.load(); // magic_number
  9364. const protocol_version = unpickler.load();
  9365. if (protocol_version !== 1001) {
  9366. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9367. }
  9368. const sys_info = unpickler.load();
  9369. if (sys_info.get('protocol_version') !== 1001) {
  9370. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9371. }
  9372. if (sys_info.get('little_endian') === false) {
  9373. throw new python.Error("Unsupported big-endian storage data.");
  9374. }
  9375. const module_source_map = new Map();
  9376. const deserialized_objects = new Map();
  9377. unpickler.persistent_load = (saved_id) => {
  9378. switch (saved_id[0]) {
  9379. case 'module': {
  9380. const [, module, ,source] = saved_id;
  9381. module_source_map.set(module, source);
  9382. return saved_id[1];
  9383. }
  9384. case 'storage': {
  9385. const [, storage_type, key, , size, view_metadata] = saved_id;
  9386. if (!deserialized_objects.has(key)) {
  9387. const obj = new storage_type(size);
  9388. deserialized_objects.set(key, obj);
  9389. }
  9390. if (view_metadata) {
  9391. const view_key = view_metadata.shift();
  9392. view_metadata.shift(); // view_offset
  9393. view_metadata.shift(); // view_size
  9394. if (!deserialized_objects.has(view_key)) {
  9395. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9396. deserialized_objects.set(view_key, view);
  9397. }
  9398. return deserialized_objects.get(view_key);
  9399. }
  9400. return deserialized_objects.get(key);
  9401. }
  9402. default: {
  9403. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9404. }
  9405. }
  9406. };
  9407. const obj = unpickler.load();
  9408. const deserialized_storage_keys = unpickler.load();
  9409. for (const deserialized_storage_key of deserialized_storage_keys) {
  9410. const storage = deserialized_objects.get(deserialized_storage_key);
  9411. storage._set_from_file(unpickler);
  9412. }
  9413. if (!obj) {
  9414. throw new python.Error('File format is not PyTorch.');
  9415. }
  9416. if (obj === 'None') {
  9417. throw new python.Error("File contains 'None' root object.");
  9418. }
  9419. return obj;
  9420. };
  9421. const _load = (entries) => {
  9422. if (f.has('constant.pkl')) {
  9423. throw python.Error("TorchScript 'torch.load' not supported.");
  9424. }
  9425. const loaded_storages = new Map();
  9426. const persistent_load = (saved_id) => {
  9427. switch (saved_id[0]) {
  9428. case 'storage': {
  9429. const [, storage_type, key, , numel] = saved_id;
  9430. if (!loaded_storages.has(key)) {
  9431. const storage = new storage_type(numel);
  9432. if (!storage._set_cdata) {
  9433. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9434. }
  9435. const name = `data/${key}`;
  9436. const stream = entries.get(name);
  9437. storage._set_cdata(stream);
  9438. loaded_storages.set(key, storage);
  9439. }
  9440. return loaded_storages.get(key);
  9441. }
  9442. default: {
  9443. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9444. }
  9445. }
  9446. };
  9447. const data_file = entries.get('data.pkl');
  9448. const unpickler = new pickle.Unpickler(data_file);
  9449. unpickler.persistent_load = persistent_load;
  9450. const result = unpickler.load();
  9451. return result;
  9452. };
  9453. if (f instanceof Map) {
  9454. const reader = new torch.PyTorchFileReader(f);
  9455. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9456. f = new Map(records);
  9457. if (f.has('pickle')) {
  9458. return legacy_load(f);
  9459. }
  9460. if (f.has('data.pkl')) {
  9461. return _load(f);
  9462. }
  9463. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9464. }
  9465. return _legacy_load(f);
  9466. });
  9467. this.registerOperator('prim::abs', (a) => {
  9468. if (typeof a === 'number' || a instanceof Number) {
  9469. return Math.abs(a);
  9470. }
  9471. if (a instanceof builtins.complex) {
  9472. return Math.hypot(a.real, a.imag);
  9473. }
  9474. throw new python.Error('Unsupported prim::abs expression type.');
  9475. });
  9476. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9477. return value;
  9478. });
  9479. this.registerOperator('prim::data', (tensor) => {
  9480. return tensor;
  9481. });
  9482. this.registerOperator('prim::device', (tensor) => {
  9483. return tensor.device;
  9484. });
  9485. this.registerOperator('prim::dtype', (tensor) => {
  9486. return tensor.dtype.scalar_type();
  9487. });
  9488. this.registerOperator('prim::is_quantized', (tensor) => {
  9489. return tensor.is_quantized;
  9490. });
  9491. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9492. return false;
  9493. });
  9494. this.registerOperator('prim::is_nested', (tensor) => {
  9495. return tensor.is_nested;
  9496. });
  9497. this.registerOperator('prim::is_sparse', (tensor) => {
  9498. return tensor.is_sparse;
  9499. });
  9500. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9501. return value;
  9502. });
  9503. this.registerOperator('prim::NumToTensor', (value) => {
  9504. const tensor = self.invoke('torch.Tensor', []);
  9505. tensor.value = value;
  9506. return tensor;
  9507. });
  9508. this.registerOperator('prim::min', (...args) => {
  9509. if (Array.isArray(args[0])) {
  9510. return Math.min.apply(null, args[0]);
  9511. }
  9512. return Math.min.apply(null, args);
  9513. });
  9514. this.registerOperator('prim::max', (...args) => {
  9515. if (Array.isArray(args[0])) {
  9516. return Math.max.apply(null, args[0]);
  9517. }
  9518. return Math.max.apply(null, args);
  9519. });
  9520. this.registerOperator('prim::shape', (tensor) => {
  9521. return tensor && tensor.size ? tensor.size() : undefined;
  9522. });
  9523. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9524. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9525. params.weight = weight;
  9526. params.bias = bias;
  9527. params.stride = stride;
  9528. params.padding = padding;
  9529. params.dilation = dilation;
  9530. params.groups = groups;
  9531. return params;
  9532. });
  9533. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9534. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9535. params.weight = weight;
  9536. params.bias = bias;
  9537. params.stride = stride;
  9538. params.padding = padding;
  9539. params.dilation = dilation;
  9540. params.groups = groups;
  9541. return params;
  9542. });
  9543. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9544. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9545. params.weight = weight;
  9546. params.bias = bias;
  9547. params.stride = stride;
  9548. params.padding = padding;
  9549. params.dilation = dilation;
  9550. params.groups = groups;
  9551. return params;
  9552. });
  9553. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9554. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9555. params.weight = weight;
  9556. params.bias = bias;
  9557. params.stride = stride;
  9558. params.padding = padding;
  9559. params.dilation = dilation;
  9560. params.groups = groups;
  9561. return params;
  9562. });
  9563. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9564. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9565. params.weight = weight;
  9566. params.bias = bias;
  9567. params.stride = stride;
  9568. params.padding = padding;
  9569. params.output_padding = output_padding;
  9570. params.dilation = dilation;
  9571. params.groups = groups;
  9572. return params;
  9573. });
  9574. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9575. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9576. params.weight = weight;
  9577. params.bias = bias;
  9578. params.stride = stride;
  9579. params.padding = padding;
  9580. params.output_padding = output_padding;
  9581. params.dilation = dilation;
  9582. params.groups = groups;
  9583. return params;
  9584. });
  9585. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9586. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9587. params.weight = weight;
  9588. params.bias = bias;
  9589. return params;
  9590. });
  9591. this.registerOperator('prim::RaiseException', (message) => {
  9592. throw new python.Error(message);
  9593. });
  9594. this.registerOperator('prim::TupleIndex', (t, i) => {
  9595. return t.elements()[i];
  9596. });
  9597. this.registerOperator('prim::TupleUnpack', (t) => {
  9598. return t.elements();
  9599. });
  9600. this.registerOperator('aten::is_scripting', () => {
  9601. return true;
  9602. });
  9603. this.registerOperator('aten::__and__', (left, right) => {
  9604. return left && right;
  9605. });
  9606. this.registerOperator('aten::__contains__', (dict, key) => {
  9607. return builtins.hasattr(dict, key);
  9608. });
  9609. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9610. return start + index * step;
  9611. });
  9612. this.registerOperator('aten::__is__', (left, right) => {
  9613. return left === right;
  9614. });
  9615. this.registerOperator('aten::__isnot__', (left, right) => {
  9616. return left !== right;
  9617. });
  9618. this.registerOperator('aten::__not__', (value) => {
  9619. if (Number.isInteger(value)) {
  9620. value = Boolean(value);
  9621. }
  9622. if (typeof value === 'boolean') {
  9623. return !value;
  9624. }
  9625. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9626. });
  9627. this.registerOperator('aten::log10', (value) => {
  9628. return Math.log10(value);
  9629. });
  9630. this.registerOperator('aten::device', (type, index) => {
  9631. return new torch.device(type, index);
  9632. });
  9633. this.registerOperator('aten::lt', (left, right) => {
  9634. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9635. return left < right;
  9636. }
  9637. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9638. });
  9639. this.registerOperator('aten::mul', (left, right) => {
  9640. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9641. return left * right;
  9642. }
  9643. if (isNaN(left) || isNaN(right)) {
  9644. return NaN;
  9645. }
  9646. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9647. return left.map((value) => value * right);
  9648. }
  9649. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9650. });
  9651. this.registerOperator('aten::div', (left, right) => {
  9652. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9653. return left / right;
  9654. }
  9655. if (isNaN(left) || isNaN(right)) {
  9656. return NaN;
  9657. }
  9658. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9659. });
  9660. this.registerFunction('torch.round', (value) => {
  9661. if (typeof value === 'number' || value instanceof Number) {
  9662. return Math.round(value);
  9663. }
  9664. if (isNaN(value)) {
  9665. return value;
  9666. }
  9667. throw new python.Error("Unsupported 'torch.round' expression type.");
  9668. });
  9669. this.registerOperator('aten::remainder', (left, right) => {
  9670. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9671. return left % right;
  9672. }
  9673. if (isNaN(left) || isNaN(right)) {
  9674. return NaN;
  9675. }
  9676. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9677. });
  9678. this.registerOperator('aten::ne', (left, right) => {
  9679. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9680. return left !== right;
  9681. }
  9682. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9683. if (isNaN(left) || isNaN(right)) {
  9684. return false;
  9685. }
  9686. return left !== right;
  9687. }
  9688. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9689. return false;
  9690. }
  9691. if (typeof left === 'string' && typeof right === 'string') {
  9692. return left !== right;
  9693. }
  9694. if (left === undefined || right === undefined) {
  9695. return true;
  9696. }
  9697. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9698. });
  9699. this.registerOperator('aten::neg', (value) => {
  9700. if (typeof value === 'number') {
  9701. return -value;
  9702. }
  9703. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9704. });
  9705. this.registerOperator('aten::pow', (left, right) => {
  9706. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9707. return Math.pow(left, right);
  9708. }
  9709. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9710. });
  9711. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9712. return -1;
  9713. });
  9714. this.registerFunction('torch.t', (tensor) => {
  9715. return tensor;
  9716. });
  9717. this.registerOperator('aten::size', (tensor, dim) => {
  9718. if (tensor && tensor.size) {
  9719. const size = tensor.size();
  9720. if (Array.isArray(size)) {
  9721. if (dim === undefined) {
  9722. return size;
  9723. }
  9724. if (Number.isInteger(dim)) {
  9725. if (dim >= 0 && dim < size.length) {
  9726. return size[dim];
  9727. }
  9728. if (dim < 0 && -dim < size.length) {
  9729. return size[size.length + dim];
  9730. }
  9731. }
  9732. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9733. }
  9734. }
  9735. if (Number.isInteger(dim)) {
  9736. return NaN;
  9737. }
  9738. return [];
  9739. });
  9740. this.registerFunction('aten::sqrt', (x) => {
  9741. return Math.sqrt(x);
  9742. });
  9743. this.registerOperator('aten::slice', (l, start, end, step) => {
  9744. if (!Array.isArray(l)) {
  9745. throw new python.Error('Slicing expected array');
  9746. }
  9747. step = step || 1;
  9748. if (step !== 1) {
  9749. throw new python.Error('Slicing only supports step=1');
  9750. }
  9751. start = Math.max(0, start >= 0 ? start : l.length + start);
  9752. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9753. return l.slice(start, end);
  9754. });
  9755. this.registerOperator('aten::sub', (left, right) => {
  9756. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9757. return left - right;
  9758. }
  9759. if (typeof left === 'number' && right instanceof builtins.complex) {
  9760. return new builtins.complex(left - right.real, right.imag);
  9761. }
  9762. if (left instanceof builtins.complex && typeof right === 'number') {
  9763. return new builtins.complex(left.real - right, left.imag);
  9764. }
  9765. if (left instanceof builtins.complex && right instanceof builtins.complex) {
  9766. return new builtins.complex(left.real - right.real, left.imag - right.imag);
  9767. }
  9768. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9769. });
  9770. this.registerFunction('torch.sym_int');
  9771. this.registerFunction('torch.sym_float');
  9772. this.registerFunction('torch.sym_ite');
  9773. this.registerFunction('torch.sym_max');
  9774. this.registerFunction('torch.sym_min');
  9775. this.registerFunction('torch.sym_not');
  9776. this.registerFunction('torch.sym_sqrt');
  9777. this.registerFunction('torch.sym_sqrt');
  9778. this.registerFunction('torch.functional.einsum');
  9779. this.registerFunction('torch.functional.norm');
  9780. this.registerFunction('torch.functional.split');
  9781. this.registerFunction('torch.nn.init.constant_');
  9782. this.registerFunction('torch.nn.init.normal_');
  9783. this.registerFunction('torch.nn.init.xavier_uniform_');
  9784. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9785. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9786. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9787. this.registerFunction('torch.nn.functional.cross_entropy');
  9788. this.registerFunction('torch.nn.functional.elu');
  9789. this.registerFunction('torch.nn.functional.gelu');
  9790. this.registerFunction('torch.nn.functional.hardsigmoid');
  9791. this.registerFunction('torch.nn.functional.hardswish');
  9792. this.registerFunction('torch.nn.functional.hardtanh');
  9793. this.registerFunction('torch.nn.functional.interpolate');
  9794. this.registerFunction('torch.nn.functional.leaky_relu');
  9795. this.registerFunction('torch.nn.functional.l1_loss');
  9796. this.registerFunction('torch.nn.functional.linear');
  9797. this.registerFunction('torch.nn.functional.log_softmax');
  9798. this.registerFunction('torch.nn.functional._max_pool2d');
  9799. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9800. this.registerFunction('torch.nn.functional.mse_loss');
  9801. this.registerFunction('torch.nn.functional.pad');
  9802. this.registerFunction('torch.nn.functional.relu');
  9803. this.registerFunction('torch.nn.functional.relu6');
  9804. this.registerFunction('torch.nn.functional.sigmoid');
  9805. this.registerFunction('torch.nn.functional.silu');
  9806. this.registerFunction('torch.nn.functional.softmax');
  9807. this.registerFunction('torch.nn.functional.tanh');
  9808. this.registerFunction('torch.values', (dict) => {
  9809. return Object.values(dict);
  9810. });
  9811. this.registerFunction('torch.warn', () => {
  9812. });
  9813. this.registerType('torch._ops.OperatorBase', class {
  9814. constructor() {
  9815. this.functorch_table = {};
  9816. }
  9817. });
  9818. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9819. constructor(name, cacheable) {
  9820. super();
  9821. this._name = name;
  9822. this.__name__ = name;
  9823. this._ns = 'higher_order';
  9824. this.__module__ = 'torch.ops.higher_order';
  9825. this._cacheable = cacheable;
  9826. }
  9827. get namespace() {
  9828. return this._ns;
  9829. }
  9830. get name() {
  9831. return this._name;
  9832. }
  9833. });
  9834. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9835. constructor(name) {
  9836. super(name, false);
  9837. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9838. }
  9839. });
  9840. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9841. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9842. constructor(name) {
  9843. super(name, false);
  9844. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9845. }
  9846. });
  9847. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9848. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9849. constructor(name) {
  9850. super(name, false);
  9851. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9852. }
  9853. });
  9854. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  9855. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9856. constructor(name) {
  9857. super(name, false);
  9858. }
  9859. });
  9860. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  9861. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9862. constructor(name) {
  9863. super(name, false);
  9864. }
  9865. });
  9866. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  9867. this.registerType('torch.Type', class {
  9868. constructor(kind, annotation_str) {
  9869. this._kind = kind;
  9870. if (annotation_str) {
  9871. this._annotation_str = annotation_str;
  9872. }
  9873. }
  9874. static get(kind, annotation_str) {
  9875. torch.Type.cache = torch.Type.cache || new Map();
  9876. if (!annotation_str) {
  9877. if (!torch.Type.cache.has(kind)) {
  9878. torch.Type.cache.set(kind, new torch.Type(kind));
  9879. }
  9880. return torch.Type.cache.get(kind);
  9881. }
  9882. return new torch.Type(kind, annotation_str);
  9883. }
  9884. kind() {
  9885. return this._kind;
  9886. }
  9887. get annotation_str() {
  9888. return this._annotation_str;
  9889. }
  9890. equals(rhs) {
  9891. return this.kind() === rhs.kind();
  9892. }
  9893. isSubtypeOf(rhs) {
  9894. if (rhs.kind() === 'AnyType' || this === rhs) {
  9895. return true;
  9896. }
  9897. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  9898. return this.isSubtypeOf(rhs.getElementType());
  9899. }
  9900. if (rhs instanceof torch.UnionType) {
  9901. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  9902. }
  9903. if (rhs instanceof torch._C.DynamicType) {
  9904. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  9905. }
  9906. return this.equals(rhs);
  9907. }
  9908. containedTypes() {
  9909. return [];
  9910. }
  9911. containedType(i) {
  9912. return this.containedTypes()[i];
  9913. }
  9914. withContained(contained_types) {
  9915. const current_contained = this.containedTypes();
  9916. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  9917. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  9918. return this;
  9919. }
  9920. return this.createWithContained(contained_types);
  9921. }
  9922. createWithContained(/* createWithContained */) {
  9923. throw new python.Error('Not implemented.');
  9924. }
  9925. isUnionType() {
  9926. return false;
  9927. }
  9928. hasFreeVariables() {
  9929. return false;
  9930. }
  9931. is_module() {
  9932. return false;
  9933. }
  9934. expect(type) {
  9935. torch._C.AT_ASSERT(this instanceof type);
  9936. return this;
  9937. }
  9938. str() {
  9939. if (this instanceof torch._C.VarType && this._annotation_str) {
  9940. return this._annotation_str;
  9941. } else if (this._kind === 'ScalarTypeType') {
  9942. return 'ScalarType';
  9943. } else if (this._kind === 'QSchemeType') {
  9944. return 'QScheme';
  9945. } else if (this._kind) {
  9946. return this._kind;
  9947. }
  9948. throw new python.Error(`Not implemented '${this.kind()}'.`);
  9949. }
  9950. __str__() {
  9951. return this.str();
  9952. }
  9953. toString() {
  9954. return this.__str__();
  9955. }
  9956. });
  9957. this.registerType('torch.ClassType', class extends torch.Type {
  9958. constructor(qualified_name, cu, is_module) {
  9959. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  9960. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  9961. this._is_module = is_module;
  9962. this._attributes = [];
  9963. this._attributeTypes = [];
  9964. this._methods = [];
  9965. this._staticmethods = new Map();
  9966. this._forward_hooks = [];
  9967. this._forward_pre_hooks = [];
  9968. this._properties = [];
  9969. this._constants = new Map();
  9970. }
  9971. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  9972. return new torch.ClassType(qualifiedName, cu, is_module);
  9973. }
  9974. qualified_name() {
  9975. return this.annotation_str;
  9976. }
  9977. name() {
  9978. return this._name;
  9979. }
  9980. is_module() {
  9981. return this._is_module;
  9982. }
  9983. is_parameter(slot) {
  9984. return this._attributes[slot].is_parameter === true;
  9985. }
  9986. is_buffer(slot) {
  9987. return this._attributes[slot].is_buffer === true;
  9988. }
  9989. addMethod(method) {
  9990. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  9991. this._methods.push(method);
  9992. }
  9993. findMethod(name) {
  9994. for (const method of this._methods) {
  9995. if (name === method.name()) {
  9996. return method;
  9997. }
  9998. }
  9999. return null;
  10000. }
  10001. getMethod(name) {
  10002. const method = this.findMethod(name);
  10003. if (!method) {
  10004. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  10005. }
  10006. return method;
  10007. }
  10008. methods() {
  10009. return this._methods;
  10010. }
  10011. addStaticMethod(func) {
  10012. this._staticmethods.set(func.name, func);
  10013. }
  10014. findStaticMethod(name) {
  10015. return this._staticmethods.get(name);
  10016. }
  10017. findHook(name) {
  10018. let hook = this.findForwardHook(name);
  10019. if (hook === null) {
  10020. hook = this.findForwardPreHook(name);
  10021. }
  10022. return hook;
  10023. }
  10024. findForwardHook(name) {
  10025. for (const hook of this._forward_hooks) {
  10026. if (name === hook.name()) {
  10027. return hook;
  10028. }
  10029. }
  10030. return null;
  10031. }
  10032. findForwardPreHook(name) {
  10033. for (const pre_hook of this._forward_pre_hooks) {
  10034. if (name === pre_hook.name()) {
  10035. return pre_hook;
  10036. }
  10037. }
  10038. return null;
  10039. }
  10040. numAttributes() {
  10041. return this._attributes.length;
  10042. }
  10043. addAttribute(name, type, is_parameter, is_buffer) {
  10044. is_parameter = is_parameter || false;
  10045. is_buffer = is_buffer || false;
  10046. const slot = this._attributes.length;
  10047. this._attributes.push({ name, type, is_parameter, is_buffer });
  10048. this._attributeTypes.push(type);
  10049. return slot;
  10050. }
  10051. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  10052. is_parameter = is_parameter || false;
  10053. is_buffer = is_buffer || false;
  10054. const slot_idx = this.findAttributeSlot(name);
  10055. if (slot_idx === null) {
  10056. return this.addAttribute(name, ty, is_parameter, is_buffer);
  10057. }
  10058. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  10059. // const TypePtr& atype = getAttribute(*slot_idx);
  10060. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10061. return slot_idx;
  10062. }
  10063. findAttributeSlot(name) {
  10064. for (let pos = 0; pos < this._attributes.length; pos++) {
  10065. if (name === this._attributes[pos].name) {
  10066. return pos;
  10067. }
  10068. }
  10069. return null;
  10070. }
  10071. findAttribute(name) {
  10072. const slot = this.findAttributeSlot(name);
  10073. if (slot !== null) {
  10074. return this._attributes[slot].type;
  10075. }
  10076. return null;
  10077. }
  10078. hasAttribute(name) {
  10079. return this._attributes.find((attr) => attr.name === name);
  10080. }
  10081. getAttribute(arg) {
  10082. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10083. return this._attributes[slot].type;
  10084. }
  10085. getAttributeName(slot) {
  10086. return this._attributes[slot].name;
  10087. }
  10088. addConstant(name, value) {
  10089. this._constants.set(name, value);
  10090. }
  10091. hasConstant(name) {
  10092. return this._constants.has(name);
  10093. }
  10094. getProperty(name) {
  10095. for (const prop of this._properties) {
  10096. if (name === prop.name) {
  10097. return prop;
  10098. }
  10099. }
  10100. return null;
  10101. }
  10102. containedTypes() {
  10103. return this._attributeTypes;
  10104. }
  10105. createWithContained(contained_types) {
  10106. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10107. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10108. for (let i = 0; i < this._attributes.length; i++) {
  10109. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10110. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10111. }
  10112. for (const method of this.methods()) {
  10113. ptr.addMethod(method);
  10114. }
  10115. return ptr;
  10116. }
  10117. str() {
  10118. return this.qualified_name();
  10119. }
  10120. });
  10121. this.registerType('torch.EnumType', class extends torch.Type {
  10122. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10123. super('EnumType', qualified_class_name);
  10124. this._name = qualified_class_name;
  10125. this._value_type = value_type;
  10126. this._enum_names_values = enum_names_values;
  10127. this._cu = cu;
  10128. }
  10129. static create(qualified_class_name, value, enum_names_values, cu) {
  10130. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10131. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10132. }
  10133. torch._C.TORCH_CHECK(false);
  10134. return null;
  10135. }
  10136. name() {
  10137. return this._name;
  10138. }
  10139. get annotation_str() {
  10140. return this._name.qualifiedName();
  10141. }
  10142. enumNamesValues() {
  10143. return this._enum_names_values;
  10144. }
  10145. compilation_unit() {
  10146. return this._cu;
  10147. }
  10148. getValueType() {
  10149. return this._value_type;
  10150. }
  10151. equals(rhs) {
  10152. if (rhs instanceof torch.EnumType) {
  10153. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10154. }
  10155. return false;
  10156. }
  10157. isSubtypeOf(rhs) {
  10158. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10159. return true;
  10160. }
  10161. return super.isSubtypeOf(rhs);
  10162. }
  10163. });
  10164. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10165. if (args.length === 1) {
  10166. const [to_flatten] = args;
  10167. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10168. const to_fill = [];
  10169. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10170. to_flatten.splice(0, to_flatten.length);
  10171. to_flatten.push(...to_fill);
  10172. } else if (args.length === 2) {
  10173. const [reference, to_fill] = args;
  10174. for (const type of reference) {
  10175. torch._C.flattenUnion(type, to_fill);
  10176. }
  10177. torch._C.filterDuplicateSubtypes(to_fill);
  10178. torch._C.sortUnion(to_fill);
  10179. } else {
  10180. throw new python.Error('Not implemented.');
  10181. }
  10182. });
  10183. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10184. if (type instanceof torch.UnionType) {
  10185. for (const inner of type.containedTypes()) {
  10186. torch._C.flattenUnion(inner, to_fill);
  10187. }
  10188. } else if (type instanceof torch.OptionalType) {
  10189. const inner = type.getElementType();
  10190. torch._C.flattenUnion(inner, to_fill);
  10191. to_fill.push(torch.NoneType.get());
  10192. } else if (type instanceof torch.NumberType) {
  10193. to_fill.push(torch.IntType.get());
  10194. to_fill.push(torch.FloatType.get());
  10195. to_fill.push(torch.ComplexType.get());
  10196. } else {
  10197. to_fill.push(type);
  10198. }
  10199. });
  10200. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10201. if (types.length === 0) {
  10202. // return;
  10203. }
  10204. /*
  10205. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10206. // We don't want nested Optionals. Also, prematurely unifying to
  10207. // `Optional` could prevent us from coalescing other types
  10208. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10209. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10210. return null;
  10211. } else {
  10212. return unifyTypes(t1, t2, default_to_union=false);
  10213. }
  10214. };
  10215. size_t end_idx = types->size()-1;
  10216. for (size_t i = types->size()-1; i > 0; --i) {
  10217. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10218. std::optional<TypePtr> unified;
  10219. unified = get_supertype((*types)[i], (*types)[j]);
  10220. if (unified) {
  10221. (*types)[j] = *unified;
  10222. (*types)[i] = (*types)[end_idx];
  10223. --end_idx;
  10224. break;
  10225. }
  10226. if (j == 0) {
  10227. break;
  10228. }
  10229. }
  10230. }
  10231. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10232. */
  10233. });
  10234. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10235. /*
  10236. std::sort(types->begin(), types->end(),
  10237. [](const TypePtr& a, const TypePtr& b) -> bool {
  10238. if (a->kind() != b->kind()) {
  10239. return a->kind() < b->kind();
  10240. }
  10241. return a->str() < b->str();
  10242. });
  10243. */
  10244. });
  10245. this.registerType('torch.UnionType', class extends torch.Type {
  10246. constructor(reference, kind) {
  10247. super(kind || 'UnionType');
  10248. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10249. this._types = [];
  10250. torch._C.standardizeVectorForUnion(reference, this._types);
  10251. if (this._types.length === 1) {
  10252. throw new python.Error('Invalid union type reference.');
  10253. }
  10254. this._can_hold_none = false;
  10255. this._has_free_variables = false;
  10256. for (const type of this._types) {
  10257. if (type instanceof torch.NoneType) {
  10258. this._can_hold_none = true;
  10259. }
  10260. if (type.hasFreeVariables()) {
  10261. this._has_free_variables = true;
  10262. }
  10263. }
  10264. }
  10265. static create(reference) {
  10266. const union_type = new torch.UnionType(reference);
  10267. /*
  10268. bool int_found = false;
  10269. bool float_found = false;
  10270. bool complex_found = false;
  10271. bool nonetype_found = false;
  10272. const update_is_opt_flags = [&](const TypePtr& t) {
  10273. if (t == IntType::get()) {
  10274. int_found = true;
  10275. } else if (t == FloatType::get()) {
  10276. float_found = true;
  10277. } else if (t == ComplexType::get()) {
  10278. complex_found = true;
  10279. } else if (t == NoneType::get()) {
  10280. nonetype_found = true;
  10281. }
  10282. };
  10283. for (const auto& t : union_type->containedTypes()) {
  10284. update_is_opt_flags(t);
  10285. }
  10286. bool numbertype_found = int_found && float_found && complex_found;
  10287. if (nonetype_found) {
  10288. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10289. return OptionalType::create(NumberType::get());
  10290. }
  10291. if (union_type->containedTypes().size() == 2) {
  10292. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10293. ? union_type->containedTypes()[0]
  10294. : union_type->containedTypes()[1];
  10295. return OptionalType::create(not_none);
  10296. }
  10297. }
  10298. */
  10299. return union_type;
  10300. }
  10301. containedTypes() {
  10302. return this._types;
  10303. }
  10304. isUnionType() {
  10305. return true;
  10306. }
  10307. hasFreeVariables() {
  10308. return this._has_free_variables;
  10309. }
  10310. equals(rhs) {
  10311. if (rhs instanceof torch.UnionType) {
  10312. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10313. return false;
  10314. }
  10315. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10316. } else if (rhs instanceof torch.OptionalType) {
  10317. if (rhs.getElementType() === torch.NumberType.get()) {
  10318. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10319. }
  10320. const optional_lhs = this.toOptional();
  10321. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10322. } else if (rhs instanceof torch.NumberType) {
  10323. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10324. }
  10325. return false;
  10326. }
  10327. isSubtypeOf(rhs) {
  10328. const rhs_types = [];
  10329. if (rhs instanceof torch.UnionType) {
  10330. if (this.containedTypes() === rhs.containedTypes()) {
  10331. return true;
  10332. }
  10333. for (const typePtr of rhs.containedTypes()) {
  10334. rhs_types.push(typePtr);
  10335. }
  10336. } else if (rhs instanceof torch.OptionalType) {
  10337. rhs_types.push(torch.NoneType.get());
  10338. if (rhs.getElementType() === torch.NumberType.get()) {
  10339. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10340. rhs_types.push(...number_types);
  10341. } else {
  10342. rhs_types.push(rhs.getElementType());
  10343. }
  10344. } else if (rhs instanceof torch.NumberType) {
  10345. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10346. rhs_types.push(...number_types);
  10347. } else {
  10348. rhs_types.push(rhs);
  10349. }
  10350. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10351. }
  10352. });
  10353. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10354. constructor(contained) {
  10355. super([contained, torch.NoneType.get()], 'OptionalType');
  10356. let is_numbertype = false;
  10357. if (contained instanceof torch.UnionType) {
  10358. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10359. }
  10360. if (super.containedTypes().length === 2) {
  10361. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10362. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10363. this._contained = torch.NumberType.get();
  10364. this._types.splice(0, this._types.length);
  10365. this._types.push(torch.NumberType.get());
  10366. this._types.push(torch.NoneType.get());
  10367. } else {
  10368. const to_subtract = [torch.NoneType.get()];
  10369. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10370. this._contained = torch.UnionType.create([without_none]);
  10371. }
  10372. this._has_free_variables = contained.hasFreeVariables();
  10373. }
  10374. static create(elem) {
  10375. return new torch.OptionalType(elem);
  10376. }
  10377. getElementType() {
  10378. return this._contained;
  10379. }
  10380. equals(rhs) {
  10381. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10382. }
  10383. isSubtypeOf(rhs) {
  10384. if (rhs instanceof torch.OptionalType) {
  10385. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10386. } else if (rhs instanceof torch.UnionType) {
  10387. throw new python.Error('Not implemented.');
  10388. }
  10389. // return super.isSubtypeOf(rhs);
  10390. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10391. }
  10392. containedTypes() {
  10393. return [this._contained];
  10394. }
  10395. createWithContained(contained_types) {
  10396. torch._C.AT_ASSERT(contained_types.length === 1);
  10397. return torch.OptionalType.create(contained_types[0]);
  10398. }
  10399. subtractTypeSetFrom(to_subtract, from) {
  10400. const types = [];
  10401. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10402. for (const t of from) {
  10403. if (!should_subtract(t)) {
  10404. types.push(t);
  10405. }
  10406. }
  10407. if (types.length === 0) {
  10408. return null;
  10409. } else if (types.length === 1) {
  10410. return types[0];
  10411. }
  10412. return torch.UnionType.create(types);
  10413. }
  10414. str() {
  10415. return `${this.getElementType().str()}?`;
  10416. }
  10417. __str__() {
  10418. return `Optional[${this.getElementType().__str__()}]`;
  10419. }
  10420. });
  10421. this.registerType('torch.ListType', class extends torch.Type {
  10422. constructor(elem) {
  10423. super('ListType');
  10424. this._elem = elem;
  10425. }
  10426. static create(elem) {
  10427. return new torch.ListType(elem);
  10428. }
  10429. getElementType() {
  10430. return this._elem;
  10431. }
  10432. equals(rhs) {
  10433. if (rhs instanceof torch.ListType) {
  10434. return this.getElementType().equals(rhs.getElementType());
  10435. }
  10436. return false;
  10437. }
  10438. isSubtypeOf(rhs) {
  10439. if (super.isSubtypeOf(rhs)) {
  10440. return true;
  10441. }
  10442. if (rhs.kind() === 'AnyListType') {
  10443. return true;
  10444. }
  10445. return false;
  10446. }
  10447. containedTypes() {
  10448. return [this._elem];
  10449. }
  10450. createWithContained(contained_types) {
  10451. return new torch.ListType(contained_types[0]);
  10452. }
  10453. hasFreeVariables() {
  10454. return this.getElementType().hasFreeVariables();
  10455. }
  10456. str() {
  10457. return `${this.getElementType().str()}[]`;
  10458. }
  10459. __str__() {
  10460. return `List[${this.getElementType().__str__()}]`;
  10461. }
  10462. });
  10463. this.registerType('torch.FutureType', class extends torch.Type {
  10464. constructor(elem) {
  10465. super('FutureType');
  10466. this._elem = elem;
  10467. }
  10468. static create(elem) {
  10469. return new torch.FutureType(elem);
  10470. }
  10471. getElementType() {
  10472. return this._elem;
  10473. }
  10474. containedTypes() {
  10475. throw new python.Error('Not implemented.');
  10476. }
  10477. str() {
  10478. return `Future(${this.getElementType().str()})`;
  10479. }
  10480. __str__() {
  10481. return `Future[${this.getElementType().__str__()}]`;
  10482. }
  10483. });
  10484. this.registerType('torch.RRefType', class extends torch.Type {
  10485. constructor(elem) {
  10486. super('RRefType');
  10487. this._elem = elem;
  10488. }
  10489. static create(elem) {
  10490. return new torch.RRefType(elem);
  10491. }
  10492. getElementType() {
  10493. return this._elem;
  10494. }
  10495. containedTypes() {
  10496. throw new python.Error('Not implemented.');
  10497. }
  10498. str() {
  10499. return `RRef(${this.getElementType().str()})`;
  10500. }
  10501. __str__() {
  10502. return `RRef[${this.getElementType().__str__()}]`;
  10503. }
  10504. });
  10505. this.registerType('torch.AwaitType', class extends torch.Type {
  10506. constructor(elem) {
  10507. super('AwaitType');
  10508. this._elem = elem;
  10509. }
  10510. static get(elem) {
  10511. return new torch.AwaitType(elem);
  10512. }
  10513. getElementType() {
  10514. return this._elem;
  10515. }
  10516. containedTypes() {
  10517. throw new python.Error('Not implemented.');
  10518. }
  10519. str() {
  10520. return `Await(${this.getElementType().str()})`;
  10521. }
  10522. __str__() {
  10523. return `Await[${this.getElementType().__str__()}]`;
  10524. }
  10525. });
  10526. this.registerType('torch.TupleType', class extends torch.Type {
  10527. constructor(elements, annotation_str, schema) {
  10528. super('TupleType', annotation_str);
  10529. this._elements = elements;
  10530. this._has_free_variables = elements.some((v) => {
  10531. if (!v) {
  10532. throw new python.Error('Can not create tuple with None type');
  10533. }
  10534. return v.hasFreeVariables();
  10535. });
  10536. this._schema = schema;
  10537. }
  10538. static create(elements) {
  10539. return new torch.TupleType(elements, null, null);
  10540. }
  10541. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10542. const args = [];
  10543. for (let i = 0; i < field_names.length; i++) {
  10544. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10545. args.push(arg);
  10546. }
  10547. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10548. return new torch.TupleType(field_types, qualified_name, schema);
  10549. }
  10550. elements() {
  10551. return this._elements;
  10552. }
  10553. name() {
  10554. return this.annotation_str;
  10555. }
  10556. containedTypes() {
  10557. return this._elements;
  10558. }
  10559. createWithContained(createWithContained) {
  10560. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10561. }
  10562. hasFreeVariables() {
  10563. return this._has_free_variables;
  10564. }
  10565. schema() {
  10566. return this._schema;
  10567. }
  10568. str() {
  10569. if (this._schema) {
  10570. return `NamedTuple(...)`;
  10571. }
  10572. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10573. }
  10574. __str__() {
  10575. if (this.annotation_str) {
  10576. return this.annotation_str;
  10577. }
  10578. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10579. }
  10580. });
  10581. this.registerType('torch.AnyType', class extends torch.Type {
  10582. constructor() {
  10583. super('AnyType');
  10584. }
  10585. static get() {
  10586. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10587. return torch.AnyType.value;
  10588. }
  10589. str() {
  10590. return 'Any';
  10591. }
  10592. __str__() {
  10593. return 'Any';
  10594. }
  10595. });
  10596. this.registerType('torch.NoneType', class extends torch.Type {
  10597. constructor() {
  10598. super('NoneType');
  10599. }
  10600. static get() {
  10601. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10602. return torch.NoneType.value;
  10603. }
  10604. equals(rhs) {
  10605. return this.kind() === rhs.kind();
  10606. }
  10607. isSubtypeOf(rhs) {
  10608. if (rhs.kind() === 'OptionalType') {
  10609. return true;
  10610. }
  10611. return super.isSubtypeOf(rhs);
  10612. }
  10613. str() {
  10614. return 'NoneType';
  10615. }
  10616. __str__() {
  10617. return 'NoneType';
  10618. }
  10619. });
  10620. this.registerType('torch.TensorType', class extends torch.Type {
  10621. constructor() {
  10622. super('TensorType');
  10623. this._is_inferred = false;
  10624. }
  10625. static get() {
  10626. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10627. return torch.TensorType.value;
  10628. }
  10629. equals(rhs) {
  10630. return this.kind() === rhs.kind();
  10631. }
  10632. isInferredType() {
  10633. return this._is_inferred;
  10634. }
  10635. str() {
  10636. return 'Tensor';
  10637. }
  10638. __str__() {
  10639. return 'Tensor';
  10640. }
  10641. });
  10642. this.registerType('torch.NumberType', class extends torch.Type {
  10643. constructor() {
  10644. super('NumberType');
  10645. }
  10646. static get() {
  10647. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10648. return torch.NumberType.value;
  10649. }
  10650. str() {
  10651. return 'Scalar';
  10652. }
  10653. __str__() {
  10654. return 'number';
  10655. }
  10656. });
  10657. this.registerType('torch.BoolType', class extends torch.Type {
  10658. constructor() {
  10659. super('BoolType');
  10660. }
  10661. static get() {
  10662. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10663. return torch.BoolType.value;
  10664. }
  10665. equals(rhs) {
  10666. return this.kind() === rhs.kind();
  10667. }
  10668. str() {
  10669. return 'bool';
  10670. }
  10671. __str__() {
  10672. return 'bool';
  10673. }
  10674. });
  10675. this.registerType('torch.IntType', class extends torch.Type {
  10676. constructor() {
  10677. super('IntType');
  10678. }
  10679. static get() {
  10680. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10681. return torch.IntType.value;
  10682. }
  10683. equals(rhs) {
  10684. return this.kind() === rhs.kind();
  10685. }
  10686. isSubtypeOf(rhs) {
  10687. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10688. }
  10689. str() {
  10690. return 'int';
  10691. }
  10692. __str__() {
  10693. return 'int';
  10694. }
  10695. });
  10696. this.registerType('torch.SymIntType', class extends torch.Type {
  10697. constructor() {
  10698. super('SymIntType');
  10699. }
  10700. static get() {
  10701. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10702. return torch.SymIntType.value;
  10703. }
  10704. equals(rhs) {
  10705. return this.kind() === rhs.kind();
  10706. }
  10707. str() {
  10708. return 'SymInt';
  10709. }
  10710. __str__() {
  10711. return 'int';
  10712. }
  10713. });
  10714. this.registerType('torch.FloatType', class extends torch.Type {
  10715. constructor() {
  10716. super('FloatType');
  10717. }
  10718. static get() {
  10719. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10720. return torch.FloatType.value;
  10721. }
  10722. equals(rhs) {
  10723. return this.kind() === rhs.kind();
  10724. }
  10725. isSubtypeOf(rhs) {
  10726. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10727. }
  10728. str() {
  10729. return 'float';
  10730. }
  10731. __str__() {
  10732. return 'float';
  10733. }
  10734. });
  10735. this.registerType('torch.StringType', class extends torch.Type {
  10736. constructor() {
  10737. super('StringType');
  10738. }
  10739. static get() {
  10740. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10741. return torch.StringType.value;
  10742. }
  10743. equals(rhs) {
  10744. return this.kind() === rhs.kind();
  10745. }
  10746. str() {
  10747. return 'str';
  10748. }
  10749. __str__() {
  10750. return 'str';
  10751. }
  10752. });
  10753. this.registerType('torch.ComplexType', class extends torch.Type {
  10754. constructor() {
  10755. super('ComplexType');
  10756. }
  10757. static get() {
  10758. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10759. return torch.ComplexType.value;
  10760. }
  10761. equals(rhs) {
  10762. return this.kind() === rhs.kind();
  10763. }
  10764. isSubtypeOf(rhs) {
  10765. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10766. }
  10767. str() {
  10768. return 'complex';
  10769. }
  10770. __str__() {
  10771. return 'complex';
  10772. }
  10773. });
  10774. this.registerType('torch.DictType', class extends torch.Type {
  10775. constructor(key, value) {
  10776. super('DictType');
  10777. this.types = [key, value];
  10778. }
  10779. static create(key, value) {
  10780. let kind = key.kind();
  10781. if (key instanceof torch._C.DynamicType) {
  10782. kind = key.dynamicKind();
  10783. }
  10784. switch (kind) {
  10785. case 'AnyType':
  10786. case 'IntType':
  10787. case 'BoolType':
  10788. case 'FloatType':
  10789. case 'ComplexType':
  10790. case 'StringType':
  10791. case 'TensorType':
  10792. case 'DeviceObjType':
  10793. return new torch.DictType(key, value);
  10794. default:
  10795. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10796. }
  10797. }
  10798. createWithContained(contained_types) {
  10799. if (contained_types.length !== 2) {
  10800. throw new python.Error('Expected 2 contained types.');
  10801. }
  10802. return torch.DictType.create(contained_types[0], contained_types[1]);
  10803. }
  10804. getKeyType() {
  10805. return this.types[0];
  10806. }
  10807. getValueType() {
  10808. return this.types[1];
  10809. }
  10810. hasFreeVariables() {
  10811. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10812. }
  10813. containedTypes() {
  10814. return this.types;
  10815. }
  10816. equals(rhs) {
  10817. if (rhs instanceof torch.DictType) {
  10818. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10819. }
  10820. return false;
  10821. }
  10822. str() {
  10823. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10824. }
  10825. __str__() {
  10826. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10827. }
  10828. });
  10829. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10830. constructor() {
  10831. super('DeviceObjType');
  10832. }
  10833. static get() {
  10834. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10835. return torch.DeviceObjType.value;
  10836. }
  10837. str() {
  10838. return 'Device';
  10839. }
  10840. __str__() {
  10841. return 'Device';
  10842. }
  10843. });
  10844. this.registerType('torch.StreamObjType', class extends torch.Type {
  10845. constructor() {
  10846. super('StreamObjType');
  10847. }
  10848. str() {
  10849. return 'Stream';
  10850. }
  10851. __str__() {
  10852. return 'Stream';
  10853. }
  10854. });
  10855. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10856. constructor() {
  10857. super('GeneratorType');
  10858. }
  10859. static get() {
  10860. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10861. return torch._C._GeneratorType.value;
  10862. }
  10863. str() {
  10864. return 'Generator';
  10865. }
  10866. __str__() {
  10867. return 'Generator';
  10868. }
  10869. });
  10870. this.registerType('torch.InterfaceType', class extends torch.Type {
  10871. constructor() {
  10872. super('InterfaceType');
  10873. }
  10874. });
  10875. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10876. constructor() {
  10877. super('DynamicType');
  10878. }
  10879. });
  10880. this.registerType('torch._C.FunctionType', class extends torch.Type {
  10881. constructor(func) {
  10882. super('FunctionType');
  10883. this._func = func;
  10884. }
  10885. static create(func) {
  10886. return new torch._C.FunctionType(func);
  10887. }
  10888. function() {
  10889. return this._func;
  10890. }
  10891. });
  10892. this.registerType('torch._C.VarType', class extends torch.Type {
  10893. constructor(name) {
  10894. super('VarType', name);
  10895. }
  10896. static create(name) {
  10897. return new torch._C.VarType(name);
  10898. }
  10899. name() {
  10900. return this._annotation_str;
  10901. }
  10902. hasFreeVariables() {
  10903. return true;
  10904. }
  10905. });
  10906. this.registerType('torch._C.AliasInfo', class {
  10907. constructor() {
  10908. this.is_write = false;
  10909. this.before_set = [];
  10910. this.after_set = [];
  10911. this.containedTypes = [];
  10912. }
  10913. addBeforeSet(value) {
  10914. this.before_set.push(value);
  10915. }
  10916. addAfterSet(value) {
  10917. this.after_set.push(value);
  10918. }
  10919. addContainedType(alias_info) {
  10920. this.containedTypes.push(alias_info);
  10921. }
  10922. str() {
  10923. const list = ['('];
  10924. list.push(this.before_set.join('|'));
  10925. if (this.after_set.length > 0) {
  10926. list.push(' -> ');
  10927. list.push(this.after_set.join('|'));
  10928. }
  10929. if (this.is_write) {
  10930. list.push('!');
  10931. }
  10932. list.push(')');
  10933. return list.join('');
  10934. }
  10935. });
  10936. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  10937. if (str.startsWith('"') && str.endsWith('"')) {
  10938. return str.slice(1, -1);
  10939. }
  10940. if (str.startsWith("'") && str.endsWith("'")) {
  10941. return str.slice(1, -1);
  10942. }
  10943. throw new python.Error(`Invalid string literal '${str}'.`);
  10944. // inline std::string parseStringLiteral(
  10945. });
  10946. this.registerType('torch._C.Token', class {
  10947. constructor() {
  10948. this.kind = '';
  10949. this.value = '';
  10950. }
  10951. text() {
  10952. return this.value;
  10953. }
  10954. });
  10955. this.registerType('torch._C.Lexer', class {
  10956. constructor(buffer) {
  10957. this.buffer = buffer;
  10958. this.position = 0;
  10959. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  10960. this.next();
  10961. }
  10962. cur() {
  10963. return this.next_tokens[0];
  10964. }
  10965. lookahead() {
  10966. if (!this.next_tokens[1].kind) {
  10967. this.position += this.cur().text().length;
  10968. this.lex(this.next_tokens[1]);
  10969. }
  10970. return this.next_tokens[1];
  10971. }
  10972. next() {
  10973. const [cur] = this.next_tokens;
  10974. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  10975. this.next_tokens[1].kind = '';
  10976. this.next_tokens[3] = cur;
  10977. const [token] = this.next_tokens;
  10978. if (token.kind) {
  10979. return cur;
  10980. }
  10981. this.position += cur.text().length;
  10982. this.lex(token);
  10983. return cur;
  10984. }
  10985. nextIf(kind) {
  10986. if (this.cur().kind !== kind) {
  10987. return false;
  10988. }
  10989. this.next();
  10990. return true;
  10991. }
  10992. expect(kind) {
  10993. if (this.cur().kind !== kind) {
  10994. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  10995. }
  10996. return this.next();
  10997. }
  10998. lex(token) {
  10999. while (this.buffer[this.position] === ' ') {
  11000. this.position += 1;
  11001. }
  11002. let i = this.position;
  11003. if (i >= this.buffer.length) {
  11004. token.kind = '\0';
  11005. token.value = '';
  11006. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  11007. token.kind = '...';
  11008. token.value = '...';
  11009. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  11010. this.kind = '[]';
  11011. this.value = '[]'; */
  11012. } 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] === '|') {
  11013. token.kind = this.buffer[i];
  11014. token.value = this.buffer[i];
  11015. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  11016. i += 1;
  11017. 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] === '_')) {
  11018. i += 1;
  11019. }
  11020. token.kind = 'id';
  11021. token.value = this.buffer.slice(this.position, i);
  11022. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  11023. token.kind = '->';
  11024. token.value = '->';
  11025. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  11026. i += 1;
  11027. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  11028. i += 1;
  11029. }
  11030. token.kind = '#';
  11031. token.value = this.buffer.slice(this.position, i);
  11032. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  11033. const quote = this.buffer[i];
  11034. i += 1;
  11035. while (i < this.buffer.length && this.buffer[i] !== quote) {
  11036. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  11037. }
  11038. i += 1;
  11039. token.kind = 'string';
  11040. token.value = this.buffer.slice(this.position, i);
  11041. } else {
  11042. throw new python.Error(`Unsupported token at '${this.position}'.`);
  11043. }
  11044. }
  11045. });
  11046. this.registerType('torch._C.SchemaTypeParser', class {
  11047. constructor(L, complete_tensor_types, allow_typevars) {
  11048. this.L = L;
  11049. this.complete_tensor_types = complete_tensor_types;
  11050. this._allow_typevars = allow_typevars;
  11051. }
  11052. parseType() {
  11053. const r = this.parseFakeAndRealType();
  11054. return { first: r[0], second: r[2] };
  11055. }
  11056. parseBaseType() {
  11057. const L = this.L;
  11058. const tok = L.cur();
  11059. const text = tok.text();
  11060. L.next();
  11061. switch (text) {
  11062. case 'Tensor': return torch.TensorType.get();
  11063. case 'bool': return torch.BoolType.get();
  11064. case 'int': return torch.IntType.get();
  11065. case 'float': return torch.FloatType.get();
  11066. case 'complex': return torch.ComplexType.get();
  11067. case 'str': return torch.StringType.get();
  11068. case 'SymInt': return torch.SymIntType.get();
  11069. case 'Scalar': return torch.NumberType.get();
  11070. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11071. case 'Device': return torch.DeviceObjType.get();
  11072. case 'Layout': return torch.Type.get('Layout');
  11073. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11074. case 'Generator': return torch._C._GeneratorType.get();
  11075. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11076. case 'Any': return torch.AnyType.get();
  11077. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11078. case 'Dimname': return torch.StringType.get();
  11079. case 'QScheme': return torch.Type.get('QSchemeType');
  11080. case 'Stream': return torch.StreamObjType.get();
  11081. case 'Storage': return torch.Type.get('Storage');
  11082. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11083. case 'NoneType': return torch.NoneType.get();
  11084. default: throw new python.Error(`Unsupported type '${text}'.`);
  11085. }
  11086. }
  11087. parseFakeAndRealType() {
  11088. const L = this.L;
  11089. let fake_value = null;
  11090. let real_value = null;
  11091. let alias_info = null;
  11092. if (L.nextIf('(')) {
  11093. const types = [];
  11094. while (!L.nextIf(')')) {
  11095. const r = this.parseType();
  11096. types.push(r.first);
  11097. if (alias_info && r.second) {
  11098. alias_info.addContainedType(r.second);
  11099. }
  11100. L.nextIf(',');
  11101. }
  11102. real_value = torch.TupleType.create(types);
  11103. fake_value = real_value;
  11104. } else if (L.cur().text() === 'Future') {
  11105. L.next();
  11106. L.expect('(');
  11107. const p = this.parseType();
  11108. const subtype = p.first;
  11109. // const subalias = p.second;
  11110. L.expect(')');
  11111. real_value = torch.FutureType.create(subtype);
  11112. fake_value = real_value;
  11113. } else if (L.cur().text() === 'Await') {
  11114. L.next();
  11115. L.expect('(');
  11116. const p = this.parseType();
  11117. const subtype = p.first;
  11118. // const subalias = p.second;
  11119. L.expect(')');
  11120. real_value = torch.AwaitType.get(subtype);
  11121. fake_value = real_value;
  11122. } else if (L.cur().text() === 'RRef') {
  11123. L.next();
  11124. L.expect('(');
  11125. const p = this.parseType();
  11126. const subtype = p.first;
  11127. // const subalias = p.second;
  11128. L.expect(')');
  11129. real_value = torch.RRefType.create(subtype);
  11130. fake_value = real_value;
  11131. } else if (L.cur().text() === 'Tensor') {
  11132. L.next();
  11133. real_value = torch.TensorType.get();
  11134. fake_value = real_value;
  11135. alias_info = this.parseAliasAnnotation();
  11136. } else if (L.cur().text() === 'Dict') {
  11137. L.next();
  11138. L.expect('(');
  11139. const key_type = this.parseType().first;
  11140. L.expect(',');
  11141. const value_type = this.parseType().first;
  11142. L.expect(')');
  11143. alias_info = this.parseAliasAnnotation();
  11144. real_value = torch.DictType.create(key_type, value_type);
  11145. fake_value = real_value;
  11146. } else if (L.nextIf('Union')) {
  11147. L.next();
  11148. L.expect('(');
  11149. const types = [];
  11150. types.push(this.parseType().first);
  11151. while (L.cur().kind !== ')') {
  11152. L.expect(',');
  11153. types.push(this.parseType().first);
  11154. }
  11155. L.expect(')');
  11156. alias_info = this.parseAliasAnnotation();
  11157. real_value = new torch.UnionType(types);
  11158. fake_value = real_value;
  11159. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11160. fake_value = real_value = parseRefinedTensor();
  11161. alias_info = parseAliasAnnotation(); */
  11162. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11163. L.next();
  11164. L.expect('.');
  11165. const torch_tok = L.expect('id');
  11166. if (torch_tok.text() !== 'torch') {
  11167. throw new python.Error('Expected classes namespace.');
  11168. }
  11169. L.expect('.');
  11170. const classes_tok = L.expect('id');
  11171. if (classes_tok.text() !== 'classes') {
  11172. throw new python.Error('Expected classes namespace.');
  11173. }
  11174. L.expect('.');
  11175. const ns_tok = L.expect('id');
  11176. L.expect('.');
  11177. const class_tok = L.expect('id');
  11178. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11179. fake_value = real_value;
  11180. if (!fake_value) {
  11181. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11182. }
  11183. } else {
  11184. real_value = this.parseBaseType();
  11185. fake_value = real_value;
  11186. if (real_value.kind() === 'ScalarTypeType' ||
  11187. real_value.kind() === 'MemoryFormat' ||
  11188. real_value.kind() === 'Layout' ||
  11189. real_value.kind() === 'SymIntType') {
  11190. fake_value = torch.IntType.get();
  11191. }
  11192. alias_info = this.parseAliasAnnotation();
  11193. }
  11194. while (true) {
  11195. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11196. L.expect('[');
  11197. L.expect(']');
  11198. fake_value = torch.ListType.create(fake_value);
  11199. real_value = torch.ListType.create(real_value);
  11200. let container = this.parseAliasAnnotation();
  11201. if (alias_info) {
  11202. if (!container) {
  11203. container = new torch._C.AliasInfo();
  11204. container.is_write = alias_info.is_write;
  11205. }
  11206. container.addContainedType(alias_info);
  11207. }
  11208. alias_info = container;
  11209. } else if (L.nextIf('?')) {
  11210. fake_value = torch.OptionalType.create(fake_value);
  11211. real_value = torch.OptionalType.create(real_value);
  11212. } else {
  11213. break;
  11214. }
  11215. }
  11216. return [fake_value, real_value, alias_info];
  11217. }
  11218. parseAliasAnnotation() {
  11219. const L = this.L;
  11220. let alias_info = null;
  11221. if (L.nextIf('(')) {
  11222. alias_info = new torch._C.AliasInfo();
  11223. do {
  11224. alias_info.addBeforeSet(L.cur().text());
  11225. L.next();
  11226. if (L.nextIf('!')) {
  11227. alias_info.is_write = true;
  11228. }
  11229. }
  11230. while (L.nextIf('|'));
  11231. if (L.nextIf('->')) {
  11232. do {
  11233. alias_info.addAfterSet(L.cur().text());
  11234. L.next();
  11235. }
  11236. while (L.nextIf('|'));
  11237. }
  11238. L.expect(')');
  11239. }
  11240. return alias_info;
  11241. }
  11242. });
  11243. this.registerType('torch.Argument', class {
  11244. constructor(...args) {
  11245. // torch/aten/src/ATen/core/function_schema.h
  11246. this.N = null;
  11247. this.default_value = null;
  11248. this.kwarg_only = false;
  11249. this.alias_info = null;
  11250. if (args.length === 2) {
  11251. [this.name, this.type] = args;
  11252. this.real_type = this.type;
  11253. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11254. [this.name, this.type, this.real_type] = args;
  11255. } else if (args.length === 6) {
  11256. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11257. } else if (args.length === 7) {
  11258. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11259. } else {
  11260. throw new python.Error('Invalid arguments.');
  11261. }
  11262. const is_alias = this.alias_info && this.alias_info.is_write;
  11263. this.is_out = this.kwarg_only && is_alias;
  11264. }
  11265. has_default_value() {
  11266. return this.default_value !== undefined;
  11267. }
  11268. is_inferred_type() {
  11269. if (this.type instanceof torch.TensorType) {
  11270. return this.type.isInferredType();
  11271. }
  11272. return false;
  11273. }
  11274. str() {
  11275. const list = [];
  11276. const type = this.real_type;
  11277. const is_opt = type instanceof torch.OptionalType;
  11278. const unopt_type = is_opt ? type.getElementType() : type;
  11279. if (unopt_type instanceof torch.ListType) {
  11280. list.push(unopt_type.getElementType().str());
  11281. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11282. list.push(this.alias_info.containedTypes[0].str());
  11283. }
  11284. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11285. } else {
  11286. list.push(unopt_type.str());
  11287. }
  11288. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11289. list.push(this.alias_info.str());
  11290. }
  11291. if (is_opt) {
  11292. list.push('?');
  11293. }
  11294. if (this.name) {
  11295. list.push(' ');
  11296. list.push(this.name);
  11297. }
  11298. if (this.default_value !== undefined) {
  11299. const value = this.default_value;
  11300. if (value === null) {
  11301. list.push('=None');
  11302. } else if (typeof value === 'boolean') {
  11303. list.push('=');
  11304. list.push(value ? 'True' : 'False');
  11305. } else if (typeof value === 'string') {
  11306. list.push(`="${value}"`);
  11307. } else if (typeof value === 'number') {
  11308. list.push(`=${value}`);
  11309. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11310. list.push(`.`);
  11311. }
  11312. } else if (Array.isArray(value)) {
  11313. list.push(`=[${value.join(', ')}]`);
  11314. }
  11315. }
  11316. return list.join('');
  11317. }
  11318. });
  11319. torch._C.TypeKind = {
  11320. StringType: 'StringType',
  11321. NumberType: 'NumberType',
  11322. IntType: 'IntType',
  11323. BoolType: 'BoolType',
  11324. DynamicType: 'DynamicType',
  11325. OptionalType: 'OptionalType',
  11326. FloatType: 'FloatType',
  11327. ComplexType: 'ComplexType',
  11328. ListType: 'ListType',
  11329. };
  11330. this.registerType('torch._C.List', class extends Array {
  11331. constructor(type, elements) {
  11332. super(elements ? elements.length : 0);
  11333. if (Array.isArray(elements)) {
  11334. for (let i = 0; i < elements.length; i++) {
  11335. this[i] = elements[i];
  11336. }
  11337. }
  11338. this.type = type;
  11339. }
  11340. elementType() {
  11341. return this.type;
  11342. }
  11343. });
  11344. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11345. return new Map();
  11346. });
  11347. this.registerFunction('torch._C.string_to_type_lut', () => {
  11348. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11349. const map = new Map();
  11350. map.set('Tensor', torch.TensorType.get());
  11351. map.set('int', torch.IntType.get());
  11352. map.set('float', torch.FloatType.get());
  11353. map.set('bool', torch.BoolType.get());
  11354. map.set('complex', torch.ComplexType.get());
  11355. map.set('str', torch.StringType.get());
  11356. map.set('Device', torch.DeviceObjType.get());
  11357. map.set('number', torch.NumberType.get());
  11358. map.set('None', torch.NoneType.get());
  11359. map.set('NoneType', torch.NoneType.get());
  11360. map.set('Any', torch.AnyType.get());
  11361. map.set('list', torch.Type.get('AnyListType'));
  11362. map.set('tuple', torch.Type.get('AnyTupleType'));
  11363. torch._C.string_to_type_lut.basePythonTypes = map;
  11364. }
  11365. return torch._C.string_to_type_lut.basePythonTypes;
  11366. });
  11367. this.registerType('torch._C.ScriptTypeParser', class {
  11368. constructor(resolver) {
  11369. this._resolver = resolver;
  11370. }
  11371. parseSchemaFromDef(def, skip_self) {
  11372. const name = def.name;
  11373. const args = this.parseArgsFromDecl(def, skip_self);
  11374. const returns = this.parseReturnFromDecl(def);
  11375. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11376. }
  11377. parseArgsFromDecl(decl, skip_self) {
  11378. const retval = [];
  11379. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11380. throw new python.Error('Unsupported function argument.');
  11381. }
  11382. const params = decl.args.args.slice();
  11383. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11384. const start = skip_self ? 1 : 0;
  11385. for (let i = start; i < params.length; i++) {
  11386. const decl_arg = params[i];
  11387. const N = null;
  11388. const default_value = undefined;
  11389. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11390. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11391. retval.push(arg);
  11392. }
  11393. return retval;
  11394. }
  11395. parseReturnFromDecl(decl) {
  11396. if (!decl.returns) {
  11397. return [];
  11398. }
  11399. if (this.parseBroadcastList(decl.returns)) {
  11400. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11401. }
  11402. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11403. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11404. }
  11405. parseTypeFromExpr(expr) {
  11406. if (this._resolver) {
  11407. if (expr instanceof ast.Name) {
  11408. const type = this._resolver.resolveType(expr.id);
  11409. if (type) {
  11410. return type;
  11411. }
  11412. }
  11413. }
  11414. return this.parseTypeFromExprImpl(expr);
  11415. }
  11416. parseTypeFromExprImpl(expr) {
  11417. if (expr instanceof ast.Subscript) {
  11418. const value_name = this.parseBaseTypeName(expr.value);
  11419. if (!value_name) {
  11420. throw new python.Error('Subscripted type must be a type identifier.');
  11421. }
  11422. return this.subscriptToType(value_name, expr);
  11423. }
  11424. const name = this.parseBaseTypeName(expr);
  11425. if (name) {
  11426. const itr = torch._C.string_to_type_lut().get(name);
  11427. if (itr) {
  11428. return itr;
  11429. }
  11430. if (this._resolver) {
  11431. const typePtr = this._resolver.resolveType(name, expr);
  11432. if (typePtr) {
  11433. return typePtr;
  11434. }
  11435. }
  11436. }
  11437. throw new python.Error(`Unknown type name '${name}'.`);
  11438. }
  11439. parseBaseTypeName(expr) {
  11440. if (expr instanceof ast.Name) {
  11441. return expr.id;
  11442. } else if (expr instanceof ast.Constant && expr.value === null) {
  11443. return 'None';
  11444. } else if (expr instanceof ast.Attribute) {
  11445. const name = expr.attr;
  11446. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11447. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11448. return name;
  11449. }
  11450. return torch._C.collectQualname(expr);
  11451. }
  11452. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11453. }
  11454. parseBroadcastList(/* expr */) {
  11455. return null;
  11456. }
  11457. parseType(str) {
  11458. const expr = ast.parse(str);
  11459. return this.parseTypeFromExpr(expr.body[0].value);
  11460. }
  11461. subscriptToType(typeName, subscript) {
  11462. if (typeName === 'Tuple' || typeName === 'tuple') {
  11463. const subscript_expr_types = [];
  11464. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11465. for (const expr of elts) {
  11466. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11467. }
  11468. return torch.TupleType.create(subscript_expr_types);
  11469. } else if (typeName === 'List' || typeName === 'list') {
  11470. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11471. throw new python.Error('List type must have exactly one element type.');
  11472. }
  11473. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11474. return torch.ListType.create(elem_type);
  11475. } else if (typeName === 'Optional') {
  11476. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11477. throw new python.Error('Optional type must have exactly one element type.');
  11478. }
  11479. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11480. return torch.OptionalType.create(elem_type);
  11481. } else if (typeName === 'Union') {
  11482. const subscript_expr_types = [];
  11483. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11484. for (const expr of elts) {
  11485. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11486. }
  11487. return torch.UnionType.create(subscript_expr_types);
  11488. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11489. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11490. if (elts.length !== 1) {
  11491. throw new python.Error('Future type must have exactly one element type.');
  11492. }
  11493. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11494. return torch.FutureType.create(elem_type);
  11495. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11496. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11497. if (elts.length !== 1) {
  11498. throw new python.Error('Await type must have exactly one element type.');
  11499. }
  11500. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11501. return torch.AwaitType.create(elem_type);
  11502. } else if (typeName === 'RRef') {
  11503. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11504. if (elts.length !== 1) {
  11505. throw new python.Error('RRef type must have exactly one element type.');
  11506. }
  11507. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11508. return torch.RRefType.create(elem_type);
  11509. } else if (typeName === 'Dict' || typeName === 'dict') {
  11510. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11511. if (elts.length !== 2) {
  11512. throw new python.Error('Dict type must have exactly two element types.');
  11513. }
  11514. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11515. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11516. return torch.DictType.create(key_type, value_type);
  11517. }
  11518. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11519. }
  11520. });
  11521. this.registerFunction('torch._C.isTorch', (expr) => {
  11522. return expr instanceof ast.Name && expr.id === 'torch';
  11523. });
  11524. this.registerFunction('torch._C.collectQualname', (select) => {
  11525. const base = select.value;
  11526. if (base instanceof ast.Name) {
  11527. return `${base.id}.${select.attr}`;
  11528. }
  11529. const basename = torch._C.collectQualname(base);
  11530. return `${basename}.${select.attr}`;
  11531. });
  11532. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11533. constructor(overloadpacket, op, op_dk, schema, tags) {
  11534. super();
  11535. this._op = op;
  11536. this._op_dk = op_dk;
  11537. this._schema = schema;
  11538. this._overloadpacket = overloadpacket;
  11539. this._tags = tags;
  11540. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11541. this._name = this._schema.name;
  11542. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11543. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11544. this.__module__ = overloadpacket.__module__;
  11545. op.__module__ = overloadpacket.__module__;
  11546. this.__qualname__ = self._name;
  11547. this.__annotations__ = {};
  11548. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11549. let is_write = null;
  11550. for (const a of this._schema.arguments) {
  11551. if (a.alias_info) {
  11552. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11553. }
  11554. }
  11555. this.is_view = is_write !== null && !is_write;
  11556. }
  11557. name() {
  11558. return this._name;
  11559. }
  11560. });
  11561. this.registerType('torch._ops.OpOverloadPacket', class {
  11562. constructor(qualified_op_name, op_name, op, overload_names) {
  11563. this._qualified_op_name = qualified_op_name;
  11564. this.__name__ = op_name;
  11565. this._op = op;
  11566. this._overload_names = overload_names;
  11567. this._dir = [];
  11568. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11569. }
  11570. get _schemas() {
  11571. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11572. }
  11573. __getattr__(key) {
  11574. key = key === 'default' ? '' : key;
  11575. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11576. const [op_, op_dk_, tags] = op_dk_tags;
  11577. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11578. const overload = this._has_script_object_arg(schema) ?
  11579. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11580. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11581. builtins.setattr(self, key, overload);
  11582. this._dir.push(key);
  11583. return overload;
  11584. }
  11585. _has_script_object_arg(schema) {
  11586. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11587. }
  11588. __call__(...args) {
  11589. const fn = execution._operators.get(this._qualified_op_name);
  11590. if (!fn) {
  11591. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11592. }
  11593. return fn(...args);
  11594. }
  11595. });
  11596. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11597. constructor(name) {
  11598. super(`torch.ops.${name}`);
  11599. this.name = name;
  11600. this._dir = [];
  11601. }
  11602. __getattr__(op_name) {
  11603. const namespace_name = this.name;
  11604. const qualified_op_name = `${namespace_name}::${op_name}`;
  11605. const module_name = `${this.__module__}.${namespace_name}`;
  11606. let op = null;
  11607. let overload_names = null;
  11608. try {
  11609. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11610. } catch {
  11611. // continue regardless of error
  11612. }
  11613. if (!op) {
  11614. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11615. }
  11616. op.__module__ = module_name;
  11617. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11618. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11619. builtins.setattr(this, op_name, opoverloadpacket);
  11620. this._dir.push(op_name);
  11621. return opoverloadpacket;
  11622. }
  11623. _get_packet(qualname, op_module) {
  11624. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11625. if (op) {
  11626. // torch.jit._builtins._register_builtin(op, qualname);
  11627. }
  11628. op.__module__ = op_module;
  11629. return [op, overload_names];
  11630. }
  11631. });
  11632. this.registerType('torch._C.graph_node_list', class {
  11633. constructor(head) {
  11634. this.head = head;
  11635. }
  11636. front() {
  11637. return this.head.next;
  11638. }
  11639. end() {
  11640. return this.head.prev;
  11641. }
  11642. [Symbol.iterator]() {
  11643. let current = this.head.next;
  11644. const prev = this.head.prev;
  11645. return {
  11646. next() {
  11647. if (current !== prev) {
  11648. const value = current;
  11649. current = current.next;
  11650. return { value, done: false };
  11651. }
  11652. return { done: true };
  11653. }
  11654. };
  11655. }
  11656. });
  11657. this.registerType('torch.Graph', class {
  11658. constructor() {
  11659. this._next_unique = 0;
  11660. this._unique_names = new Map();
  11661. this._name_base_suffix = new Map();
  11662. this.all_nodes = new Set();
  11663. this.all_values = new Set();
  11664. this.all_blocks = new Set();
  11665. this._block = new torch.Block(this, null);
  11666. this._insert_before = this.return_node();
  11667. }
  11668. insert(opname, args, kwargs, range) {
  11669. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11670. }
  11671. create(kind, ...args) {
  11672. let inputs = null;
  11673. let num_outputs = 1;
  11674. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11675. [inputs, num_outputs] = args;
  11676. } else if (args.length === 1) {
  11677. if (typeof args[0] === 'number') {
  11678. [num_outputs] = args;
  11679. } else if (Array.isArray(args[0])) {
  11680. [inputs] = args;
  11681. }
  11682. }
  11683. const n = new torch.Node(this, kind);
  11684. if (inputs) {
  11685. for (const i of inputs) {
  11686. n.addInput(i);
  11687. }
  11688. }
  11689. for (let i = 0; i < num_outputs; i++) {
  11690. n.addOutput();
  11691. }
  11692. return n;
  11693. }
  11694. createClone(n, value_map, copy_blocks) {
  11695. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11696. const r = n.allocNewInstance(this);
  11697. for (const o of n.outputs()) {
  11698. r.addOutput().copyMetadata(o);
  11699. }
  11700. r.cloneFrom(n);
  11701. for (const i of n.inputs()) {
  11702. r.addInput(value_map(i));
  11703. }
  11704. if (copy_blocks) {
  11705. for (const b of n.blocks()) {
  11706. r.addBlock().cloneFrom(b, value_map);
  11707. }
  11708. }
  11709. return r;
  11710. }
  11711. createNone() {
  11712. const n = this.create('prim::Constant');
  11713. n.output().setType(torch.NoneType.get());
  11714. return n;
  11715. }
  11716. createUninitialized(typ) {
  11717. const n = this.create('prim::Uninitialized');
  11718. n.output().setType(typ);
  11719. return n;
  11720. }
  11721. createEnumValue(e) {
  11722. const enum_type = e.type().expect(torch.EnumType);
  11723. const n = this.create('prim::EnumValue', [e]);
  11724. n.output().setType(enum_type.getValueType());
  11725. return n;
  11726. }
  11727. createList(contained_type, values) {
  11728. const n = this.create('prim::ListConstruct', values);
  11729. for (const v of values) {
  11730. if (!v.type().isSubtypeOf(contained_type)) {
  11731. throw new python.Error('Invalid list item.');
  11732. }
  11733. }
  11734. n.output().setType(torch.ListType.create(contained_type));
  11735. return n;
  11736. }
  11737. createListUnpack(v, size) {
  11738. const list_type = v.type().expect(torch.ListType);
  11739. const elem_type = list_type.getElementType();
  11740. const n = this.create('prim::ListUnpack', [v], 0);
  11741. for (let i = 0; i < size; i++) {
  11742. n.addOutput().setType(elem_type);
  11743. }
  11744. return n;
  11745. }
  11746. createTuple(values, tuple_type) {
  11747. if (!tuple_type) {
  11748. const types = values.map((v) => v.type());
  11749. tuple_type = torch.TupleType.create(types);
  11750. }
  11751. const n = this.create('prim::TupleConstruct', values);
  11752. n.output().setType(tuple_type);
  11753. return n;
  11754. }
  11755. createTupleUnpack(v) {
  11756. const tt = v.type().expect(torch.TupleType);
  11757. const n = this.create('prim::TupleUnpack', [v], 0);
  11758. for (const element of tt.elements()) {
  11759. n.addOutput().setType(element);
  11760. }
  11761. return n;
  11762. }
  11763. createTupleIndex(tup, idx, output_type) {
  11764. const n = this.create('prim::TupleIndex', [tup, idx]);
  11765. n.output().setType(output_type);
  11766. return n;
  11767. }
  11768. createTupleSlice(tup, beg, step_size, num_values) {
  11769. const new_vals = [];
  11770. const tt = tup.type().expect(torch.TupleType);
  11771. let i = beg;
  11772. for (let j = 0; j < num_values; j++) {
  11773. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11774. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11775. new_vals.push(tupleIndex.output());
  11776. i += step_size;
  11777. }
  11778. const n = this.createTuple(new_vals);
  11779. return n;
  11780. }
  11781. createDict(key_type, value_type, keys, values) {
  11782. if (keys.length !== values.length) {
  11783. throw new python.Error('Invalid dictionary size.');
  11784. }
  11785. const n = this.create('prim::DictConstruct');
  11786. const length = keys.length;
  11787. for (let i = 0; i < length; i++) {
  11788. if (!keys[i].type().isSubtypeOf(key_type)) {
  11789. throw new python.Error('Invalid key.');
  11790. }
  11791. if (!values[i].type().isSubtypeOf(value_type)) {
  11792. throw new python.Error('Invalid value.');
  11793. }
  11794. n.addInput(keys[i]);
  11795. n.addInput(values[i]);
  11796. }
  11797. n.output().setType(torch.DictType.create(key_type, value_type));
  11798. return n;
  11799. }
  11800. createObject(type) {
  11801. const node = this.create('prim::CreateObject');
  11802. node.output().setType(type);
  11803. return node;
  11804. }
  11805. createIsInstance(v, types) {
  11806. const n = this.create('prim::isinstance', [v], 1);
  11807. n.tys_('types', types);
  11808. n.output().setType(torch.BoolType.get());
  11809. return n;
  11810. }
  11811. createSetAttr(obj, field, newValue) {
  11812. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11813. n.s_('name', field);
  11814. return n;
  11815. }
  11816. createGetAttr(obj, field) {
  11817. const n = this.create('prim::GetAttr', [obj]);
  11818. n.s_('name', field);
  11819. const classType = obj.type();
  11820. const outputType = classType.getAttribute(field);
  11821. n.output().setType(outputType);
  11822. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11823. return n;
  11824. }
  11825. createLoad(name, type) {
  11826. const n = this.create('prim::Load', [], 1);
  11827. n.s_('name', name);
  11828. n.output().setType(type);
  11829. return n;
  11830. }
  11831. createStore(name, v) {
  11832. const n = this.create('prim::Store', [v], 0);
  11833. n.s_('name', name);
  11834. return n;
  11835. }
  11836. inputs() {
  11837. return this._block.inputs();
  11838. }
  11839. outputs() {
  11840. return this._block.outputs();
  11841. }
  11842. nodes() {
  11843. return this._block.nodes();
  11844. }
  11845. param_node() {
  11846. return this._block.param_node();
  11847. }
  11848. return_node() {
  11849. return this._block.return_node();
  11850. }
  11851. block() {
  11852. return this._block;
  11853. }
  11854. addInput(name) {
  11855. return this._block.addInput(name);
  11856. }
  11857. insertNode(node) {
  11858. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11859. return node.insertBefore(this._insert_before);
  11860. }
  11861. insertConstant(val, loc, scope) {
  11862. return torch._C.insertConstant(this, val, loc, scope);
  11863. }
  11864. insertMethodCall(method_name, matched) {
  11865. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11866. .s_('name', method_name)
  11867. .output().setType(matched.return_types[0]);
  11868. return result;
  11869. }
  11870. insertUncheckedCast(v, type) {
  11871. const n = this.create('prim::unchecked_cast', [v]);
  11872. this.insertNode(n);
  11873. n.output().setType(type);
  11874. return n.output();
  11875. }
  11876. insertToList(v, type) {
  11877. let dim = 0;
  11878. let ptr = type;
  11879. while (ptr instanceof torch.ListType) {
  11880. ptr = ptr.getElementType();
  11881. dim += 1;
  11882. }
  11883. let elem_ty = 0;
  11884. if (ptr instanceof torch.IntType) {
  11885. elem_ty = 0;
  11886. } else if (ptr instanceof torch.FloatType) {
  11887. elem_ty = 1;
  11888. } else if (ptr instanceof torch.BoolType) {
  11889. elem_ty = 2;
  11890. } else if (ptr instanceof torch.ComplexType) {
  11891. elem_ty = 3;
  11892. } else {
  11893. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  11894. }
  11895. const dim_val = this.insertConstant(dim);
  11896. const elem_ty_val = this.insertConstant(elem_ty);
  11897. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  11898. n.output().setType(type);
  11899. return n.output();
  11900. }
  11901. insertFunctionCall(callee, matched) {
  11902. const func_name = callee.name();
  11903. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  11904. const inputs = [fn_constant, ...matched.inputs];
  11905. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  11906. return result;
  11907. }
  11908. insertPoint() {
  11909. return this._insert_before;
  11910. }
  11911. setInsertPoint(node) {
  11912. if (node instanceof torch.Block) {
  11913. node = node.return_node();
  11914. }
  11915. this._insert_before = node;
  11916. }
  11917. freeNode(n) {
  11918. this.all_nodes.delete(n);
  11919. }
  11920. freeValue(v) {
  11921. v.setDebugName('');
  11922. this.all_values.delete(v);
  11923. }
  11924. freeBlock(b) {
  11925. this.all_blocks.delete(b);
  11926. }
  11927. copy() {
  11928. const new_g = new torch.Graph();
  11929. new_g.cloneFrom(this);
  11930. return new_g;
  11931. }
  11932. cloneFrom(src) {
  11933. const env = (v) => {
  11934. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  11935. };
  11936. this.block().cloneFrom(src.block(), env);
  11937. }
  11938. set_op_version(version) {
  11939. this._op_version = version;
  11940. }
  11941. get_op_version() {
  11942. return this._op_version;
  11943. }
  11944. print(out, print_source_locations) {
  11945. out.write('graph(');
  11946. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  11947. out.write('):\n');
  11948. const groups = [];
  11949. for (const node of this.nodes()) {
  11950. node.print(out, 1, groups, print_source_locations);
  11951. }
  11952. out.write(' return (');
  11953. torch._C.printValueRefs(out, this.outputs());
  11954. out.write(')\n');
  11955. for (let i = 0; i < groups.length; i++) {
  11956. const fg = groups[i];
  11957. out.write('with ');
  11958. out.write(fg.kind());
  11959. out.write(`_${i} = `);
  11960. out.write(fg.g('Subgraph'));
  11961. }
  11962. return out;
  11963. }
  11964. toString() {
  11965. const out = new io.StringIO();
  11966. this.print(out, true);
  11967. return out.toString();
  11968. }
  11969. });
  11970. this.registerType('torch.Block', class {
  11971. constructor(graph, node) {
  11972. this._graph = graph;
  11973. this._input = graph.create('prim::Param', 0);
  11974. this._output = graph.create('prim::Return', 0);
  11975. this._owning_node = node;
  11976. this._input.next = this._output;
  11977. this._input.prev = this._output;
  11978. this._output.next = this._input;
  11979. this._output.prev = this._input;
  11980. this._graph.all_blocks.add(this);
  11981. this._output._owning_block = this;
  11982. // output_.topo_position_ = kUpperBound;
  11983. this._input._owning_block = this;
  11984. // input_.topo_position_ = kLowerBound;
  11985. }
  11986. inputs() {
  11987. return this._input.outputs();
  11988. }
  11989. outputs() {
  11990. return this._output.inputs();
  11991. }
  11992. nodes() {
  11993. return new torch._C.graph_node_list(this._input);
  11994. }
  11995. return_node() {
  11996. return this._output;
  11997. }
  11998. param_node() {
  11999. return this._input;
  12000. }
  12001. owningNode() {
  12002. return this._owning_node;
  12003. }
  12004. owningGraph() {
  12005. return this._graph;
  12006. }
  12007. addInput(name) {
  12008. const value = this._input.addOutput();
  12009. value.setDebugName(name || '');
  12010. return value;
  12011. }
  12012. registerOutput(value) {
  12013. this._output.addInput(value);
  12014. return this.outputs().length - 1;
  12015. }
  12016. appendNode(n) {
  12017. if (n._graph !== this._graph || n.inBlockList()) {
  12018. throw new python.Error('Node not in graph.');
  12019. }
  12020. n.insertBefore(this._output);
  12021. return n;
  12022. }
  12023. cloneFrom(src, value_map) {
  12024. const local_map = new Map();
  12025. const env = (v) => {
  12026. if (local_map.has(v)) {
  12027. return local_map.get(v);
  12028. }
  12029. return value_map(v);
  12030. };
  12031. const graph = this.owningGraph();
  12032. for (const input of src.inputs()) {
  12033. local_map.set(input, this.addInput().copyMetadata(input));
  12034. }
  12035. for (const node of src.nodes()) {
  12036. const new_node = this.appendNode(graph.createClone(node, env));
  12037. for (let i = 0; i < node.outputs().length; i++) {
  12038. const oo = node.outputs()[i];
  12039. const no = new_node.outputs()[i];
  12040. local_map.set(oo, no);
  12041. no.copyMetadata(oo);
  12042. }
  12043. }
  12044. for (const output of src.outputs()) {
  12045. this.registerOutput(env(output));
  12046. }
  12047. }
  12048. eraseOutput(i) {
  12049. this._output.removeInput(i);
  12050. }
  12051. destroy() {
  12052. this._output.removeAllInputs();
  12053. for (const n of this.nodes()) {
  12054. n.destroy();
  12055. }
  12056. this._output.destroy();
  12057. this._input.destroy();
  12058. this._graph.freeBlock(this);
  12059. }
  12060. });
  12061. this.registerType('torch.Node', class {
  12062. constructor(graph, kind) {
  12063. this._kind = kind;
  12064. this._graph = graph;
  12065. this._owning_block = null;
  12066. this._values = new Map();
  12067. this._inputs = [];
  12068. this._outputs = [];
  12069. this._blocks = [];
  12070. this._graph.all_nodes.add(this);
  12071. this._prev = null;
  12072. this._next = null;
  12073. this._source_range = null;
  12074. this._op = null;
  12075. }
  12076. owningGraph() {
  12077. return this._graph;
  12078. }
  12079. owningBlock() {
  12080. return this._owning_block;
  12081. }
  12082. kind() {
  12083. return this._kind;
  12084. }
  12085. schema() {
  12086. if (this._op) {
  12087. return this._op.schema();
  12088. }
  12089. // Node::schema() throws while torch.Node.schema() does not.
  12090. const op = this.maybeOperator();
  12091. if (op) {
  12092. return op.schema();
  12093. }
  12094. return null;
  12095. // return this.getOperator().schema();
  12096. }
  12097. hasNamedInput(name) {
  12098. for (const argument of this.schema().arguments) {
  12099. if (argument.name === name) {
  12100. return true;
  12101. }
  12102. }
  12103. return false;
  12104. }
  12105. matches(schema) {
  12106. if (torch._C.isBlockListedSchema(schema)) {
  12107. return false;
  12108. }
  12109. if (this.kind() !== schema.name) {
  12110. return false;
  12111. }
  12112. const actuals = this.inputs();
  12113. const formals = schema.arguments;
  12114. if (actuals.length < formals.length) {
  12115. return false;
  12116. }
  12117. const type_env = new Map();
  12118. for (let i = 0; i < formals.length; i++) {
  12119. let formal = formals[i].type;
  12120. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12121. if (!matched_type.success()) {
  12122. return false;
  12123. }
  12124. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12125. if (resolved) {
  12126. formal = resolved;
  12127. }
  12128. if (!actuals[i].type().isSubtypeOf(formal)) {
  12129. return false;
  12130. }
  12131. }
  12132. if (!schema.is_vararg && actuals.length !== formals.length) {
  12133. return false;
  12134. }
  12135. return true;
  12136. }
  12137. mustBeNone() {
  12138. return this._kind === 'prim::AutogradZero' ||
  12139. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12140. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12141. }
  12142. maybeSchema() {
  12143. const op = this.maybeOperator();
  12144. if (op) {
  12145. return op.schema();
  12146. }
  12147. return null;
  12148. }
  12149. maybeOperator() {
  12150. if (!this._op) {
  12151. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12152. for (const candidate of candidates) {
  12153. if (this.matches(candidate.schema())) {
  12154. this._op = candidate;
  12155. break;
  12156. }
  12157. }
  12158. }
  12159. return this._op;
  12160. }
  12161. getOperator() {
  12162. const maybe = this.maybeOperator();
  12163. if (maybe) {
  12164. return maybe;
  12165. }
  12166. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12167. }
  12168. getOperation() {
  12169. return this.getOperator().getOperation(this);
  12170. }
  12171. isNondeterministic() {
  12172. const schema = this.maybeSchema();
  12173. if (!this.kind().startsWith('aten::')) {
  12174. return false;
  12175. }
  12176. if (!schema) {
  12177. return false;
  12178. }
  12179. const schema_info = new torch._C.SchemaInfo(schema);
  12180. if (this.hasNamedInput('train')) {
  12181. throw new python.Error('Not Implemented.');
  12182. // const value = constant_as<bool>(this.namedInput("train"));
  12183. // if (value) {
  12184. // schema_info.addArgumentValue('train', value);
  12185. // }
  12186. }
  12187. return schema_info.is_nondeterministic();
  12188. }
  12189. hasSideEffects() {
  12190. switch (this._kind) {
  12191. case 'prim::PythonOp':
  12192. case 'prim::IgnoredPythonOp':
  12193. case 'prim::Print':
  12194. case 'prim::RaiseException':
  12195. case 'aten::warn':
  12196. case 'aten::save':
  12197. case 'aten::manual_seed':
  12198. case 'prim::AddStatValue':
  12199. case 'prim::TimePoint':
  12200. case 'prim::CallFunction':
  12201. case 'prim::CallMethod':
  12202. case 'prim::BailoutTemplate':
  12203. case 'prim::BailOut':
  12204. case 'prim::rpc_async':
  12205. case 'prim::rpc_sync':
  12206. case 'prim::rpc_remote':
  12207. case 'aten::wait':
  12208. case 'cuda::set_stream':
  12209. case 'cuda::_set_device':
  12210. case 'cuda::_current_device':
  12211. case 'cuda::synchronize':
  12212. case 'prim::Enter':
  12213. case 'prim::Exit':
  12214. return true;
  12215. default:
  12216. break;
  12217. }
  12218. const op = this.maybeOperator();
  12219. if (!op) {
  12220. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12221. return false;
  12222. }
  12223. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12224. torch._C.TORCH_INTERNAL_ASSERT(
  12225. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12226. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12227. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12228. }
  12229. switch (op.aliasAnalysisKind()) {
  12230. case 'PURE_FUNCTION':
  12231. case 'FROM_SCHEMA':
  12232. case 'INTERNAL_SPECIAL_CASE':
  12233. return false;
  12234. case 'CONSERVATIVE':
  12235. return true;
  12236. default:
  12237. break;
  12238. }
  12239. torch._C.TORCH_INTERNAL_ASSERT(false);
  12240. return false;
  12241. }
  12242. inputs() {
  12243. return this._inputs;
  12244. }
  12245. outputs() {
  12246. return this._outputs;
  12247. }
  12248. input(i) {
  12249. if (i === undefined) {
  12250. torch._C.AT_ASSERT(this._inputs.length === 1);
  12251. return this._inputs[0];
  12252. }
  12253. return this._inputs[i];
  12254. }
  12255. output(i) {
  12256. if (i === undefined) {
  12257. torch._C.AT_ASSERT(this._outputs.length === 1);
  12258. return this._outputs[0];
  12259. }
  12260. return this._outputs[i];
  12261. }
  12262. hasUses() {
  12263. for (const o of this.outputs()) {
  12264. if (o.uses().length > 0) {
  12265. return true;
  12266. }
  12267. }
  12268. return false;
  12269. }
  12270. blocks() {
  12271. return this._blocks;
  12272. }
  12273. insertInput(i, value) {
  12274. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12275. this._op = null;
  12276. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12277. const use = this.findUseForInput(use_itr);
  12278. use.offset += 1;
  12279. }
  12280. this._inputs.splice(i, 0, value);
  12281. value._uses.push(new torch.Use(this, i));
  12282. return value;
  12283. }
  12284. addInput(value) {
  12285. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12286. this._op = null;
  12287. const use = new torch.Use(this, this._inputs.length);
  12288. value.uses().push(use);
  12289. this._inputs.push(value);
  12290. return value;
  12291. }
  12292. addOutput() {
  12293. const value = new torch.Value(this, this._outputs.length);
  12294. this._outputs.push(value);
  12295. return value;
  12296. }
  12297. addBlock() {
  12298. this._op = null;
  12299. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12300. return this._blocks[this._blocks.length - 1];
  12301. }
  12302. get prev() {
  12303. return this._prev;
  12304. }
  12305. set prev(value) {
  12306. this._prev = value;
  12307. }
  12308. get next() {
  12309. return this._next;
  12310. }
  12311. set next(value) {
  12312. this._next = value;
  12313. }
  12314. insertBefore(n) {
  12315. if (!n.inBlockList()) {
  12316. throw new python.Error('Node not in block.');
  12317. }
  12318. this.insertAfter(n.prev);
  12319. return this;
  12320. }
  12321. insertAfter(n) {
  12322. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12323. torch._C.AT_ASSERT(n.owningBlock());
  12324. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12325. this._owning_block = n.owningBlock();
  12326. const next = n.next;
  12327. n.next = this;
  12328. this.prev = n;
  12329. this.next = next;
  12330. next.prev = this;
  12331. // this.assignTopoPosition();
  12332. return this;
  12333. }
  12334. allocNewInstance(g) {
  12335. return new torch.Node(g, this.kind());
  12336. }
  12337. cloneFrom(s) {
  12338. this._source_range = s._source_range;
  12339. if (s._scope && !s._scope.isBlank()) {
  12340. this._scope = s._scope;
  12341. }
  12342. this.copyAttributes(s);
  12343. this._callstack = s._callstack;
  12344. }
  12345. copyAttributes(rhs) {
  12346. this._values = new Map(rhs._values);
  12347. return this;
  12348. }
  12349. dropInput(i) {
  12350. torch._C.AT_ASSERT(i < this._inputs.length);
  12351. const input_node = this._inputs[i];
  12352. const use_it = this.findUseForInput(i);
  12353. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12354. this._inputs[i] = null;
  12355. return input_node;
  12356. }
  12357. eraseOutput(i) {
  12358. torch._C.AT_ASSERT(i < this._outputs.length);
  12359. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12360. this._op = null;
  12361. const n = this._outputs[i];
  12362. this._outputs.splice(i, 1);
  12363. this.owningGraph().freeValue(n);
  12364. for (let j = i; j < this._outputs.length; j++) {
  12365. this._outputs[j]._offset--;
  12366. }
  12367. }
  12368. eraseBlock(i) {
  12369. this._op = null;
  12370. const n = this._blocks[i];
  12371. this._blocks.splice(i, 1);
  12372. n.destroy();
  12373. }
  12374. findUseForInput(i) {
  12375. const input_uses = this._inputs[i]._uses;
  12376. for (const use_it of input_uses) {
  12377. if (use_it.user === this && use_it.offset === i) {
  12378. return use_it;
  12379. }
  12380. }
  12381. throw new python.Error('Input use not found.');
  12382. }
  12383. moveBefore(n) {
  12384. this.removeFromList();
  12385. this.insertBefore(n);
  12386. }
  12387. removeInput(i) {
  12388. this._op = null;
  12389. this.dropInput(i);
  12390. for (let j = i + 1; j < this._inputs.length; j++) {
  12391. const it = this.findUseForInput(j);
  12392. it.offset--;
  12393. }
  12394. this._inputs.splice(i, 1);
  12395. }
  12396. removeAllInputs() {
  12397. this._op = null;
  12398. for (let i = 0; i < this._inputs.length; i++) {
  12399. this.dropInput(i);
  12400. }
  12401. this._inputs = [];
  12402. }
  12403. inBlockList() {
  12404. return this.next !== null;
  12405. }
  12406. removeFromList() {
  12407. this._owning_block = null;
  12408. const next = this.next;
  12409. const prev = this.prev;
  12410. prev.next = next;
  12411. next.prev = prev;
  12412. this.next = null;
  12413. this.prev = null;
  12414. }
  12415. destroy() {
  12416. while (this.outputs().length > 0) {
  12417. this.eraseOutput(this.outputs().length - 1);
  12418. }
  12419. while (this.blocks().length > 0) {
  12420. this.eraseBlock(this.blocks().length - 1);
  12421. }
  12422. this.removeAllInputs();
  12423. if (this.inBlockList()) {
  12424. this.removeFromList();
  12425. }
  12426. this._graph.freeNode(this);
  12427. }
  12428. replaceAllUsesWith(n) {
  12429. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12430. const nOutputs = this.outputs().length;
  12431. for (let i = 0; i < nOutputs; i++) {
  12432. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12433. }
  12434. }
  12435. s_(name, value) {
  12436. this._values.set(name, [value, 's']);
  12437. return this;
  12438. }
  12439. s(name) {
  12440. return this._values.get(name)[0];
  12441. }
  12442. ss_(name, value) {
  12443. this._values.set(name, [value, 'ss']);
  12444. return this;
  12445. }
  12446. ss(name) {
  12447. return this._values.get(name)[0];
  12448. }
  12449. i_(name, value) {
  12450. this._values.set(name, [value, 'i']);
  12451. return this;
  12452. }
  12453. i(name) {
  12454. return this._values.get(name)[0];
  12455. }
  12456. f_(name, value) {
  12457. this._values.set(name, [value, 'f']);
  12458. return this;
  12459. }
  12460. f(name) {
  12461. return this._values.get(name)[0];
  12462. }
  12463. c_(name, value) {
  12464. this._values.set(name, [value, 'c']);
  12465. return this;
  12466. }
  12467. c(name) {
  12468. return this._values.get(name)[0];
  12469. }
  12470. t_(name, value) {
  12471. this._values.set(name, [value, 't']);
  12472. return this;
  12473. }
  12474. t(name) {
  12475. return this._values.get(name)[0];
  12476. }
  12477. tys_(name, value) {
  12478. this._values.set(name, [value, 'tys']);
  12479. return this;
  12480. }
  12481. tys(name) {
  12482. return this._values.get(name)[0];
  12483. }
  12484. ival_(name, value) {
  12485. this._values.set(name, [value, 'ival']);
  12486. return this;
  12487. }
  12488. ival(name) {
  12489. return this._values.get(name)[0];
  12490. }
  12491. hasAttribute(name) {
  12492. return this._values.has(name);
  12493. }
  12494. hasAttributes() {
  12495. return this._values.size > 0;
  12496. }
  12497. attributeNames() {
  12498. return Array.from(this._values.keys());
  12499. }
  12500. kindOf(name) {
  12501. return this._values.get(name)[1];
  12502. }
  12503. setSourceRange(r) {
  12504. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12505. this._source_range = r;
  12506. return this;
  12507. }
  12508. sourceRange() {
  12509. if (this._source_range) {
  12510. return this._source_range;
  12511. }
  12512. return new torch._C.SourceRange();
  12513. }
  12514. print_attributes(out, ignore_subgraph) {
  12515. ignore_subgraph = ignore_subgraph || false;
  12516. out.write('[');
  12517. const names = this.attributeNames();
  12518. for (let i = 0; i < names.length; i++) {
  12519. const name = names[i];
  12520. if (ignore_subgraph && name === 'Subgraph') {
  12521. continue;
  12522. }
  12523. if (i > 0) {
  12524. out.write(', ');
  12525. }
  12526. out.write(`${name}=`);
  12527. this.printAttrValue(out, name);
  12528. }
  12529. out.write(']');
  12530. }
  12531. printTypeList(out, items) {
  12532. out.write('[');
  12533. for (let i = 0; i < items.length; i++) {
  12534. const item = items[i];
  12535. if (i++ > 0) {
  12536. out.write(', ');
  12537. }
  12538. out.write(item.str());
  12539. }
  12540. out.write(']');
  12541. }
  12542. printAttrValue(out, name) {
  12543. const kind = this.kindOf(name);
  12544. switch (kind) {
  12545. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12546. case 'ss': case 'ival': case 'ty':
  12547. out.write(this[kind](name));
  12548. break;
  12549. case 's':
  12550. out.write(`"${this.s(name)}"`);
  12551. break;
  12552. case 't':
  12553. out.write(`"{}"`);
  12554. break;
  12555. case 'ts': out.write('[<Tensors>]'); break;
  12556. case 'g': out.write('[<Graph>]'); break;
  12557. case 'gs': out.write('[<Graphs>]'); break;
  12558. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12559. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12560. }
  12561. }
  12562. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12563. print_source_locations = print_source_locations === false ? false : true;
  12564. print_attributes = print_attributes === false ? false : true;
  12565. print_scopes = print_scopes === false ? false : true;
  12566. print_body = print_body === false ? false : true;
  12567. const outs = this.outputs();
  12568. torch._C.indent(out, level);
  12569. torch._C.const_value_list_with_types(out, outs, ', ');
  12570. out.write(' = ');
  12571. if (this.kind() === 'prim::PythonOp') {
  12572. throw new python.Error('Not implemented.');
  12573. } else if (this.hasAttribute('Subgraph') && groups) {
  12574. throw new python.Error('Not implemented.');
  12575. } else {
  12576. out.write(this.kind());
  12577. if (print_attributes && this.hasAttributes()) {
  12578. this.print_attributes(out);
  12579. }
  12580. }
  12581. out.write('(');
  12582. torch._C.printValueRefs(out, this.inputs());
  12583. out.write(')');
  12584. if (print_scopes) {
  12585. //
  12586. }
  12587. if (print_source_locations) {
  12588. let r = this.sourceRange();
  12589. if (r.source()) {
  12590. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12591. if (orig) {
  12592. r = orig;
  12593. }
  12594. }
  12595. const file_line_col = r.file_line_col();
  12596. if (file_line_col !== null) {
  12597. const [filename, line, col] = file_line_col;
  12598. out.write(` # ${filename}:${line}:${col}`);
  12599. }
  12600. }
  12601. if (!print_body) {
  12602. return out;
  12603. }
  12604. out.write('\n');
  12605. for (let i = 0; i < this.blocks().length; i++) {
  12606. const b = this.blocks().at(i);
  12607. torch._C.indent(out, level + 1);
  12608. out.write(`block${i}(`);
  12609. torch._C.const_value_list_with_types(out, b.inputs());
  12610. out.write('):\n');
  12611. for (const nested of b.nodes()) {
  12612. nested.print(out, level + 2, groups);
  12613. }
  12614. torch._C.indent(out, level + 2);
  12615. out.write('-> (');
  12616. torch._C.printValueRefs(out, b.outputs());
  12617. out.write(')\n');
  12618. }
  12619. return out;
  12620. }
  12621. toString() {
  12622. const out = new io.StringIO();
  12623. this.print(out, 0, true);
  12624. return out.toString();
  12625. }
  12626. });
  12627. this.registerType('torch.Value', class {
  12628. constructor(node, offset) {
  12629. this._node = node;
  12630. this._offset = offset;
  12631. this._unique = node._graph._next_unique++;
  12632. this._uses = [];
  12633. this._node._graph.all_values.add(this);
  12634. }
  12635. unique() {
  12636. return this._unique;
  12637. }
  12638. node() {
  12639. return this._node;
  12640. }
  12641. owningGraph() {
  12642. return this._node.owningGraph();
  12643. }
  12644. uses() {
  12645. return this._uses;
  12646. }
  12647. hasUses() {
  12648. return this._uses.length > 0;
  12649. }
  12650. mustBeNone() {
  12651. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12652. }
  12653. mustNotBeNone() {
  12654. return this._node.kind() !== 'prim::AutogradAdd' &&
  12655. this.type() !== torch.NoneType.get() &&
  12656. !(this.type() instanceof torch.OptionalType) &&
  12657. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12658. }
  12659. isValidName(name) {
  12660. if (name.length === 0) {
  12661. return true;
  12662. }
  12663. if (torch._C.isNumber(name)) {
  12664. return false;
  12665. }
  12666. return true;
  12667. }
  12668. hasDebugName() {
  12669. return this._unique_name && this._unique_name.length > 0;
  12670. }
  12671. setDebugName(name) {
  12672. if (!this.isValidName(name)) {
  12673. throw new python.Error(`Invalid name '${name}'.`);
  12674. }
  12675. const names = this.node().owningGraph()._unique_names;
  12676. if (this.hasDebugName()) {
  12677. names.delete(this._unique_name);
  12678. this._unique_name = '';
  12679. }
  12680. if (!name) {
  12681. return this;
  12682. }
  12683. const old_owner_of_name = names.get(name);
  12684. if (old_owner_of_name) {
  12685. let suffix = 1;
  12686. let name_base = name;
  12687. const last_dot_pos = name.lastIndexOf('.');
  12688. if (last_dot_pos !== -1) {
  12689. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12690. suffix = Number(name.substring(last_dot_pos + 1));
  12691. name_base = name.substring(0, last_dot_pos);
  12692. }
  12693. }
  12694. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12695. if (names_suffixes.has(name_base)) {
  12696. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12697. }
  12698. let replacement_name = null;
  12699. do {
  12700. replacement_name = `${name_base}.${suffix++}`;
  12701. } while (names.has(replacement_name));
  12702. names_suffixes.set(name_base, suffix);
  12703. old_owner_of_name.setDebugName(replacement_name);
  12704. }
  12705. names.set(name, this);
  12706. this._unique_name = name;
  12707. return this;
  12708. }
  12709. debugName() {
  12710. if (this.hasDebugName()) {
  12711. return this._unique_name;
  12712. }
  12713. return this.unique().toString();
  12714. }
  12715. type() {
  12716. return this._type;
  12717. }
  12718. setType(type) {
  12719. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12720. if (type instanceof torch._C.DynamicType) {
  12721. type = type.fallback();
  12722. }
  12723. this._type = type;
  12724. for (const use of this._uses) {
  12725. use.user._op = null;
  12726. }
  12727. return this;
  12728. }
  12729. set value(value) { // remove
  12730. if (value instanceof torch.Value) {
  12731. throw new python.Error('Value cannot be a value.');
  12732. }
  12733. this._value = value;
  12734. }
  12735. get value() { // remove
  12736. return this._value;
  12737. }
  12738. replaceFirstUseWith(newValue) {
  12739. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12740. const [u] = this.uses();
  12741. u.user._inputs[u.offset] = newValue;
  12742. newValue._uses.push(u);
  12743. this._uses.shift();
  12744. }
  12745. replaceAllUsesWith(newValue) {
  12746. while (this.uses().length > 0) {
  12747. this.replaceFirstUseWith(newValue);
  12748. }
  12749. }
  12750. copyMetadata(from) {
  12751. this.setType(from.type());
  12752. if (from.hasDebugName()) {
  12753. this.setDebugName(from.debugName());
  12754. }
  12755. return this;
  12756. }
  12757. toString() {
  12758. return `${this.debugName()} : ${this.type().toString()}`;
  12759. }
  12760. });
  12761. this.registerType('torch.Use', class {
  12762. constructor(user, offset) {
  12763. this.user = user;
  12764. this.offset = offset;
  12765. }
  12766. });
  12767. this.registerType('torch._C.IValue', class {
  12768. constructor(value, tag) {
  12769. this.value = value;
  12770. if (tag) {
  12771. this.tag = tag;
  12772. } else if (value === undefined) {
  12773. this.tag = 'None';
  12774. this.value = null;
  12775. } else if (typeof value === 'boolean') {
  12776. this.tag = 'Bool';
  12777. } else if (typeof value === 'string') {
  12778. this.tag = 'String';
  12779. } else if (value instanceof torch.Tensor) {
  12780. this.tag = 'Tensor';
  12781. } else if (value instanceof torch.ScriptObject) {
  12782. this.tag = 'Object';
  12783. } else if (Array.isArray(value)) {
  12784. this.tag = 'GenericList';
  12785. } else if (value instanceof torch._C.Tuple) {
  12786. this.tag = 'Tuple';
  12787. } else if (value instanceof torch.device) {
  12788. this.tag = 'Device';
  12789. } else if (Number.isInteger(value)) {
  12790. this.tag = 'Int';
  12791. } else if (typeof value === 'number') {
  12792. this.tag = 'Double';
  12793. } else if (value instanceof builtins.complex) {
  12794. this.tag = 'ComplexDouble';
  12795. } else if (value instanceof torch._C.EnumHolder) {
  12796. this.tag = 'Enum';
  12797. } else {
  12798. throw new python.Error('Unsupported type.');
  12799. }
  12800. }
  12801. isNone() {
  12802. return this.tag === 'None';
  12803. }
  12804. isBool() {
  12805. return this.tag === 'Bool';
  12806. }
  12807. toBool() {
  12808. return this.value;
  12809. }
  12810. isObject() {
  12811. return this.tag === 'Object';
  12812. }
  12813. toObject() {
  12814. return this.value;
  12815. }
  12816. isTensor() {
  12817. return this.tag === 'Tensor';
  12818. }
  12819. toTensor() {
  12820. return this.value;
  12821. }
  12822. isDouble() {
  12823. return this.tag === 'Double';
  12824. }
  12825. toDouble() {
  12826. return this.value;
  12827. }
  12828. isComplexDouble() {
  12829. return this.tag === 'ComplexDouble' || this.tag === 'Complex';
  12830. }
  12831. toComplexDouble() {
  12832. return this.value;
  12833. }
  12834. isInt() {
  12835. return this.tag === 'Int';
  12836. }
  12837. toInt() {
  12838. if (this.isInt()) {
  12839. return this.value;
  12840. } else if (this.isSymInt()) {
  12841. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12842. }
  12843. throw new python.Error('Expected int.');
  12844. }
  12845. isString() {
  12846. return this.tag === 'String';
  12847. }
  12848. toStringRef() {
  12849. return this.value;
  12850. }
  12851. isList() {
  12852. return this.tag === 'GenericList';
  12853. }
  12854. toList() {
  12855. return this.value;
  12856. }
  12857. toListRef() {
  12858. return this.value;
  12859. }
  12860. isBoolList() {
  12861. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12862. }
  12863. isIntList() {
  12864. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12865. }
  12866. isDoubleList() {
  12867. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12868. }
  12869. isDevice() {
  12870. return this.tag === 'Device';
  12871. }
  12872. toDevice() {
  12873. return this.value;
  12874. }
  12875. isGenerator() {
  12876. return this.tag === 'Generator';
  12877. }
  12878. isStream() {
  12879. return this.tag === 'Stream';
  12880. }
  12881. isGenericDict() {
  12882. return this.tag === 'GenericDict';
  12883. }
  12884. isEnum() {
  12885. return this.tag === 'Enum';
  12886. }
  12887. toEnumHolder() {
  12888. return this.value;
  12889. }
  12890. isTuple() {
  12891. return this.tag === 'Tuple';
  12892. }
  12893. toTupleRef() {
  12894. return this.value;
  12895. }
  12896. isCustomClass() {
  12897. return torch._C.isCustomClass(this);
  12898. }
  12899. equals(rhs) {
  12900. switch (this.tag) {
  12901. case 'None': return rhs.isNone();
  12902. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  12903. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  12904. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  12905. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  12906. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  12907. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  12908. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  12909. case 'GenericList': {
  12910. if (rhs.isList()) {
  12911. const a = this.toList();
  12912. const b = rhs.toList();
  12913. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  12914. }
  12915. return false;
  12916. }
  12917. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  12918. }
  12919. }
  12920. is(rhs) {
  12921. return this.equals(rhs);
  12922. }
  12923. type() {
  12924. switch (this.tag) {
  12925. case 'None': return torch.NoneType.get();
  12926. case 'Bool': return torch.BoolType.get();
  12927. case 'Int': return torch.IntType.get();
  12928. case 'Double': return torch.FloatType.get();
  12929. case 'String': return torch.StringType.get();
  12930. case 'Device': return torch.DeviceObjType.get();
  12931. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  12932. case 'Enum': return this.toEnumHolder().type();
  12933. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  12934. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  12935. }
  12936. }
  12937. });
  12938. this.registerFunction('torch._C.indent', (out, level) => {
  12939. for (let i = 0; i < level; i++) {
  12940. out.write(' ');
  12941. }
  12942. return out;
  12943. });
  12944. this.registerFunction('torch._C.printValueRef', (out, n) => {
  12945. out.write(`%${n.debugName()}`);
  12946. });
  12947. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  12948. for (let i = 0; i < nodes.length; i++) {
  12949. const n = nodes[i];
  12950. if (i > 0) {
  12951. out.write(', ');
  12952. }
  12953. torch._C.printValueRef(out, n);
  12954. }
  12955. return out;
  12956. });
  12957. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  12958. for (let i = 0; i < values.length; i++) {
  12959. const n = values[i];
  12960. if (i > 0) {
  12961. out.write(delim);
  12962. }
  12963. torch._C.printValueRef(out, n);
  12964. out.write(' : ');
  12965. out.write(n.type().str());
  12966. }
  12967. });
  12968. this.register('torch.jit._script');
  12969. this.register('torch.jit._trace');
  12970. this.registerType('torch._C.Parser', class {
  12971. constructor(source) {
  12972. this.L = source;
  12973. }
  12974. parse() {
  12975. const p = ast.parse(this.L.text_str(), this.L.filename());
  12976. return p;
  12977. }
  12978. parseExp() {
  12979. const expr = ast.parse(this.L.text_str());
  12980. return expr.body[0].value;
  12981. }
  12982. });
  12983. this.registerType('torch._C.StringCordView', class {
  12984. });
  12985. this.registerType('torch._C.Source', class {
  12986. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  12987. if (text_view instanceof Uint8Array) {
  12988. const decoder = new TextDecoder('utf-8');
  12989. this._text_view = decoder.decode(text_view);
  12990. } else if (typeof text_view === 'string') {
  12991. this._text_view = text_view;
  12992. } else {
  12993. throw new python.Error('Invalid text view.');
  12994. }
  12995. this._filename = filename;
  12996. this._starting_line_no = starting_line_no;
  12997. this._gen_ranges = gen_ranges;
  12998. this.calc_line_start_offsets();
  12999. }
  13000. text_str() {
  13001. return this._text_view;
  13002. }
  13003. size() {
  13004. return this._text_view.length;
  13005. }
  13006. filename() {
  13007. return this._filename;
  13008. }
  13009. calc_line_start_offsets() {
  13010. let pos = 0;
  13011. this._line_starting_offsets = [0];
  13012. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  13013. pos += 1;
  13014. this._line_starting_offsets.push(pos);
  13015. }
  13016. }
  13017. offset_for_line(line) {
  13018. return this._line_starting_offsets[line];
  13019. }
  13020. lineno_for_offset(offset) {
  13021. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  13022. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  13023. }
  13024. lineno_to_source_lineno(lineno) {
  13025. if (this._filename) {
  13026. return lineno + this._starting_line_no;
  13027. }
  13028. return lineno;
  13029. }
  13030. findSourceRangeThatGenerated(range) {
  13031. if (!this._gen_ranges) {
  13032. return null;
  13033. }
  13034. return this._gen_ranges.findSourceRangeThatGenerated(range);
  13035. }
  13036. });
  13037. this.registerType('torch._C.SourceRange', class {
  13038. constructor(...args) {
  13039. if (args.length === 0) {
  13040. this._source_view = null;
  13041. } else if (args.length === 2) {
  13042. let node = null;
  13043. [this._source_view, node] = args;
  13044. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  13045. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  13046. } else if (args.length === 3) {
  13047. [this._source_view, this._start, this._end] = args;
  13048. } else {
  13049. throw new python.Error('Not implemented.');
  13050. }
  13051. }
  13052. source() {
  13053. return this._source_view;
  13054. }
  13055. file_line_col() {
  13056. if (!this._source_view || this.source().filename() === null) {
  13057. return null;
  13058. }
  13059. const lineno = this._source_view.lineno_for_offset(this._start);
  13060. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  13061. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  13062. }
  13063. start() {
  13064. return this._start;
  13065. }
  13066. toString() {
  13067. const loc = this.file_line_col();
  13068. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  13069. }
  13070. });
  13071. this.registerType('torch._C.QualifiedName', class {
  13072. constructor(...args) {
  13073. let name = null;
  13074. if (args.length === 1 && typeof args[0] === 'string') {
  13075. [name] = args;
  13076. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13077. name = args[0].join('.');
  13078. } else {
  13079. name = `${args[0].qualifiedName()}.${args[1]}`;
  13080. }
  13081. const index = name.lastIndexOf('.');
  13082. this._qualifiedName = name;
  13083. this._prefix = index === -1 ? '' : name.substring(0, index);
  13084. this._name = index === -1 ? name : name.substring(index + 1);
  13085. }
  13086. qualifiedName() {
  13087. return this._qualifiedName; // "foo.bar.baz"
  13088. }
  13089. prefix() {
  13090. return this._prefix; // "foo.bar"
  13091. }
  13092. name() {
  13093. return this._name; // "baz"
  13094. }
  13095. atoms() {
  13096. return this._qualifiedName.split('.');
  13097. }
  13098. });
  13099. this.registerType('torch._C.Resolver', class {
  13100. resolveValue() {
  13101. throw new python.Error('Not implemented.');
  13102. }
  13103. resolveType() {
  13104. throw new python.Error('Not implemented.');
  13105. }
  13106. });
  13107. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13108. torch._C.customClasses = torch._C.customClasses || new Map();
  13109. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13110. const name = class_type.name().qualifiedName();
  13111. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13112. torch._C.customClasses.set(name, class_type);
  13113. });
  13114. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13115. torch._C.customClasses = torch._C.customClasses || new Map();
  13116. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13117. return ret;
  13118. });
  13119. this.registerFunction('torch._C.isCustomClass', (v) => {
  13120. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13121. });
  13122. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13123. constructor(cu, constant_table, source_loader, version) {
  13124. super();
  13125. this._cu = cu;
  13126. this._constant_table = constant_table;
  13127. this._source_loader = source_loader;
  13128. this._version = version;
  13129. this._loaded_sources = new Set();
  13130. this._sources = new Map();
  13131. const sources = this._sources;
  13132. ast.AST.prototype.range = function() {
  13133. if (!this._range) {
  13134. if (sources.has(this.filename)) {
  13135. const source_view = sources.get(this.filename);
  13136. this._range = new torch._C.SourceRange(source_view, this);
  13137. } else {
  13138. this._range = new torch._C.SourceRange();
  13139. }
  13140. }
  13141. return this._range;
  13142. };
  13143. this._to_be_defined = new Map();
  13144. this._env = new Map([
  13145. ['torch', new torch._C.BuiltinModule('aten', version)],
  13146. ['ops', new torch._C.OpsValue(version)],
  13147. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13148. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13149. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13150. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13151. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13152. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13153. ]);
  13154. }
  13155. loadType(name) {
  13156. const type_parser = new torch._C.ScriptTypeParser(this);
  13157. return type_parser.parseType(name.qualifiedName());
  13158. }
  13159. resolveType(name) {
  13160. name = new torch._C.QualifiedName(name);
  13161. return this.findNamedType(name);
  13162. }
  13163. resolveValue(name, m, loc) {
  13164. if (this._env.has(name)) {
  13165. return this._env.get(name);
  13166. }
  13167. const graph = m.graph();
  13168. switch (name) {
  13169. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13170. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13171. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13172. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13173. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13174. default: return null;
  13175. }
  13176. }
  13177. findNamedType(name) {
  13178. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13179. if (custom_class) {
  13180. return custom_class;
  13181. }
  13182. this.parseSourceIfNeeded(name.prefix());
  13183. const key = name.qualifiedName();
  13184. const it = this._to_be_defined.get(key);
  13185. if (it && it instanceof ast.ClassDef) {
  13186. this._to_be_defined.delete(key);
  13187. this.importNamedType(name.prefix(), it);
  13188. }
  13189. return this._cu.get_type(name);
  13190. }
  13191. importNamedType(qualifier, class_def) {
  13192. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13193. if (class_def.bases.length === 0) {
  13194. this.importClass(qualified_name, class_def, false);
  13195. return;
  13196. }
  13197. const superclass_name = class_def.bases[0].id;
  13198. if (superclass_name === 'Module') {
  13199. this.importClass(qualified_name, class_def, true);
  13200. } else if (superclass_name === 'NamedTuple') {
  13201. this.importNamedTuple(qualified_name, class_def);
  13202. } else if (superclass_name === 'Interface') {
  13203. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13204. } else if (superclass_name === 'ModuleInterface') {
  13205. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13206. } else if (superclass_name === 'Enum') {
  13207. this.importEnum(qualified_name, class_def);
  13208. } else {
  13209. throw new python.Error('TorchScript does not support class inheritance.');
  13210. }
  13211. }
  13212. importClass(qualified_classname, class_def, is_module) {
  13213. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13214. return;
  13215. }
  13216. const parameter_names = new Set();
  13217. const buffer_names = new Set();
  13218. const methods = [];
  13219. const method_resolvers = [];
  13220. const attributes = [];
  13221. const constants = [];
  13222. const pre_hook_names = new Set();
  13223. const pre_hook_def_map = new Map();
  13224. const hook_names = new Set();
  13225. const hook_def_map = new Map();
  13226. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13227. for (const stmt of class_def.body) {
  13228. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13229. let target = null;
  13230. let annotation = null;
  13231. let value = null;
  13232. if (stmt instanceof ast.Assign) {
  13233. [target] = stmt.targets;
  13234. value = stmt.value;
  13235. } else {
  13236. target = stmt.target;
  13237. annotation = stmt.annotation;
  13238. value = stmt.value;
  13239. }
  13240. if (target instanceof ast.Name) {
  13241. const name = this._cu.execution.identifier(target);
  13242. switch (name) {
  13243. case '__annotations__': {
  13244. continue;
  13245. }
  13246. case '__parameters__': {
  13247. for (const elt of value.elts) {
  13248. parameter_names.add(elt.value);
  13249. }
  13250. break;
  13251. }
  13252. case '__buffers__': {
  13253. for (const elt of value.elts) {
  13254. buffer_names.add(elt.value);
  13255. }
  13256. break;
  13257. }
  13258. case '__forward_pre_hooks__': {
  13259. for (const elt of value.elts) {
  13260. pre_hook_names.add(elt.value);
  13261. }
  13262. break;
  13263. }
  13264. case '__forward_hooks__': {
  13265. for (const elt of value.elts) {
  13266. hook_names.add(elt.value);
  13267. }
  13268. break;
  13269. }
  13270. default: {
  13271. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13272. if (fixed_up) {
  13273. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13274. } else if (value) {
  13275. constants.push({ name, value, annotation });
  13276. } else {
  13277. attributes.push({ name, value, annotation });
  13278. }
  13279. break;
  13280. }
  13281. }
  13282. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13283. const name = target.slice.value;
  13284. attributes.push({ name, value, annotation: stmt.value });
  13285. continue;
  13286. } else {
  13287. throw new python.Error('Unexpected statement kind in module metadata.');
  13288. }
  13289. } else if (stmt instanceof ast.FunctionDef) {
  13290. const def = stmt;
  13291. const def_name = def.name;
  13292. if (pre_hook_names.has(def_name)) {
  13293. pre_hook_def_map.set(def_name, def);
  13294. } else if (hook_names.has(def_name)) {
  13295. hook_def_map.set(def_name, def);
  13296. } else {
  13297. methods.push(def);
  13298. method_resolvers.push(this);
  13299. }
  13300. } else {
  13301. throw new python.Error('Unexpected statement kind in class body.');
  13302. }
  13303. }
  13304. const type_parser = new torch._C.ScriptTypeParser(this);
  13305. for (const assign of attributes) {
  13306. const name = assign.name;
  13307. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13308. const is_parameter = parameter_names.has(name);
  13309. const is_buffer = buffer_names.has(name);
  13310. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13311. }
  13312. for (const constant of constants) {
  13313. class_type.addConstant(constant.name, constant.value);
  13314. }
  13315. this._cu.register_type(class_type);
  13316. const self = new torch._C.SimpleSelf(class_type);
  13317. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13318. }
  13319. importEnum(qualified_name, enum_def) {
  13320. const names_values = [];
  13321. let value_type = null;
  13322. const set_or_check_type = (t) => {
  13323. if (!value_type) {
  13324. value_type = t;
  13325. } else if (value_type !== t) {
  13326. throw new python.Error('Enum class with varying value types are not supported.');
  13327. }
  13328. };
  13329. for (const stmt of enum_def.body) {
  13330. if (stmt instanceof ast.Assign === false) {
  13331. throw new python.Error('Unexpected statement in Enum class body.');
  13332. }
  13333. const assign = stmt;
  13334. const name = assign.targets[0].id;
  13335. let ivalue = null;
  13336. const rhs = assign.value;
  13337. switch (rhs.type) {
  13338. case 'str':
  13339. ivalue = new torch._C.IValue(rhs.value, 'String');
  13340. set_or_check_type(torch.StringType.get());
  13341. break;
  13342. case 'int':
  13343. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13344. set_or_check_type(torch.IntType.get());
  13345. break;
  13346. case 'float':
  13347. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13348. set_or_check_type(torch.FloatType.get());
  13349. break;
  13350. default:
  13351. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13352. }
  13353. names_values.push([name, ivalue]);
  13354. }
  13355. if (!value_type) {
  13356. throw new python.Error('No enum values defined.');
  13357. }
  13358. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13359. this._cu.register_type(enum_type);
  13360. }
  13361. importNamedTuple(qualified_name, named_tuple_def) {
  13362. const type_parser = new torch._C.ScriptTypeParser(this);
  13363. const field_names = [];
  13364. const field_types = [];
  13365. const field_defaults = [];
  13366. for (const stmt of named_tuple_def.body) {
  13367. if (stmt instanceof ast.AnnAssign === false) {
  13368. throw new python.Error('Unexpected statement in NamedTuple body.');
  13369. }
  13370. const assign = stmt;
  13371. const target = this._cu.execution.identifier(stmt.target);
  13372. // const annotation = this._cu.execution.type(stmt.annotation);
  13373. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13374. field_names.push(target);
  13375. // field_types.push(annotation);
  13376. field_types.push(type);
  13377. }
  13378. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13379. this._cu.register_type(tt);
  13380. }
  13381. importFunction(qualifier, def) {
  13382. const definitions = [def];
  13383. const resolvers = [this];
  13384. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13385. }
  13386. parseSourceIfNeeded(qualifier) {
  13387. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13388. return;
  13389. }
  13390. this._loaded_sources.add(qualifier);
  13391. const src = this._source_loader(qualifier);
  13392. if (!src) {
  13393. return;
  13394. }
  13395. this._sources.set(src.filename(), src);
  13396. const p = new torch._C.Parser(src);
  13397. const L = p.parse();
  13398. this.parsePossibleVersionNumber(p);
  13399. for (const stmt of L.body) {
  13400. if (stmt instanceof ast.ClassDef) {
  13401. const name = `${qualifier}.${stmt.name}`;
  13402. this._to_be_defined.set(name, stmt);
  13403. } else if (stmt instanceof ast.FunctionDef) {
  13404. const name = `${qualifier}.${stmt.name}`;
  13405. this._to_be_defined.set(name, stmt);
  13406. }
  13407. }
  13408. }
  13409. parsePossibleVersionNumber(/* p */) {
  13410. }
  13411. parseImports(/* p */) {
  13412. }
  13413. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13414. const replacements = new Map([
  13415. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13416. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13417. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13418. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13419. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13420. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13421. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13422. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13423. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13424. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13425. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13426. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13427. ]);
  13428. const mangleRe = /\.___torch_mangle_\d+/g;
  13429. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13430. if (replacements.has(demangled_classname)) {
  13431. const lhs = assign.target;
  13432. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13433. return null;
  13434. }
  13435. const type = assign.annotation.id;
  13436. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13437. if (lhs.id === attr_name && type === expected_type) {
  13438. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13439. const typename_expr = p.parseExp();
  13440. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13441. }
  13442. }
  13443. return null;
  13444. }
  13445. LEGACY_import_methods(mod, src) {
  13446. const self = new torch._C.SimpleSelf(mod.type());
  13447. const prefix = mod.type().name();
  13448. const p = new torch._C.Parser(src);
  13449. const L = p.parse();
  13450. this.parsePossibleVersionNumber(L);
  13451. this.parseImports(L);
  13452. const definitions = [];
  13453. const resolvers = [];
  13454. for (const def of L.body) {
  13455. if (def instanceof ast.FunctionDef) {
  13456. definitions.push(def);
  13457. resolvers.push(this);
  13458. }
  13459. }
  13460. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13461. }
  13462. findFunction(name) {
  13463. this.parseSourceIfNeeded(name.prefix());
  13464. const key = name.qualifiedName();
  13465. const it = this._to_be_defined.get(key);
  13466. if (it && it instanceof ast.FunctionDef) {
  13467. this._to_be_defined.delete(key);
  13468. this.importFunction(name.prefix(), it);
  13469. }
  13470. return this._cu.find_function(name);
  13471. }
  13472. });
  13473. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13474. constructor(otherResolver, functionTable) {
  13475. super();
  13476. this._otherResolver = otherResolver;
  13477. this._functionTable = functionTable;
  13478. }
  13479. resolveValue(name, m, loc) {
  13480. const it = this._functionTable.get(name);
  13481. if (it) {
  13482. return new torch._C.FunctionValue(it);
  13483. }
  13484. return this._otherResolver.resolveValue(name, m, loc);
  13485. }
  13486. resolveType(name, loc) {
  13487. return this._otherResolver.resolveType(name, loc);
  13488. }
  13489. });
  13490. this.registerType('torch._C.SourceRangeDeserializer', class {
  13491. constructor(text_table) {
  13492. this.cached_sources = new Map();
  13493. this._text_table = text_table || [];
  13494. }
  13495. deserialize(iv) {
  13496. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13497. const [file, start, end] = iv;
  13498. const source = this.deserialize_source(file);
  13499. return new torch._C.SourceRange(source, start, end);
  13500. }
  13501. deserialize_source(iv) {
  13502. const tup = iv;
  13503. if (this.cached_sources.has(tup)) {
  13504. return this.cached_sources.get(tup);
  13505. }
  13506. let source = null;
  13507. const tup_elems = tup;
  13508. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13509. if (this._text_table.length > 0) {
  13510. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13511. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13512. const filename = this._text_table[fnameIndex];
  13513. const pieces = [];
  13514. const strs = [];
  13515. for (const i of textIndex) {
  13516. pieces.push(this._text_table[i]);
  13517. strs.push(this._text_table[i]);
  13518. }
  13519. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13520. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13521. } else {
  13522. const [text, filename, starting_line_no] = tup_elems;
  13523. source = new torch._C.Source(text, filename, starting_line_no);
  13524. }
  13525. this.cached_sources.set(tup, source);
  13526. return source;
  13527. }
  13528. });
  13529. this.registerType('torch._C.SourceRangeUnpickler', class {
  13530. });
  13531. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13532. constructor (data) {
  13533. super();
  13534. this.data = data;
  13535. this.deserializer = null;
  13536. this.unpickled_records = null;
  13537. }
  13538. unpickle() {
  13539. if (this.unpickled_records) {
  13540. return;
  13541. }
  13542. const unpickler = new pickle.Unpickler(this.data);
  13543. const ivalues = unpickler.load();
  13544. torch._C.TORCH_CHECK(ivalues.length > 0);
  13545. this.unpickled_records = [];
  13546. let lines = null;
  13547. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13548. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13549. lines = ivalues[2];
  13550. } else {
  13551. this.deserializer = new torch._C.SourceRangeDeserializer();
  13552. lines = ivalues;
  13553. }
  13554. for (const tup_elems of lines) {
  13555. const [offset, range] = tup_elems;
  13556. const source_range = this.deserializer.deserialize(range);
  13557. this.unpickled_records.push([offset, source_range]);
  13558. }
  13559. }
  13560. findSourceRangeThatGenerated(range) {
  13561. this.unpickle();
  13562. const start = range.start();
  13563. const records = this.unpickled_records;
  13564. for (let i = 0; i < records.length; i++) {
  13565. const [offset, target] = records[i];
  13566. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13567. if (start >= offset && start < next) {
  13568. return target;
  13569. }
  13570. }
  13571. return null;
  13572. }
  13573. });
  13574. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13575. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13576. });
  13577. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13578. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13579. if (!reader.has_record(path)) {
  13580. return null;
  13581. }
  13582. const stream = reader.get_record(path);
  13583. let gen_ranges = null;
  13584. const debug_file = `${path}.debug_pkl`;
  13585. if (reader.has_record(debug_file)) {
  13586. const debug_stream = reader.get_record(debug_file);
  13587. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13588. }
  13589. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13590. });
  13591. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13592. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13593. this._compilation_unit = cu;
  13594. this._reader = reader;
  13595. this._storage_context = storage_context;
  13596. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13597. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13598. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13599. this._constant_table = [];
  13600. const SourceLoader = (qualifier) => {
  13601. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13602. };
  13603. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13604. }
  13605. deserialize() {
  13606. const execution = this._compilation_unit.execution;
  13607. const code_prefix = this._code_prefix;
  13608. for (const name of this._reader.get_all_records()) {
  13609. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13610. const file = name.substring(code_prefix.length);
  13611. const stream = this._reader.get_record(name);
  13612. const buffer = stream.peek();
  13613. execution.add(file, buffer);
  13614. }
  13615. }
  13616. const torch = execution.import('torch');
  13617. execution.builtins.torch = torch;
  13618. execution.builtins.Tensor = torch.Tensor;
  13619. execution.builtins.ops = torch.ops;
  13620. execution.builtins.inf = torch.inf;
  13621. execution.builtins.CONSTANTS = {};
  13622. execution._resolver = this._source_importer;
  13623. if (this._reader.has_record('model.json')) {
  13624. return this.LEGACY_deserialize();
  13625. }
  13626. const constants = this.readArchive('constants');
  13627. for (let i = 0; i < constants.length; i++) {
  13628. let val = constants[i];
  13629. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13630. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13631. const obj = torch.ScriptObject.create(type);
  13632. obj._ivalue = val;
  13633. val = obj;
  13634. }
  13635. execution.builtins.CONSTANTS[`c${i}`] = val;
  13636. this._constant_table.push(val);
  13637. }
  13638. const obj = this.readArchive('data');
  13639. const convertObject = (obj) => {
  13640. if (obj.__class__) {
  13641. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13642. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13643. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13644. for (let i = 0; i < type.numAttributes(); i++) {
  13645. const k = type.getAttributeName(i);
  13646. const t = type.getAttribute(i);
  13647. const v = obj[k];
  13648. if (t instanceof torch.ClassType) {
  13649. module.__setattr__(k, convertObject(v));
  13650. } else {
  13651. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13652. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13653. type._attributes[i].type = this._source_importer.resolveType(name);
  13654. }
  13655. module.__setattr__(k, obj[k]);
  13656. }
  13657. }
  13658. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13659. if (value && value.__class__ === builtins.method) {
  13660. module[key] = value;
  13661. }
  13662. }
  13663. return module;
  13664. }
  13665. throw new python.Error('Module class not found.');
  13666. };
  13667. return convertObject(obj);
  13668. }
  13669. LEGACY_deserialize() {
  13670. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13671. const execution = this._compilation_unit.execution;
  13672. const caffe2 = execution.proto.caffe2;
  13673. const torch = execution.import('torch');
  13674. const stream = this._reader.get_record('model.json');
  13675. const buffer = stream.peek();
  13676. const decoder = new TextDecoder('utf-8');
  13677. const content = decoder.decode(buffer);
  13678. const obj = JSON.parse(content);
  13679. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13680. const tensorTypeMap = new Map([
  13681. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13682. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13683. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13684. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13685. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13686. [caffe2.TensorProto.DataType.INT64, 'Long']
  13687. ]);
  13688. const tensor_table = (model.tensors || []).map((constant) => {
  13689. const key = constant.data.key;
  13690. if (!tensorTypeMap.has(constant.data_type)) {
  13691. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13692. }
  13693. const type = tensorTypeMap.get(constant.data_type);
  13694. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13695. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13696. const storage_type = execution.resolve(`torch.${type}Storage`);
  13697. const size = (shape || []).reduce((a, b) => a * b, 1);
  13698. const offset = parseInt(constant.offset, 10) || 0;
  13699. const storage = new storage_type(size);
  13700. const itemsize = storage.dtype.itemsize();
  13701. const stream = this._reader.get_record(key);
  13702. if (stream) {
  13703. const buffer = stream.peek();
  13704. const length = size * itemsize;
  13705. const data = buffer.slice(offset, offset + length);
  13706. storage._set_cdata(data);
  13707. }
  13708. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13709. tensor.name = key;
  13710. return tensor;
  13711. });
  13712. execution.builtins.CONSTANTS = {};
  13713. for (let i = 0; i < tensor_table.length; i++) {
  13714. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13715. }
  13716. const attributes = [];
  13717. if (this._reader.has_record('attributes.pkl')) {
  13718. const stream = this._reader.get_record('attributes.pkl');
  13719. const buffer = stream.peek();
  13720. const unpickler = new pickle.Unpickler(buffer);
  13721. const obj = unpickler.load();
  13722. attributes.push(...obj);
  13723. }
  13724. this._LEGACY_moduleStack = ['__torch__'];
  13725. const module_def = model.main_module;
  13726. for (const tensor of tensor_table) {
  13727. this._constant_table.push(tensor);
  13728. }
  13729. return this.LEGACY_convertModule(module_def);
  13730. }
  13731. LEGACY_convertModule(module_def) {
  13732. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13733. const numPushed = atoms.length;
  13734. for (const atom of atoms) {
  13735. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13736. this._LEGACY_moduleStack.push(sanitized);
  13737. }
  13738. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13739. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13740. for (const sub_def of module_def.submodules || []) {
  13741. const submodule = this.LEGACY_convertModule(sub_def);
  13742. module.register_module(sub_def.name, submodule);
  13743. }
  13744. for (const param_def of module_def.parameters || []) {
  13745. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13746. if (param_def.isBuffer) {
  13747. module.register_buffer(param_def.name, tensor);
  13748. } else {
  13749. module.register_parameter(param_def.name, tensor, false);
  13750. }
  13751. }
  13752. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13753. for (const attr_def of module_def.attributes || []) {
  13754. if (module.hasattr(attr_def.name)) {
  13755. continue;
  13756. }
  13757. throw new python.Error('Not implemented.');
  13758. // IValue ivalue;
  13759. // if (attr_def.id() >= 0) {
  13760. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13761. // }
  13762. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13763. }
  13764. if (module_def.torchscript_arena) {
  13765. const key = module_def.torchscript_arena.key;
  13766. const file = key.substring('code/'.length);
  13767. const name = file.replace(/\.py$/, '').split('/').join('.');
  13768. const code = execution.import(name);
  13769. if (code.forward.__class__ === execution.builtins.function) {
  13770. module.forward = code.forward;
  13771. }
  13772. }
  13773. // let gen_ranges = null;
  13774. if (module_def.torchscript_debug_arena) {
  13775. throw new python.Error('Not implemented.');
  13776. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13777. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13778. }
  13779. if (module_def.torchscript_arena) {
  13780. const filename = module_def.torchscript_arena.key;
  13781. const stream = this._reader.get_record(filename);
  13782. const data = stream.peek();
  13783. const src = new torch._C.Source(data, filename);
  13784. this._source_importer.LEGACY_import_methods(module, src);
  13785. }
  13786. if (module_def.get_state_attribute_id) {
  13787. throw new python.Error('Not implemented.');
  13788. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13789. }
  13790. /*
  13791. const module_type = module._ivalue().type();
  13792. const N = module_type.numAttributes();
  13793. for (let i = 0; i < N; ++i) {
  13794. const v = module._ivalue().getSlot(i);
  13795. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13796. torch._C.TORCH_CHECK(!v.isNone());
  13797. }
  13798. }
  13799. */
  13800. for (let i = 0; i < numPushed; i++) {
  13801. this._LEGACY_moduleStack.pop();
  13802. }
  13803. return module;
  13804. }
  13805. readArchive(archive_name) {
  13806. const type_resolver = (qn) => {
  13807. const cls = this._source_importer.loadType(qn);
  13808. return cls;
  13809. };
  13810. const ObjLoaderFunc = (/* type, ivalue */) => {
  13811. };
  13812. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13813. }
  13814. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13815. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13816. const stream = stream_reader.get_record(picklename);
  13817. if (!stream) {
  13818. throw new python.Error(`File '${picklename}' is not found.`);
  13819. }
  13820. const buffer = stream.peek();
  13821. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13822. const read_record = (name) => {
  13823. const stream = stream_reader.get_record(tensor_dir_path + name);
  13824. return stream.length <= 0x40000 ? stream.peek() : stream;
  13825. };
  13826. const execution = this._compilation_unit.execution;
  13827. const pickle = execution.__import__('pickle');
  13828. const Unpickler = class extends pickle.Unpickler {
  13829. find_class(module, name) {
  13830. return super.find_class(module, name);
  13831. }
  13832. };
  13833. const unpickler = new Unpickler(buffer);
  13834. unpickler.persistent_load = (saved_id) => {
  13835. if (saved_id[0] !== 'storage') {
  13836. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13837. }
  13838. const [, storage_type, key, , size] = saved_id;
  13839. if (storage_context && storage_context.has_storage(key)) {
  13840. return storage_context.get_storage(key);
  13841. }
  13842. const storage = new storage_type(size);
  13843. if (!storage._set_cdata) {
  13844. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  13845. }
  13846. const storage_ptr = read_record(key);
  13847. storage._set_cdata(storage_ptr);
  13848. if (storage_context) {
  13849. storage_context.add_storage(key);
  13850. }
  13851. return storage;
  13852. };
  13853. return unpickler.load();
  13854. }
  13855. });
  13856. this.registerType('torch._C.WithInsertPoint', class {
  13857. constructor(...args) {
  13858. let n = null;
  13859. if (args.length === 1 && args[0] instanceof torch.Block) {
  13860. const [b] = args;
  13861. n = b.return_node();
  13862. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13863. [n] = args;
  13864. } else {
  13865. throw new python.Error('Invalid arguments.');
  13866. }
  13867. this._prev = n.owningGraph().insertPoint();
  13868. n.owningGraph().setInsertPoint(n);
  13869. }
  13870. dispose() {
  13871. this._prev.owningGraph().setInsertPoint(this._prev);
  13872. }
  13873. });
  13874. this.registerType('torch._C.Environment', class {
  13875. constructor(method, resolver, b, next) {
  13876. this.method = method;
  13877. this.resolver = resolver;
  13878. this.b = b;
  13879. this.next = next;
  13880. this.value_table = new Map();
  13881. this.type_table = new Map();
  13882. this.error_messages = new Map();
  13883. }
  13884. setVariableTypeError(name, msg) {
  13885. /* eslint-disable consistent-this */
  13886. let runner = this;
  13887. /* eslint-enable consistent-this */
  13888. while (runner.next) {
  13889. runner = runner.next;
  13890. }
  13891. runner.error_messages.set(name, msg);
  13892. }
  13893. insertLoad(name, type) {
  13894. const g = this.b.owningGraph();
  13895. const load = g.insertNode(g.createLoad(name, type));
  13896. if (torch._C.meaningfulName(name)) {
  13897. load.output().setDebugName(name);
  13898. }
  13899. return new torch._C.SimpleValue(load.output());
  13900. }
  13901. insertStore(name, loc, v, type) {
  13902. const g = this.b.owningGraph();
  13903. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  13904. this.type_table.set(name, type);
  13905. }
  13906. findInThisFrame(name) {
  13907. if (this.value_table.has(name)) {
  13908. return this.value_table.get(name);
  13909. }
  13910. if (this.type_table.has(name)) {
  13911. return this.insertLoad(name, this.type_table.get(name));
  13912. }
  13913. return null;
  13914. }
  13915. findInParentFrame(name) {
  13916. return this.next ? this.next.findInAnyFrame(name) : null;
  13917. }
  13918. setType(name, type) {
  13919. this.type_table.set(name, type);
  13920. }
  13921. findInAnyFrame(name) {
  13922. /* eslint-disable consistent-this */
  13923. const self = this;
  13924. /* eslint-enable consistent-this */
  13925. for (let runner = self; runner; runner = runner.next) {
  13926. const r = runner.findInThisFrame(name);
  13927. if (r) {
  13928. return r;
  13929. }
  13930. }
  13931. return null;
  13932. }
  13933. block() {
  13934. return this.b;
  13935. }
  13936. setVar(loc, name, value) {
  13937. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  13938. }
  13939. setSugaredVar(loc, name, value, annotated_type) {
  13940. let as_simple_value = torch._C.asSimple(value);
  13941. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  13942. as_simple_value.setDebugName(name);
  13943. }
  13944. const parent = this.findInParentFrame(name);
  13945. if (parent) {
  13946. if (annotated_type) {
  13947. throw new python.Error('Type already defined in an outer block.');
  13948. }
  13949. if (!as_simple_value) {
  13950. throw new python.Error('Only reassignments to first-class values are allowed.');
  13951. }
  13952. const simple_parent = torch._C.asSimple(parent);
  13953. if (!simple_parent) {
  13954. throw new python.Error('Only reassignments to first-class values are allowed.');
  13955. }
  13956. const parent_type = torch._C.unshapedType(simple_parent.type());
  13957. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  13958. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  13959. throw new python.Error('Incompatible types.');
  13960. }
  13961. }
  13962. if (as_simple_value) {
  13963. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  13964. throw new python.Error('Invalid type.');
  13965. }
  13966. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  13967. this.insertStore(name, loc, as_simple_value, value_store_type);
  13968. } else {
  13969. this.value_table.set(name, value);
  13970. }
  13971. }
  13972. getSugaredVar(ident, range, required) {
  13973. required = required || true;
  13974. let retval = this.findInAnyFrame(ident);
  13975. if (!retval) {
  13976. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  13977. ['print', new torch._C.PrintValue()],
  13978. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  13979. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  13980. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  13981. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  13982. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  13983. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  13984. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  13985. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  13986. ['range', torch._C.SpecialFormValue.create('prim::range')],
  13987. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  13988. ]);
  13989. if (torch._C.Environment.globals.has(ident)) {
  13990. retval = torch._C.Environment.globals.get(ident);
  13991. }
  13992. }
  13993. if (!retval) {
  13994. const type = this.resolver.resolveType(ident, range);
  13995. if (type instanceof torch.TupleType) {
  13996. retval = new torch.jit.NamedTupleConstructor(type);
  13997. }
  13998. }
  13999. if (!retval) {
  14000. retval = this.resolver.resolveValue(ident, this.method, range);
  14001. }
  14002. if (!retval) {
  14003. const type = this.resolver.resolveType(ident, range);
  14004. if (type instanceof torch.ClassType) {
  14005. retval = new torch.jit.ClassValue(type);
  14006. }
  14007. }
  14008. if (!retval && required) {
  14009. throw new python.Error(`The name '${ident}' is not defined.`);
  14010. }
  14011. return retval;
  14012. }
  14013. getVar(ident, range) {
  14014. return this.getSugaredVar(ident, range).asValue(range, this.method);
  14015. }
  14016. definedVariables() {
  14017. return Array.from(this.type_table.keys());
  14018. }
  14019. });
  14020. this.registerType('torch._C.Refinement', class {
  14021. constructor(identifier, type) {
  14022. this._identifier = identifier;
  14023. this._type = type;
  14024. }
  14025. identifier() {
  14026. return this._identifier;
  14027. }
  14028. type() {
  14029. return this._type;
  14030. }
  14031. });
  14032. this.registerType('torch._C.RefinementSet', class {
  14033. constructor(...args) {
  14034. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  14035. this._true_refinements = [args[0]];
  14036. this._false_refinements = [];
  14037. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  14038. this._true_refinements = [args[0]];
  14039. this._false_refinements = [args[1]];
  14040. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  14041. [this._true_refinements, this._false_refinements] = args;
  14042. } else {
  14043. throw new python.Error('Not implemented.');
  14044. }
  14045. }
  14046. Not() {
  14047. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  14048. }
  14049. activeRefinements() {
  14050. return this._true_refinements;
  14051. }
  14052. });
  14053. this.registerFunction('torch._C.CondValue', class {
  14054. constructor(...args) {
  14055. if (args.length === 3) {
  14056. [this._value, this._refinements, this._static_if] = args;
  14057. } else if (args.length === 4) {
  14058. const [g, loc, static_value, refinements] = args;
  14059. this._value = g.insertConstant(static_value, loc);
  14060. this._refinements = refinements;
  14061. this._static_if = static_value;
  14062. } else {
  14063. throw new python.Error('Invalid number of arguments.');
  14064. }
  14065. }
  14066. value() {
  14067. return this._value;
  14068. }
  14069. staticIf() {
  14070. return this._static_if;
  14071. }
  14072. refinements() {
  14073. return this._refinements;
  14074. }
  14075. });
  14076. this.registerFunction('torch._C.asSimple', (value) => {
  14077. if (value instanceof torch._C.SimpleValue) {
  14078. return value.getValue();
  14079. }
  14080. return null;
  14081. });
  14082. this.registerFunction('torch._C.isNumber', (str) => {
  14083. return /^[0-9]+$/.test(str);
  14084. });
  14085. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14086. if (torch._C.isNumber(field)) {
  14087. return `_${field}`;
  14088. }
  14089. return field;
  14090. });
  14091. this.registerFunction('torch._C.meaningfulName', (name) => {
  14092. if (name.length === 0) {
  14093. return false;
  14094. }
  14095. if (name[0] === '$') {
  14096. return false;
  14097. }
  14098. if (name[0] !== '_') {
  14099. return true;
  14100. }
  14101. return !/\d+/.test(name.slice(1));
  14102. });
  14103. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14104. const key = `${val.value}:${val.tag}`;
  14105. const existing_constant = map.get(key);
  14106. if (existing_constant) {
  14107. return existing_constant;
  14108. }
  14109. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14110. const new_constant = graph.insertConstant(val, r);
  14111. map.set(key, new_constant);
  14112. guard.dispose();
  14113. return new_constant;
  14114. });
  14115. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14116. if (schema.overload_name) {
  14117. return `${schema.name}.${schema.overload_name}`;
  14118. }
  14119. return schema.name;
  14120. });
  14121. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14122. const value_map_func = (v) => value_map.get(v);
  14123. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14124. for (let i = 0; i < inputs.length; i++) {
  14125. value_map.set(callee.inputs()[i], inputs[i]);
  14126. }
  14127. for (const node of callee.nodes()) {
  14128. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14129. for (let i = 0; i < node.outputs().length; i++) {
  14130. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14131. }
  14132. }
  14133. const outputs = [];
  14134. for (const output of callee.outputs()) {
  14135. outputs.push(value_map_func(output));
  14136. }
  14137. return outputs;
  14138. });
  14139. this.registerType('TemplateEnv', class {
  14140. });
  14141. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14142. constructor() {
  14143. this.state = 'UNINITIALIZED';
  14144. this._builtins_by_name = new Map();
  14145. }
  14146. getAllBuiltinFunctionsFor(name) {
  14147. if (this.state === 'UNINITIALIZED') {
  14148. this.loadBuiltinFunctions();
  14149. this.state = 'INITIALIZED';
  14150. }
  14151. if (!this._builtins_by_name.has(name)) {
  14152. return [];
  14153. }
  14154. return this._builtins_by_name.get(name);
  14155. }
  14156. loadBuiltinFunctions() {
  14157. /*
  14158. for (const scalar of ['float', 'int', 'complex']) {
  14159. const env = new torch.C.TemplateEnv();
  14160. env.s('Scalar', scalar);
  14161. this.loadSource(scalar_operators_source.format(env), 'aten');
  14162. }
  14163. for (const scalar of ['float', 'int']) {
  14164. const env = new torch.C.TemplateEnv();
  14165. env.s('Scalar', scalar);
  14166. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14167. }
  14168. using str_pair = std::pair<std::string, std::string>;
  14169. const std::vector<str_pair> name_len = {
  14170. str_pair('single', '1'),
  14171. str_pair('pair', '2'),
  14172. str_pair('triple', '3'),
  14173. str_pair('quadruple', '4'),
  14174. };
  14175. for (const auto scalar : {'float', 'int'}) {
  14176. for (const auto& pair : name_len) {
  14177. const env = new torch.C.TemplateEnv();
  14178. env.s('Scalar', scalar);
  14179. env.s('name', pair.first);
  14180. env.s('Length', pair.second);
  14181. this.loadSource(_ntuple_ops.format(env), 'aten');
  14182. }
  14183. }
  14184. for (auto rhs : {'number', 'Tensor'}) {
  14185. at::jit::TemplateEnv env;
  14186. env.s('Rhs_Type', rhs);
  14187. this.loadSource(floordiv.format(env), 'aten');
  14188. }
  14189. this.loadSource(aten_ops, 'aten');
  14190. this.loadSource(aten_ops_additional, 'aten');
  14191. this.loadSource(tensor_properties, 'prim');
  14192. */
  14193. }
  14194. loadSource(/* source, the_namespace */) {
  14195. }
  14196. });
  14197. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14198. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14199. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14200. });
  14201. this.registerFunction('torch._C.get_operator_version_map', () => {
  14202. return new Map();
  14203. });
  14204. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14205. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14206. let arg_type = arg.type;
  14207. if (arg_type instanceof torch._C.DynamicType) {
  14208. arg_type = arg_type.fallback();
  14209. }
  14210. const argument_is_list = arg_type instanceof torch.ListType;
  14211. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14212. const arg_is_broadcasting_list = arg.N > 0;
  14213. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14214. });
  14215. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14216. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14217. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14218. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14219. return true;
  14220. }
  14221. return false;
  14222. });
  14223. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14224. if (opt_type instanceof torch._C.DynamicType) {
  14225. return torch._C.unwrapOptional(opt_type.fallback());
  14226. }
  14227. if (opt_type instanceof torch.OptionalType) {
  14228. return opt_type.getElementType();
  14229. }
  14230. return opt_type;
  14231. });
  14232. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14233. const possibleSchemas = [];
  14234. if (version === undefined) {
  14235. return possibleSchemas;
  14236. }
  14237. for (const entry of torch._C.get_operator_version_map()) {
  14238. const old_symbol_name = entry.first;
  14239. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14240. if (base_name === name) {
  14241. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14242. if (possibleUpgrader.has_value()) {
  14243. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14244. }
  14245. }
  14246. }
  14247. return possibleSchemas;
  14248. });
  14249. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14250. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14251. return current_version < latest_update;
  14252. });
  14253. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14254. const it = torch._C.get_operator_version_map().get(name);
  14255. if (it) {
  14256. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14257. }
  14258. return true;
  14259. });
  14260. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14261. if (values.length === 1) {
  14262. return values[0];
  14263. }
  14264. let named_tuple = null;
  14265. if (field_names) {
  14266. const types = values.map((v) => v.type());
  14267. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14268. }
  14269. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14270. });
  14271. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14272. const v_type = value.type();
  14273. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14274. return false;
  14275. }
  14276. const arg_type = torch._C.unwrapOptional(arg.type);
  14277. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14278. });
  14279. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14280. const list_type = list_type_;
  14281. if (list_type instanceof torch.ListType === false) {
  14282. return false;
  14283. }
  14284. if (type.isSubtypeOf(list_type_)) {
  14285. return true;
  14286. }
  14287. if (type instanceof torch.TupleType) {
  14288. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14289. }
  14290. return false;
  14291. });
  14292. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14293. for (let i = 0; i < kwargs.length; i++) {
  14294. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14295. return i;
  14296. }
  14297. if (kwargs[i].name() === name) {
  14298. return i;
  14299. }
  14300. }
  14301. return null;
  14302. });
  14303. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14304. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14305. const list_elements = [];
  14306. for (const named_value of varargs) {
  14307. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14308. if (!matched_value) {
  14309. return null;
  14310. }
  14311. list_elements.push(matched_value);
  14312. }
  14313. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14314. });
  14315. this.registerType('torch._C.MatchTypeReturn', class {
  14316. constructor(reason) {
  14317. this._reason = reason;
  14318. }
  14319. static Success() {
  14320. return new torch._C.MatchTypeReturn(null);
  14321. }
  14322. success() {
  14323. return this._reason === null;
  14324. }
  14325. });
  14326. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14327. if (!formal.hasFreeVariables()) {
  14328. if (formal instanceof torch._C.DynamicType) {
  14329. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14330. }
  14331. return torch._C.MatchTypeReturn.Success();
  14332. }
  14333. if (formal instanceof torch._C.VarType) {
  14334. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14335. if (it === null) {
  14336. type_env.set(formal.name(), actual);
  14337. return torch._C.MatchTypeReturn.Success();
  14338. } else if (torch._C.unifyTypes(it, actual)) {
  14339. return torch._C.MatchTypeReturn.Success();
  14340. }
  14341. return new torch._C.MatchTypeReturn('Cannot match var.');
  14342. } else if (formal instanceof torch.ListType) {
  14343. if (actual instanceof torch.ListType) {
  14344. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14345. if (!innerMatch.success()) {
  14346. return innerMatch;
  14347. }
  14348. return torch._C.MatchTypeReturn.Success();
  14349. } else if (actual instanceof torch.TupleType) {
  14350. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14351. if (maybe_tuple_unified) {
  14352. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14353. }
  14354. }
  14355. return new torch._C.MatchTypeReturn('Cannot match list.');
  14356. } else if (formal instanceof torch.TupleType) {
  14357. if (actual instanceof torch.TupleType) {
  14358. if (formal.elements().length !== actual.elements().length) {
  14359. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14360. }
  14361. for (let i = 0; i < formal.elements().length; i++) {
  14362. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14363. if (!result.success()) {
  14364. return result;
  14365. }
  14366. }
  14367. return torch._C.MatchTypeReturn.Success();
  14368. }
  14369. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14370. } else if (formal instanceof torch.FutureType) {
  14371. if (actual instanceof torch.FutureType) {
  14372. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14373. if (!innerMatch.success()) {
  14374. return innerMatch;
  14375. }
  14376. return torch._C.MatchTypeReturn.Success();
  14377. }
  14378. return new torch._C.MatchTypeReturn('Cannot match future.');
  14379. } else if (formal instanceof torch.AwaitType) {
  14380. if (actual instanceof torch.AwaitType) {
  14381. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14382. if (!innerMatch.success()) {
  14383. return innerMatch;
  14384. }
  14385. return torch._C.MatchTypeReturn.Success();
  14386. }
  14387. return new torch._C.MatchTypeReturn('Cannot match await.');
  14388. } else if (formal instanceof torch.RRefType) {
  14389. if (actual instanceof torch.RRefType) {
  14390. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14391. if (!innerMatch.success()) {
  14392. return innerMatch;
  14393. }
  14394. return torch._C.MatchTypeReturn.Success();
  14395. }
  14396. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14397. } else if (formal instanceof torch.OptionalType) {
  14398. if (actual instanceof torch.OptionalType) {
  14399. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14400. if (!optionedMatch.success()) {
  14401. return optionedMatch;
  14402. }
  14403. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14404. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14405. }
  14406. return torch._C.MatchTypeReturn.Success();
  14407. } else if (formal instanceof torch.DictType) {
  14408. if (actual instanceof torch.DictType) {
  14409. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14410. if (!key_match.success()) {
  14411. return key_match;
  14412. }
  14413. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14414. if (!value_match.success()) {
  14415. return value_match;
  14416. }
  14417. return torch._C.MatchTypeReturn.Success();
  14418. }
  14419. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14420. }
  14421. throw new python.Error('Unhandled free variable container.');
  14422. });
  14423. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14424. let value = named_value.value(graph);
  14425. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14426. const repeated = Array(arg.N).fill(value);
  14427. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14428. }
  14429. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14430. if (!matched.success()) {
  14431. if (failure_messages) {
  14432. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14433. }
  14434. return null;
  14435. }
  14436. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14437. if (!concrete_type) {
  14438. if (failure_messages) {
  14439. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14440. }
  14441. return null;
  14442. }
  14443. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14444. if (!value.type().isSubtypeOf(concrete_type)) {
  14445. if (failure_messages) {
  14446. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14447. }
  14448. return null;
  14449. }
  14450. return value;
  14451. });
  14452. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14453. if (concrete_type instanceof torch.OptionalType) {
  14454. const op = concrete_type;
  14455. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14456. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14457. }
  14458. }
  14459. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14460. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14461. }
  14462. if (value.type() instanceof torch.TupleType) {
  14463. const value_tuple = value.type();
  14464. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14465. const unpacked = torch._C.createTupleUnpack(value);
  14466. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14467. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14468. }
  14469. if (concrete_type instanceof torch.TupleType) {
  14470. const concrete_tuple = concrete_type;
  14471. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14472. concrete_tuple.elements().length === value_tuple.elements().length) {
  14473. const unpacked = torch._C.createTupleUnpack(value);
  14474. const converted = [];
  14475. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14476. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14477. }
  14478. value = graph.insertNode(graph.createTuple(converted)).output();
  14479. }
  14480. }
  14481. }
  14482. if (allow_conversions) {
  14483. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14484. const value_equals_number = value.type() === torch.NumberType.get();
  14485. const concrete_float = concrete_type === torch.FloatType.get();
  14486. const concrete_complex = concrete_type === torch.ComplexType.get();
  14487. const concrete_int = concrete_type === torch.IntType.get();
  14488. const concrete_number = concrete_type === torch.NumberType.get();
  14489. if (value_isa_tensor) {
  14490. if (concrete_float) {
  14491. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14492. } else if (concrete_complex) {
  14493. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14494. } else if (concrete_int) {
  14495. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14496. } else if (concrete_number) {
  14497. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14498. }
  14499. } else if (value_equals_number) {
  14500. if (concrete_float) {
  14501. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14502. } else if (concrete_complex) {
  14503. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14504. } else if (concrete_int) {
  14505. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14506. }
  14507. } else if (value.type() === torch.BoolType.get()) {
  14508. if (concrete_float) {
  14509. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14510. } else if (concrete_int || concrete_number) {
  14511. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14512. }
  14513. }
  14514. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14515. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14516. }
  14517. }
  14518. return value;
  14519. });
  14520. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14521. if (!type.hasFreeVariables()) {
  14522. if (type instanceof torch._C.DynamicType) {
  14523. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14524. }
  14525. return type;
  14526. }
  14527. if (type instanceof torch._C.VarType) {
  14528. return type_env.get(type.annotation_str);
  14529. }
  14530. const contained = type.containedTypes();
  14531. if (contained.length === 0) {
  14532. return type;
  14533. }
  14534. const new_contained = [];
  14535. for (const t of contained) {
  14536. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14537. if (!r) {
  14538. return null;
  14539. }
  14540. new_contained.push(r);
  14541. }
  14542. return type.withContained(new_contained);
  14543. });
  14544. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14545. if (torch._C.isBlockListedSchema(schema)) {
  14546. return null;
  14547. }
  14548. const err = null;
  14549. const type_env = new Map();
  14550. const positional_inputs = [];
  14551. const used_kwarg = kwargs.map(() => false);
  14552. const is_aten = schema.name.startsWith('aten::');
  14553. let used_args = 0;
  14554. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14555. const arg = schema.arguments[schema_i];
  14556. let actual_named_value = null;
  14557. if (arg.name === 'self' && self) {
  14558. actual_named_value = self;
  14559. self = null;
  14560. } else if (!arg.kwarg_only && used_args < args.length) {
  14561. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14562. const value = args[used_args].value(graph);
  14563. const actual_type = value.type();
  14564. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14565. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14566. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14567. if (!list) {
  14568. return null;
  14569. }
  14570. used_args = args.length;
  14571. positional_inputs.push(list);
  14572. continue;
  14573. }
  14574. }
  14575. actual_named_value = args[used_args];
  14576. used_args++;
  14577. } else {
  14578. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14579. if (Number.isInteger(kwarg_idx)) {
  14580. const nv = kwargs[kwarg_idx];
  14581. if (used_kwarg[kwarg_idx]) {
  14582. if (failure_messages) {
  14583. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14584. }
  14585. return null;
  14586. }
  14587. used_kwarg[kwarg_idx] = true;
  14588. actual_named_value = nv;
  14589. } else if (arg.has_default_value()) {
  14590. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14591. } else {
  14592. if (failure_messages) {
  14593. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14594. }
  14595. return null;
  14596. }
  14597. }
  14598. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14599. if (!positional) {
  14600. return null;
  14601. }
  14602. positional_inputs.push(positional);
  14603. }
  14604. if (self !== null) {
  14605. if (failure_messages) {
  14606. throw new python.Error('Provided self argument not used in schema.');
  14607. }
  14608. return null;
  14609. }
  14610. if (schema.is_vararg) {
  14611. for (; used_args < args.length; used_args++) {
  14612. positional_inputs.push(args[used_args].value(graph));
  14613. }
  14614. }
  14615. if (used_args < args.length) {
  14616. if (failure_messages) {
  14617. throw new python.Error('Too many positional arguments.');
  14618. }
  14619. return null;
  14620. }
  14621. for (let i = 0; i < kwargs.length; i++) {
  14622. const nv = kwargs[i];
  14623. if (!used_kwarg[i]) {
  14624. if (failure_messages) {
  14625. if (schema.argumentIndexWithName(nv.name()) === null) {
  14626. throw new python.Error('Keyword argument unknown.');
  14627. } else {
  14628. throw new python.Error('Keyword argument specified twice.');
  14629. }
  14630. }
  14631. return null;
  14632. }
  14633. }
  14634. const returns = schema.returns;
  14635. const return_types = returns.map((r) => {
  14636. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14637. if (!result) {
  14638. throw new python.Error('Unbound type variable.');
  14639. }
  14640. return result;
  14641. });
  14642. const return_has_field_names = returns.every((r) => !r.name);
  14643. let return_field_names = null;
  14644. if (return_has_field_names) {
  14645. return_field_names = returns.map((r) => r.name);
  14646. }
  14647. const schema_name = torch._C.getFullSchemaName(schema);
  14648. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14649. });
  14650. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14651. self = self || null;
  14652. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14653. if (result) {
  14654. return result;
  14655. }
  14656. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14657. });
  14658. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14659. self = self || null;
  14660. render_errors = render_errors || false;
  14661. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14662. if (schemas.length === 1) {
  14663. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14664. }
  14665. for (const allow_conversions of [false, true]) {
  14666. for (let i = 0; i < schemas.length; i++) {
  14667. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14668. if (matched_schema) {
  14669. return [i, matched_schema];
  14670. }
  14671. }
  14672. }
  14673. if (!render_errors) {
  14674. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14675. }
  14676. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14677. });
  14678. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14679. const variants = torch._C.getAllOperatorsFor(name);
  14680. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14681. const graph_version = graph.get_op_version();
  14682. const schemas = [];
  14683. const upgrader_schemas = [];
  14684. for (const op of variants) {
  14685. let found_upgrader = false;
  14686. const op_name = torch._C.getFullSchemaName(op.schema());
  14687. if (Number.isInteger(graph_version)) {
  14688. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14689. if (version_entry) {
  14690. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14691. if (old_schema_entry.has_value()) {
  14692. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14693. upgrader_schemas.push(old_schema);
  14694. found_upgrader = true;
  14695. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14696. throw new python.Error('Valid upgrader must be present.');
  14697. }
  14698. }
  14699. }
  14700. if (!found_upgrader) {
  14701. schemas.push(op.schema());
  14702. }
  14703. }
  14704. if (variants.length === 0) {
  14705. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14706. for (const old_schema_entry of oldSchemas) {
  14707. const old_schema = torch._C.parseSchema(old_schema_entry);
  14708. upgrader_schemas.push(old_schema);
  14709. }
  14710. }
  14711. for (const schema of upgrader_schemas) {
  14712. schemas.push(schema);
  14713. }
  14714. for (const method of builtin_functions) {
  14715. method.ensure_defined();
  14716. schemas.push(method.getSchema());
  14717. }
  14718. if (schemas.length === 0) {
  14719. const user_function_name = name;
  14720. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  14721. }
  14722. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14723. if (matched[0] < variants.length + upgrader_schemas.length) {
  14724. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14725. }
  14726. const fn = builtin_functions[matched.first - variants.size()];
  14727. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14728. });
  14729. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14730. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14731. for (const ret of matched_schema.return_types) {
  14732. n.addOutput().setType(ret);
  14733. }
  14734. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14735. n.getOperation();
  14736. } else {
  14737. n.setHistoricSchemaName(matched_schema.schema_name);
  14738. }
  14739. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14740. });
  14741. this.registerFunction('torch._C.unshapedType', (type) => {
  14742. if (type.isSubtypeOf(torch.TensorType.get())) {
  14743. return torch.TensorType.get();
  14744. }
  14745. const contained = type.containedTypes();
  14746. if (contained.length === 0) {
  14747. return type;
  14748. }
  14749. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14750. });
  14751. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14752. default_to_union = default_to_union || false;
  14753. type_hint = type_hint || null;
  14754. if (t1.isSubtypeOf(t2)) {
  14755. return t2;
  14756. } else if (t2.isSubtypeOf(t1)) {
  14757. return t1;
  14758. }
  14759. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14760. return t1.merge(t2);
  14761. }
  14762. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14763. return torch.OptionalType.create(t2);
  14764. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14765. return torch.OptionalType.create(t1);
  14766. }
  14767. if (t1 instanceof torch.OptionalType) {
  14768. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14769. if (elem) {
  14770. return torch.OptionalType.create(elem);
  14771. }
  14772. } else if (t2 instanceof torch.OptionalType) {
  14773. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14774. if (elem) {
  14775. return torch.OptionalType.create(elem);
  14776. }
  14777. }
  14778. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14779. if (t1.elements().size() !== t2.elements().size()) {
  14780. return null;
  14781. }
  14782. const elements = [];
  14783. for (let i = 0; i < t1.elements().length; i++) {
  14784. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14785. if (elem) {
  14786. elements.push(elem);
  14787. } else {
  14788. return null;
  14789. }
  14790. }
  14791. return torch.TupleType.create(elements);
  14792. }
  14793. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14794. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14795. if (elem) {
  14796. return torch.FutureType.create(elem);
  14797. }
  14798. }
  14799. const t1_unshaped = torch._C.unshapedType(t1);
  14800. const t2_unshaped = torch._C.unshapedType(t2);
  14801. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14802. return t2_unshaped;
  14803. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14804. return t1_unshaped;
  14805. }
  14806. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14807. return type_hint;
  14808. }
  14809. return null;
  14810. });
  14811. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14812. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14813. if (default_to_union && !unified) {
  14814. return torch.UnionType.create([t1, t2]);
  14815. }
  14816. return unified;
  14817. });
  14818. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14819. if (elements.length === 0) {
  14820. return null;
  14821. }
  14822. let [ret_type] = elements;
  14823. for (let i = 1; i < elements.length && ret_type; i++) {
  14824. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14825. if (!maybe_unified) {
  14826. return null;
  14827. }
  14828. ret_type = maybe_unified;
  14829. }
  14830. return ret_type;
  14831. });
  14832. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14833. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14834. });
  14835. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14836. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14837. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14838. ivalue.isDevice() || ivalue.isEnum()) {
  14839. return true;
  14840. }
  14841. if (ivalue.isTensor()) {
  14842. return torch._C.insertableTensor(ivalue.toTensor());
  14843. }
  14844. if (ivalue.isList() || ivalue.isTuple()) {
  14845. let elems = [];
  14846. if (ivalue.isTuple()) {
  14847. elems = ivalue.toTupleRef().elements();
  14848. } else {
  14849. elems = ivalue.toListRef();
  14850. }
  14851. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14852. }
  14853. if (ivalue.isGenericDict()) {
  14854. const dict = ivalue.toGenericDict();
  14855. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14856. }
  14857. return false;
  14858. });
  14859. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14860. loc = loc || null;
  14861. scope = scope || null;
  14862. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14863. if (value !== undefined) {
  14864. return value;
  14865. }
  14866. throw new python.Error('Unsupported value kind.');
  14867. });
  14868. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14869. if (val instanceof torch._C.IValue) {
  14870. const n = g.create('prim::Constant');
  14871. if (val.isTensor()) {
  14872. const ref = val.toTensor();
  14873. if (!torch._C.insertableTensor(val.toTensor())) {
  14874. n.destroy();
  14875. return null;
  14876. }
  14877. if (!ref.defined()) {
  14878. n.destroy();
  14879. return g.insertNode(g.createNone()).output();
  14880. }
  14881. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  14882. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  14883. n.t_('value', ref);
  14884. } else if (val.isInt()) {
  14885. n.i_('value', val.toInt());
  14886. n.output().setType(torch.IntType.get());
  14887. } else if (val.isDouble()) {
  14888. n.f_('value', val.toDouble());
  14889. n.output().setType(torch.FloatType.get());
  14890. } else if (val.isComplexDouble()) {
  14891. n.c_('value', val.toComplexDouble());
  14892. n.output().setType(torch.ComplexType.get());
  14893. } else if (val.isBool()) {
  14894. n.i_('value', val.toBool());
  14895. n.output().setType(torch.BoolType.get());
  14896. } else if (val.isList()) {
  14897. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  14898. if (fast_path_list || torch._C.insertableIValue(val)) {
  14899. n.ival_('value', val);
  14900. n.output().setType(val.type());
  14901. } else {
  14902. n.destroy();
  14903. return null;
  14904. }
  14905. } else if (val.isString()) {
  14906. n.s_('value', val.toStringRef());
  14907. n.output().setType(torch.StringType.get());
  14908. } else if (val.isDevice()) {
  14909. n.s_('value', val.toDevice().__str__());
  14910. n.output().setType(torch.DeviceObjType.get());
  14911. } else if (val.isGenerator()) {
  14912. n.ival_('value', val.toGenerator());
  14913. n.output().setType(torch._C_._GeneratorType.get());
  14914. } else if (val.isStream()) {
  14915. n.ival_('value', val);
  14916. n.output().setType(torch.StreamObjType.get());
  14917. } else if (val.isNone()) {
  14918. n.output().setType(torch.NoneType.get());
  14919. // n.ival_('value', null); // remove
  14920. } else if (val.isTuple()) {
  14921. if (torch._C.insertableIValue(val)) {
  14922. n.ival_('value', val);
  14923. n.output().setType(val.type());
  14924. } else {
  14925. n.destroy();
  14926. return null;
  14927. }
  14928. } else if (val.isObject()) {
  14929. const ref = val.toObjectRef();
  14930. // see: [Constant Object Weak CompilationUnit Reference]
  14931. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  14932. n.ival_('value', val);
  14933. n.output().setType(val.type());
  14934. } else {
  14935. n.destroy();
  14936. return null;
  14937. }
  14938. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  14939. n.ival_('value', val);
  14940. n.output().setType(val.type());
  14941. } else {
  14942. n.destroy();
  14943. return null;
  14944. }
  14945. if (loc) {
  14946. n.setSourceRange(loc);
  14947. }
  14948. if (scope) {
  14949. n.setScope(scope);
  14950. }
  14951. return g.insertNode(n).output();
  14952. }
  14953. const n = g.create('prim::Constant');
  14954. let type = null;
  14955. if (val === null) {
  14956. n.ival_('value', val);
  14957. type = torch.NoneType.get();
  14958. } else if (typeof val === 'string') {
  14959. n.s_('value', val);
  14960. type = torch.StringType.get();
  14961. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  14962. n.ss_('value', val);
  14963. type = torch.ListType.create(torch.StringType.get());
  14964. } else if (typeof val === 'boolean') {
  14965. n.i_('value', val === true ? 1 : 0);
  14966. type = torch.BoolType.get();
  14967. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  14968. n.i_('value', val);
  14969. type = torch.IntType.get();
  14970. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  14971. n.f_('value', val);
  14972. type = torch.FloatType.get();
  14973. } else if (val instanceof torch.Tensor) {
  14974. n.t_('value', val);
  14975. type = torch.TensorType.get();
  14976. } else if (val instanceof torch.ScriptObject) {
  14977. n.ival_('value', val);
  14978. type = val.type();
  14979. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  14980. n.ival_('value', val);
  14981. type = torch.ListType.create(torch.IntType.get());
  14982. } else {
  14983. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  14984. }
  14985. if (type) {
  14986. n.output().setType(type);
  14987. }
  14988. if (loc) {
  14989. n.setSourceRange(loc);
  14990. }
  14991. if (scope) {
  14992. n.setScope(scope);
  14993. }
  14994. return g.insertNode(n).output();
  14995. });
  14996. this.registerFunction('torch._C.toIValue', (v) => {
  14997. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  14998. return null;
  14999. }
  15000. const node = v.node();
  15001. const type = v.type();
  15002. if (type.isSubtypeOf(torch.TensorType.get())) {
  15003. return new torch._C.IValue(node.t('value'), 'Tensor');
  15004. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  15005. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  15006. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  15007. return new torch._C.IValue(node.i('value'), 'Int');
  15008. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  15009. return new torch._C.IValue(node.f('value'), 'Double');
  15010. } else if (type.isSubtypeOf(torch.ComplexType.get()) && node.kindOf('value') === 'c') {
  15011. return new torch._C.IValue(node.c('value'), 'Complex');
  15012. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  15013. let list = node.ival('value');
  15014. list = list.isList ? list : new torch._C.IValue(list); // remove
  15015. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  15016. return list;
  15017. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  15018. const dict = node.ival('value');
  15019. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  15020. return dict;
  15021. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  15022. const tup = node.ival('value');
  15023. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  15024. return tup;
  15025. } else if (type === torch.StringType.get()) {
  15026. const s = new torch._C.IValue(node.s('value'), 'String');
  15027. return s;
  15028. } else if (type === torch.DeviceObjType.get()) {
  15029. const d = new torch.device(node.s('value'));
  15030. return new torch._C.IValue(d);
  15031. } else if (type === torch._C._GeneratorType.get()) {
  15032. throw new python.Error('Not implemented.');
  15033. // const generator = node.ival('value').toGenerator();
  15034. // return generator;
  15035. } else if (type === torch.StreamObjType.get()) {
  15036. throw new python.Error('Not implemented.');
  15037. // const s = node.ival('value').toStream();
  15038. // return s;
  15039. } else if (node.mustBeNone()) {
  15040. return new torch._C.IValue();
  15041. } else if (type.kind() === 'EnumType') {
  15042. const enum_val = node.ival('value');
  15043. return enum_val;
  15044. } else if (type instanceof torch.ClassType && !type.is_module()) {
  15045. const class_val = node.ival('value');
  15046. return new torch._C.IValue(class_val, 'Object');
  15047. }
  15048. throw new python.Error('Unsupported constant literal.');
  15049. });
  15050. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  15051. const ivalue = torch._C.toIValue(v);
  15052. if (ivalue) {
  15053. return ivalue[target]();
  15054. }
  15055. return default_value === undefined ? null : default_value;
  15056. });
  15057. this.registerType('torch._C.NamedValue', class {
  15058. constructor(...args) {
  15059. if (args.length === 1) {
  15060. if (args[0] instanceof torch.Value) {
  15061. [this._value] = args;
  15062. } else {
  15063. [this._ivalue] = args;
  15064. }
  15065. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  15066. [this._loc, this._name, this._value] = args;
  15067. } else {
  15068. throw new python.Error('Invalid argument.');
  15069. }
  15070. }
  15071. name() {
  15072. return this._name;
  15073. }
  15074. value(g) {
  15075. if (!this._value) {
  15076. return torch._C.insertConstant(g, this._ivalue);
  15077. }
  15078. return this._value;
  15079. }
  15080. type() {
  15081. if (this._value) {
  15082. return this._value.type();
  15083. }
  15084. return this._ivalue.type();
  15085. }
  15086. });
  15087. this.registerType('torch._C.SugaredValue', class {
  15088. kind() {
  15089. throw new python.Error('Not implemented.');
  15090. }
  15091. shouldEmitUnrolled() {
  15092. return this.staticLen() !== null;
  15093. }
  15094. });
  15095. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15096. constructor(value) {
  15097. super();
  15098. this._value = value;
  15099. }
  15100. kind() {
  15101. return `value of type '${this._value.type().annotation_str}'`;
  15102. }
  15103. asValue(/* range, m */) {
  15104. return this._value;
  15105. }
  15106. getValue() {
  15107. return this._value;
  15108. }
  15109. asTuple(loc, m, size_hint) {
  15110. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15111. if (this._value.type() instanceof torch.TupleType) {
  15112. const outputs = torch._C.createTupleUnpack(this._value);
  15113. return outputs.map((v) => make_simple_value(v));
  15114. } else if (this._value.type() instanceof torch.ListType) {
  15115. if (!size_hint) {
  15116. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15117. }
  15118. const graph = this._value.owningGraph();
  15119. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15120. return unpack.outputs().map((v) => make_simple_value(v));
  15121. } else if (this._value.type().kind() === 'AnyTupleType') {
  15122. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15123. }
  15124. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15125. }
  15126. attr(loc, m, field) {
  15127. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15128. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15129. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15130. }
  15131. }
  15132. if (this._value.type() instanceof torch.TupleType) {
  15133. throw new python.Error('Not implemented.');
  15134. }
  15135. if (this._value.type() instanceof torch.AwaitType) {
  15136. throw new python.Error('Not implemented.');
  15137. }
  15138. if (this._value.type() instanceof torch.ClassType) {
  15139. const classType = this._value.type();
  15140. if (classType.findMethod(field)) {
  15141. return new torch._C.MethodValue(this.getValue(), [field]);
  15142. }
  15143. if (classType.hasAttribute(field)) {
  15144. const g = m.graph();
  15145. const n = g.insertNode(g.createGetAttr(this._value, field));
  15146. return new torch._C.SimpleValue(n.output());
  15147. }
  15148. const prop = classType.getProperty(field);
  15149. if (prop) {
  15150. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15151. }
  15152. } else if (this._value.type() instanceof torch.InterfaceType) {
  15153. throw new python.Error('Not implemented.');
  15154. } else if (this._value.type() instanceof torch.EnumType) {
  15155. const g = m.graph();
  15156. if (field === 'name') {
  15157. const n = g.insertNode(g.createEnumName(this._value));
  15158. return new torch._C.SimpleValue(n.output());
  15159. }
  15160. if (field === 'value') {
  15161. const n = g.insertNode(g.createEnumValue(this._value));
  15162. return new torch._C.SimpleValue(n.output());
  15163. }
  15164. }
  15165. if (field === 'type') {
  15166. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15167. if (builtin) {
  15168. return builtin;
  15169. }
  15170. }
  15171. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15172. if (builtin) {
  15173. return builtin;
  15174. }
  15175. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15176. return torch._C.SpecialFormValue.create('prim::tolist');
  15177. }
  15178. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15179. return torch._C.SpecialFormValue.create('aten::index');
  15180. }
  15181. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15182. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15183. if (builtin) {
  15184. return builtin;
  15185. }
  15186. }
  15187. throw new python.Error('Object has no attribute or method.');
  15188. }
  15189. setAttr(loc, m, field, newValue) {
  15190. const type = this._value.type();
  15191. if (type instanceof torch.ClassType === false) {
  15192. throw new python.Error('Cannot set attribute on non-class type.');
  15193. }
  15194. const classType = type;
  15195. let expectedType = classType.findAttribute(field);
  15196. if (!expectedType) {
  15197. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15198. if (isInitializing) {
  15199. if (this.isRecursive(classType, newValue.type())) {
  15200. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15201. }
  15202. classType.addAttribute(field, newValue.type());
  15203. expectedType = newValue.type();
  15204. const insertPoint = m.graph().insertPoint();
  15205. const topLevelBlock = m.graph().block();
  15206. if (insertPoint.owningBlock() !== topLevelBlock) {
  15207. throw new python.Error('First assignment cannot be in a control-flow block.');
  15208. }
  15209. } else {
  15210. const prop = classType.getProperty(field);
  15211. if (prop && prop.setter) {
  15212. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15213. return;
  15214. }
  15215. if (prop && !prop.setter) {
  15216. throw new python.Error('Tried to set read-only attribute.');
  15217. }
  15218. throw new python.Error('Tried to set nonexistent attribute.');
  15219. }
  15220. }
  15221. torch._C.AT_ASSERT(expectedType);
  15222. const newType = newValue.type();
  15223. if (!newType.isSubtypeOf(expectedType)) {
  15224. throw new python.Error('Wrong type for attribute assignment.');
  15225. }
  15226. const g = m.graph();
  15227. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15228. }
  15229. getitem(loc, m, idx, type_hint) {
  15230. const val = this.getValue();
  15231. const val_type = val.type();
  15232. const g = m.graph();
  15233. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15234. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15235. } else if (val_type instanceof torch.DictType) {
  15236. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15237. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15238. 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));
  15239. } else if (val_type instanceof torch.ClassType) {
  15240. const class_type = val_type;
  15241. if (class_type.is_module() && type_hint) {
  15242. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15243. res.setType(type_hint);
  15244. return new torch._C.SimpleValue(res);
  15245. }
  15246. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15247. }
  15248. throw new python.Error('Object is not subscriptable.');
  15249. }
  15250. });
  15251. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15252. constructor(self, method_names) {
  15253. super();
  15254. this._self = self;
  15255. this._method_names = method_names;
  15256. }
  15257. call(loc, f, args, kwargs /*, n_binders */) {
  15258. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15259. const schemas = [];
  15260. for (const method_name of this._method_names) {
  15261. const type = this._self.type();
  15262. if (type instanceof torch.ClassType) {
  15263. const class_type = type;
  15264. const method = class_type.getMethod(method_name);
  15265. method.ensure_defined();
  15266. schemas.push(method.getSchema());
  15267. } else if (type instanceof torch.InterfaceType) {
  15268. const interface_type = type;
  15269. schemas.push(interface_type.getMethod(method_name));
  15270. } else {
  15271. throw new python.Error('Method constructed that is not a class or interface.');
  15272. }
  15273. }
  15274. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15275. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15276. output.node().setSourceRange(loc);
  15277. return new torch._C.SimpleValue(output);
  15278. }
  15279. });
  15280. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15281. constructor(type) {
  15282. super();
  15283. this._type = type;
  15284. }
  15285. attr(loc, m, field) {
  15286. const hook = this._type.findHook(field);
  15287. if (hook) {
  15288. return new torch._C.FunctionValue(hook);
  15289. }
  15290. if (field !== '__new__') {
  15291. throw new python.Error('Tried to lookup unknown attribute on class.');
  15292. }
  15293. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15294. }
  15295. });
  15296. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15297. constructor(type) {
  15298. super();
  15299. this._type = type;
  15300. }
  15301. call(loc, m, args, kwargs /*, n_binders */) {
  15302. const g = m.graph();
  15303. const schema = this._type.schema();
  15304. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15305. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15306. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15307. self.setType(this._type);
  15308. return new torch._C.SimpleValue(self);
  15309. }
  15310. });
  15311. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15312. constructor(enum_type) {
  15313. super();
  15314. this._enum_type = enum_type;
  15315. }
  15316. attr(loc, m, field) {
  15317. const names_values = this._enum_type.enumNamesValues();
  15318. const it = names_values.find((nv) => nv[0] === field);
  15319. if (it === null) {
  15320. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15321. }
  15322. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15323. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15324. }
  15325. });
  15326. this.registerType('torch._C.EnumHolder', class {
  15327. constructor(type, name, value) {
  15328. this._type = type;
  15329. this._name = name;
  15330. this._value = value;
  15331. }
  15332. name() {
  15333. return this._name;
  15334. }
  15335. type() {
  15336. return this._type;
  15337. }
  15338. });
  15339. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15340. constructor(...args) {
  15341. super();
  15342. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15343. this._callees = [args[0]];
  15344. } else {
  15345. throw new python.Error('Not implemented.');
  15346. }
  15347. }
  15348. call(loc, f, args, kwargs /*, n_binders */) {
  15349. const schemas = [];
  15350. for (const callee of this._callees) {
  15351. callee.ensure_defined();
  15352. schemas.push(callee.getSchema());
  15353. }
  15354. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15355. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15356. output.node().setSourceRange(loc);
  15357. return new torch._C.SimpleValue(output);
  15358. }
  15359. });
  15360. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15361. });
  15362. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15363. call(loc, m, args, kwargs /*, n_binders */) {
  15364. const g = m.graph();
  15365. if (kwargs.length > 0) {
  15366. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15367. }
  15368. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15369. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15370. return new torch._C.NoneValue();
  15371. }
  15372. });
  15373. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15374. constructor(form) {
  15375. super();
  15376. this._form = form;
  15377. }
  15378. form() {
  15379. return this._form;
  15380. }
  15381. static create(form) {
  15382. return new torch._C.SpecialFormValue(form);
  15383. }
  15384. });
  15385. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15386. return new torch._C.MagicMethod(name, base);
  15387. });
  15388. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15389. constructor(symbol, self) {
  15390. super();
  15391. this.symbol = symbol;
  15392. this.self = self;
  15393. }
  15394. call(loc, m, args, kwargs /*, n_binders */) {
  15395. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15396. }
  15397. static tryCreate(symbol, self) {
  15398. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15399. if (!self) {
  15400. return new torch._C.BuiltinFunction(symbol, null);
  15401. }
  15402. const index = op.schema().argumentIndexWithName('self');
  15403. if (index) {
  15404. const type_env = new Map();
  15405. const formal_type = op.schema().arguments()[index].type();
  15406. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15407. if (!matched.success()) {
  15408. continue;
  15409. }
  15410. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15411. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15412. continue;
  15413. }
  15414. return new torch._C.BuiltinFunction(symbol, self);
  15415. }
  15416. }
  15417. return null;
  15418. }
  15419. });
  15420. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15421. constructor(name, version) {
  15422. super();
  15423. this.name = name;
  15424. this.version = version || null;
  15425. }
  15426. attr(loc, m, field) {
  15427. if (field === 'autograd') {
  15428. return new torch._C.BuiltinModule('aten', this.version);
  15429. }
  15430. const sym = `${this.name}::${field}`;
  15431. return new torch._C.BuiltinFunction(sym, null);
  15432. }
  15433. });
  15434. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15435. constructor(version) {
  15436. super();
  15437. this._version = version;
  15438. }
  15439. attr(loc, m, field) {
  15440. return new torch._C.BuiltinModule(field, this._version);
  15441. }
  15442. });
  15443. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15444. constructor(constants) {
  15445. super();
  15446. this._constants = constants;
  15447. this.non_holding_object_cache = new Map();
  15448. }
  15449. attr(loc, m, field) {
  15450. const offset = parseInt(field.substring(1), 10);
  15451. if (!Number.isInteger(offset)) {
  15452. throw new python.Error(`Invalid constant identifier '${field}.`);
  15453. }
  15454. if (offset < 0 || offset >= this._constants.length) {
  15455. throw new python.Error('Invalid constant index.');
  15456. }
  15457. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15458. let value = null;
  15459. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15460. const obj = ivalue.toObject();
  15461. if (!this.non_holding_object_cache.has(obj)) {
  15462. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15463. }
  15464. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15465. } else {
  15466. value = m.graph().insertConstant(this._constants[offset], loc);
  15467. }
  15468. value.setType(torch._C.unshapedType(value.type()));
  15469. return new torch._C.SimpleValue(value);
  15470. }
  15471. });
  15472. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15473. constructor(type, method) {
  15474. super(method, null);
  15475. this._type = type;
  15476. }
  15477. call(loc, m, args, kwargs, n_binders) {
  15478. if (args.length === 1 && kwargs.length === 0) {
  15479. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15480. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15481. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15482. const v = args[0].value(m.graph());
  15483. if (v.type().isSubtypeOf(this._type)) {
  15484. return new torch._C.SimpleValue(v);
  15485. } 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)) {
  15486. const len = len_op.call(loc, m, [v], [], 1);
  15487. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15488. }
  15489. }
  15490. return super.call(loc, m, args, kwargs, n_binders);
  15491. }
  15492. });
  15493. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15494. constructor(desugared_name, base) {
  15495. super();
  15496. this._base_value = base;
  15497. this._desugared_name = desugared_name;
  15498. }
  15499. call(loc, m, args, kwargs, n_binders) {
  15500. if (args.length > 0) {
  15501. const self = args[0].value(m.graph());
  15502. if (self.type() instanceof torch.ClassType) {
  15503. return new torch._C.SimpleValue(self)
  15504. .attr(loc, m, this._desugared_name)
  15505. .call(loc, m, args.slice(1), kwargs, n_binders);
  15506. }
  15507. }
  15508. if (!this._base_value) {
  15509. throw new python.Error('Invalid magic method.');
  15510. }
  15511. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15512. }
  15513. });
  15514. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15515. constructor(loc, m, inputs, static_len) {
  15516. super();
  15517. static_len = static_len || null;
  15518. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15519. throw new python.Error('Invalid range inputs.');
  15520. }
  15521. const g = m.graph();
  15522. if (inputs.length === 1) {
  15523. [this._end] = inputs;
  15524. this._start = g.insertConstant(0, loc);
  15525. this._step = g.insertConstant(1, loc);
  15526. this._has_only_end = true;
  15527. } else {
  15528. [this._start, this._end] = inputs;
  15529. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15530. this._has_only_end = false;
  15531. }
  15532. this._static_len = static_len;
  15533. }
  15534. staticLen() {
  15535. return this._static_len;
  15536. }
  15537. iter() {
  15538. return this;
  15539. }
  15540. len(loc, m) {
  15541. if (this._static_len) {
  15542. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15543. }
  15544. if (this._has_only_end) {
  15545. return this._end;
  15546. }
  15547. const g = m.graph();
  15548. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15549. }
  15550. getitem(loc, m, idx /*, type_hint */) {
  15551. if (this._has_only_end) {
  15552. return new torch._C.SimpleValue(idx);
  15553. }
  15554. const g = m.graph();
  15555. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15556. }
  15557. });
  15558. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15559. });
  15560. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15561. constructor(name, si) {
  15562. super();
  15563. this._basename = name;
  15564. this._si = si;
  15565. }
  15566. attr(loc, m, name) {
  15567. const fullName = new torch._C.QualifiedName(this._basename, name);
  15568. const serializable_type = this._si.findNamedType(fullName);
  15569. if (serializable_type) {
  15570. if (serializable_type instanceof torch.ClassType) {
  15571. return new torch._C.ClassValue(serializable_type);
  15572. } else if (serializable_type instanceof torch.TupleType) {
  15573. return new torch._C.NamedTupleConstructor(serializable_type);
  15574. } else if (serializable_type instanceof torch.EnumType) {
  15575. return new torch._C.SugaredEnumClass(serializable_type);
  15576. }
  15577. }
  15578. const fn = this._si.findFunction(fullName);
  15579. if (fn) {
  15580. return new torch._C.FunctionValue(fn);
  15581. }
  15582. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15583. }
  15584. });
  15585. this.registerType('torch.package.PackageImporter', class {
  15586. constructor(reader) {
  15587. this.zip_reader = reader;
  15588. }
  15589. load_pickle(module, resource) {
  15590. const name = `${module.replace(/\./, '/')}/${resource}`;
  15591. const stream = this.zip_reader.get_record(name);
  15592. const loaded_reduces = new Map();
  15593. this.storage_context = new torch._C.DeserializationStorageContext();
  15594. const unpickler = new pickle.Unpickler(stream);
  15595. unpickler.persistent_load = (saved_id) => {
  15596. switch (saved_id[0]) {
  15597. case 'storage': {
  15598. const [, storage_type, key, , size] = saved_id;
  15599. if (!this.storage_context.has_storage(key)) {
  15600. const storage = new storage_type(size);
  15601. if (!storage._set_cdata) {
  15602. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15603. }
  15604. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15605. const buffer = stream.peek();
  15606. storage._set_cdata(buffer);
  15607. this.storage_context.add_storage(key, storage);
  15608. }
  15609. return this.storage_context.get_storage(key);
  15610. }
  15611. case 'reduce_package': {
  15612. if (saved_id.length === 2) {
  15613. const [, func, args] = saved_id;
  15614. return execution.invoke(func, args);
  15615. }
  15616. const [, reduce_id, func, args] = saved_id;
  15617. if (!loaded_reduces.has(reduce_id)) {
  15618. const value = execution.invoke(func, [this].concat(args));
  15619. loaded_reduces.set(reduce_id, value);
  15620. }
  15621. return loaded_reduces.get(reduce_id);
  15622. }
  15623. default: {
  15624. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15625. }
  15626. }
  15627. };
  15628. const obj = unpickler.load();
  15629. this.storage_context = null;
  15630. return obj;
  15631. }
  15632. import_module(name) {
  15633. return execution.import(name);
  15634. }
  15635. });
  15636. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15637. const cu = new torch.jit.CompilationUnit();
  15638. cu.execution = execution;
  15639. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15640. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15641. module.forward = cpp_module.forward; // remove
  15642. return module;
  15643. });
  15644. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15645. switch (arguments.length) {
  15646. case 4: {
  15647. const [device, extra_files] = args;
  15648. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15649. return deserializer.deserialize(device, extra_files);
  15650. }
  15651. case 5: {
  15652. const [storage_context, device, ts_id] = args;
  15653. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15654. return deserializer.deserialize(device, null);
  15655. }
  15656. default: {
  15657. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15658. }
  15659. }
  15660. });
  15661. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15662. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15663. });
  15664. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15665. if (value instanceof torch.Node) {
  15666. const n = value;
  15667. if (n.kind() === 'prim::CallFunction') {
  15668. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15669. const function_constant = n.input(0).node();
  15670. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15671. return torch._C.tryToGraphFunction(fun_type.function());
  15672. }
  15673. if (n.kind() === 'prim::CallMethod') {
  15674. const name = n.s('name');
  15675. const class_type = n.input(0).type();
  15676. if (class_type instanceof torch.ClassType) {
  15677. const fn = class_type.getMethod(name);
  15678. return torch._C.tryToGraphFunction(fn);
  15679. }
  15680. }
  15681. return null;
  15682. } else if (value instanceof torch._C.Function) {
  15683. const fn = value;
  15684. if (!fn.isGraphFunction()) {
  15685. return null;
  15686. }
  15687. return fn;
  15688. }
  15689. throw new python.Error('Not implemented.');
  15690. });
  15691. this.registerType('torch._C.ModuleInstanceInfo', class {
  15692. constructor(module_type, instance_name) {
  15693. this._module_type = module_type;
  15694. this._instance_name = instance_name;
  15695. }
  15696. });
  15697. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15698. torch._C.TORCH_CHECK(step !== 0);
  15699. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15700. if (start._ === Number.MAX_SAFE_INTEGER) {
  15701. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15702. }
  15703. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15704. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15705. }
  15706. if (start._ < 0) {
  15707. start._ += length;
  15708. if (start._ < 0) {
  15709. start._ = (step < 0) ? -1 : 0;
  15710. }
  15711. } else if (start._ >= length) {
  15712. start._ = (step < 0) ? length - 1 : length;
  15713. }
  15714. if (stop._ < 0) {
  15715. stop._ += length;
  15716. if (stop._ < 0) {
  15717. stop._ = (step < 0) ? -1 : 0;
  15718. }
  15719. } else if (stop._ >= length) {
  15720. stop._ = (step < 0) ? length - 1 : length;
  15721. }
  15722. if (step < 0) {
  15723. if (stop._ < start._) {
  15724. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15725. }
  15726. } else if (start._ < stop._) {
  15727. return Math.floor((stop._ - start._ - 1) / step + 1);
  15728. }
  15729. return 0;
  15730. });
  15731. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15732. if (v.node().kind() === 'prim::TupleConstruct') {
  15733. return v.node().inputs();
  15734. }
  15735. const g = v.owningGraph();
  15736. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15737. });
  15738. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15739. /*
  15740. const new_node_cs = new_node.callstack();
  15741. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15742. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15743. if (new_node_cs) {
  15744. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15745. } else {
  15746. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15747. }
  15748. }
  15749. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15750. for (const block of new_node.blocks()) {
  15751. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15752. }
  15753. */
  15754. });
  15755. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15756. if (arg === undefined || typeof arg === 'boolean') {
  15757. const inline_optimized_graph = arg === undefined ? true : arg;
  15758. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15759. return torch._C.inlineCallTo(to_replace, callee, graph);
  15760. }
  15761. if (arg instanceof torch.Graph === false) {
  15762. throw new python.Error('Invalid argument.');
  15763. }
  15764. const callee_graph = arg;
  15765. const guard = new torch._C.WithInsertPoint(to_replace);
  15766. const value_map = new Map();
  15767. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15768. const new_callstack_entries = new Map();
  15769. let module_instance_info = null;
  15770. if (to_replace.kind() === 'prim::CallMethod') {
  15771. const class_type_ptr = to_replace.input(0).type();
  15772. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15773. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15774. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15775. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15776. } else {
  15777. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15778. }
  15779. }
  15780. const updated_nodes = new Set();
  15781. for (const kv of value_map) {
  15782. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15783. if (is_graph_input === -1) {
  15784. continue;
  15785. }
  15786. const new_node = kv[1].node();
  15787. if (updated_nodes.has(new_node)) {
  15788. continue;
  15789. }
  15790. updated_nodes.add(new_node);
  15791. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15792. }
  15793. const old_outputs = to_replace.outputs();
  15794. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15795. for (let i = 0; i < old_outputs.length; i++) {
  15796. if (old_outputs[i].hasDebugName()) {
  15797. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15798. }
  15799. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15800. }
  15801. to_replace.destroy();
  15802. guard.dispose();
  15803. return new_outputs;
  15804. });
  15805. this.registerFunction('torch._C.inlineCalls', (block) => {
  15806. for (const cur of block.nodes()) {
  15807. switch (cur.kind()) {
  15808. case 'prim::CallFunction': {
  15809. const graphFunction = torch._C.tryToGraphFunction(cur);
  15810. if (graphFunction) {
  15811. const function_constant = cur.input(0).node();
  15812. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15813. cur.removeInput(0);
  15814. let g = null;
  15815. const fallback = function_constant.hasAttribute('fallback');
  15816. if (fallback && graphFunction.get_executor().isOptimized()) {
  15817. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15818. if (!exec_plans.empty()) {
  15819. g = exec_plans.begin().second.graph;
  15820. torch._C.Inline(g);
  15821. }
  15822. }
  15823. if (g === null) {
  15824. g = graphFunction.optimized_graph();
  15825. }
  15826. torch._C.inlineCallTo(cur, graphFunction, g);
  15827. }
  15828. break;
  15829. }
  15830. case 'prim::CallMethod': {
  15831. const graphFunction = torch._C.tryToGraphFunction(cur);
  15832. if (graphFunction) {
  15833. torch._C.inlineCallTo(cur, graphFunction);
  15834. }
  15835. break;
  15836. }
  15837. default: {
  15838. for (const b of cur.blocks()) {
  15839. torch._C.inlineCalls(b);
  15840. }
  15841. }
  15842. }
  15843. }
  15844. });
  15845. this.registerFunction('torch._C.Inline', (graph) => {
  15846. torch._C.inlineCalls(graph.block());
  15847. });
  15848. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15849. torch._C.Inline(graph);
  15850. });
  15851. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15852. });
  15853. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15854. const cu = new torch.jit.CompilationUnit();
  15855. cu.execution = execution;
  15856. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15857. return torch.jit._script.wrap_cpp_module(cpp_module);
  15858. });
  15859. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15860. const init_fn = (script_module) => {
  15861. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15862. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15863. }
  15864. };
  15865. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15866. });
  15867. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15868. has_storage(name) {
  15869. return this.has(name);
  15870. }
  15871. get_storage(name) {
  15872. return this.get(name);
  15873. }
  15874. add_storage(name, storage) {
  15875. return this.set(name, storage);
  15876. }
  15877. });
  15878. this.registerType('torch.ScriptFunction', class {
  15879. constructor(name, graph /*, function_creator */) {
  15880. this._name = name;
  15881. this._graph = graph;
  15882. }
  15883. });
  15884. this.registerType('torch.ScriptMethod', class {
  15885. constructor(owner, value) {
  15886. this._owner = owner;
  15887. this._function = value;
  15888. }
  15889. get name() {
  15890. return this._function.name();
  15891. }
  15892. get owner() {
  15893. return this._owner;
  15894. }
  15895. __call__(/* args, kwargs */) {
  15896. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  15897. }
  15898. get graph() {
  15899. return this._function.graph();
  15900. }
  15901. get schema() {
  15902. // return this.function().getSchema();
  15903. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  15904. }
  15905. get code() {
  15906. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  15907. }
  15908. get code_with_constants() {
  15909. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  15910. }
  15911. });
  15912. this.registerType('torch.ScriptObject', class {
  15913. constructor(type) {
  15914. this._typ = type;
  15915. this._ivalue = {};
  15916. }
  15917. static create(type) {
  15918. if (type.is_module()) {
  15919. return new torch.ScriptModule(type);
  15920. }
  15921. return new torch.ScriptObject(type);
  15922. }
  15923. type() {
  15924. return this._typ;
  15925. }
  15926. _type() {
  15927. return this._typ; // torch.ClassType
  15928. }
  15929. __setstate__(state) {
  15930. const [attrs, qualname] = state;
  15931. this._typ = torch._C.getCustomClass(qualname);
  15932. if (!this._typ) {
  15933. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  15934. }
  15935. for (let i = 0; i < this._typ.numAttributes(); i++) {
  15936. const name = this._typ.getAttributeName(i);
  15937. this.__setattr__(name, attrs[i]);
  15938. }
  15939. }
  15940. find_method(basename) {
  15941. for (const fn of this.type().methods()) {
  15942. if (fn.name() === basename) {
  15943. return new torch.ScriptMethod(this /* _value() */, fn);
  15944. }
  15945. }
  15946. return null;
  15947. }
  15948. _get_method(name) {
  15949. const method = this.find_method(name);
  15950. if (method) {
  15951. return method;
  15952. }
  15953. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  15954. return null;
  15955. }
  15956. _has_method(name) {
  15957. return this.find_method(name) ? true : false;
  15958. }
  15959. _method_names() {
  15960. return this.type().methods().map((fn) => fn.name());
  15961. }
  15962. __setattr__(name, value) {
  15963. // if (this._type.hasContant(name))
  15964. this._ivalue[name] = value;
  15965. }
  15966. __getattr__(name) {
  15967. return this._ivalue[name];
  15968. }
  15969. hasattr(name) {
  15970. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  15971. }
  15972. getattr(name) {
  15973. return this.__getattr__(name);
  15974. }
  15975. _properties() {
  15976. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  15977. }
  15978. is_weak_compilation_ref() {
  15979. return true; // not implemented
  15980. }
  15981. });
  15982. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  15983. constructor(...args) {
  15984. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  15985. const [class_name, cu, shouldMangle] = args;
  15986. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  15987. } else {
  15988. super(...args);
  15989. }
  15990. }
  15991. get qualified_name() {
  15992. return this.type().qualified_name();
  15993. }
  15994. get code_with_constants() {
  15995. const const_map = {};
  15996. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  15997. return [null, const_map];
  15998. }
  15999. get graph() {
  16000. if (!this._graph) {
  16001. const fn = this._typ.getMethod('forward');
  16002. this._graph = fn.graph();
  16003. }
  16004. return this._graph;
  16005. }
  16006. static create_module_object(class_name, cu, shouldMangle) {
  16007. shouldMangle = shouldMangle || false;
  16008. if (!class_name.prefix()) {
  16009. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  16010. }
  16011. if (shouldMangle && cu.get_class(class_name)) {
  16012. class_name = cu.mangle(class_name);
  16013. }
  16014. const cls = torch.ClassType.create(class_name, cu, true);
  16015. cu.register_type(cls);
  16016. return [cls, cu];
  16017. }
  16018. register_module(name, module) {
  16019. this.type().addOrCheckAttribute(name, module.type());
  16020. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  16021. }
  16022. register_buffer(name, v) {
  16023. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  16024. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16025. }
  16026. register_parameter(name, v, is_buffer) {
  16027. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  16028. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16029. }
  16030. register_attribute(name, t, v, is_param, is_buffer) {
  16031. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  16032. // _ivalue()->setAttr(name, v);
  16033. }
  16034. });
  16035. this.registerType('torch.ModuleDict', class {
  16036. constructor(mod) {
  16037. this._module = mod;
  16038. }
  16039. items() {
  16040. const result = new Map();
  16041. const type = this._module.type();
  16042. for (let i = 0; i < type.numAttributes(); i++) {
  16043. const k = type.getAttributeName(i);
  16044. const t = type.getAttribute(i);
  16045. if (t && t.is_module()) {
  16046. result.set(k, this._module.__getattr__(k));
  16047. }
  16048. }
  16049. return result;
  16050. }
  16051. });
  16052. this.registerType('torch.ParameterDict', 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. if (type.is_parameter(i)) {
  16061. const k = type.getAttributeName(i);
  16062. const v = this._module.__getattr__(k);
  16063. if (v instanceof torch.Tensor) {
  16064. result.set(k, v);
  16065. }
  16066. }
  16067. }
  16068. return result;
  16069. }
  16070. });
  16071. this.registerType('torch.BufferDict', class {
  16072. constructor(mod) {
  16073. this._module = mod;
  16074. }
  16075. items() {
  16076. const result = new Map();
  16077. const type = this._module.type();
  16078. for (let i = 0; i < type.numAttributes(); i++) {
  16079. if (type.is_buffer(i)) {
  16080. const t = type.getAttribute(i);
  16081. if (t.isSubtypeOf(torch.TensorType.get())) {
  16082. const k = type.getAttributeName(i);
  16083. const v = this._module.__getattr__(k);
  16084. result.set(k, v);
  16085. }
  16086. }
  16087. }
  16088. return result;
  16089. }
  16090. });
  16091. this.registerType('torch._C.to_ir', class {
  16092. constructor(def, _resolver, self, method) {
  16093. this.method = method;
  16094. this.graph = method.graph();
  16095. this.resolver = _resolver;
  16096. this.integral_constants = new Map();
  16097. this.fp_constants = new Map();
  16098. this.complex_constants = new Map();
  16099. this.exit_blocks = new Set();
  16100. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16101. this._loop_status = 'NOT_IN_LOOP';
  16102. this.environment_stack = null;
  16103. this._def_stack = [];
  16104. this._temp_name_count = 0;
  16105. torch._C.AT_ASSERT(this.resolver);
  16106. this.pushFrame(this.graph.block(), true);
  16107. if (self && def && def.args.args.length === 0) {
  16108. throw new python.Error('Method must have a self argument.');
  16109. }
  16110. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16111. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16112. torch._C.ConvertToSSA(this.graph);
  16113. torch._C.CanonicalizeModifiedLoops(this.graph);
  16114. torch._C.NormalizeOps(this.graph.block());
  16115. torch._C.runCleanupPasses(this.graph);
  16116. }
  16117. pushFrame(b, starts_def) {
  16118. starts_def = starts_def || false;
  16119. if (starts_def) {
  16120. this._def_stack.push({});
  16121. }
  16122. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16123. }
  16124. popFrame(ends_def) {
  16125. const old_frame = this.environment_stack;
  16126. this.environment_stack = this.environment_stack.next;
  16127. if (ends_def) {
  16128. this._def_stack.pop();
  16129. }
  16130. return old_frame;
  16131. }
  16132. emitDef(def, self, block) {
  16133. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16134. if (schema.returns.length === 1) {
  16135. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16136. }
  16137. const args = this.emitFormalArguments(def, self, schema, block);
  16138. this.emitStatements(def.body);
  16139. this.handleMaybeNoReturn(def, block);
  16140. const returns = [this.emitOutput(def, schema, block)];
  16141. return new torch.FunctionSchema(def.name, '', args, returns);
  16142. }
  16143. emitFormalArguments(def, self, schema, block) {
  16144. const args = [];
  16145. const params = def.args.args;
  16146. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16147. if (schema.arguments.length !== expected_annotation_size) {
  16148. throw new python.Error('Invalid formal arguments.');
  16149. }
  16150. let it = 0;
  16151. if (self) {
  16152. const param = params[it];
  16153. const name = param.arg;
  16154. const new_input = block.addInput().setDebugName(name);
  16155. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16156. args.push(new torch.Argument(name, new_input.type()));
  16157. it++;
  16158. }
  16159. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16160. let arg_annotation_idx = 0;
  16161. for (; it < params.length; it++) {
  16162. const param = params[it];
  16163. const name = param.arg;
  16164. const new_input = block.addInput();
  16165. if (torch._C.meaningfulName(name)) {
  16166. new_input.setDebugName(name);
  16167. }
  16168. let arg = schema.arguments[arg_annotation_idx++];
  16169. if (shouldDeriveType) {
  16170. if (schema.arguments.length === 1) {
  16171. throw new python.Error('Invalid schema.');
  16172. }
  16173. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16174. arg = arg.cloneWithType(inferredStateType);
  16175. }
  16176. args.push(arg);
  16177. new_input.setType(arg.type);
  16178. this.environment_stack.setVar(param.range(), name, new_input);
  16179. }
  16180. return args;
  16181. }
  16182. emitOutput(range, schema, block) {
  16183. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16184. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16185. block.registerOutput(placeholder_return);
  16186. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16187. }
  16188. emitStatements(stmts) {
  16189. for (let i = 0; i < stmts.length; i++) {
  16190. const stmt = stmts[i];
  16191. if (stmt instanceof ast.If) {
  16192. this.emitIf(stmt);
  16193. } else if (stmt instanceof ast.While) {
  16194. this.emitWhile(stmt);
  16195. } else if (stmt instanceof ast.For) {
  16196. this.emitFor(stmt);
  16197. } else if (stmt instanceof ast.Assign) {
  16198. this.emitAssignment(stmt);
  16199. } else if (stmt instanceof ast.AnnAssign) {
  16200. this.emitAssignment(stmt);
  16201. } else if (stmt instanceof ast.Expr) {
  16202. this.emitSugaredExpr(stmt.value, 0);
  16203. } else if (stmt instanceof ast.Return) {
  16204. this.emitReturn(stmt);
  16205. } else if (stmt instanceof ast.Pass) {
  16206. // pass
  16207. } else if (stmt instanceof ast.With) {
  16208. this.emitWith(stmt);
  16209. } else {
  16210. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16211. }
  16212. if (this.exit_blocks.has(this.environment_stack.block())) {
  16213. return;
  16214. }
  16215. }
  16216. }
  16217. emitWith(stmt) {
  16218. const targets = stmt.items;
  16219. const entered = [];
  16220. for (const target of targets) {
  16221. const e = target.context_expr;
  16222. const rhs = this.emitExpr(e);
  16223. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16224. entered.push(rhs);
  16225. if (rhs.type() instanceof torch.ClassType === false) {
  16226. throw new python.Error('With item expression must return an object.');
  16227. }
  16228. const rhsClass = rhs.type();
  16229. const enterMethod = rhsClass.findMethod('__enter__');
  16230. const exitMethod = rhsClass.findMethod('__exit__');
  16231. if (!enterMethod || !exitMethod) {
  16232. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16233. }
  16234. const enterSchema = enterMethod.getSchema();
  16235. if (enterSchema.arguments.length !== 1) {
  16236. throw new python.Error('__enter__ must have only one argument and one return value.');
  16237. }
  16238. const exitSchema = exitMethod.getSchema();
  16239. if (exitSchema.arguments.length === 4) {
  16240. for (let i = 1; i < 4; i++) {
  16241. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16242. throw new python.Error('Argument of __exit__ must have Any type.');
  16243. }
  16244. }
  16245. } else {
  16246. throw new python.Error('__exit__ must have four arguments');
  16247. }
  16248. n.output(0).setType(enterSchema.returns[0].type);
  16249. if (target.optional_vars) {
  16250. throw new python.Error('Not implemented.');
  16251. // Var i = target.var().get();
  16252. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16253. }
  16254. }
  16255. this.emitStatements(stmt.body);
  16256. while (entered.length > 0) {
  16257. const input = entered.pop();
  16258. const n = this.graph.create('prim::Exit');
  16259. this.graph.insertNode(n);
  16260. n.addInput(input);
  16261. }
  16262. }
  16263. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16264. let max_trip_count_val = null;
  16265. if (iter_val === null) {
  16266. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16267. } else {
  16268. max_trip_count_val = iter_val.len(range, this.method);
  16269. }
  16270. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16271. const body_block = n.addBlock();
  16272. {
  16273. const condition_block = n.addBlock();
  16274. this.pushFrame(condition_block);
  16275. let out = null;
  16276. if (cond) {
  16277. const insert = new torch._C.WithInsertPoint(condition_block);
  16278. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16279. insert.dispose();
  16280. } else {
  16281. const insert = new torch._C.WithInsertPoint(n);
  16282. out = this.graph.insertConstant(true, range);
  16283. insert.dispose();
  16284. }
  16285. condition_block.registerOutput(out);
  16286. this.popFrame();
  16287. }
  16288. n.addInput(max_trip_count_val);
  16289. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16290. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16291. {
  16292. this.pushFrame(body_block);
  16293. const guard = new torch._C.WithInsertPoint(body_block);
  16294. if (iter_val !== null && targets) {
  16295. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16296. const sv = new torch._C.SimpleValue(cur_elem);
  16297. const target_exprs = targets;
  16298. this.validateAssignLhsExpr(target_exprs, range);
  16299. if (target_exprs.length > 1) {
  16300. throw new python.Error('Not implemented.');
  16301. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16302. // target_exprs = ListExpr.create(range, [tl]);
  16303. }
  16304. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16305. }
  16306. emit_body();
  16307. this.popFrame();
  16308. guard.dispose();
  16309. }
  16310. loop_guard.dispose();
  16311. }
  16312. emitFor(...args) {
  16313. if (args.length === 1 && args[0] instanceof ast.For) {
  16314. const [stmt] = args;
  16315. const emit_body = () => this.emitStatements(stmt.body);
  16316. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16317. } else if (args.length === 4) {
  16318. const [targets, itrs, loc, emit_body] = args;
  16319. if (itrs instanceof ast.Tuple) {
  16320. throw new python.Error('List of iterables is not supported currently.');
  16321. }
  16322. const sv = this.emitSugaredExpr(itrs, 1);
  16323. const iterable = sv.iter(loc, this.method);
  16324. if (iterable.shouldEmitUnrolled()) {
  16325. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16326. } else {
  16327. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16328. }
  16329. } else {
  16330. throw new python.Error('Not implemented.');
  16331. }
  16332. }
  16333. emitWhile(stmt) {
  16334. const cond = stmt.test;
  16335. const emit_body = () => this.emitStatements(stmt.body);
  16336. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16337. }
  16338. emitIsInstance(obj, classinfo) {
  16339. const lhs_val = this.emitExpr(obj);
  16340. const lhs_types = [];
  16341. const rhs_types = [];
  16342. const gather_rhs = (expr) => {
  16343. if (expr instanceof ast.Tuple) {
  16344. for (const e of expr.elts) {
  16345. gather_rhs(e);
  16346. }
  16347. return;
  16348. }
  16349. const type = this._typeParser.parseTypeFromExpr(expr);
  16350. rhs_types.push(type);
  16351. };
  16352. lhs_types.push(lhs_val.type());
  16353. gather_rhs(classinfo);
  16354. torch._C.standardizeVectorForUnion(lhs_types);
  16355. torch._C.standardizeVectorForUnion(rhs_types);
  16356. let refinement = new torch._C.RefinementSet([], []);
  16357. let unified_true = null;
  16358. let unified_false = null;
  16359. const isinstance_types = [];
  16360. const not_isinstance_types = [];
  16361. let true_refinements = [];
  16362. let false_refinements = [];
  16363. let all_lhs_subtype_some_rhs = true;
  16364. for (const lhs_type of lhs_types) {
  16365. if (lhs_type === torch.AnyType.get()) {
  16366. isinstance_types.push(...rhs_types);
  16367. not_isinstance_types.push(torch.AnyType.get());
  16368. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16369. all_lhs_subtype_some_rhs = false;
  16370. }
  16371. break;
  16372. }
  16373. const get_smaller_type = (t1, t2) => {
  16374. if (t1.isSubtypeOf(t2)) {
  16375. return t1;
  16376. } else if (t2.isSubtypeOf(t1)) {
  16377. return t2;
  16378. }
  16379. return null;
  16380. };
  16381. let found_refinement = null;
  16382. for (const rhs_type of rhs_types) {
  16383. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16384. if (!maybe_smaller_type) {
  16385. continue;
  16386. } else if (maybe_smaller_type === lhs_type) {
  16387. found_refinement = lhs_type;
  16388. } else if (maybe_smaller_type === rhs_type) {
  16389. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16390. }
  16391. }
  16392. if (found_refinement) {
  16393. if (found_refinement === lhs_type) {
  16394. all_lhs_subtype_some_rhs &= true;
  16395. }
  16396. isinstance_types.push(found_refinement);
  16397. } else {
  16398. not_isinstance_types.push(lhs_type);
  16399. all_lhs_subtype_some_rhs = false;
  16400. }
  16401. }
  16402. if (isinstance_types.length > 0) {
  16403. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16404. }
  16405. if (obj instanceof ast.Name && unified_true) {
  16406. const ident = obj.id;
  16407. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16408. }
  16409. if (not_isinstance_types.length > 0) {
  16410. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16411. }
  16412. if (obj instanceof ast.Name && unified_false) {
  16413. const ident = obj.id;
  16414. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16415. }
  16416. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16417. const is_statically_false = isinstance_types.length === 0;
  16418. if (all_lhs_subtype_some_rhs) {
  16419. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16420. }
  16421. if (is_statically_false) {
  16422. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16423. }
  16424. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16425. return new torch._C.CondValue(result, refinement, null);
  16426. }
  16427. emitIf(stmt) {
  16428. const cond_value = this.emitCondExpr(stmt.test);
  16429. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16430. }
  16431. emitCondExpr(expr) {
  16432. /*
  16433. switch (expr.kind()) {
  16434. case TK_AND:
  16435. case TK_OR: {
  16436. const binop = BinOp(expr);
  16437. return emitShortCircuitLogical(
  16438. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16439. }
  16440. case TK_NOT: {
  16441. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16442. Value* result = emitBuiltinCall(
  16443. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16444. std::optional<bool> static_if;
  16445. if (v.staticIf()) {
  16446. static_if = !*v.staticIf();
  16447. }
  16448. return CondValue(result, v.refinements().Not(), static_if);
  16449. } break;
  16450. case TK_IS:
  16451. case TK_ISNOT: {
  16452. // meta programming on AST for is/is not cases and emit branches base on
  16453. const cond_op = BinOp(expr);
  16454. Value* lhs_val = emitExpr(cond_op.lhs());
  16455. Value* rhs_val = emitExpr(cond_op.rhs());
  16456. const lhs_none = canBeNone(lhs_val);
  16457. const rhs_none = canBeNone(rhs_val);
  16458. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16459. // AA, -> statically IS always holds, IS_NOT never holds
  16460. // AN , NA-> statically IS_NOT always holds, IS never holds
  16461. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16462. bool its_is = expr.kind() == TK_IS;
  16463. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16464. return CondValue(*graph, expr.range(), its_is, {});
  16465. } else if (
  16466. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16467. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16468. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16469. return CondValue(*graph, expr.range(), !its_is, {});
  16470. } else {
  16471. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16472. Value* cond_value = emitBuiltinCall(
  16473. expr.get()->range(),
  16474. *method.graph(),
  16475. kind,
  16476. {lhs_val, rhs_val},
  16477. {});
  16478. const refinements = RefinementSet(findIsNoneRefinements(
  16479. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16480. return CondValue(cond_value, refinements, null);
  16481. }
  16482. } break;
  16483. */
  16484. if (expr instanceof ast.UnaryOp) {
  16485. throw new python.Error('Not implemented.');
  16486. }
  16487. if (expr instanceof ast.Call) {
  16488. const apply = expr;
  16489. const callee = expr.func;
  16490. if (callee instanceof ast.Name) {
  16491. if (callee.id === 'isinstance') {
  16492. this.checkApplyNumInputs(apply, 2);
  16493. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16494. }
  16495. if (callee.id === 'hasattr') {
  16496. this.checkApplyNumInputs(apply, 2);
  16497. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16498. }
  16499. const sv = this.emitSugaredExpr(callee, 1);
  16500. if (sv instanceof torch._C.SpecialFormValue) {
  16501. if (sv.form() === 'prim::isinstance') {
  16502. this.checkApplyNumInputs(apply, 2);
  16503. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16504. }
  16505. }
  16506. }
  16507. }
  16508. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16509. let static_if = null;
  16510. const kind = expr_out.node().kind();
  16511. if (kind === 'aten::is_scripting') {
  16512. static_if = true;
  16513. } else if (kind === 'aten::has_torch_function') {
  16514. static_if = false;
  16515. }
  16516. const maybe_ivalue = torch._C.toIValue(expr_out);
  16517. if (maybe_ivalue) {
  16518. static_if = maybe_ivalue.toBool();
  16519. }
  16520. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16521. }
  16522. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16523. if (cond_value.staticIf() !== null) {
  16524. if (cond_value.staticIf()) {
  16525. this.insertRefinements(loc, cond_value.refinements());
  16526. this.emitStatements(trueBranch);
  16527. } else {
  16528. this.insertRefinements(loc, cond_value.refinements().Not());
  16529. this.emitStatements(falseBranch);
  16530. }
  16531. return;
  16532. }
  16533. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16534. n.addInput(cond_value.value());
  16535. const true_block = n.addBlock();
  16536. const false_block = n.addBlock();
  16537. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16538. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16539. const true_exits = this.exit_blocks.has(true_block);
  16540. const false_exits = this.exit_blocks.has(false_block);
  16541. if (true_exits && false_exits) {
  16542. this.exit_blocks.add(n.owningBlock());
  16543. }
  16544. const mutated_variables = new Set();
  16545. for (const v of save_true.definedVariables()) {
  16546. const insert = new torch._C.WithInsertPoint(false_block);
  16547. if (save_false.findInAnyFrame(v) || false_exits) {
  16548. mutated_variables.add(v);
  16549. } else {
  16550. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16551. }
  16552. insert.dispose();
  16553. }
  16554. for (const v of save_false.definedVariables()) {
  16555. const insert = new torch._C.WithInsertPoint(true_block);
  16556. if (save_true.findInAnyFrame(v) || true_exits) {
  16557. mutated_variables.add(v);
  16558. } else {
  16559. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16560. }
  16561. insert.dispose();
  16562. }
  16563. for (const x of mutated_variables) {
  16564. let tv = null;
  16565. let fv = null;
  16566. {
  16567. const insert = new torch._C.WithInsertPoint(true_block);
  16568. if (!true_exits) {
  16569. tv = save_true.getVar(x, loc);
  16570. }
  16571. insert.dispose();
  16572. }
  16573. {
  16574. const insert = new torch._C.WithInsertPoint(false_block);
  16575. if (!false_exits) {
  16576. fv = save_false.getVar(x, loc);
  16577. }
  16578. insert.dispose();
  16579. }
  16580. if (true_exits && false_exits) {
  16581. continue;
  16582. } else if (true_exits) {
  16583. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16584. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16585. } else if (false_exits) {
  16586. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16587. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16588. }
  16589. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16590. let full_type = null;
  16591. if (maybe_sugared_x) {
  16592. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16593. if (maybe_simple) {
  16594. full_type = maybe_simple.type();
  16595. }
  16596. }
  16597. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16598. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16599. if (!unified) {
  16600. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16601. throw new python.Error('Type mismatch.');
  16602. } else {
  16603. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16604. continue;
  16605. }
  16606. }
  16607. this.environment_stack.setType(x, unified);
  16608. }
  16609. }
  16610. emitSingleIfBranch(b, branch, refinements) {
  16611. this.pushFrame(b);
  16612. const guard = new torch._C.WithInsertPoint(b);
  16613. this.insertRefinements(branch, refinements);
  16614. this.emitStatements(branch);
  16615. const frame = this.popFrame();
  16616. guard.dispose();
  16617. return frame;
  16618. }
  16619. create(kind, loc, n_outputs) {
  16620. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16621. }
  16622. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16623. is_dict_constructor = is_dict_constructor || false;
  16624. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16625. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16626. if (!is_dict_constructor && candidate_types.length === 0) {
  16627. throw new python.Error("No matching types found in Union type annotation.");
  16628. } else if (candidate_types.length === 1) {
  16629. [refined_type_hint_ptr._] = candidate_types;
  16630. } else {
  16631. all_candidates._ = candidate_types;
  16632. }
  16633. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16634. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16635. }
  16636. if (is_dict_constructor) {
  16637. return;
  16638. }
  16639. if (all_candidates._.length === 0) {
  16640. if (type_match(refined_type_hint_ptr._)) {
  16641. do_if_match();
  16642. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16643. do_if_anytype();
  16644. } else {
  16645. throw new python.Error('Invalid annotation type.');
  16646. }
  16647. }
  16648. }
  16649. emitToBool(loc, v) {
  16650. let out = null;
  16651. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16652. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16653. if (!out) {
  16654. throw new python.Error('Could not cast value to bool.');
  16655. }
  16656. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16657. throw new python.Error('Expected a bool expression for condition.');
  16658. }
  16659. return out;
  16660. }
  16661. emitUnaryOp(tree, magicMethod, opSymbol) {
  16662. const inputs = [tree.operand];
  16663. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16664. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16665. if (val.node().kind() !== opSymbol) {
  16666. return val;
  16667. }
  16668. const maybe_out_stack = torch._C.runNodeIfInputsAreConstant(val.node());
  16669. if (!maybe_out_stack) {
  16670. return val;
  16671. }
  16672. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16673. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16674. }
  16675. emitAssignment(stmt) {
  16676. if (stmt instanceof ast.AnnAssign) {
  16677. return this.emitSingleAssignment(stmt);
  16678. }
  16679. if (stmt.targets.length === 1) {
  16680. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16681. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16682. for (const [key, value] of entries) {
  16683. assign[key] = value;
  16684. }
  16685. return this.emitSingleAssignment(assign);
  16686. }
  16687. if (stmt.targets.length <= 1) {
  16688. throw new python.Error('Invalid assignment.');
  16689. }
  16690. throw new python.Error('Not implemented.');
  16691. /*
  16692. const tmp_name = this.createTempName('$tmp_assign_');
  16693. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16694. const ident = new ast.Name(tmp_name);
  16695. for (const expr of lhs_list) {
  16696. const assign = new ast.Assign(targets, value, ctx);
  16697. this.emitSingleAssignment(Assign.create(stmt,
  16698. List<Expr>.create(expr.range(), [expr]),
  16699. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16700. Maybe<Expr>::create(stmt.range())));
  16701. }
  16702. */
  16703. }
  16704. emitSingleAssignment(stmt) {
  16705. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16706. const rhs = stmt.value;
  16707. const lhs = stmt.target;
  16708. if (lhs instanceof ast.Name) {
  16709. let type = null;
  16710. if (stmt.annotation) {
  16711. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16712. }
  16713. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16714. // BC HACK
  16715. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16716. } else if (lhs instanceof ast.Tuple) {
  16717. this.emitTupleAssign(lhs, rhs);
  16718. } else if (lhs instanceof ast.Attribute) {
  16719. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16720. } else {
  16721. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16722. }
  16723. }
  16724. emitSelectAssign(lhs, rhs, type, loc) {
  16725. if (!rhs) {
  16726. throw new python.Error('Expected RHS for assignment.');
  16727. }
  16728. let type_hint = null;
  16729. if (type) {
  16730. type_hint = this._typeParser.parseTypeFromExpr(type);
  16731. }
  16732. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16733. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16734. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16735. }
  16736. emitTupleAssign(...args) {
  16737. if (args.length === 2) {
  16738. const [tl, rhs] = args;
  16739. let n_binders = tl.elts.length;
  16740. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16741. if (starred_unpack) {
  16742. n_binders--;
  16743. }
  16744. const output = this.emitSugaredExpr(rhs, n_binders);
  16745. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16746. } else if (args.length === 5) {
  16747. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16748. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16749. if (outputs.length < n_binders) {
  16750. throw new python.Error('Not enough values to unpack.');
  16751. }
  16752. if (outputs.length > n_binders && !starred_unpack) {
  16753. throw new python.Error('Too many values to unpack.');
  16754. }
  16755. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16756. } else {
  16757. throw new python.Error('Not implemented.');
  16758. }
  16759. }
  16760. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16761. let i = 0;
  16762. for (const assignee of lhs_exprs) {
  16763. if (assignee instanceof ast.Subscript) {
  16764. throw new python.Error('Not implemented.');
  16765. /*
  16766. this.emitSubscriptAssign(
  16767. rhs_loc,
  16768. Subscript(assignee),
  16769. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16770. i++;
  16771. */
  16772. } else if (assignee instanceof ast.Name) {
  16773. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16774. i++;
  16775. } else if (assignee instanceof ast.Starred) {
  16776. throw new python.Error('Not implemented.');
  16777. /*
  16778. const var = Starred(assignee).expr();
  16779. if (var.kind() != TK_VAR) {
  16780. throw(
  16781. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16782. }
  16783. size_t n_matched = outputs.size() - n_binders;
  16784. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16785. const values = fmap(
  16786. outputs_ref.slice(i, n_matched),
  16787. [&](const std::shared_ptr<SugaredValue>& v) {
  16788. return v.asValue(assignee.range(), method);
  16789. });
  16790. const tup = graph.insertNode(graph.createTuple(values)).output();
  16791. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16792. i += n_matched;
  16793. */
  16794. } else if (assignee instanceof ast.Tuple) {
  16795. throw new python.Error('Not implemented.');
  16796. /*
  16797. // recursively emit tuple assignments on tuple literal input
  16798. TupleLiteral sub_tl = TupleLiteral(assignee);
  16799. size_t sub_n_binders = sub_tl.inputs().length;
  16800. bool sub_starred_unpack =
  16801. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16802. if (sub_starred_unpack)
  16803. sub_n_binders--;
  16804. emitTupleAssign(
  16805. sub_tl,
  16806. outputs.at(i),
  16807. rhs_loc,
  16808. sub_n_binders,
  16809. sub_starred_unpack);
  16810. i++;
  16811. */
  16812. } else if (assignee instanceof ast.Attribute) {
  16813. throw new python.Error('Not implemented.');
  16814. /*
  16815. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16816. i++;
  16817. */
  16818. } else {
  16819. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16820. }
  16821. }
  16822. }
  16823. emitReturn(stmt) {
  16824. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16825. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16826. if (declared_return_type) {
  16827. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16828. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16829. }
  16830. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16831. throw new python.Error(`Invalid return type.`);
  16832. }
  16833. } else {
  16834. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16835. if (!declared_return_type) {
  16836. declared_return_type = actual_return.type();
  16837. }
  16838. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16839. if (!merged_return_type) {
  16840. throw new python.Error(`Invalid return type.`);
  16841. }
  16842. declared_return_type = merged_return_type;
  16843. }
  16844. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16845. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16846. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16847. }
  16848. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16849. this.exit_blocks.add(this.environment_stack.block());
  16850. }
  16851. getNamedValues(trees, maybe_unpack) {
  16852. const values = [];
  16853. for (const tree of trees) {
  16854. if (maybe_unpack && tree instanceof ast.Starred) {
  16855. throw new python.Error('Starred argument not supported.');
  16856. } else {
  16857. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16858. }
  16859. }
  16860. return values;
  16861. }
  16862. getValues(trees, maybe_unpack) {
  16863. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16864. }
  16865. emitExpr(tree, type_hint) {
  16866. type_hint = type_hint || null;
  16867. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16868. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16869. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16870. }
  16871. return out_val;
  16872. }
  16873. emitSugaredExpr(tree, n_binders, type_hint) {
  16874. if (tree instanceof ast.Name) { // TK_VAR
  16875. return this.environment_stack.getSugaredVar(tree.id);
  16876. } else if (tree instanceof ast.Attribute) {
  16877. const sv = this.emitSugaredExpr(tree.value, 1);
  16878. return sv.attr(tree.range(), this.method, tree.attr);
  16879. } else if (tree instanceof ast.Call) { // TK_APPLY
  16880. return this.emitApplyExpr(tree, n_binders, type_hint);
  16881. } if (tree instanceof ast.Subscript) {
  16882. return this.emitSubscript(tree, type_hint);
  16883. }
  16884. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  16885. }
  16886. emitApplyExpr(apply, n_binders, type_hint) {
  16887. type_hint = type_hint || null;
  16888. const sv = this.emitSugaredExpr(apply.func, 1);
  16889. const loc = apply.func.range();
  16890. if (sv instanceof torch._C.SpecialFormValue) {
  16891. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  16892. }
  16893. const args = this.getNamedValues(apply.args, true);
  16894. const kwargs = this.emitAttributes(apply.keywords);
  16895. return sv.call(loc, this.method, args, kwargs, n_binders);
  16896. }
  16897. emitAttributes(attributes) {
  16898. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  16899. }
  16900. emitApplySpecialForm(form, apply, sv, type_hint) {
  16901. switch (form) {
  16902. case 'prim::fork': {
  16903. throw new python.Error('Not implemented.');
  16904. }
  16905. case 'prim::awaitable': {
  16906. throw new python.Error('Not implemented.');
  16907. }
  16908. case 'prim::annotate': {
  16909. this.checkApplyNumInputs(apply, 2);
  16910. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16911. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  16912. if (!expr.type().isSubtypeOf(type)) {
  16913. throw new python.Error('Invalid expression type.');
  16914. }
  16915. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  16916. const none = this.graph.createNone();
  16917. none.output().setType(type);
  16918. this.graph.insertNode(none);
  16919. expr = none.output();
  16920. }
  16921. return new torch._C.SimpleValue(expr);
  16922. }
  16923. case 'prim::unchecked_cast': {
  16924. this.checkApplyNumInputs(apply, 2);
  16925. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16926. let v = this.emitExpr(apply.args[1]);
  16927. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  16928. v = this.graph.insertUncheckedCast(v, type);
  16929. }
  16930. return new torch._C.SimpleValue(v);
  16931. }
  16932. case 'prim::GetAttr': {
  16933. this.checkApplyNumInputsRange(apply, 2, 3);
  16934. const obj = this.emitSugaredExpr(apply.args[0], 1);
  16935. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  16936. throw new python.Error('Invalid argument.');
  16937. }
  16938. const name = apply.args[1].value;
  16939. if (apply.args.length === 2) {
  16940. return obj.attr(apply, this.method, name);
  16941. } else if (obj.hasAttr(apply, this.method, name)) {
  16942. return obj.attr(apply, this.method, name);
  16943. }
  16944. return this.emitSugaredExpr(apply.inputs()[2], 1);
  16945. }
  16946. case 'prim::Uninitialized': {
  16947. this.checkApplyNumInputs(apply, 1);
  16948. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16949. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  16950. return new torch._C.SimpleValue(out.output());
  16951. }
  16952. case 'prim::TupleConstruct': {
  16953. throw new python.Error('Not implemented.');
  16954. }
  16955. case 'prim::isinstance': {
  16956. this.checkApplyNumInputs(apply, 2);
  16957. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  16958. return new torch._C.SimpleValue(result.value());
  16959. }
  16960. case 'prim::tolist': {
  16961. const value = apply.func.value;
  16962. const operand = this.emitSugaredExpr(value, 1);
  16963. if (!type_hint) {
  16964. throw new python.Error('Expected type hint for result of tolist().');
  16965. }
  16966. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  16967. }
  16968. case 'prim::HasAttr': {
  16969. throw new python.Error('Not implemented.');
  16970. }
  16971. case 'prim::CreateObject': {
  16972. if (apply.args.length !== 1) {
  16973. throw python.Error('Only one argument to __new__ allowed.');
  16974. }
  16975. const arg = this.emitSugaredExpr(apply.args[0], 1);
  16976. if (arg instanceof torch._C.ClassValue === false) {
  16977. throw python.Error('Expected class value as argument to __new__.');
  16978. }
  16979. const class_arg = arg;
  16980. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  16981. createNode.setSourceRange(apply.range());
  16982. return new torch._C.SimpleValue(createNode.output());
  16983. }
  16984. case 'prim::range': {
  16985. const input_vals = this.getValues(apply.args, true);
  16986. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  16987. }
  16988. case 'prim::enumerate': {
  16989. throw new python.Error('Not implemented.');
  16990. }
  16991. case 'prim::zip': {
  16992. throw new python.Error('Not implemented.');
  16993. }
  16994. case 'prim::list': {
  16995. throw new python.Error('Not implemented.');
  16996. }
  16997. case 'prim::dict': {
  16998. throw new python.Error('Not implemented.');
  16999. }
  17000. case 'aten::index': {
  17001. throw new python.Error('Not implemented.');
  17002. }
  17003. default: {
  17004. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  17005. }
  17006. }
  17007. }
  17008. emitSimpleExpr(tree, type_hint) {
  17009. if (tree instanceof ast.Constant) {
  17010. if (tree.value === true) {
  17011. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  17012. } else if (tree.value === false) {
  17013. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  17014. } else if (tree.value === null) {
  17015. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  17016. } else if (typeof tree.value === 'string') {
  17017. return this.emitStringLiteral(tree);
  17018. }
  17019. return this.emitConst(tree);
  17020. } else if (tree instanceof ast.List) {
  17021. return this.emitListLiteral(tree, type_hint);
  17022. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  17023. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  17024. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Constant) {
  17025. const c = tree.operand;
  17026. if (c.type === 'complex') {
  17027. return this.emitConst(new ast.Constant(new builtins.complex(-c.value.real, -c.value.imag), 'complex'));
  17028. }
  17029. return this.emitConst(new ast.Constant(-c.value, c.type));
  17030. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  17031. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  17032. } else if (tree instanceof ast.BinOp) {
  17033. return this.emitBinaryOp(tree);
  17034. } else if (tree instanceof ast.Dict) {
  17035. return this.emitDictLiteral(tree, type_hint);
  17036. } else if (tree instanceof ast.Tuple) {
  17037. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  17038. return this.graph.insertNode(this.graph.createTuple(values)).output();
  17039. }
  17040. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  17041. }
  17042. getNodeKind(kind /*, ninputs */) {
  17043. if (kind instanceof ast.Add) {
  17044. return 'aten::add';
  17045. } else if (kind instanceof ast.Sub) {
  17046. return 'aten::sub';
  17047. } else if (kind instanceof ast.Mult) {
  17048. return 'aten::mul';
  17049. }
  17050. /*
  17051. case TK_UNARY_MINUS: return 'aten::neg';
  17052. case TK_POW: return 'aten::pow';
  17053. case '@': return 'aten::matmul';
  17054. case TK_STARRED: return 'prim::Starred';
  17055. case '/': return 'aten::div';
  17056. case '%': return 'aten::remainder';
  17057. case TK_NE: return 'aten::ne';
  17058. case TK_EQ: return 'aten::eq';
  17059. case '<': return 'aten::lt';
  17060. case '>': return 'aten::gt';
  17061. case TK_LE: return 'aten::le';
  17062. case TK_GE: return 'aten::ge';
  17063. case TK_AND: return 'aten::__and__';
  17064. case TK_OR: return 'aten::__or__';
  17065. case TK_IS: return 'aten::__is__';
  17066. case TK_ISNOT: return 'aten::__isnot__';
  17067. case TK_NOT: return 'aten::__not__';
  17068. case TK_FLOOR_DIV: return 'aten::floordiv';
  17069. case TK_LSHIFT: return 'aten::__lshift__';
  17070. case TK_RSHIFT: return 'aten::__rshift__';
  17071. case '&': return 'aten::__and__';
  17072. case '|': return 'aten::__or__';
  17073. case '^': return 'aten::__xor__';
  17074. case TK_IN: return 'aten::__contains__';
  17075. */
  17076. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17077. }
  17078. getOperatorOverload(kind /*, ninputs */) {
  17079. if (kind instanceof ast.Add) {
  17080. return '__add__';
  17081. } else if (kind instanceof ast.Sub) {
  17082. return '__sub__';
  17083. } else if (kind instanceof ast.Mult) {
  17084. return '__mul__';
  17085. }
  17086. /*
  17087. case TK_UNARY_MINUS: return "__neg__";
  17088. case '~': return "__invert__";
  17089. case TK_POW: return "__pow__";
  17090. case '/': return "__truediv__";
  17091. case '%': return "__mod__";
  17092. case TK_NE: return "__ne__";
  17093. case TK_EQ: return "__eq__";
  17094. case '<': return "__lt__";
  17095. case '>': return "__gt__";
  17096. case TK_LE: return "__le__";
  17097. case TK_GE: return "__ge__";
  17098. case '&': return "__and__";
  17099. case '|': return "__or__";
  17100. case '^': return "__xor__";
  17101. case TK_IN: return "__contains__";
  17102. case TK_LSHIFT: return "__lshift__";
  17103. case TK_RSHIFT: return "__rshift__";
  17104. */
  17105. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17106. }
  17107. emitBinaryOp(tree) {
  17108. const inputs = [tree.left, tree.right];
  17109. const kind = this.getNodeKind(tree.op, inputs.length);
  17110. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17111. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17112. if (tree.op instanceof ast.In) {
  17113. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17114. throw new python.Error('Not implemented.');
  17115. }
  17116. if (named_values[0].type() instanceof torch.TupleType &&
  17117. named_values[1].type() instanceof torch.TupleType &&
  17118. kind === 'aten::add') {
  17119. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17120. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17121. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17122. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17123. }
  17124. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17125. }
  17126. emitDictLiteral(dl, type_hint) {
  17127. const key_trees = dl.keys;
  17128. const value_trees = dl.values;
  17129. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17130. const keys = [];
  17131. const values = [];
  17132. let rhs_value_type = null;
  17133. for (let i = 0; i < key_trees.length; i++) {
  17134. keys.push(this.emitExpr(key_trees[i]));
  17135. values.push(this.emitExpr(value_trees[i]));
  17136. if (i === 0) {
  17137. rhs_value_type = values[i].type();
  17138. } else {
  17139. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17140. throw new python.Error('Dict keys must contain only a single type.');
  17141. }
  17142. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17143. }
  17144. }
  17145. const refined_type_hint = { _: type_hint };
  17146. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17147. const all_candidates = { _: [] };
  17148. const default_refined_type_hint_setter = () => {
  17149. if (keys.length === 0) {
  17150. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17151. } else {
  17152. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17153. if (rhs_value_type instanceof torch.UnionType) {
  17154. throw new python.Error('Dict values consist of heterogeneous types.');
  17155. }
  17156. }
  17157. };
  17158. if (type_hint) {
  17159. const type_match = (t) => t instanceof torch.DictType;
  17160. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17161. if (all_candidates._.length > 0 && values.length === 0) {
  17162. throw new python.Error('Cannot assign an empty dict.');
  17163. }
  17164. } else {
  17165. default_refined_type_hint_setter();
  17166. }
  17167. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17168. if (values.length > 0) {
  17169. if (all_candidates._.length > 0) {
  17170. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17171. }
  17172. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17173. throw new python.Error('Type annotation does not match key type.');
  17174. }
  17175. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17176. throw new python.Error('Type annotation does not match value type.');
  17177. }
  17178. }
  17179. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17180. if (annotated_union_type) {
  17181. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17182. n.output().setType(annotated_union_type);
  17183. result = n;
  17184. }
  17185. return result.output();
  17186. }
  17187. emitStringLiteral(c) {
  17188. return torch._C.insertConstant(this.graph, c.value, c.range());
  17189. }
  17190. emitConst(c) {
  17191. if (c.type === 'int') {
  17192. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17193. } else if (c.type === 'complex') {
  17194. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17195. } else if (c.type === 'float') {
  17196. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17197. }
  17198. throw new python.Error(`Unsupported constant type.`);
  17199. }
  17200. emitListLiteral(ll, type_hint) {
  17201. type_hint = type_hint || null;
  17202. const values = this.getValues(ll.elts, true);
  17203. if (values.length === 0 && type_hint === null) {
  17204. throw new python.Error('Not implemented.');
  17205. }
  17206. let inferred_elem_type = torch.TensorType.get();
  17207. const refined_type_hint = { _: type_hint };
  17208. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17209. const all_candidates = { _: [] };
  17210. if (refined_type_hint._) {
  17211. const do_if_type_match = () => {
  17212. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17213. };
  17214. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17215. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17216. if (all_candidates._.length > 0 && values.len === 0) {
  17217. throw new python.Error('Cannot assign an empty list.');
  17218. }
  17219. }
  17220. if (values.length !== 0) {
  17221. const types = values.map((v) => v.type());
  17222. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17223. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17224. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17225. throw new python.Error('Not implemented.');
  17226. }
  17227. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17228. throw new python.Error('Not implemented.');
  17229. }
  17230. if (all_candidates._.length !== 0) {
  17231. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17232. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17233. }
  17234. if (!refined_type_hint._) {
  17235. inferred_elem_type = unified_elem_type;
  17236. }
  17237. }
  17238. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17239. if (annotated_union_type) {
  17240. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17241. n.output().setType(annotated_union_type);
  17242. result = n;
  17243. }
  17244. return result.output();
  17245. }
  17246. insertRefinements(loc, ref) {
  17247. for (const r of ref.activeRefinements()) {
  17248. const v = this.environment_stack.getVar(r.identifier(), loc);
  17249. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17250. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17251. }
  17252. }
  17253. shouldDeriveSetStateType(def, schema) {
  17254. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17255. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17256. if (!shouldInfer) {
  17257. return false;
  17258. }
  17259. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17260. throw new python.Error(`Invalid '__setstate' method.`);
  17261. }
  17262. return true;
  17263. }
  17264. checkApplyNumInputs(apply, expected_inputs) {
  17265. if (apply.args.length !== expected_inputs) {
  17266. throw new python.Error('Invalid number of arguments.');
  17267. }
  17268. if (apply.keywords.length > 0) {
  17269. throw new python.Error('Invalid number of keyword arguments.');
  17270. }
  17271. }
  17272. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17273. const position_arg_size = apply.args.length;
  17274. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17275. throw new python.Error('Invalid number of arguments.');
  17276. }
  17277. if (apply.keywords.length > 0) {
  17278. throw new python.Error('Invalid number of keyword arguments.');
  17279. }
  17280. }
  17281. validateAssignLhsExpr(lhs /*, r */) {
  17282. let num_normal_assign = 0;
  17283. let num_starred = 0;
  17284. for (const assignee of lhs) {
  17285. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17286. num_normal_assign++;
  17287. } else if (assignee instanceof ast.Starred) {
  17288. num_starred++;
  17289. } else {
  17290. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17291. }
  17292. }
  17293. if (num_starred > 1) {
  17294. throw new python.Error('Only one starred expression is allowed.');
  17295. }
  17296. if (num_starred > 0 && num_normal_assign === 0) {
  17297. throw new python.Error('Invalid starred expression.');
  17298. }
  17299. return num_starred;
  17300. }
  17301. createTempName(prefix) {
  17302. return `${prefix}${this._temp_name_count++}`;
  17303. }
  17304. handleMaybeNoReturn(def, block) {
  17305. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17306. if (this.exit_blocks.size === 0) {
  17307. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17308. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17309. }
  17310. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17311. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17312. b.dispose();
  17313. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17314. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17315. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17316. }
  17317. }
  17318. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17319. let adj_index = input_index;
  17320. const tuple_len = tuple_type.elements().length;
  17321. if (input_index < 0) {
  17322. adj_index = tuple_len + input_index;
  17323. }
  17324. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17325. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17326. }
  17327. return adj_index;
  17328. }
  17329. emitTupleIndex(loc, tuple_val, idx_val) {
  17330. const tuple_typ = tuple_val.type();
  17331. const elems = tuple_typ.elements();
  17332. let output_type = null;
  17333. if (idx_val.type() !== torch.IntType.get()) {
  17334. throw new python.Error('Tuple index must be an integer.');
  17335. }
  17336. const idx = torch._C.toIValue(idx_val);
  17337. if (idx) {
  17338. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17339. output_type = elems[adj_index];
  17340. } else {
  17341. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17342. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17343. }
  17344. [output_type] = elems;
  17345. }
  17346. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17347. }
  17348. getSliceInd(idx_val, loc) {
  17349. const ivalue = torch._C.toIValue(idx_val);
  17350. if (ivalue && ivalue.isInt()) {
  17351. return ivalue.toInt();
  17352. }
  17353. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17354. }
  17355. emitTupleSlice(loc, tuple_val, tuple_args) {
  17356. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17357. const tuple_len = tuple_type.elements().length;
  17358. const [beg_val, end_val, step] = tuple_args;
  17359. let step_size = 1;
  17360. if (step) {
  17361. const val = torch._C.toIValue(step.value(this.graph));
  17362. torch._C.TORCH_CHECK(val.isInt());
  17363. step_size = val.toInt();
  17364. }
  17365. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17366. if (beg_val) {
  17367. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17368. }
  17369. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17370. if (end_val) {
  17371. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17372. }
  17373. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17374. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17375. }
  17376. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17377. const args = [];
  17378. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17379. if (dim) {
  17380. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17381. args.emplace_back(new torch._C.NamedValue(dim));
  17382. } else {
  17383. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17384. }
  17385. if (sliceable.type() instanceof torch.TupleType) {
  17386. const tuple_args = [];
  17387. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17388. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17389. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17390. return this.emitTupleSlice(loc, args[0], tuple_args);
  17391. }
  17392. if (!step) {
  17393. step = this.graph.insertConstant(1, loc);
  17394. }
  17395. args.push(new torch._C.NamedValue(loc, 'start', start));
  17396. args.push(new torch._C.NamedValue(loc, 'end', end));
  17397. args.push(new torch._C.NamedValue(loc, 'step', step));
  17398. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17399. }
  17400. emitSlice(loc, input, dim, slice) {
  17401. let start = null;
  17402. let end = null;
  17403. let step = null;
  17404. if (slice.lower) {
  17405. start = this.emitExpr(slice.lower);
  17406. }
  17407. if (slice.upper) {
  17408. end = this.emitExpr(slice.upper);
  17409. }
  17410. if (slice.step) {
  17411. step = this.emitExpr(slice.step);
  17412. }
  17413. return this.emitSliceOp(loc, input, dim, start, end, step);
  17414. }
  17415. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17416. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17417. const slice_exp = subscript_exprs;
  17418. let maybe_dim = null;
  17419. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17420. maybe_dim = this.graph.insertConstant(0, loc);
  17421. }
  17422. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17423. }
  17424. emitSubscript(subscript, type_hint) {
  17425. type_hint = type_hint === undefined ? null : type_hint;
  17426. const sv = this.emitSugaredExpr(subscript.value, 1);
  17427. const subscript_exprs = subscript.slice;
  17428. const range = subscript.range();
  17429. const val_range = subscript.value;
  17430. if (subscript_exprs instanceof ast.Tuple) {
  17431. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17432. }
  17433. if (subscript_exprs instanceof ast.Slice) {
  17434. if (sv.kind() === 'module') {
  17435. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17436. const [slice] = subscript_exprs;
  17437. const tuple_args = [];
  17438. if (slice.start().present()) {
  17439. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17440. tuple_args.push(begin);
  17441. } else {
  17442. tuple_args.push(null);
  17443. }
  17444. if (slice.end().present()) {
  17445. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17446. tuple_args.push(end);
  17447. } else {
  17448. tuple_args.push(null);
  17449. }
  17450. if (slice.step().present()) {
  17451. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17452. tuple_args.push(step);
  17453. } else {
  17454. tuple_args.push(null);
  17455. }
  17456. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17457. return new torch._C.SimpleValue(tupleSliceValue);
  17458. }
  17459. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17460. }
  17461. const sliceable = sv.asValue(val_range, this.method);
  17462. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17463. if (subscript_sv instanceof torch._C.SliceValue) {
  17464. const slice_value = subscript_sv;
  17465. let dim = null;
  17466. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17467. dim = this.method.graph().insertConstant(0, val_range);
  17468. }
  17469. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17470. return new torch._C.SimpleValue(sliced);
  17471. }
  17472. const idx = subscript_sv.asValue(val_range, this.method);
  17473. if (sliceable.type() instanceof torch.TupleType) {
  17474. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17475. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17476. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17477. }
  17478. return sv.getitem(range, this.method, idx, type_hint);
  17479. }
  17480. });
  17481. this.registerType('torch.jit.CompilationUnit', class {
  17482. constructor() {
  17483. this._functions = new Map();
  17484. this._classes = new Map();
  17485. }
  17486. register_type(namedType) {
  17487. this._classes.set(namedType.annotation_str, namedType);
  17488. }
  17489. register_function(fn) {
  17490. const name = fn.qualname().qualifiedName();
  17491. torch._C.TORCH_CHECK(!this._functions.has(name));
  17492. this._functions.set(name, fn);
  17493. return fn;
  17494. }
  17495. define(...args) {
  17496. if (Array.isArray(args[1])) {
  17497. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17498. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17499. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17500. const functions = [];
  17501. const function_table = new Map();
  17502. const record_function = (fn) => {
  17503. function_table.set(fn.name(), fn);
  17504. functions.push(fn);
  17505. this.register_function(fn);
  17506. };
  17507. for (let i = 0; i < properties.length; i++) {
  17508. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17509. const getter_fn = property_fns.getGetter();
  17510. const setter_fn = property_fns.getSetter();
  17511. record_function(getter_fn);
  17512. if (setter_fn) {
  17513. record_function(setter_fn);
  17514. }
  17515. }
  17516. for (let i = 0; i < definitions.length; i++) {
  17517. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17518. record_function(fn);
  17519. }
  17520. for (const [name, fn] of function_table) {
  17521. if (name === '__init__') {
  17522. fn.ensure_defined();
  17523. }
  17524. }
  17525. for (const fn of functions) {
  17526. fn.ensure_defined();
  17527. }
  17528. return functions;
  17529. } else if (args[1] instanceof ast.FunctionDef) {
  17530. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17531. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17532. const creator = (method) => {
  17533. return new torch._C.to_ir(def, _resolver, self, method);
  17534. };
  17535. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17536. if (shouldMangle && this.find_function(name)) {
  17537. name = this.mangle(name);
  17538. }
  17539. const graph = new torch.Graph();
  17540. graph.set_op_version(operator_set_version);
  17541. const fn = new torch._C.GraphFunction(name, graph, creator);
  17542. fn.__ast__ = def; // remove
  17543. if (self) {
  17544. if (type === 'hook') {
  17545. self.getClassType().addForwardHook(fn);
  17546. } else if (type === 'prehook') {
  17547. self.getClassType().addPreHook(fn);
  17548. } else {
  17549. self.getClassType().addMethod(fn);
  17550. }
  17551. }
  17552. return fn;
  17553. }
  17554. throw new python.Error('Invalid arguments.');
  17555. }
  17556. get_type(name) {
  17557. return this._classes.get(name.qualifiedName());
  17558. }
  17559. get_class(name) {
  17560. return this.get_type(name);
  17561. }
  17562. find_function(name) {
  17563. const key = name.qualifiedName();
  17564. return this._functions.get(key);
  17565. }
  17566. });
  17567. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17568. const ctrl = new torch._C.ControlFlowLoadStores();
  17569. ctrl.run(graph);
  17570. const exit_vars = new torch._C.LoopContinuations();
  17571. exit_vars.run(graph);
  17572. torch._C.InlineLoopCondition(graph);
  17573. const erase_loads_stores = new torch._C.EraseLoadStores();
  17574. erase_loads_stores.run(graph);
  17575. torch._C.TransformExits(graph);
  17576. });
  17577. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17578. /*
  17579. LoopView loop(n);
  17580. if (loop.loopType() != LoopView::ModifiedLoop) {
  17581. return;
  17582. }
  17583. const g = n.owningGraph();
  17584. WithInsertPoint node_insert(n);
  17585. const zero = g.insertConstant(0);
  17586. const one = g.insertConstant(1);
  17587. const max_trip_count = loop.maxTripCount();
  17588. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17589. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17590. const inp_condition = toIValue(loop.inputCond());
  17591. if (inp_condition == null || inp_condition.toBool() == false) {
  17592. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17593. }
  17594. loop.replaceInputCondition(condition);
  17595. n.addOutput().setType(IntType::get());
  17596. WithInsertPoint loop_insert(loop.bodyBlock());
  17597. n.addInput(zero);
  17598. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17599. // unset unique name for jitter, its replacement does not have a name
  17600. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17601. const inc_iter = g.insert(aten::add, {new_iter, one});
  17602. loop.bodyBlock().registerOutput(inc_iter);
  17603. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17604. const loop_continue = loop.nextCond();
  17605. const new_condition =
  17606. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17607. loop.bodyBlock().eraseOutput(0);
  17608. loop.bodyBlock().insertOutput(0, new_condition);
  17609. */
  17610. });
  17611. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17612. for (const n of block.nodes()) {
  17613. for (const b of n.blocks()) {
  17614. torch._C.canonicalizeModifiedLoops(b);
  17615. }
  17616. if (n.kind() === 'prim::Loop') {
  17617. torch._C.canonicalizeModifiedLoop(n);
  17618. }
  17619. }
  17620. });
  17621. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17622. torch._C.canonicalizeModifiedLoops(graph.block());
  17623. });
  17624. this.registerType('torch._C.MiniEnvironment', class {
  17625. constructor(b, next) {
  17626. this.next = next || null;
  17627. this.table = new Map();
  17628. }
  17629. setVar(name, value) {
  17630. this.table.set(name, value);
  17631. }
  17632. definedVariables() {
  17633. const result = Array.from(this.table.keys());
  17634. return result.sort();
  17635. }
  17636. findInThisFrame(name) {
  17637. if (this.table.has(name)) {
  17638. return this.table.get(name);
  17639. }
  17640. return null;
  17641. }
  17642. findInAnyFrame(name) {
  17643. /* eslint-disable consistent-this */
  17644. const self = this;
  17645. /* eslint-enable consistent-this */
  17646. for (let runner = self; runner; runner = runner.next) {
  17647. const r = runner.findInThisFrame(name);
  17648. if (r) {
  17649. return r;
  17650. }
  17651. }
  17652. return null;
  17653. }
  17654. });
  17655. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17656. });
  17657. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17658. });
  17659. this.registerType('torch._C.ControlFlowLoadStores', class {
  17660. constructor() {
  17661. this.environment_stack = null;
  17662. }
  17663. pushFrame(b) {
  17664. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17665. }
  17666. popFrame() {
  17667. const old_frame = this.environment_stack;
  17668. this.environment_stack = this.environment_stack.next;
  17669. return old_frame;
  17670. }
  17671. addBlockInput(b, type, name) {
  17672. const g = b.owningGraph();
  17673. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17674. }
  17675. addBlockOutput(exit_block, type, name) {
  17676. const insert = new torch._C.WithInsertPoint(exit_block);
  17677. const g = exit_block.owningGraph();
  17678. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17679. exit_block.registerOutput(block_exit);
  17680. insert.dispose();
  17681. }
  17682. addNodeOutput(n, type, name) {
  17683. const out = n.addOutput().setType(type);
  17684. if (torch._C.meaningfulName(name)) {
  17685. out.setDebugName(name);
  17686. }
  17687. const g = n.owningGraph();
  17688. g.createStore(name, out).insertAfter(n);
  17689. }
  17690. addNodeInput(n, type, name) {
  17691. const g = n.owningGraph();
  17692. const inp = g.createLoad(name, type).insertBefore(n).output();
  17693. n.addInput(inp);
  17694. }
  17695. addIfLoadStores(n) {
  17696. const [true_block, false_block] = n.blocks();
  17697. const true_vars = this.addControlFlowLoadStores(true_block);
  17698. const false_vars = this.addControlFlowLoadStores(false_block);
  17699. const mutated_variables = new Set();
  17700. for (const v of true_vars.definedVariables()) {
  17701. if (false_vars.findInAnyFrame(v)) {
  17702. mutated_variables.add(v);
  17703. }
  17704. }
  17705. for (const v of false_vars.definedVariables()) {
  17706. if (true_vars.findInAnyFrame(v)) {
  17707. mutated_variables.add(v);
  17708. }
  17709. }
  17710. for (const x of mutated_variables) {
  17711. const true_type = true_vars.findInAnyFrame(x);
  17712. const false_type = false_vars.findInAnyFrame(x);
  17713. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17714. this.addBlockOutput(true_block, true_type, x);
  17715. this.addBlockOutput(false_block, false_type, x);
  17716. this.addNodeOutput(n, unified, x);
  17717. }
  17718. }
  17719. addLoopLoadStores(n) {
  17720. const [body_block] = n.blocks();
  17721. const loop_vars = this.addControlFlowLoadStores(body_block);
  17722. for (const name of loop_vars.definedVariables()) {
  17723. const parent_type = this.environment_stack.findInAnyFrame(name);
  17724. if (!parent_type) {
  17725. continue;
  17726. }
  17727. const block_type = loop_vars.findInThisFrame(name);
  17728. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17729. this.addNodeInput(n, parent_type, name);
  17730. this.addBlockInput(body_block, unified_type, name);
  17731. this.addBlockOutput(body_block, block_type, name);
  17732. this.addNodeOutput(n, unified_type, name);
  17733. }
  17734. }
  17735. addControlFlowLoadStores(block) {
  17736. this.pushFrame(block);
  17737. for (const n of block.nodes()) {
  17738. switch (n.kind()) {
  17739. case 'prim::If': {
  17740. this.addIfLoadStores(n);
  17741. break;
  17742. }
  17743. case 'prim::Loop': {
  17744. this.addLoopLoadStores(n);
  17745. break;
  17746. }
  17747. case 'prim::Closure': {
  17748. for (const b of n.blocks()) {
  17749. this.addControlFlowLoadStores(b);
  17750. }
  17751. break;
  17752. }
  17753. case 'prim::Store': {
  17754. this.environment_stack.setVar(n.s('name'), n.input().type());
  17755. break;
  17756. }
  17757. case 'prim::ComprehensionScope': {
  17758. this.addControlFlowLoadStores(n.blocks().at(0));
  17759. break;
  17760. }
  17761. default: {
  17762. break;
  17763. }
  17764. }
  17765. }
  17766. return this.popFrame();
  17767. }
  17768. run(graph) {
  17769. this.addControlFlowLoadStores(graph.block());
  17770. }
  17771. });
  17772. this.registerType('torch._C.LoopContinuations', class {
  17773. constructor() {
  17774. this._graph = null;
  17775. this._false_val = null;
  17776. this._curr_loop = null;
  17777. }
  17778. assignExitContinuations(block) {
  17779. for (const n of block.nodes()) {
  17780. switch (n.kind()) {
  17781. case 'prim::If': {
  17782. this.assignExitContinuations(n.blocks().at(0));
  17783. this.assignExitContinuations(n.blocks().at(1));
  17784. break;
  17785. }
  17786. case 'prim::Closure': {
  17787. const closure_block = new torch._C.LoopContinuations();
  17788. closure_block.run(n.blocks().at(0));
  17789. break;
  17790. }
  17791. case 'prim::Loop': {
  17792. const prev_loop = this._curr_loop;
  17793. this._curr_loop = n;
  17794. this.assignExitContinuations(n.blocks().at(0));
  17795. this._curr_loop = prev_loop;
  17796. break;
  17797. }
  17798. case 'prim::ContinueStmt': {
  17799. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17800. const header_block = loop_continuation.addBlock();
  17801. const [, pre_header] = this._curr_loop.blocks();
  17802. header_block.cloneFrom(pre_header, (v) => v);
  17803. this.InlineBlockBeforeNode(n, header_block);
  17804. loop_continuation.addInput(header_block.outputs()[0]);
  17805. loop_continuation.eraseBlock(0);
  17806. this.addLoopCarriedOutputs(loop_continuation);
  17807. n.destroy();
  17808. break;
  17809. }
  17810. case 'prim::BreakStmt': {
  17811. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17812. loop_exit.addInput(this._false_val);
  17813. this.addLoopCarriedOutputs(loop_exit);
  17814. n.destroy();
  17815. break;
  17816. }
  17817. default: {
  17818. break;
  17819. }
  17820. }
  17821. }
  17822. }
  17823. run(...args) {
  17824. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17825. const [graph] = args;
  17826. this.run(graph.block());
  17827. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17828. const [b] = args;
  17829. {
  17830. this._graph = b.owningGraph();
  17831. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17832. this._false_val = this._graph.insertConstant(false);
  17833. guard.dispose();
  17834. }
  17835. this.assignExitContinuations(b);
  17836. } else {
  17837. throw new python.Error('Not implemented.');
  17838. }
  17839. }
  17840. });
  17841. this.registerType('torch._C.LoopView', class {
  17842. constructor(node) {
  17843. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17844. this._node = node;
  17845. }
  17846. bodyBlock() {
  17847. return this._node.blocks().at(0);
  17848. }
  17849. nextCond() {
  17850. return this.bodyBlock().outputs()[0];
  17851. }
  17852. carriedOutputs() {
  17853. return this._node.outputs();
  17854. }
  17855. bodyCarriedInputs() {
  17856. return this.bodyBlock().inputs().slice(1);
  17857. }
  17858. bodyCarriedOutputs() {
  17859. return this.bodyBlock().outputs().slice(1);
  17860. }
  17861. });
  17862. this.registerType('torch._C.WithLoopStatus', class {
  17863. constructor(to_ir, new_status) {
  17864. this._to_ir = to_ir;
  17865. this._prev = this._to_ir._loop_status;
  17866. this._to_ir._loop_status = new_status;
  17867. }
  17868. dispose() {
  17869. this._to_ir._loop_status = this._prev;
  17870. }
  17871. });
  17872. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17873. for (const block_node of block.nodes()) {
  17874. block_node.moveBefore(before_node);
  17875. }
  17876. });
  17877. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  17878. if (args.length === 1 && args[0] instanceof torch.Block) {
  17879. const [block] = args;
  17880. for (const n of block.nodes()) {
  17881. for (const b of n.blocks()) {
  17882. torch._C.inlineLoopCondition(b);
  17883. }
  17884. if (n.kind() === 'prim::Loop') {
  17885. torch._C.inlineLoopCondition(n);
  17886. }
  17887. }
  17888. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  17889. const [n] = args;
  17890. const [body_block, pre_header] = n.blocks();
  17891. const temp_block = n.addBlock();
  17892. temp_block.cloneFrom(pre_header, (v) => v);
  17893. torch._C.InlineBlockBeforeNode(n, temp_block);
  17894. n.insertInput(1, temp_block.outputs()[0]);
  17895. n.eraseBlock(2);
  17896. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  17897. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  17898. n.eraseBlock(1);
  17899. } else {
  17900. throw new python.Error('Not implemented.');
  17901. }
  17902. });
  17903. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  17904. torch._C.inlineLoopCondition(graph.block());
  17905. });
  17906. this.registerType('torch._C.EraseLoadStores', class {
  17907. pushFrame(b) {
  17908. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  17909. }
  17910. popFrame() {
  17911. const old_frame = this.environment_stack;
  17912. this.environment_stack = this.environment_stack.next;
  17913. return old_frame;
  17914. }
  17915. eraseBlockLoadStores(block) {
  17916. this.pushFrame(block);
  17917. for (const n of block.nodes()) {
  17918. switch (n.kind()) {
  17919. case 'prim::Store': {
  17920. this.environment_stack.setVar(n.s('name'), n.input());
  17921. n.destroy();
  17922. break;
  17923. }
  17924. case 'prim::Load': {
  17925. const name = n.s('name');
  17926. const value = this.environment_stack.findInAnyFrame(name);
  17927. torch._C.TORCH_INTERNAL_ASSERT(value);
  17928. n.output().replaceAllUsesWith(value);
  17929. n.destroy();
  17930. break;
  17931. }
  17932. case 'prim::ComprehensionScope': {
  17933. const [body] = n.blocks();
  17934. this.eraseBlockLoadStores(body);
  17935. for (const body_node of body.nodes()) {
  17936. body_node.moveBefore(n);
  17937. }
  17938. n.destroy();
  17939. break;
  17940. }
  17941. default: {
  17942. for (const b of n.blocks()) {
  17943. this.eraseBlockLoadStores(b);
  17944. }
  17945. break;
  17946. }
  17947. }
  17948. }
  17949. this.popFrame();
  17950. }
  17951. run(graph) {
  17952. this.eraseBlockLoadStores(graph.block());
  17953. }
  17954. });
  17955. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  17956. });
  17957. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  17958. });
  17959. this.registerType('torch._C.ExitPair', class {
  17960. constructor(exit_v, exit_val_ref) {
  17961. const exit_vals = [];
  17962. for (const v of exit_val_ref) {
  17963. exit_vals.push(v);
  17964. }
  17965. if (exit_v.type() !== torch.BoolType.get()) {
  17966. throw new python.Error('Invalid exit value type.');
  17967. }
  17968. this.first = exit_v;
  17969. this.second = exit_vals;
  17970. }
  17971. hasExited() {
  17972. return this.first;
  17973. }
  17974. exitValues() {
  17975. return this.second;
  17976. }
  17977. });
  17978. this.registerType('torch._C.ExitTransformer', class {
  17979. constructor(graph) {
  17980. this._graph = graph;
  17981. this._target_block = null;
  17982. this._unit_values = new Map();
  17983. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  17984. this._true_val = this._graph.insertConstant(true);
  17985. this._false_val = this._graph.insertConstant(false);
  17986. this._throws_val = this.getUnitValue(torch.BoolType.get());
  17987. guard.dispose();
  17988. }
  17989. getUnitValue(type) {
  17990. const maybe_val = this._unit_values.get(type);
  17991. if (maybe_val) {
  17992. return maybe_val;
  17993. }
  17994. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  17995. this._unit_values.set(type, unit);
  17996. return unit;
  17997. }
  17998. transformReturnStmts() {
  17999. this._current_exit_kind = 'prim::ReturnStmt';
  18000. this.transformExits(this._graph.block());
  18001. }
  18002. transformLoopContinuations() {
  18003. this._current_exit_kind = 'prim::LoopContinuation';
  18004. this.transformExits(this._graph.block());
  18005. }
  18006. destroyNodeAfterExit(n) {
  18007. for (const output of n.outputs()) {
  18008. if (output.uses().length > 0) {
  18009. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  18010. }
  18011. }
  18012. n.destroy();
  18013. }
  18014. deleteAfterExitNodes(block, iter) {
  18015. const nodes = block.nodes();
  18016. if (iter === nodes.end()) {
  18017. return;
  18018. }
  18019. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  18020. for (const it of Array.from(nodes).reverse()) {
  18021. if (it === iter) {
  18022. break;
  18023. }
  18024. if (it !== block.return_node()) {
  18025. this.destroyNodeAfterExit(it);
  18026. }
  18027. }
  18028. this.destroyNodeAfterExit(iter);
  18029. insert.dispose();
  18030. }
  18031. updateTargetBlock(block) {
  18032. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  18033. this._target_block = block;
  18034. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  18035. this._target_block = block;
  18036. }
  18037. }
  18038. transformLoop(node) {
  18039. const loop = new torch._C.LoopView(node);
  18040. const body = loop.bodyBlock();
  18041. const exit_pair = this.transformExits(body);
  18042. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  18043. return this.constructWontExitPair();
  18044. }
  18045. const insert = new torch._C.WithInsertPoint(body);
  18046. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  18047. new_if.addInput(exit_pair.hasExited());
  18048. new_if.addBlock().registerOutput(this._false_val);
  18049. new_if.addBlock().registerOutput(loop.nextCond());
  18050. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  18051. loop.bodyBlock().eraseOutput(0);
  18052. loop.bodyBlock().insertOutput(0, new_condition);
  18053. node.addInput(this._false_val);
  18054. body.addInput().setType(torch.BoolType.get());
  18055. body.registerOutput(exit_pair.hasExited());
  18056. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  18057. for (const exit_value of exit_pair.exitValues()) {
  18058. const typ = exit_value.type();
  18059. node.addInput(this.getUnitValue(typ));
  18060. node.addOutput().setType(typ);
  18061. body.addInput().setType(typ);
  18062. body.registerOutput(exit_value);
  18063. }
  18064. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  18065. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  18066. insert.dispose();
  18067. return result;
  18068. }
  18069. calcIfExitStatus(then_status, else_status) {
  18070. if (then_status === 'THROWS') {
  18071. return else_status;
  18072. } else if (else_status === 'THROWS') {
  18073. return then_status;
  18074. }
  18075. if (then_status === 'WONT' && else_status === 'WONT') {
  18076. return 'WONT';
  18077. }
  18078. if (then_status === 'WILL' && else_status === 'WILL') {
  18079. return 'WILL';
  18080. }
  18081. return 'MIGHT';
  18082. }
  18083. transformIf(node) {
  18084. const [then_block, else_block] = node.blocks();
  18085. let then_pair = this.transformExits(then_block);
  18086. let else_pair = this.transformExits(else_block);
  18087. const then_status = this.getExitStatus(then_pair);
  18088. const else_status = this.getExitStatus(else_pair);
  18089. const if_status = this.calcIfExitStatus(then_status, else_status);
  18090. if (if_status === 'THROWS') {
  18091. return this.constructThrowsExitPair();
  18092. }
  18093. if (if_status === 'WONT') {
  18094. return this.constructWontExitPair();
  18095. }
  18096. if (then_status === 'WONT' || then_status === 'THROWS') {
  18097. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18098. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18099. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18100. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18101. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18102. }
  18103. let has_exited = null;
  18104. if (if_status === 'WILL') {
  18105. has_exited = this._true_val;
  18106. } else {
  18107. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18108. has_exited = node.outputs().at(node.outputs().length - 1);
  18109. }
  18110. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18111. const num_exit_vals = then_pair.exitValues().size();
  18112. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18113. return new torch._C.ExitPair(has_exited, exit_vals);
  18114. }
  18115. transformExits(block) {
  18116. const prev_target_block = this._target_block;
  18117. this.updateTargetBlock(block);
  18118. let exit_pair = this.constructWontExitPair();
  18119. for (const node of block.nodes()) {
  18120. const it = node.next;
  18121. switch (node.kind()) {
  18122. case 'prim::RaiseException': {
  18123. exit_pair = this.constructThrowsExitPair();
  18124. break;
  18125. }
  18126. case 'prim::ReturnStmt':
  18127. case 'prim::LoopContinuation': {
  18128. if (node.kind() === this._current_exit_kind) {
  18129. exit_pair = this.constructWillExitPair(node.inputs());
  18130. node.destroy();
  18131. }
  18132. break;
  18133. }
  18134. case 'prim::If': {
  18135. exit_pair = this.transformIf(node);
  18136. break;
  18137. }
  18138. case 'prim::With': {
  18139. exit_pair = this.transformWith(node);
  18140. break;
  18141. }
  18142. case 'prim::Closure': {
  18143. this.transformExits(node.blocks().at(0));
  18144. break;
  18145. }
  18146. case 'prim::Loop': {
  18147. exit_pair = this.transformLoop(node);
  18148. break;
  18149. }
  18150. default: {
  18151. break;
  18152. }
  18153. }
  18154. const status = this.getExitStatus(exit_pair);
  18155. if (status === 'WILL' || status === 'THROWS') {
  18156. this.deleteAfterExitNodes(block, it);
  18157. break;
  18158. }
  18159. if (status === 'MIGHT') {
  18160. throw new python.Error('Not implemented.');
  18161. // const nodes = block.nodes();
  18162. // if (node === nodes[nodes.length - 1]) {
  18163. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18164. // }
  18165. // break;
  18166. }
  18167. }
  18168. if (this._target_block === block) {
  18169. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18170. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18171. new_if.addBlock();
  18172. new_if.addBlock();
  18173. new_if.addInput(exit_pair.hasExited());
  18174. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18175. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18176. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18177. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18178. }
  18179. exit_pair = this.constructWontExitPair();
  18180. }
  18181. this._target_block = prev_target_block;
  18182. return exit_pair;
  18183. }
  18184. constructThrowsExitPair() {
  18185. return new torch._C.ExitPair(this._throws_val, []);
  18186. }
  18187. constructWontExitPair() {
  18188. return new torch._C.ExitPair(this._false_val, []);
  18189. }
  18190. constructWillExitPair(exit_val_ref) {
  18191. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18192. }
  18193. getExitStatus(exit_pair) {
  18194. const exit_v = exit_pair.hasExited();
  18195. if (exit_v === this._true_val) {
  18196. return 'WILL';
  18197. } else if (exit_v === this._false_val) {
  18198. return 'WONT';
  18199. } else if (exit_v === this._throws_val) {
  18200. return 'THROWS';
  18201. }
  18202. return 'MIGHT';
  18203. }
  18204. static owningNodeKind(block) {
  18205. if (block.owningNode()) {
  18206. return block.owningNode().kind();
  18207. }
  18208. return null;
  18209. }
  18210. static isGraphOrClosureBlock(block) {
  18211. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18212. }
  18213. static removeOutputs(b) {
  18214. while (b.outputs().length > 0) {
  18215. b.eraseOutput(0);
  18216. }
  18217. }
  18218. static registerBlockOutputs(b, outs) {
  18219. for (const out of outs) {
  18220. b.registerOutput(out);
  18221. }
  18222. }
  18223. static replaceBlockOutputs(b, outs) {
  18224. torch._C.ExitTransformer.removeOutputs(b);
  18225. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18226. }
  18227. });
  18228. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18229. });
  18230. this.registerFunction('torch._C.TransformExits', (graph) => {
  18231. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18232. const e_loop = new torch._C.ExitTransformer(graph);
  18233. e_loop.transformLoopContinuations();
  18234. const e_ret = new torch._C.ExitTransformer(graph);
  18235. e_ret.transformReturnStmts();
  18236. torch._C.inlineConsecutiveIfs(graph.block());
  18237. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18238. });
  18239. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18240. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18241. const args = iter.inputs();
  18242. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18243. newSub.replaceInput(0, args[1]);
  18244. newSub.replaceInput(1, args[0]);
  18245. iter.destroyCurrent();
  18246. return true;
  18247. }
  18248. return false;
  18249. });
  18250. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18251. });
  18252. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18253. const args = iter.inputs();
  18254. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18255. if (iter.kind() === 'aten::__is__') {
  18256. iter.replaceWithNewSymbol('aten::eq');
  18257. iter.destroyCurrent();
  18258. return true;
  18259. }
  18260. if (iter.kind() === 'aten::__isnot__') {
  18261. iter.replaceWithNewSymbol('aten::ne');
  18262. iter.destroyCurrent();
  18263. return true;
  18264. }
  18265. }
  18266. return false;
  18267. });
  18268. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18269. for (const it of block.nodes()) {
  18270. for (const sub of it.blocks()) {
  18271. torch._C.NormalizeOps(sub);
  18272. }
  18273. if (torch._C.normalizeRSub(it)) {
  18274. continue;
  18275. }
  18276. if (torch._C.normalizeOpAliases(it)) {
  18277. continue;
  18278. }
  18279. if (torch._C.normalizeIsBool(it)) {
  18280. continue;
  18281. }
  18282. }
  18283. });
  18284. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18285. return false;
  18286. });
  18287. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18288. /*
  18289. torch._C.liftClosures(to_clean);
  18290. torch._C.inlineForkedClosures(to_clean);
  18291. */
  18292. if (torch._C.getInlineEverythingMode()) {
  18293. torch._C.Inline(to_clean);
  18294. }
  18295. /*
  18296. torch._C.eraseListLiterals(to_clean);
  18297. */
  18298. torch._C.LowerSimpleTuples(to_clean);
  18299. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18300. torch._C.ConstantPooling(to_clean);
  18301. /*
  18302. torch._C.CanonicalizeOutputs(to_clean);
  18303. torch._C.AnnotateWarns(to_clean);
  18304. */
  18305. });
  18306. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18307. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18308. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18309. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18310. constructor(cpp_module) {
  18311. super();
  18312. this._initializing = true;
  18313. this._c = cpp_module;
  18314. }
  18315. static _construct(cpp_module, init_fn) {
  18316. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18317. init_fn(script_module);
  18318. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18319. return script_module;
  18320. }
  18321. static _finalize_scriptmodule(script_module) {
  18322. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18323. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18324. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18325. script_module._initializing = false;
  18326. }
  18327. get graph() {
  18328. // return this._c._get_method('forward').graph;
  18329. return this._c.graph;
  18330. }
  18331. get code_with_constants() {
  18332. // return this.forward.code_with_constants;
  18333. return this._c.code_with_constants;
  18334. }
  18335. __setattr__(name, value) {
  18336. if (this._initializing) {
  18337. super.__setattr__(name, value);
  18338. } else if (this._modules.has(name)) {
  18339. this._modules.set(name, value);
  18340. } else if (this._c.hasattr(name)) {
  18341. this._c.setattr(name, value);
  18342. } else {
  18343. //
  18344. }
  18345. }
  18346. __getattr__(name) {
  18347. if (this._initializing) {
  18348. return super.__getattr__(name);
  18349. }
  18350. if (this._modules.has(name)) {
  18351. return this._modules.get(name);
  18352. }
  18353. if (this._c.hasattr(name)) {
  18354. return this._c.getattr(name);
  18355. }
  18356. if (this._c._has_method(name)) {
  18357. //
  18358. }
  18359. return super.__getattr__(name);
  18360. }
  18361. });
  18362. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18363. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18364. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18365. torch.CompilationUnit = torch.jit.CompilationUnit;
  18366. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18367. torch._C.ScriptModule = torch.ScriptModule;
  18368. torch._C.ClassType = torch.ClassType;
  18369. this.registerType('torch._C.FlatBuffersLoader', class {
  18370. constructor(cu) {
  18371. this._cu = cu;
  18372. const torch = cu.execution.__import__('torch');
  18373. this._torch = torch;
  18374. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18375. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18376. this._ivalue_parsers = new Map();
  18377. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18378. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18379. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18380. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18381. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18382. }
  18383. parseModule(module) {
  18384. this._module = module;
  18385. this._all_functions = new Map();
  18386. this._all_ivalues = new Array(module.ivalues.length);
  18387. this._all_types = new Array(module.object_types.length);
  18388. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18389. for (let i = 0; i < mobile_ivalue_size; i++) {
  18390. this.parseAndPopulate(i, module.ivalues[i]);
  18391. }
  18392. const m = this._all_ivalues[module.state_obj];
  18393. for (const [name, value] of this._all_functions) {
  18394. const class_index = module.ivalues[name].val.class_type;
  18395. const class_type = this._all_types[class_index];
  18396. if (value) {
  18397. class_type.addMethod(value);
  18398. }
  18399. }
  18400. m._min_operator_version = module.operator_version;
  18401. m._bytecode_version = module.bytecode_version;
  18402. return m;
  18403. }
  18404. parseAndPopulate(i, ivalue) {
  18405. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18406. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18407. } else {
  18408. this._all_ivalues[i] = this.parseIValue(ivalue);
  18409. }
  18410. }
  18411. parseFunction(/* val */) {
  18412. return null;
  18413. }
  18414. parseIValue(ivalue) {
  18415. if (ivalue.val) {
  18416. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18417. return callback(ivalue);
  18418. }
  18419. return null;
  18420. }
  18421. parseTensor(ivalue) {
  18422. return this.parseTensorFromMetadata(ivalue.val);
  18423. }
  18424. parseTensorFromMetadata(metadata) {
  18425. if (metadata.quantized_schema) {
  18426. throw new torch.Error('Quantized schema not implemented.');
  18427. }
  18428. const index = metadata.storage_location_index;
  18429. const data = this._module.storage_data[index].data;
  18430. const dtype = this._dtypes.get(metadata.scalar_type);
  18431. const size = data.length / dtype.itemsize();
  18432. const storage = new torch.storage.TypedStorage(size, dtype);
  18433. storage._set_cdata(data);
  18434. const tensor = new torch.Tensor();
  18435. const shape = Array.from(metadata.sizes);
  18436. const stride = Array.from(metadata.strides);
  18437. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18438. return tensor;
  18439. }
  18440. parseObject(ivalue) {
  18441. const object = ivalue.val;
  18442. const obj_type = this._module.object_types[object.type_index];
  18443. const cls = this.getOrCreateClassTypeForObject(object);
  18444. switch (obj_type.type) {
  18445. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18446. const torch = this._torch;
  18447. const obj = torch.ScriptObject.create(cls);
  18448. for (let i = 0; i < object.attrs.length; i++) {
  18449. const attr_name = obj_type.attr_names[i];
  18450. const val = this._all_ivalues[object.attrs[i]];
  18451. obj.__setattr__(attr_name, val);
  18452. }
  18453. return obj;
  18454. }
  18455. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18456. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18457. default: {
  18458. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18459. }
  18460. }
  18461. }
  18462. getOrCreateClassTypeForObject(object) {
  18463. let cls = this._all_types[object.type_index];
  18464. const obj_type = this._module.object_types[object.type_index];
  18465. if (!cls) {
  18466. const name = obj_type.type_name;
  18467. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18468. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18469. if (!cls) {
  18470. const torch = this._torch;
  18471. cls = torch.ClassType.create(name, this._cu, true);
  18472. this._cu.register_type(cls);
  18473. }
  18474. } else {
  18475. // cls = c10::parseType(qn_str).cast<ClassType>();
  18476. }
  18477. this._all_types[object.type_index] = cls;
  18478. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18479. for (let i = 0; i < object.attrs.length; i++) {
  18480. // const val = this._all_ivalues[object.attrs[i]];
  18481. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18482. }
  18483. }
  18484. }
  18485. return cls;
  18486. }
  18487. });
  18488. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18489. constructor(export_module, flat_args_adapter) {
  18490. super();
  18491. const export_graph = copy.deepcopy(export_module.graph);
  18492. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18493. this.graph = torch.fx.Graph();
  18494. this.graph.owning_module = this;
  18495. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18496. this.flat_args_adapter = flat_args_adapter;
  18497. this.adapted = false;
  18498. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18499. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18500. }
  18501. });
  18502. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18503. constructor(input_specs, output_specs) {
  18504. this.input_specs = input_specs;
  18505. this.output_specs = output_specs;
  18506. }
  18507. get user_inputs() {
  18508. const user_inputs = [];
  18509. for (const s of this.input_specs) {
  18510. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18511. continue;
  18512. }
  18513. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18514. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18515. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18516. user_inputs.push(s.arg.name);
  18517. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18518. user_inputs.push(s.arg.value);
  18519. } else {
  18520. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18521. }
  18522. }
  18523. return user_inputs;
  18524. }
  18525. get user_outputs() {
  18526. const user_outputs = [];
  18527. for (const s of this.output_specs) {
  18528. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18529. continue;
  18530. }
  18531. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18532. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18533. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18534. user_outputs.push(s.arg.name);
  18535. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18536. user_outputs.push(s.arg.value);
  18537. } else {
  18538. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18539. }
  18540. }
  18541. return user_outputs;
  18542. }
  18543. get inputs_to_parameters() {
  18544. return new Map(this.input_specs
  18545. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18546. .map((s) => [s.arg.name, s.target]));
  18547. }
  18548. get inputs_to_buffers() {
  18549. return new Map(this.input_specs
  18550. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18551. .map((s) => [s.arg.name, s.target]));
  18552. }
  18553. get inputs_to_lifted_tensor_constants() {
  18554. return new Map(this.input_specs
  18555. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18556. .map((s) => [s.arg.name, s.target]));
  18557. }
  18558. });
  18559. torch.export.graph_signature.InputKind = {
  18560. USER_INPUT: 0,
  18561. PARAMETER: 1,
  18562. BUFFER: 2,
  18563. CONSTANT_TENSOR: 3,
  18564. CUSTOM_OBJ: 4,
  18565. TOKEN: 5
  18566. };
  18567. this.registerType('torch.export.graph_signature.InputSpec', class {
  18568. constructor(kind, arg, target, persistent) {
  18569. this.kind = kind;
  18570. this.arg = arg;
  18571. this.target = target;
  18572. this.persistent = persistent || null;
  18573. }
  18574. });
  18575. torch.export.graph_signature.OutputKind = {
  18576. USER_OUTPUT: 0,
  18577. LOSS_OUTPUT: 1,
  18578. BUFFER_MUTATION: 2,
  18579. GRADIENT_TO_PARAMETER: 3,
  18580. GRADIENT_TO_USER_INPUT: 4,
  18581. USER_INPUT_MUTATION: 5,
  18582. TOKEN: 6
  18583. };
  18584. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18585. constructor(kind, arg, target) {
  18586. this.kind = kind;
  18587. this.arg = arg;
  18588. this.target = target;
  18589. }
  18590. });
  18591. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18592. constructor(name, value) {
  18593. this.name = name;
  18594. this.value = value; // Union[int, float, bool, str, None]
  18595. }
  18596. });
  18597. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18598. constructor(name) {
  18599. this.name = name;
  18600. }
  18601. });
  18602. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18603. constructor(name) {
  18604. this.name = name;
  18605. }
  18606. });
  18607. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18608. constructor(name, class_fqn, fake_val) {
  18609. this.name = name;
  18610. this.class_fqn = class_fqn;
  18611. this.fake_val = fake_val;
  18612. }
  18613. });
  18614. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18615. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18616. // graph._codegen = torch.fx.graph.CodeGen()
  18617. this._graph_module = this._create_graph_module_for_export(root, graph);
  18618. if (root instanceof torch.fx.GraphModule) {
  18619. // this._graph_module.meta.update(root.meta);
  18620. }
  18621. this._graph_signature = graph_signature;
  18622. this._state_dict = state_dict;
  18623. this._range_constraints = range_constraints;
  18624. this._module_call_graph = module_call_graph;
  18625. this._example_inputs = example_inputs;
  18626. this._constants = tensor_constants || constants || {};
  18627. }
  18628. _create_graph_module_for_export(root, graph) {
  18629. let gm = null;
  18630. try {
  18631. gm = new torch.fx.GraphModule(root, graph);
  18632. } catch {
  18633. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18634. gm._graph = graph;
  18635. }
  18636. return gm;
  18637. }
  18638. get graph_module() {
  18639. return this._graph_module;
  18640. }
  18641. get graph() {
  18642. return this._graph_module.graph;
  18643. }
  18644. get graph_signature() {
  18645. return this._graph_signature;
  18646. }
  18647. get state_dict() {
  18648. return this._state_dict;
  18649. }
  18650. get constants() {
  18651. return this._constants;
  18652. }
  18653. });
  18654. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18655. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18656. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18657. return new torch.fx.graph_module.GraphModule(root, graph);
  18658. });
  18659. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18660. module = torch.export._remove_effect_tokens(module);
  18661. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18662. });
  18663. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18664. return new torch.fx.graph_module.GraphModule(root, graph);
  18665. });
  18666. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18667. constructor(exported_program, state_dict, constants, example_inputs) {
  18668. this.exported_program = exported_program;
  18669. this.state_dict = state_dict;
  18670. this.constants = constants;
  18671. this.example_inputs = example_inputs;
  18672. }
  18673. });
  18674. torch._export.serde.serialize._SYM_OPS = new Set([
  18675. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18676. operator.neg, operator.pos, operator.and_, operator.or_,
  18677. math.trunc, torch.sym_not,
  18678. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18679. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18680. operator.truediv, operator.and_
  18681. ]);
  18682. this.registerType('torch._export.serde.union._Union', class {
  18683. constructor(obj) {
  18684. if (obj.$type) {
  18685. this.type = obj.$type;
  18686. this[obj.$type] = obj.$value;
  18687. delete obj.$type;
  18688. delete obj.$value;
  18689. } else if (obj.type) {
  18690. this.type = obj.type;
  18691. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18692. this[obj.type] = Object.fromEntries(entries);
  18693. } else {
  18694. let entries = Object.entries(obj);
  18695. if (entries.length > 1) {
  18696. entries = entries.filter(([, value]) => value !== null);
  18697. }
  18698. if (entries.length !== 1) {
  18699. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18700. }
  18701. const [entry] = entries;
  18702. const [type, value] = entry;
  18703. this.type = type;
  18704. this[type] = value;
  18705. }
  18706. }
  18707. get value() {
  18708. return this[this.type];
  18709. }
  18710. });
  18711. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18712. constructor(obj) {
  18713. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18714. this.name = obj.name;
  18715. }
  18716. });
  18717. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18718. constructor(obj) {
  18719. super(obj);
  18720. switch (this.type) {
  18721. case 'as_int':
  18722. case 'as_ints':
  18723. case 'as_float':
  18724. case 'as_floats':
  18725. case 'as_bool':
  18726. case 'as_bools':
  18727. case 'as_string':
  18728. case 'as_strings':
  18729. case 'as_scalar_type':
  18730. case 'as_device':
  18731. case 'as_memory_format':
  18732. case 'as_layout':
  18733. break;
  18734. case 'as_none':
  18735. this.as_none = null;
  18736. break;
  18737. case 'as_tensor':
  18738. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18739. break;
  18740. case 'as_tensors':
  18741. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18742. break;
  18743. case 'as_graph':
  18744. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18745. break;
  18746. case 'as_sym_int':
  18747. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18748. break;
  18749. case 'as_sym_ints':
  18750. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18751. break;
  18752. case 'as_sym_bool':
  18753. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18754. break;
  18755. case 'as_sym_bools':
  18756. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18757. break;
  18758. case 'as_sym_float':
  18759. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18760. break;
  18761. case 'as_sym_floats':
  18762. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18763. break;
  18764. case 'as_optional_tensors':
  18765. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18766. break;
  18767. case 'as_custom_obj':
  18768. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18769. break;
  18770. // case 'as_graph': GraphArgument
  18771. default:
  18772. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18773. }
  18774. }
  18775. });
  18776. this.registerType('torch._export.serde.schema.Node', class {
  18777. constructor(obj) {
  18778. this.target = obj.target;
  18779. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18780. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18781. this.metadata = new Map(Object.entries(obj.metadata));
  18782. }
  18783. });
  18784. torch._export.serde.schema.ScalarType = {
  18785. UNKNOWN: 0,
  18786. BYTE: 1,
  18787. CHAR: 2,
  18788. SHORT: 3,
  18789. INT: 4,
  18790. LONG: 5,
  18791. HALF: 6,
  18792. FLOAT: 7,
  18793. DOUBLE: 8,
  18794. COMPLEXHALF: 9,
  18795. COMPLEXFLOAT: 10,
  18796. COMPLEXDOUBLE: 11,
  18797. BOOL: 12,
  18798. BFLOAT16: 13,
  18799. UINT16: 28,
  18800. FLOAT8E4M3FN: 29,
  18801. FLOAT8E5M2: 30,
  18802. FLOAT8E4M3FNUZ: 31,
  18803. FLOAT8E5M2FNUZ: 32,
  18804. };
  18805. torch._export.serde.schema.Layout = {
  18806. Unknown: 0,
  18807. SparseCoo: 1,
  18808. SparseCsr: 2,
  18809. SparseCsc: 3,
  18810. SparseBsr: 4,
  18811. SparseBsc: 5,
  18812. _mkldnn: 6,
  18813. Strided: 7
  18814. };
  18815. torch._export.serde.schema.MemoryFormat = {
  18816. Unknown: 0,
  18817. ContiguousFormat: 1,
  18818. ChannelsLast: 2,
  18819. ChannelsLast3d: 3,
  18820. PreserveFormat: 4,
  18821. };
  18822. this.registerType('torch._export.serde.schema.Device', class {
  18823. constructor(obj) {
  18824. Object.assign(this, { ...obj });
  18825. }
  18826. });
  18827. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18828. constructor(obj) {
  18829. obj = obj.meta || obj;
  18830. this.dtype = obj.dtype;
  18831. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18832. this.requires_grad = obj.requires_grad;
  18833. this.device = obj.device;
  18834. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18835. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18836. this.layout = obj.layout;
  18837. }
  18838. });
  18839. this.registerType('torch._export.serde.schema.Graph', class {
  18840. constructor(obj) {
  18841. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18842. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18843. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18844. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18845. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18846. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18847. this.is_single_tensor_return = obj.is_single_tensor_return;
  18848. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18849. if (obj.contants) {
  18850. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18851. // graph_signature -> input_specs -> tensor_constant
  18852. }
  18853. }
  18854. });
  18855. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18856. constructor(obj) {
  18857. Object.assign(this, { ...obj });
  18858. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18859. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18860. }
  18861. });
  18862. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18863. constructor(obj) {
  18864. Object.assign(this, { ...obj });
  18865. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18866. }
  18867. });
  18868. this.registerType('torch._export.serde.schema.GraphModule', class {
  18869. constructor(obj) {
  18870. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18871. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18872. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18873. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18874. }
  18875. });
  18876. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  18877. constructor(obj) {
  18878. Object.assign(this, { ...obj });
  18879. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  18880. }
  18881. });
  18882. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  18883. this.registerType('torch._export.serde.schema.SymExpr', class {
  18884. constructor(obj) {
  18885. this.expr_str = obj.expr_str;
  18886. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  18887. }
  18888. });
  18889. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  18890. constructor(obj) {
  18891. super(obj);
  18892. if (this.type === 'as_int') {
  18893. // continue
  18894. } else if (this.type === 'as_expr') {
  18895. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18896. } else {
  18897. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  18898. }
  18899. }
  18900. });
  18901. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  18902. constructor(obj) {
  18903. super(obj);
  18904. if (this.type === 'as_bool') {
  18905. // continue
  18906. } else if (this.type === 'as_expr') {
  18907. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18908. } else {
  18909. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  18910. }
  18911. }
  18912. });
  18913. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  18914. constructor(obj) {
  18915. super(obj);
  18916. Object.assign(this, { ...obj });
  18917. }
  18918. });
  18919. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  18920. constructor(obj) {
  18921. super(obj);
  18922. Object.assign(this, { ...obj });
  18923. }
  18924. });
  18925. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  18926. constructor(obj) {
  18927. super(obj);
  18928. Object.assign(this, { ...obj });
  18929. }
  18930. });
  18931. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  18932. constructor(obj) {
  18933. Object.assign(this, { ...obj });
  18934. }
  18935. });
  18936. this.registerType('torch._export.serde.schema.GraphSignature', class {
  18937. constructor(obj) {
  18938. this.input_specs = [];
  18939. if (Array.isArray(obj.input_specs)) {
  18940. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  18941. }
  18942. if (Array.isArray(obj.user_inputs)) {
  18943. for (const user_input of obj.user_inputs) {
  18944. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  18945. }
  18946. }
  18947. if (obj.inputs_to_parameters) {
  18948. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  18949. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  18950. }
  18951. }
  18952. this.output_specs = [];
  18953. if (Array.isArray(obj.output_specs)) {
  18954. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  18955. }
  18956. }
  18957. });
  18958. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  18959. constructor(obj) {
  18960. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18961. }
  18962. });
  18963. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  18964. constructor(obj) {
  18965. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18966. this.parameter_name = obj.parameter_name;
  18967. }
  18968. });
  18969. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  18970. constructor(obj) {
  18971. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18972. this.buffer_name = obj.buffer_name;
  18973. }
  18974. });
  18975. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  18976. constructor(obj) {
  18977. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18978. this.tensor_constant_name = obj.tensor_constant_name;
  18979. }
  18980. });
  18981. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  18982. constructor(obj) {
  18983. this.name = obj.name;
  18984. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  18985. }
  18986. });
  18987. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  18988. constructor(obj) {
  18989. super(obj);
  18990. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  18991. // continue
  18992. } else if (this.type === 'as_none') {
  18993. this.as_none = null;
  18994. } else {
  18995. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  18996. }
  18997. }
  18998. });
  18999. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  19000. constructor(obj) {
  19001. super(obj);
  19002. if (this.type === 'user_input') {
  19003. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  19004. } else if (this.type === 'parameter') {
  19005. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  19006. } else if (this.type === 'buffer') {
  19007. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  19008. } else if (this.type === 'tensor_constant') {
  19009. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  19010. } else if (this.type === 'constant_input') {
  19011. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  19012. } else {
  19013. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  19014. }
  19015. /*
  19016. custom_obj: InputToCustomObjSpec
  19017. token: InputTokenSpec
  19018. */
  19019. }
  19020. });
  19021. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  19022. constructor(obj) {
  19023. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19024. }
  19025. });
  19026. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  19027. constructor(obj) {
  19028. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19029. this.buffer_name = obj.buffer_name;
  19030. }
  19031. });
  19032. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  19033. constructor(obj) {
  19034. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19035. this.parameter_name = obj.parameter_name;
  19036. }
  19037. });
  19038. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  19039. constructor(obj) {
  19040. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19041. this.user_input_name = obj.user_input_name;
  19042. }
  19043. });
  19044. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  19045. constructor(obj) {
  19046. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19047. this.user_input_name = obj.user_input_name;
  19048. }
  19049. });
  19050. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  19051. constructor(obj) {
  19052. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  19053. }
  19054. });
  19055. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  19056. constructor(obj) {
  19057. super(obj);
  19058. if (this.type === 'user_output') {
  19059. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  19060. } else if (this.type === 'loss_output') {
  19061. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  19062. } else if (this.type === 'buffer_mutation') {
  19063. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  19064. } else if (this.type === 'gradient_to_parameter') {
  19065. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  19066. } else if (this.type === 'gradient_to_user_input') {
  19067. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  19068. } else if (this.type === 'user_input_mutation') {
  19069. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  19070. } else if (this.type === 'token') {
  19071. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  19072. }
  19073. }
  19074. });
  19075. this.registerType('torch._export.serde.schema.TensorArgument', class {
  19076. constructor(obj) {
  19077. this.name = obj.name;
  19078. }
  19079. });
  19080. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19081. constructor(obj) {
  19082. this.name = obj.name;
  19083. }
  19084. });
  19085. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19086. constructor(obj) {
  19087. this.name = obj.name;
  19088. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19089. }
  19090. });
  19091. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19092. constructor(obj) {
  19093. super(obj);
  19094. if (this.type === 'as_tensor') {
  19095. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19096. } else if (this.type === 'as_none') {
  19097. this.as_none = null;
  19098. } else {
  19099. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19100. }
  19101. }
  19102. });
  19103. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19104. const legacy_file = `data/weights/${model_name}.pt`;
  19105. if (f.has(legacy_file)) {
  19106. return f.get(legacy_file);
  19107. }
  19108. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19109. if (!f.has(weights_config_file)) {
  19110. return null;
  19111. }
  19112. const weights_config = f.get(weights_config_file);
  19113. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19114. const state_dict = new builtins.dict();
  19115. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19116. if (payload_meta.use_pickle) {
  19117. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19118. const weight_tensor = torch.load(weight_bytes);
  19119. state_dict.set(weight_fqn, weight_tensor);
  19120. } else {
  19121. const tensor_meta = payload_meta.tensor_meta;
  19122. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19123. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19124. const strides = tensor_meta.strides.map((s) => s.as_int);
  19125. const storage_offset = tensor_meta.storage_offset.as_int;
  19126. const weight_tensor = new torch.Tensor();
  19127. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19128. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19129. if (payload_meta.is_param) {
  19130. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19131. } else {
  19132. state_dict.set(weight_fqn, weight_tensor);
  19133. }
  19134. }
  19135. }
  19136. return state_dict;
  19137. });
  19138. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19139. const legacy_file = `data/constants/${model_name}.pt`;
  19140. if (f.has(legacy_file)) {
  19141. const entries = f.get(legacy_file);
  19142. return new builtins.dict(entries);
  19143. }
  19144. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19145. if (!f.has(constants_config_file)) {
  19146. return null;
  19147. }
  19148. const constants_config = f.get(constants_config_file);
  19149. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19150. const constants = new builtins.dict();
  19151. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19152. const path_name = payload_meta.path_name;
  19153. if (path_name.startsWith('tensor_')) {
  19154. if (payload_meta.use_pickle) {
  19155. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19156. const constant_tensor = torch.load(constant_bytes);
  19157. constants.set(constant_fqn, constant_tensor);
  19158. } else {
  19159. const tensor_meta = payload_meta.tensor_meta;
  19160. const tensor = constant_file_map.get(payload_meta.path_name);
  19161. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19162. const strides = tensor_meta.strides.map((s) => s.as_int);
  19163. const storage_offset = tensor_meta.storage_offset.as_int;
  19164. const constant_tensor = new torch.Tensor();
  19165. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19166. constants.set(constant_fqn, constant_tensor);
  19167. }
  19168. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19169. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19170. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19171. constants.set(constant_fqn, custom_obj);
  19172. }
  19173. }
  19174. return constants;
  19175. });
  19176. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19177. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19178. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19179. }
  19180. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19181. });
  19182. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19183. const file_map = new builtins.dict();
  19184. for (const payload_meta of Object.values(config.config)) {
  19185. if (payload_meta.use_pickle) {
  19186. continue;
  19187. }
  19188. if (file_map.has(payload_meta.path_name)) {
  19189. continue;
  19190. }
  19191. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19192. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19193. file_map.set(payload_meta.path_name, tensor);
  19194. }
  19195. return file_map;
  19196. });
  19197. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19198. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19199. const itemsize = dtype.itemsize();
  19200. const num_elements = tensor_bytes.length / itemsize;
  19201. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19202. storage._set_cdata(tensor_bytes);
  19203. const tensor = new torch.Tensor();
  19204. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19205. tensor.requires_grad = tensor_meta.requires_grad || false;
  19206. return tensor;
  19207. });
  19208. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19209. const exported_programs = new Map();
  19210. for (const name of f.keys()) {
  19211. const match = name.match(/^models\/([^/]+)\.json$/);
  19212. if (match) {
  19213. const [, model_name] = match;
  19214. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19215. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19216. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19217. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19218. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19219. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19220. exported_programs.set(model_name, exported_program);
  19221. }
  19222. }
  19223. return { exported_programs };
  19224. });
  19225. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19226. if (data === null) {
  19227. return data;
  19228. }
  19229. if (cls) {
  19230. return new cls(data);
  19231. }
  19232. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19233. });
  19234. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19235. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19236. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19237. });
  19238. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19239. constructor(expected_opset_version) {
  19240. this.expected_opset_version = expected_opset_version;
  19241. }
  19242. deserialize(exported_program, state_dict, constants, example_inputs) {
  19243. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19244. /*
  19245. symbol_name_to_range = {
  19246. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19247. for k, v in exported_program.range_constraints.items()
  19248. }
  19249. */
  19250. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19251. const res = deserializer.deserialize(
  19252. exported_program.graph_module,
  19253. state_dict,
  19254. constants,
  19255. example_inputs,
  19256. symbol_name_to_range);
  19257. const range_constraints = null;
  19258. /*
  19259. range_constraints = self.deserialize_range_constraints(
  19260. symbol_name_to_range, res.names_to_symbols,
  19261. )
  19262. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19263. self._validate_model_opset_version(model_opset_version)
  19264. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19265. */
  19266. return new torch.export.exported_program.ExportedProgram(
  19267. res.graph_module, res.graph_module.graph, res.signature,
  19268. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19269. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19270. res.constants);
  19271. // return upgrader.upgrade(exported_program)
  19272. }
  19273. });
  19274. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19275. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19276. return serialized;
  19277. }
  19278. if (serialized === null || serialized.length === 0) {
  19279. return new builtins.dict();
  19280. }
  19281. const artifact = torch.load(serialized);
  19282. return artifact;
  19283. });
  19284. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19285. constructor() {
  19286. this.serialized_name_to_node = new builtins.dict();
  19287. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19288. this.graph = new torch.fx.Graph();
  19289. this.module = new torch.nn.Module();
  19290. }
  19291. save_graph_module() {
  19292. const Context = class {
  19293. constructor(self) {
  19294. this.self = self;
  19295. }
  19296. __enter__() {
  19297. this.saved = [
  19298. this.self.graph,
  19299. this.self.module,
  19300. this.self.serialized_name_to_node,
  19301. this.self.serialized_name_to_meta,
  19302. this.self.unbacked_symbols,
  19303. ];
  19304. this.self.graph = new torch.fx.graph.Graph();
  19305. this.self.module = new torch.nn.modules.module.Module();
  19306. this.self.serialized_name_to_node = new builtins.dict();
  19307. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19308. this.self.unbacked_symbols = new Set();
  19309. }
  19310. __exit__(/* exc_type, exc_value, traceback */) {
  19311. const self = this.self;
  19312. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19313. }
  19314. };
  19315. return new Context(this);
  19316. }
  19317. deserialize_graph_output(output) {
  19318. if (output.type === 'as_tensor') {
  19319. return this.serialized_name_to_node.get(output.as_tensor.name);
  19320. } else if (output.type === 'as_sym_int') {
  19321. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19322. } else if (output.type === 'as_sym_bool') {
  19323. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19324. } else if (output.type === 'as_int') {
  19325. return this.serialized_name_to_node.get(output.as_int.as_name);
  19326. } else if (output.type === 'as_none') {
  19327. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19328. }
  19329. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19330. }
  19331. deserialize_graph(serialized_graph) {
  19332. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19333. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19334. this.serialized_name_to_meta.set(name, meta_val);
  19335. }
  19336. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19337. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19338. }
  19339. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19340. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19341. }
  19342. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19343. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19344. }
  19345. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19346. const input = serialized_graph.inputs[i];
  19347. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19348. const node_name = input.value.name;
  19349. const placeholder_node = this.graph.placeholder(node_name);
  19350. placeholder_node.name = node_name;
  19351. this.sync_fx_node(node_name, placeholder_node);
  19352. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19353. const node_name = this.signature.input_specs[i].arg.name;
  19354. const placeholder_node = this.graph.placeholder(node_name);
  19355. placeholder_node.meta.set('val', this.deserialize_input(input));
  19356. } else {
  19357. throw new python.Error(`Invalid input ${input.type}.`);
  19358. }
  19359. }
  19360. for (const serialized_node of serialized_graph.nodes) {
  19361. const target = this.deserialize_operator(serialized_node.target);
  19362. this.deserialize_node(serialized_node, target);
  19363. }
  19364. let outputs = [];
  19365. for (const output of serialized_graph.outputs) {
  19366. outputs.push(this.deserialize_graph_output(output));
  19367. }
  19368. if (serialized_graph.is_single_tensor_return) {
  19369. [outputs] = outputs;
  19370. } else {
  19371. outputs = new builtins.tuple(outputs);
  19372. }
  19373. const output_node = this.graph.output(outputs);
  19374. if (serialized_graph.is_single_tensor_return) {
  19375. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19376. } else {
  19377. /* output_node.meta['val'] = tuple(
  19378. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19379. for arg in output_node.args[0]
  19380. ) */
  19381. }
  19382. return self.graph;
  19383. }
  19384. deserialize_operator(serialized_target) {
  19385. let module = null;
  19386. let serialized_target_names = null;
  19387. if (serialized_target.startsWith('_operator')) {
  19388. module = operator;
  19389. serialized_target_names = serialized_target.split('.').slice(1);
  19390. } else if (serialized_target.startsWith('torch')) {
  19391. module = torch;
  19392. serialized_target_names = serialized_target.split('.').slice(1);
  19393. } else if (serialized_target.startsWith('#')) {
  19394. return self.deserialize_extension_operator(serialized_target);
  19395. } else {
  19396. return serialized_target;
  19397. }
  19398. let target = module;
  19399. for (const name of serialized_target_names) {
  19400. target = builtins.getattr(target, name);
  19401. if (!target) {
  19402. return serialized_target;
  19403. }
  19404. }
  19405. return target;
  19406. }
  19407. deserialize_node(serialized_node, target) {
  19408. let fx_node = null;
  19409. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19410. const name = serialized_node.outputs[0].value.as_name;
  19411. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19412. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19413. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19414. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19415. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19416. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19417. for (const x of [...args, ...kwargs.values()]) {
  19418. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19419. x.meta.update(metadata);
  19420. }
  19421. }
  19422. const name = serialized_node.outputs.length === 1 &&
  19423. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19424. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19425. serialized_node.outputs[0].as_tensor.name : null;
  19426. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19427. this.deserialize_outputs(serialized_node, fx_node);
  19428. fx_node.meta.update(metadata);
  19429. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19430. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19431. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19432. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19433. this.deserialize_outputs(serialized_node, fx_node);
  19434. } else if (typeof target === 'string') {
  19435. // Handle unresolved operators
  19436. execution.emit('resolve', target);
  19437. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19438. throw new python.Error(`Unsupported node target type '${target}'.`);
  19439. }
  19440. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19441. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19442. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19443. this.deserialize_outputs(serialized_node, fx_node);
  19444. } else {
  19445. throw new python.Error(`Unsupported node target type '${target}'.`);
  19446. }
  19447. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19448. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19449. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19450. }
  19451. }
  19452. deserialize_input_spec(i) {
  19453. if (i.type === 'user_input') {
  19454. return new torch.export.graph_signature.InputSpec(
  19455. torch.export.graph_signature.InputKind.USER_INPUT,
  19456. this.deserialize_argument_spec(i.user_input.arg),
  19457. null);
  19458. } else if (i.type === 'parameter') {
  19459. return new torch.export.graph_signature.InputSpec(
  19460. torch.export.graph_signature.InputKind.PARAMETER,
  19461. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19462. i.parameter.parameter_name,
  19463. );
  19464. } else if (i.type === 'buffer') {
  19465. return new torch.export.graph_signature.InputSpec(
  19466. torch.export.graph_signature.InputKind.BUFFER,
  19467. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19468. i.buffer.buffer_name,
  19469. i.buffer.persistent,
  19470. );
  19471. } else if (i.type === 'tensor_constant') {
  19472. return new torch.export.graph_signature.InputSpec(
  19473. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19474. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19475. i.tensor_constant.tensor_constant_name);
  19476. } else if (i.type === 'custom_obj') {
  19477. return new torch.export.graph_signature.InputSpec(
  19478. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19479. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19480. i.custom_obj.custom_obj_name);
  19481. } else if (i.type === 'token') {
  19482. return new torch.export.graph_signature.InputSpec(
  19483. torch.export.graph_signature.InputKind.TOKEN,
  19484. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19485. null);
  19486. } else if (i.type === 'constant_input') {
  19487. return new torch.export.graph_signature.InputSpec(
  19488. torch.export.graph_signature.InputKind.USER_INPUT,
  19489. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19490. null);
  19491. }
  19492. throw new python.Error(`Unknown input spec ${i}`);
  19493. }
  19494. deserialize_constant_input(inp) {
  19495. if (inp.type === 'as_int') {
  19496. return inp.as_int;
  19497. } else if (inp.type === 'as_float') {
  19498. return inp.as_float;
  19499. } else if (inp.type === 'as_string') {
  19500. return inp.as_string;
  19501. } else if (inp.type === 'as_bool') {
  19502. return inp.as_bool;
  19503. } else if (inp.type === 'as_none') {
  19504. return null;
  19505. }
  19506. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19507. }
  19508. deserialize_output_spec(o) {
  19509. if (o.type === 'user_output') {
  19510. return new torch.export.graph_signature.OutputSpec(
  19511. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19512. this.deserialize_argument_spec(o.user_output.arg),
  19513. null);
  19514. } else if (o.type === 'loss_output') {
  19515. return new torch.export.graph_signature.OutputSpec(
  19516. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19517. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19518. null);
  19519. } else if (o.type === 'buffer_mutation') {
  19520. return new torch.export.graph_signature.OutputSpec(
  19521. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19522. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19523. o.buffer_mutation.buffer_name);
  19524. } else if (o.type === 'gradient_to_parameter') {
  19525. return new torch.export.graph_signature.OutputSpec(
  19526. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19527. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19528. o.gradient_to_parameter.parameter_name);
  19529. } else if (o.type === 'gradient_to_user_input') {
  19530. return new torch.export.graph_signature.OutputSpec(
  19531. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19532. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19533. o.gradient_to_user_input.user_input_name);
  19534. } else if (o.type === 'user_input_mutation') {
  19535. return new torch.export.graph_signature.OutputSpec(
  19536. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19537. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19538. o.user_input_mutation.user_input_name);
  19539. } else if (o.type === 'token') {
  19540. return new torch.export.graph_signature.OutputSpec(
  19541. torch.export.graph_signature.OutputKind.TOKEN,
  19542. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19543. null);
  19544. }
  19545. throw new python.Error(`Unknown output spec ${o}.`);
  19546. }
  19547. deserialize_signature(sig) {
  19548. return new torch.export.graph_signature.ExportGraphSignature(
  19549. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19550. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19551. }
  19552. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19553. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19554. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19555. this.sympy_functions = new Map([
  19556. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19557. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19558. ['Where', torch.utils._sympy.functions.Where],
  19559. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19560. ['Mod', torch.utils._sympy.functions.Mod],
  19561. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19562. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19563. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19564. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19565. ['LShift', torch.utils._sympy.functions.LShift],
  19566. ['RShift', torch.utils._sympy.functions.RShift],
  19567. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19568. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19569. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19570. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19571. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19572. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19573. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19574. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19575. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19576. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19577. ['Identity', torch.utils._sympy.functions.Identity],
  19578. ]);
  19579. this.symbol_name_to_symbol = new Map();
  19580. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19581. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19582. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19583. /*
  19584. if symbol_name_to_range:
  19585. for k, vr in symbol_name_to_range.items():
  19586. lower = int(vr.lower)
  19587. if vr.upper >= 2: # max is >= 2, not sym bool range
  19588. lower = max(2, lower)
  19589. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19590. */
  19591. this.example_inputs = null;
  19592. if (example_inputs) {
  19593. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19594. }
  19595. this.deserialize_graph(serialized_graph_module.graph);
  19596. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19597. return {
  19598. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19599. signature: this.signature,
  19600. module_call_graph,
  19601. names_to_symbols: this.symbol_name_to_symbol,
  19602. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19603. constants: this.constants,
  19604. example_inputs: this.example_inputs,
  19605. };
  19606. }
  19607. sync_fx_node(name, fx_node) {
  19608. if (this.serialized_name_to_node.has(name)) {
  19609. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19610. }
  19611. this.serialized_name_to_node.set(name, fx_node);
  19612. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19613. }
  19614. deserialize_sym_op_inputs(inputs) {
  19615. return inputs.map((input) => this.deserialize_input(input.arg));
  19616. }
  19617. deserialize_inputs(target, serialized_node) {
  19618. const schema_args = this._get_schema_from_target(target).arguments;
  19619. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19620. const args = new builtins.list();
  19621. const kwargs = new builtins.dict();
  19622. for (const schema_arg of schema_args) {
  19623. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19624. if (is_positional) {
  19625. args.push(actual_args.get(schema_arg.name));
  19626. } else if (actual_args.has(schema_arg.name)) {
  19627. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19628. }
  19629. }
  19630. return [args, kwargs];
  19631. }
  19632. deserialize_hoo_inputs(inputs) {
  19633. const args = [];
  19634. const kwargs = new builtins.dict();
  19635. for (const input_ of inputs) {
  19636. if (input_.name === '') {
  19637. args.push(this.deserialize_input(input_.arg));
  19638. } else {
  19639. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19640. }
  19641. }
  19642. return [new builtins.tuple(args), kwargs];
  19643. }
  19644. deserialize_input(inp) {
  19645. const value = inp.value;
  19646. const typ_ = inp.type;
  19647. if (typ_ === 'as_none') {
  19648. return null;
  19649. } else if (typ_ === 'as_tensor') {
  19650. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19651. } else if (typ_ === 'as_scalar_type') {
  19652. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19653. } else if (typ_ === 'as_memory_format') {
  19654. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19655. } else if (typ_ === 'as_layout') {
  19656. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19657. } else if (typ_ === 'as_graph') {
  19658. const context = this.save_graph_module();
  19659. context.__enter__();
  19660. this.deserialize_graph(value.graph);
  19661. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19662. context.__exit__(null, null, null);
  19663. this.module.register_module(value.name, submodule);
  19664. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19665. } else if (typ_ === 'as_device') {
  19666. return this.deserialize_device(inp.as_device);
  19667. } else if (typ_ === 'as_int') {
  19668. return inp.as_int;
  19669. } else if (typ_ === 'as_float') {
  19670. return inp.as_float;
  19671. } else if (typ_ === 'as_bool') {
  19672. return inp.as_bool;
  19673. } else if (typ_ === 'as_string') {
  19674. return inp.as_string;
  19675. } else if (typ_ === 'as_sym_int') {
  19676. return this.deserialize_sym_argument(inp.as_sym_int);
  19677. } else if (typ_ === 'as_sym_float') {
  19678. return this.deserialize_sym_argument(inp.as_sym_float);
  19679. } else if (typ_ === 'as_sym_bool') {
  19680. return this.deserialize_sym_argument(inp.as_sym_bool);
  19681. } else if (Array.isArray(value)) {
  19682. if (value.length === 0) {
  19683. return [];
  19684. } else if (typ_ === 'as_tensors') {
  19685. const result = [];
  19686. for (const arg of value) {
  19687. result.push(this.serialized_name_to_node.get(arg.name));
  19688. }
  19689. return result;
  19690. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19691. return Array.from(value);
  19692. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19693. return value.map((arg) => this.deserialize_sym_argument(arg));
  19694. } else if (typ_ === 'as_optional_tensors') {
  19695. const deserialize_optional_tensor_args = (a) => {
  19696. if (a.type === 'as_none') {
  19697. return null;
  19698. } else if (a.type === 'as_tensor') {
  19699. return this.serialized_name_to_node.get(a.value.name);
  19700. }
  19701. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19702. };
  19703. return value.map((item) => deserialize_optional_tensor_args(item));
  19704. }
  19705. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19706. } else if (typ_ === 'as_custom_obj') {
  19707. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19708. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19709. }
  19710. return this.constants[inp.as_custom_obj.name];
  19711. } else if (typ_ === 'as_operator') {
  19712. return this.deserialize_operator(inp.as_operator);
  19713. }
  19714. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19715. }
  19716. deserialize_sym_argument(sym_arg) {
  19717. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19718. if (sym_arg.type === 'as_int') {
  19719. return sym_arg.as_int;
  19720. } else if (sym_arg.type === 'as_name') {
  19721. return this.serialized_name_to_node.get(sym_arg.as_name);
  19722. }
  19723. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19724. if (sym_arg.type === 'as_float') {
  19725. return sym_arg.as_float;
  19726. } else if (sym_arg.type === 'as_name') {
  19727. return this.serialized_name_to_node.get(sym_arg.as_name);
  19728. }
  19729. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19730. if (sym_arg.type === 'as_bool') {
  19731. return sym_arg.as_bool;
  19732. } else if (sym_arg.type === 'as_name') {
  19733. return this.serialized_name_to_node.get(sym_arg.as_name);
  19734. }
  19735. }
  19736. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19737. }
  19738. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19739. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19740. }
  19741. deserialize_outputs(serialized_node, fx_node) {
  19742. if (serialized_node.outputs.length === 0) {
  19743. return;
  19744. }
  19745. if (serialized_node.outputs.length === 1 &&
  19746. serialized_node.outputs[0].type === 'as_tensor') {
  19747. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19748. return;
  19749. } else if (serialized_node.outputs.length === 1 &&
  19750. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19751. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19752. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19753. return;
  19754. }
  19755. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19756. }
  19757. deserialize_multiple_outputs(serialized_node, fx_node) {
  19758. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19759. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19760. let name = '';
  19761. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19762. name = arg.name;
  19763. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19764. name = arg.as_name;
  19765. } else {
  19766. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19767. }
  19768. const individual_output = this.graph.create_node(
  19769. 'call_function',
  19770. operator.getitem,
  19771. new builtins.tuple([fx_node, idx]),
  19772. null,
  19773. name,
  19774. );
  19775. this.sync_fx_node(name, individual_output);
  19776. meta_val.push(this.serialized_name_to_meta.get(name));
  19777. individual_output.meta.update(deserialized_metadata);
  19778. };
  19779. const generate_getitems = (meta_val, fx_node, args) => {
  19780. for (let idx = 0; idx < args.length; idx++) {
  19781. let arg = args[idx];
  19782. if (arg instanceof torch._export.serde.schema.Argument) {
  19783. arg = arg.value;
  19784. }
  19785. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19786. generate_getitem(meta_val, fx_node, arg, idx);
  19787. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19788. const list_output = this.graph.create_node(
  19789. 'call_function',
  19790. operator.getitem,
  19791. (fx_node, idx),
  19792. );
  19793. meta_val.push([]);
  19794. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  19795. list_output.meta.update(deserialized_metadata);
  19796. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  19797. } else {
  19798. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19799. }
  19800. }
  19801. };
  19802. const meta_val = [];
  19803. if (serialized_node.outputs.length === 1) {
  19804. // assert isinstance(serialized_node.outputs[0].value, list)
  19805. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19806. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19807. } else {
  19808. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19809. }
  19810. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19811. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19812. }
  19813. deserialize_metadata(metadata) {
  19814. const ret = new builtins.dict();
  19815. const stack_trace = metadata.get('stack_trace');
  19816. if (stack_trace) {
  19817. ret.set('stack_trace', stack_trace);
  19818. }
  19819. const deserialize_meta_func = (serialized_target) => {
  19820. let module = null;
  19821. let serialized_target_names = [];
  19822. if (serialized_target.startsWith('torch.nn')) {
  19823. module = torch.nn;
  19824. serialized_target_names = serialized_target.split('.').slice(1);
  19825. } else if (serialized_target.startsWith('torch')) {
  19826. module = torch;
  19827. serialized_target_names = serialized_target.split('.').slice(1);
  19828. } else {
  19829. return this.deserialize_operator(serialized_target);
  19830. }
  19831. let target = module;
  19832. for (const name of serialized_target_names) {
  19833. if (!builtins.hasattr(target, name)) {
  19834. return serialized_target;
  19835. }
  19836. target = builtins.getattr(target, name);
  19837. }
  19838. return target;
  19839. };
  19840. const nn_module_stack_str = metadata.get('nn_module_stack');
  19841. if (nn_module_stack_str) {
  19842. const import_nn_module_stack = (key, path, ty) => {
  19843. return [key, [path, ty]];
  19844. };
  19845. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19846. ret.set('nn_module_stack', nn_module_stack);
  19847. }
  19848. const source_fn_st_str = metadata.get('source_fn_stack');
  19849. if (source_fn_st_str) {
  19850. const source_fn_st = [];
  19851. for (const source_fn_str of source_fn_st_str.split(';')) {
  19852. const [name, target_str] = source_fn_str.split(',');
  19853. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19854. }
  19855. ret.set('source_fn_stack', source_fn_st);
  19856. }
  19857. const torch_fn = metadata.get('torch_fn');
  19858. if (torch_fn) {
  19859. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19860. }
  19861. const custom_str = metadata.get('custom');
  19862. if (custom_str) {
  19863. ret.set('custom', JSON.parse(custom_str));
  19864. }
  19865. return ret;
  19866. }
  19867. deserialize_argument_spec(x) {
  19868. if (x.type === 'as_tensor') {
  19869. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19870. } else if (x.type === 'as_sym_int') {
  19871. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19872. } else if (x.type === 'as_custom_obj') {
  19873. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19874. }
  19875. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19876. }
  19877. deserialize_tensor_meta(tensor_meta) {
  19878. try {
  19879. this.fake_tensor_mode.__enter__();
  19880. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  19881. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  19882. const device = this.deserialize_device(tensor_meta.device);
  19883. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19884. return torch.empty_strided(sizes, strides, dtype, null, device);
  19885. } finally {
  19886. this.fake_tensor_mode.__exit__(null, null, null);
  19887. }
  19888. }
  19889. deserialize_script_obj_meta(script_obj_meta) {
  19890. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  19891. }
  19892. _parse_sym_expr(expr_str, hint) {
  19893. const _process_sym_expr = (sym, hint) => {
  19894. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  19895. return sym;
  19896. }
  19897. expr_str = sym.__str__();
  19898. for (const arg of sym.args) {
  19899. this._parse_sym_expr(arg);
  19900. }
  19901. if (this.symbol_name_to_symbol.has(expr_str)) {
  19902. sym = this.symbol_name_to_symbol.get(expr_str);
  19903. } else {
  19904. this.symbol_name_to_symbol.set(expr_str, sym);
  19905. 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])) {
  19906. this.unbacked_symbols.add(sym);
  19907. }
  19908. }
  19909. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  19910. this.shape_env.add_var_to_val(sym, hint);
  19911. }
  19912. const vr = this.symbol_name_to_range.get(expr_str);
  19913. if (vr) {
  19914. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  19915. }
  19916. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  19917. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  19918. }
  19919. return sym;
  19920. };
  19921. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  19922. const expr = sympy.core.sympify.sympify(expr_str, locals);
  19923. return _process_sym_expr(expr, hint);
  19924. }
  19925. deserialize_sym_int(s) {
  19926. const val = s.value;
  19927. let hint = null;
  19928. if (s.type === 'as_expr') {
  19929. if (val.hint === null) {
  19930. hint = null;
  19931. } else {
  19932. // assert val.hint.type == "as_int"
  19933. hint = val.hint.value;
  19934. }
  19935. const sym = this._parse_sym_expr(val.expr_str, hint);
  19936. return this.shape_env.create_symintnode(sym, hint);
  19937. } else if (s.type === 'as_int') {
  19938. // assert type(val) is int
  19939. return val;
  19940. }
  19941. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  19942. }
  19943. deserialize_sym_bool(s) {
  19944. const val = s.value;
  19945. let hint = null;
  19946. if (s.type === 'as_expr') {
  19947. if (val.hint === null) {
  19948. hint = null;
  19949. } else {
  19950. // assert val.hint.type == "as_bool"
  19951. hint = val.hint.value;
  19952. }
  19953. const sym = this._parse_sym_expr(val.expr_str, hint);
  19954. return this.shape_env.create_symboolnode(sym, hint);
  19955. } else if (s.type === 'as_bool') {
  19956. // assert type(val) is bool
  19957. return val;
  19958. }
  19959. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  19960. }
  19961. deserialize_device(d) {
  19962. if (d.index === null) {
  19963. return new torch.device(d.type);
  19964. }
  19965. return new torch.device(d.type, d.index);
  19966. }
  19967. _get_schema_from_target(target) {
  19968. if (target instanceof torch._ops.OpOverload) {
  19969. return target._schema;
  19970. }
  19971. throw new python.Error(`Unsupported schema '${target.name}'.`);
  19972. }
  19973. _is_single_tensor_return(target) {
  19974. const schema = this._get_schema_from_target(target);
  19975. const returns = schema.returns;
  19976. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  19977. }
  19978. });
  19979. this.registerType('torch._export.verifier.Verifier', class {});
  19980. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  19981. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  19982. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  19983. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  19984. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  19985. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  19986. constructor(mod, dynamo_ctx) {
  19987. builtins.object.__setattr__(self, '_orig_mod', mod);
  19988. // this._super_module_initialized = false;
  19989. super();
  19990. // this._super_module_initialized = true;
  19991. this._orig_mod = mod;
  19992. this.dynamo_ctx = dynamo_ctx;
  19993. // this._initialize();
  19994. this.training = this._orig_mod.training;
  19995. }
  19996. });
  19997. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  19998. this.registerType('torch._dynamo.hooks.Hooks', class {});
  19999. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  20000. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  20001. this.registerType('torch._TorchCompileInductorWrapper', class {});
  20002. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  20003. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  20004. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  20005. const module = new types.ModuleType(name);
  20006. execution.register('sys').modules.set(name, module);
  20007. const context = new python.Execution.Context(module, null);
  20008. execution.exec(meta.get('module_src'), context);
  20009. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  20010. const state = meta.get('state');
  20011. if (state) {
  20012. if (obj.__setstate__) {
  20013. obj.__setstate__(state);
  20014. } else {
  20015. for (const [key, value] of state) {
  20016. obj[key] = value;
  20017. }
  20018. }
  20019. }
  20020. return obj;
  20021. });
  20022. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  20023. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  20024. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  20025. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  20026. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  20027. this.registerType('torch.device', class {
  20028. constructor(type, index) {
  20029. this.type = type;
  20030. this.index = index ? index : null;
  20031. }
  20032. __str__() {
  20033. return this.index === null ? this.type : `${this.type}:${this.index}`;
  20034. }
  20035. toString() {
  20036. const index = this.index === null ? '' : `, index=${this.index}`;
  20037. return `device(type='${this.type}'${index})`;
  20038. }
  20039. });
  20040. this.registerType('torch.memory_format', class {
  20041. constructor(name) {
  20042. this.name = name;
  20043. }
  20044. __str__() {
  20045. return `torch.${this.name}`;
  20046. }
  20047. toString() {
  20048. return this.__str__();
  20049. }
  20050. });
  20051. this.registerType('torch.dtype', class {
  20052. constructor(scalar_type, name, itemsize) {
  20053. this._scalar_type = scalar_type;
  20054. this._name = name;
  20055. this._itemsize = itemsize;
  20056. }
  20057. scalar_type() {
  20058. return this._scalar_type;
  20059. }
  20060. itemsize() {
  20061. return this._itemsize;
  20062. }
  20063. __reduce__() {
  20064. return this._name;
  20065. }
  20066. __str__() {
  20067. return `torch.${this._name}`;
  20068. }
  20069. toString() {
  20070. return this.__str__();
  20071. }
  20072. });
  20073. this.registerType('torch.layout', class {
  20074. constructor(name) {
  20075. this._name = name;
  20076. }
  20077. __str__() {
  20078. return `torch.${this._name}`;
  20079. }
  20080. toString() {
  20081. return this.__str__();
  20082. }
  20083. });
  20084. this.registerType('torch.qscheme', class {
  20085. constructor(name) {
  20086. this._name = name;
  20087. }
  20088. __str__() {
  20089. return this._name;
  20090. }
  20091. toString() {
  20092. return this.__str__();
  20093. }
  20094. });
  20095. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20096. __setstate__(state) {
  20097. [this.hooks_dict_ref, this.id] = state;
  20098. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20099. }
  20100. });
  20101. this.registerType('torch.storage._StorageBase', class {
  20102. constructor(size, dtype) {
  20103. this._size = size;
  20104. this._dtype = dtype;
  20105. this._device = null;
  20106. }
  20107. get device() {
  20108. return this._device;
  20109. }
  20110. get dtype() {
  20111. return this._dtype;
  20112. }
  20113. element_size() {
  20114. return this._dtype.element_size;
  20115. }
  20116. size() {
  20117. return this._size;
  20118. }
  20119. get data() {
  20120. return this._cdata;
  20121. }
  20122. _set_cdata(data) {
  20123. const length = this.size() * this.dtype.itemsize();
  20124. if (length !== data.length) {
  20125. throw new python.Error('Typed storage data size mismatch.');
  20126. }
  20127. this._cdata = data;
  20128. }
  20129. _set_from_file(unpickler) {
  20130. const buffer = unpickler.read(8);
  20131. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20132. if (size !== this.size()) {
  20133. throw new python.Error('Typed storage size mismatch.');
  20134. }
  20135. const itemsize = this.dtype.itemsize();
  20136. const data = unpickler.stream(itemsize * size);
  20137. this._set_cdata(data);
  20138. }
  20139. static _new_with_file(unpickler) {
  20140. const buffer = unpickler.read(8);
  20141. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20142. const storage = new this(size);
  20143. const itemsize = storage.dtype.itemsize();
  20144. const data = unpickler.stream(itemsize * size);
  20145. storage._set_cdata(data);
  20146. return storage;
  20147. }
  20148. });
  20149. this.registerType('torch.storage.UntypedStorage', class {
  20150. constructor(size) {
  20151. this._size = size;
  20152. }
  20153. _set_cdata(data) {
  20154. if (this._size !== data.length) {
  20155. throw new python.Error('Untyped storage data size mismatch.');
  20156. }
  20157. this._cdata = data;
  20158. }
  20159. });
  20160. this.registerType('torch.storage.TypedStorage', class {
  20161. constructor(...args) {
  20162. if (args.length === 0) {
  20163. this._size = 0;
  20164. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20165. [this._size] = args;
  20166. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20167. if (args[3] instanceof torch.device) {
  20168. [this._size, this.dtype, , this._device] = args;
  20169. } else {
  20170. [this._size, this.dtype] = args;
  20171. }
  20172. } else {
  20173. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20174. }
  20175. }
  20176. get device() {
  20177. return this._device;
  20178. }
  20179. get dtype() {
  20180. return this._dtype;
  20181. }
  20182. set dtype(value) {
  20183. this._dtype = value;
  20184. }
  20185. element_size() {
  20186. return this._dtype.element_size;
  20187. }
  20188. size() {
  20189. return this._size;
  20190. }
  20191. get data() {
  20192. return this._cdata;
  20193. }
  20194. _set_cdata(data) {
  20195. const length = this.size() * this.dtype.itemsize();
  20196. if (length !== data.length) {
  20197. throw new python.Error('Storage data size mismatch.');
  20198. }
  20199. this._cdata = data;
  20200. }
  20201. _set_from_file(unpickler) {
  20202. const buffer = unpickler.read(8);
  20203. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20204. if (size !== this.size()) {
  20205. throw new python.Error('Storage size mismatch.');
  20206. }
  20207. const itemsize = this.dtype.itemsize();
  20208. const data = unpickler.stream(itemsize * size);
  20209. this._set_cdata(data);
  20210. }
  20211. static _new_with_file(unpickler) {
  20212. const buffer = unpickler.read(8);
  20213. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20214. const storage = new this(size);
  20215. const itemsize = storage.dtype.itemsize();
  20216. const data = unpickler.stream(itemsize * size);
  20217. storage._set_cdata(data);
  20218. return storage;
  20219. }
  20220. });
  20221. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20222. });
  20223. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20224. constructor(...args) {
  20225. // eslint-disable-next-line no-constructor-return
  20226. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20227. }
  20228. });
  20229. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20230. constructor(...args) {
  20231. // eslint-disable-next-line no-constructor-return
  20232. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20233. }
  20234. });
  20235. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20236. constructor(...args) {
  20237. // eslint-disable-next-line no-constructor-return
  20238. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20239. }
  20240. });
  20241. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20242. constructor(...args) {
  20243. // eslint-disable-next-line no-constructor-return
  20244. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20245. }
  20246. });
  20247. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20248. constructor(...args) {
  20249. // eslint-disable-next-line no-constructor-return
  20250. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20251. }
  20252. });
  20253. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20254. constructor(...args) {
  20255. // eslint-disable-next-line no-constructor-return
  20256. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20257. }
  20258. });
  20259. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20260. constructor(...args) {
  20261. // eslint-disable-next-line no-constructor-return
  20262. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20263. }
  20264. });
  20265. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20266. constructor(...args) {
  20267. // eslint-disable-next-line no-constructor-return
  20268. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20269. }
  20270. });
  20271. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20272. constructor(...args) {
  20273. // eslint-disable-next-line no-constructor-return
  20274. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20275. }
  20276. });
  20277. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20278. constructor(...args) {
  20279. // eslint-disable-next-line no-constructor-return
  20280. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20281. }
  20282. });
  20283. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20284. constructor(...args) {
  20285. // eslint-disable-next-line no-constructor-return
  20286. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20287. }
  20288. });
  20289. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20290. constructor(...args) {
  20291. // eslint-disable-next-line no-constructor-return
  20292. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20293. }
  20294. });
  20295. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20296. constructor(...args) {
  20297. // eslint-disable-next-line no-constructor-return
  20298. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20299. }
  20300. });
  20301. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20302. constructor(...args) {
  20303. // eslint-disable-next-line no-constructor-return
  20304. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20305. }
  20306. });
  20307. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20308. constructor(...args) {
  20309. // eslint-disable-next-line no-constructor-return
  20310. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20311. }
  20312. });
  20313. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20314. constructor(...args) {
  20315. // eslint-disable-next-line no-constructor-return
  20316. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20317. }
  20318. });
  20319. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20320. constructor(...args) {
  20321. // eslint-disable-next-line no-constructor-return
  20322. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20323. }
  20324. });
  20325. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20326. constructor(...args) {
  20327. // eslint-disable-next-line no-constructor-return
  20328. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20329. }
  20330. });
  20331. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20332. constructor(...args) {
  20333. // eslint-disable-next-line
  20334. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20335. }
  20336. });
  20337. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20338. constructor(...args) {
  20339. // eslint-disable-next-line no-constructor-return
  20340. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20341. }
  20342. });
  20343. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20344. constructor(...args) {
  20345. // eslint-disable-next-line no-constructor-return
  20346. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20347. }
  20348. });
  20349. this.registerType('torch.Size', class extends Array {
  20350. constructor(size) {
  20351. super(size.length);
  20352. for (let i = 0; i < size.length; i++) {
  20353. this[i] = size[i];
  20354. }
  20355. }
  20356. __len__() {
  20357. return this.length;
  20358. }
  20359. });
  20360. this.registerType('torch._C.TensorMeta', class {
  20361. });
  20362. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20363. });
  20364. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20365. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20366. super();
  20367. if (storage) {
  20368. this._storage = storage;
  20369. }
  20370. if (shape !== null && shape !== undefined) {
  20371. this._shape = shape;
  20372. }
  20373. if (dtype) {
  20374. this._dtype = dtype;
  20375. }
  20376. this._layout = layout || torch.strided;
  20377. if (device) {
  20378. this._device = device;
  20379. }
  20380. if (requires_grad !== undefined) {
  20381. this.requires_grad = requires_grad;
  20382. }
  20383. }
  20384. clone() {
  20385. const tensor = new torch.Tensor(this._storage, this._shape, this._dtype, this._layout, this._device, this.requires_grad);
  20386. tensor._storage_offset = this._storage_offset;
  20387. tensor._stride = this._stride;
  20388. tensor._values = this._values;
  20389. tensor._indices = this._indices;
  20390. tensor.__quantized__ = this.__quantized__;
  20391. tensor.__nested__ = this.__nested__;
  20392. tensor.data = this.data;
  20393. tensor._backward_hooks = this._backward_hooks;
  20394. return tensor;
  20395. }
  20396. get device() {
  20397. if (this._device !== undefined) {
  20398. return this._device;
  20399. }
  20400. return this.storage().device;
  20401. }
  20402. get dtype() {
  20403. if (this._dtype !== undefined) {
  20404. return this._dtype;
  20405. }
  20406. if (this._layout === torch.sparse_coo) {
  20407. return this._values.dtype;
  20408. }
  20409. return this.storage().dtype;
  20410. }
  20411. get shape() {
  20412. return this._shape;
  20413. }
  20414. get layout() {
  20415. return this._layout;
  20416. }
  20417. get values() {
  20418. if (this._layout === torch.sparse_coo) {
  20419. return this._values;
  20420. }
  20421. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20422. }
  20423. get indices() {
  20424. if (this._layout === torch.sparse_coo) {
  20425. return this._indices;
  20426. }
  20427. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20428. }
  20429. get is_quantized() {
  20430. return this.__quantized__ === true;
  20431. }
  20432. get is_nested() {
  20433. return this.__nested__ === true;
  20434. }
  20435. get is_sparse() {
  20436. return this.layout !== torch.strided;
  20437. }
  20438. size() {
  20439. return this._shape;
  20440. }
  20441. storage() {
  20442. return this._storage;
  20443. }
  20444. storage_offset() {
  20445. return this._storage_offset;
  20446. }
  20447. stride() {
  20448. return this._stride;
  20449. }
  20450. resize_(shape) {
  20451. this._shape = shape;
  20452. }
  20453. __len__() {
  20454. return this._shape[0];
  20455. }
  20456. __setstate__(state) {
  20457. switch (state.length) {
  20458. case 3:
  20459. break;
  20460. case 4:
  20461. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20462. break;
  20463. case 5:
  20464. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20465. break;
  20466. default:
  20467. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20468. }
  20469. }
  20470. set_(source, storage_offset, size, stride) {
  20471. this._storage = source;
  20472. this._storage_offset = storage_offset;
  20473. this._shape = size;
  20474. this._stride = stride;
  20475. }
  20476. __bool__() {
  20477. return true;
  20478. }
  20479. __int__() {
  20480. const storage = this.storage();
  20481. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20482. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20483. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20484. return view.getBigInt64(0, true);
  20485. }
  20486. return NaN;
  20487. }
  20488. __float__() {
  20489. const storage = this.storage();
  20490. if (storage && storage.dtype.__reduce__() === 'float32') {
  20491. if (storage.size() !== undefined && storage.data.length === 4) {
  20492. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20493. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20494. return view.getFloat32(0, true);
  20495. }
  20496. }
  20497. return NaN;
  20498. }
  20499. __str__() {
  20500. return 'tensor(...)';
  20501. }
  20502. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20503. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20504. t.__setstate__([null, storage_offset, size, stride]);
  20505. return t;
  20506. }
  20507. });
  20508. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20509. constructor(data, requires_grad) {
  20510. super();
  20511. this.data = data || new torch.Tensor([]);
  20512. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20513. }
  20514. });
  20515. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20516. });
  20517. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20518. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20519. super();
  20520. this.allow_fallback_kernels = allow_fallback_kernels;
  20521. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20522. this.shape_env = shape_env;
  20523. this.enter_stack = [];
  20524. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20525. }
  20526. __enter__() {
  20527. const prev_only_lift_cpu_tensors = null;
  20528. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20529. if (this === maybe_prev_fake_mode) {
  20530. torch._C._set_dispatch_mode(this);
  20531. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20532. } else {
  20533. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20534. return super.__enter__();
  20535. }
  20536. return this;
  20537. }
  20538. __exit__(exc_type, exc_value, traceback) {
  20539. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20540. if (live) {
  20541. super.__exit__(exc_type, exc_value, traceback);
  20542. if (maybe_prev_fake_mode !== null) {
  20543. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20544. }
  20545. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20546. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20547. }
  20548. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20549. }
  20550. }
  20551. });
  20552. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20553. constructor(requires_grad /*, device, dtype */) {
  20554. super(undefined, requires_grad);
  20555. }
  20556. });
  20557. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20558. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20559. constructor(...args) {
  20560. // eslint-disable-next-line no-constructor-return
  20561. return new torch.Tensor(...args);
  20562. }
  20563. });
  20564. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20565. constructor(...args) {
  20566. // eslint-disable-next-line no-constructor-return
  20567. return new torch.Tensor(...args);
  20568. }
  20569. });
  20570. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20571. constructor(...args) {
  20572. // eslint-disable-next-line no-constructor-return
  20573. return new torch.Tensor(...args);
  20574. }
  20575. });
  20576. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20577. constructor(...args) {
  20578. // eslint-disable-next-line no-constructor-return
  20579. return new torch.Tensor(...args);
  20580. }
  20581. });
  20582. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20583. constructor(...args) {
  20584. // eslint-disable-next-line no-constructor-return
  20585. return new torch.Tensor(...args);
  20586. }
  20587. });
  20588. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20589. constructor(...args) {
  20590. // eslint-disable-next-line no-constructor-return
  20591. return new torch.Tensor(...args);
  20592. }
  20593. });
  20594. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20595. constructor(...args) {
  20596. // eslint-disable-next-line no-constructor-return
  20597. return new torch.Tensor(...args);
  20598. }
  20599. });
  20600. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20601. constructor(...args) {
  20602. // eslint-disable-next-line no-constructor-return
  20603. return new torch.Tensor(...args);
  20604. }
  20605. });
  20606. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20607. constructor(...args) {
  20608. // eslint-disable-next-line no-constructor-return
  20609. return new torch.Tensor(...args);
  20610. }
  20611. });
  20612. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20613. constructor(...args) {
  20614. // eslint-disable-next-line no-constructor-return
  20615. return new torch.Tensor(...args);
  20616. }
  20617. });
  20618. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20619. constructor(...args) {
  20620. // eslint-disable-next-line no-constructor-return
  20621. return new torch.Tensor(...args);
  20622. }
  20623. });
  20624. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20625. constructor(...args) {
  20626. // eslint-disable-next-line no-constructor-return
  20627. return new torch.Tensor(...args);
  20628. }
  20629. });
  20630. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20631. constructor(...args) {
  20632. // eslint-disable-next-line no-constructor-return
  20633. return new torch.Tensor(...args);
  20634. }
  20635. });
  20636. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20637. constructor(...args) {
  20638. // eslint-disable-next-line no-constructor-return
  20639. return new torch.Tensor(...args);
  20640. }
  20641. });
  20642. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20643. constructor(...args) {
  20644. // eslint-disable-next-line no-constructor-return
  20645. return new torch.Tensor(...args);
  20646. }
  20647. });
  20648. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20649. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20650. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20651. constructor(...args) {
  20652. // eslint-disable-next-line no-constructor-return
  20653. return new torch.Tensor(...args);
  20654. }
  20655. });
  20656. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20657. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20658. constructor(...args) {
  20659. // eslint-disable-next-line no-constructor-return
  20660. return new torch.Tensor(...args);
  20661. }
  20662. });
  20663. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20664. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20665. constructor(...args) {
  20666. // eslint-disable-next-line no-constructor-return
  20667. return new torch.Tensor(...args);
  20668. }
  20669. });
  20670. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20671. this.registerType('torchao.dtypes.utils.Layout', class {});
  20672. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20673. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20674. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20675. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20676. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20677. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20678. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20679. this.registerType('torch.SymBool', class {
  20680. constructor(node) {
  20681. this.node = node;
  20682. }
  20683. });
  20684. this.registerType('torch.SymInt', class {
  20685. constructor(node) {
  20686. this.node = node;
  20687. }
  20688. toString() {
  20689. return this.node.__str__();
  20690. }
  20691. });
  20692. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20693. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20694. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20695. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20696. /* eslint-disable no-multi-assign */
  20697. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20698. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20699. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20700. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20701. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20702. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20703. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20704. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20705. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20706. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20707. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20708. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20709. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20710. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20711. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20712. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20713. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20714. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20715. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20716. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20717. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20718. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20719. torch.bits8 = new torch.dtype(21, 'bits8');
  20720. torch.bits16 = new torch.dtype(22, 'bits16');
  20721. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20722. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20723. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20724. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20725. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  20726. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  20727. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  20728. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20729. ['uint8', 'BYTE'],
  20730. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20731. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20732. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20733. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20734. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20735. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20736. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20737. torch.channels_last = new torch.memory_format('channels_last');
  20738. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20739. torch.preserve_format = new torch.memory_format('preserve_format');
  20740. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20741. ['contiguous_format', 'ContiguousFormat'],
  20742. ['channels_last', 'ChannelsLast'],
  20743. ['channels_last_3d', 'ChannelsLast3d'],
  20744. ['preserve_format', 'PreserveFormat']
  20745. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20746. /* eslint-enable no-multi-assign */
  20747. torch.strided = new torch.layout('strided');
  20748. torch.sparse_coo = new torch.layout('sparse_coo');
  20749. torch.sparse_csr = new torch.layout('sparse_csr');
  20750. torch.sparse_csc = new torch.layout('sparse_csc');
  20751. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20752. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20753. torch._mkldnn = new torch.layout('_mkldnn');
  20754. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20755. ['sparse_coo', 'SparseCoo'],
  20756. ['sparse_csr', 'SparseCsr'],
  20757. ['sparse_csc', 'SparseCsc'],
  20758. ['sparse_bsr', 'SparseBsr'],
  20759. ['sparse_bsc', 'SparseBsc'],
  20760. ['_mkldnn', '_mkldnn'],
  20761. ['strided', 'Strided'],
  20762. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20763. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20764. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20765. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20766. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20767. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20768. torch.inf = this.register('math').inf;
  20769. this.registerFunction('fastcore.basics._using_attr');
  20770. this.registerFunction('fastcore.imports.noop');
  20771. this.registerType('fastcore.basics.fastuple', class {});
  20772. this.registerType('fastcore.basics.GetAttr', class {});
  20773. this.registerType('fastcore.dispatch._TypeDict', class {});
  20774. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20775. this.registerType('fastcore.foundation.L', class {});
  20776. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20777. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20778. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20779. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20780. this.registerType('fastai.basic_train.Learner', class {});
  20781. this.registerType('fastai.basic_train.Recorder', class {});
  20782. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20783. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20784. return self.invoke(cls, [tensor]);
  20785. });
  20786. this.registerFunction('fastai.torch_core.trainable_params');
  20787. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20788. const tensor = self.invoke(type, [func(...args)]);
  20789. Object.assign(tensor, dict);
  20790. return tensor;
  20791. });
  20792. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20793. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20794. constructor(x) {
  20795. super();
  20796. Object.assign(this, x);
  20797. }
  20798. });
  20799. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20800. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20801. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20802. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20803. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20804. this.registerFunction('fastai.torch_core.uniform');
  20805. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20806. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20807. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20808. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20809. this.registerFunction('fastai.callback.hook._hook_inner');
  20810. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20811. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20812. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20813. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20814. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20815. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20816. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20817. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20818. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20819. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20820. this.registerType('fastai.data.core.Datasets', class {});
  20821. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20822. this.registerType('fastai.data.core.FilteredBase', class {});
  20823. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20824. this.registerType('fastai.data.core.TfmdLists', class {});
  20825. this.registerType('fastai.data.load._FakeLoader', class {});
  20826. this.registerFunction('fastai.data.load._wif');
  20827. this.registerType('fastai.data.transforms.Categorize', class {});
  20828. this.registerType('fastai.data.transforms.Category', class {});
  20829. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20830. this.registerType('fastai.data.transforms.ColReader', class {});
  20831. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20832. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20833. this.registerType('fastai.data.transforms.Normalize', class {});
  20834. this.registerType('fastai.data.transforms.parent_label', class {});
  20835. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20836. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20837. this.registerType('fastai.data.transforms.ToTensor', class {});
  20838. this.registerType('fastai.data_block.CategoryList', class {});
  20839. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20840. this.registerType('fastai.imports.noop', class {});
  20841. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20842. this.registerType('fastai.layers.ConvLayer', class {});
  20843. this.registerType('fastai.layers.Embedding', class {});
  20844. this.registerType('fastai.layers.Flatten', class {});
  20845. this.registerType('fastai.layers.FlattenedLoss', class {});
  20846. this.registerType('fastai.layers.LinBnDrop', class {});
  20847. this.registerType('fastai.layers.MergeLayer', class {});
  20848. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20849. this.registerType('fastai.layers.ResBlock', class {});
  20850. this.registerType('fastai.layers.SelfAttention', class {});
  20851. this.registerType('fastai.layers.SigmoidRange', class {});
  20852. this.registerType('fastai.layers.TimeDistributed', class {});
  20853. this.registerType('fastai.layers.ToTensorBase', class {});
  20854. this.registerType('fastai.learner._ConstantFunc', class {});
  20855. this.registerType('fastai.learner.Metric', class {});
  20856. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20857. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20858. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20859. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20860. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20861. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20862. this.registerType('fastai.learner.Recorder', class {});
  20863. this.registerType('fastai.losses.BaseLoss', class {});
  20864. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20865. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20866. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20867. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20868. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20869. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20870. this.registerType('fastai.metrics.Dice', class {});
  20871. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20872. this.registerFunction('fastai.metrics._rmse');
  20873. this.registerFunction('fastai.metrics.accuracy');
  20874. this.registerFunction('fastai.metrics.accuracy_multi');
  20875. this.registerFunction('fastai.metrics.foreground_acc');
  20876. this.registerFunction('fastai.metrics.mse');
  20877. this.registerFunction('fastai.metrics.error_rate');
  20878. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  20879. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  20880. this.registerFunction('fastai.optimizer.Adam');
  20881. this.registerFunction('fastai.optimizer.adam_step');
  20882. this.registerFunction('fastai.optimizer.average_grad');
  20883. this.registerFunction('fastai.optimizer.average_sqr_grad');
  20884. this.registerFunction('fastai.optimizer.RAdam');
  20885. this.registerFunction('fastai.optimizer.step_stat');
  20886. this.registerFunction('fastai.optimizer.weight_decay');
  20887. this.registerType('fastai.tabular.core.Categorify', class {});
  20888. this.registerType('fastai.tabular.core.FillMissing', class {});
  20889. this.registerType('fastai.tabular.core.FillStrategy', class {});
  20890. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  20891. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  20892. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  20893. this.registerType('fastai.tabular.core.Tabular', class {});
  20894. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  20895. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  20896. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  20897. this.registerType('fastai.tabular.model.TabularModel', class {});
  20898. this.registerFunction('fastai.vision.augment.aug_transforms');
  20899. this.registerFunction('fastai.vision.augment.dihedral_mat');
  20900. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  20901. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  20902. this.registerType('fastai.vision.augment._WarpCoord', class {});
  20903. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  20904. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  20905. this.registerType('fastai.vision.augment.Brightness', class {});
  20906. this.registerType('fastai.vision.augment.flip_mat', class {});
  20907. this.registerType('fastai.vision.augment.Flip', class {});
  20908. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  20909. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  20910. this.registerType('fastai.vision.augment.Resize', class {});
  20911. this.registerType('fastai.vision.augment.rotate_mat', class {});
  20912. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  20913. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  20914. this.registerType('fastai.vision.augment.zoom_mat', class {});
  20915. this.registerType('fastai.vision.core.PILImage', class {});
  20916. this.registerType('fastai.vision.core.PILMask', class {});
  20917. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  20918. this.registerType('fastai.vision.data.ImageList', class {});
  20919. this.registerType('fastai.vision.data.ImageItemList', class {});
  20920. this.registerType('fastai.vision.image.Image', class {});
  20921. this.registerType('fastai.vision.image.RandTransform', class {});
  20922. this.registerType('fastai.vision.image.TfmCrop', class {});
  20923. this.registerFunction('fastai.vision.learner._resnet_split');
  20924. this.registerFunction('fastai.vision.learner.default_split');
  20925. this.registerFunction('fastai.vision.learner.default_split');
  20926. this.registerType('fastai.vision.learner.TimmBody', class {});
  20927. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  20928. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  20929. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  20930. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  20931. this.registerFunction('fastai.vision.transform._crop_pad');
  20932. }
  20933. exec(code , context) {
  20934. const ast = this.ast;
  20935. const program = ast.parse(code, '', null, null);
  20936. if (!program) {
  20937. throw new python.Error("Module '?' parse error.");
  20938. }
  20939. this.block(program.body, context);
  20940. }
  20941. debug(/* file */) {
  20942. }
  20943. source(file) {
  20944. if (this._sources.has(file)) {
  20945. return this._sources.get(file);
  20946. }
  20947. return null;
  20948. }
  20949. read(file) {
  20950. const buffer = this.source(file);
  20951. if (buffer) {
  20952. const debug = this.debug(file);
  20953. return this.parse(file, buffer, debug);
  20954. }
  20955. return null;
  20956. }
  20957. parse(filename, buffer, debug) {
  20958. const ast = this.ast;
  20959. const source = this._utf8Decoder.decode(buffer);
  20960. const program = ast.parse(source, filename, null, debug);
  20961. if (!program) {
  20962. throw new python.Error(`Module '${filename}' parse error.`);
  20963. }
  20964. return program;
  20965. }
  20966. import(name, current, level) {
  20967. if (level) {
  20968. let bits = current.split('.');
  20969. if (bits.length < level) {
  20970. throw new python.Error('Invalid relative import beyond top-level package.');
  20971. }
  20972. bits = bits.slice(0, bits.length - level);
  20973. const base = bits.join('.');
  20974. name = name ? [base, name].join('.') : base;
  20975. }
  20976. const index = name.lastIndexOf('.');
  20977. let parent = null;
  20978. let child = null;
  20979. if (index > 0) {
  20980. parent = name.substring(0, index);
  20981. child = name.substring(index + 1);
  20982. this.import(parent);
  20983. }
  20984. if (!this._modules.has(name)) {
  20985. const module = this._registry.get(name) || new this.builtins.module(name);
  20986. module.__package__ = name;
  20987. this._modules.set(name, module);
  20988. const path = name.split('.').join('/');
  20989. module.__path__ = [path];
  20990. const file = `${path}.py`;
  20991. const program = this.read(file);
  20992. if (program) {
  20993. module.__file__ = file;
  20994. for (const [name, value] of Object.entries(this.builtins)) {
  20995. switch (name) {
  20996. case '__class__':
  20997. case '__package__':
  20998. case '__module__':
  20999. case '__name__':
  21000. case '__path__':
  21001. case '__file__':
  21002. break;
  21003. default:
  21004. module[name] = value;
  21005. break;
  21006. }
  21007. }
  21008. const context = new python.Execution.Context(module, null);
  21009. if (name !== 'builtins') {
  21010. context.set('__builtins__', this._modules.get('builtins'));
  21011. }
  21012. this.block(program.body, context);
  21013. }
  21014. if (parent) {
  21015. const parent_module = this._modules.get(parent);
  21016. parent_module[child] = module;
  21017. }
  21018. }
  21019. return this._modules.get(name);
  21020. }
  21021. __import__(name, globals, locals, fromlist, level) {
  21022. let module = null;
  21023. level = level || 0;
  21024. if (level === 0) {
  21025. module = this.import(name);
  21026. } else {
  21027. globals = globals || {};
  21028. let current = globals.__package__;
  21029. if (!current) {
  21030. const spec = globals.__spec__;
  21031. if (spec) {
  21032. current = spec.parent;
  21033. } else {
  21034. const name = globals.__name__;
  21035. const bits = name.split('.');
  21036. bits.pop();
  21037. current = bits.join('.');
  21038. }
  21039. }
  21040. module = this.import(name, current, level);
  21041. }
  21042. if (!fromlist) {
  21043. if (level === 0) {
  21044. return this.import(name.split('.')[0]);
  21045. } else if (name) {
  21046. throw new python.Error(`Unsupported relative import '${name}'.`);
  21047. // cut_off = len(name) - len(name.partition('.')[0])
  21048. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  21049. }
  21050. } else if (module.__path__) {
  21051. const handle_fromlist = (module, fromlist, recursive) => {
  21052. for (const name of fromlist) {
  21053. if (name === '*') {
  21054. if (!recursive && module.__all__) {
  21055. handle_fromlist(module, module.__all__, true);
  21056. }
  21057. } else if (!module[name]) {
  21058. this.import(`${module.__name__}.${name}`);
  21059. }
  21060. }
  21061. return module;
  21062. };
  21063. handle_fromlist(module, fromlist);
  21064. }
  21065. return module;
  21066. }
  21067. module(name) {
  21068. return this._modules.get(name);
  21069. }
  21070. resolve(name) {
  21071. const index = name.lastIndexOf('.');
  21072. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  21073. const moduleName = index === -1 ? '' : name.substring(0, index);
  21074. const module = this.import(moduleName);
  21075. let type = module ? module[memberName] : null;
  21076. if (!type) {
  21077. if (!this._unresolved.has(name)) {
  21078. const moduleName = name.split('.').shift();
  21079. if (this._registry.has(moduleName) && moduleName !== '__main__' && moduleName !== '__torch__') {
  21080. this.emit('resolve', name);
  21081. }
  21082. const type = this._createType(name, class {});
  21083. this._unresolved.set(name, type);
  21084. }
  21085. type = this._unresolved.get(name);
  21086. }
  21087. return type;
  21088. }
  21089. invoke(target, args) {
  21090. const builtins = this.builtins;
  21091. if (typeof target === 'string') {
  21092. target = this.resolve(target);
  21093. }
  21094. if (target) {
  21095. if (target.__class__ === builtins.type) {
  21096. if (target.prototype && target.prototype.__class__ === target) {
  21097. return Reflect.construct(target, args);
  21098. }
  21099. const obj = Object.create(target);
  21100. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21101. obj.__init__(...args);
  21102. }
  21103. return obj;
  21104. } else if (target.__class__ === builtins.function) {
  21105. if (target.__call__) {
  21106. return target.__call__(args);
  21107. }
  21108. return target(...args);
  21109. }
  21110. }
  21111. throw new python.Error('Unsupported invoke target.');
  21112. }
  21113. call(target, name, args, keywords, context) {
  21114. const builtins = this.builtins;
  21115. const callTarget = this.target(target, context);
  21116. const callArguments = args.map((arg) => this.expression(arg, context));
  21117. if (!callTarget || (name !== null && !callTarget[name])) {
  21118. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21119. name = null;
  21120. callArguments.shift();
  21121. } else {
  21122. const targetName = `${this.identifier(target)}.${name}`;
  21123. throw new python.Error(`Unknown function '${targetName}'.`);
  21124. }
  21125. }
  21126. const func = name ? callTarget[name] : callTarget;
  21127. if (func.__class__ === builtins.type) {
  21128. if (func.prototype && func.prototype.__class__ === func) {
  21129. return Reflect.construct(func, callArguments);
  21130. }
  21131. const obj = Object.create(func);
  21132. obj.__class__ = func;
  21133. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21134. obj.__init__(...args);
  21135. }
  21136. return obj;
  21137. }
  21138. if (func.__class__ === builtins.function) {
  21139. if (func.__call__) {
  21140. return func.__call__(callArguments);
  21141. }
  21142. }
  21143. if (func.__class__ === builtins.method) {
  21144. if (func.__call__) {
  21145. return func.__call__([callTarget].concat(callArguments));
  21146. }
  21147. }
  21148. if (typeof func === 'function') {
  21149. return func.apply(callTarget, callArguments);
  21150. }
  21151. throw new python.Error('Unsupported call expression.');
  21152. }
  21153. apply(method, args, context) {
  21154. const locals = Array.prototype.slice.call(args);
  21155. context = new python.Execution.Context(context.globals, {});
  21156. args = method.args.posonlyargs.concat(method.args.args);
  21157. const default_pos = args.length - method.args.defaults.length;
  21158. for (let i = 0; i < method.args.args.length; i++) {
  21159. const arg = method.args.args[i];
  21160. let value = null;
  21161. if (locals.length > 0) {
  21162. value = locals.shift();
  21163. } else if (i >= default_pos) {
  21164. value = this.expression(method.args.defaults[i - default_pos], context);
  21165. } else {
  21166. throw new python.Error('Missing required positional argument.');
  21167. }
  21168. context.set(arg.arg, value);
  21169. }
  21170. return this.block(method.body, context);
  21171. }
  21172. block(statements, context) {
  21173. statements = Array.prototype.slice.call(statements);
  21174. while (statements.length > 0) {
  21175. const stmt = statements.shift();
  21176. const value = this.statement(stmt, context);
  21177. if (value !== undefined) {
  21178. return value;
  21179. }
  21180. }
  21181. return undefined;
  21182. }
  21183. statement(stmt, context) {
  21184. const ast = this.ast;
  21185. const builtins = this.builtins;
  21186. if (stmt instanceof ast.Pass) {
  21187. // pass
  21188. } else if (stmt instanceof ast.Constant) {
  21189. // pass
  21190. } else if (stmt instanceof ast.Return) {
  21191. return this.expression(stmt.value, context);
  21192. } else if (stmt instanceof ast.FunctionDef) {
  21193. const module = context.get('__name__');
  21194. /* eslint-disable consistent-this */
  21195. const self = this;
  21196. /* eslint-enable consistent-this */
  21197. const parent = context.get('__class__');
  21198. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21199. const func = {
  21200. __class__: type,
  21201. __globals__: context,
  21202. __module__: module,
  21203. __name__: stmt.name,
  21204. __code__: stmt,
  21205. __call__(args) {
  21206. return self.apply(this.__code__, args, this.__globals__);
  21207. }
  21208. };
  21209. context.set(stmt.name, func);
  21210. } else if (stmt instanceof ast.ClassDef) {
  21211. const bases = stmt.bases.map((base) => this.base(base, context));
  21212. if (bases.length > 1) {
  21213. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21214. }
  21215. const base = bases.length === 1 ? bases[0] : null;
  21216. const name = `${context.get('__name__')}.${stmt.name}`;
  21217. const value = this._createType(name, base ? class extends base {} : class {});
  21218. value.__bases__ = bases;
  21219. context.set(stmt.name, value);
  21220. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21221. } else if (stmt instanceof ast.AnnAssign) {
  21222. const target = this.identifier(stmt.target, context);
  21223. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21224. } else if (stmt instanceof ast.Assign) {
  21225. this.expression(stmt, context);
  21226. } else if (stmt instanceof ast.If) {
  21227. const test = this.expression(stmt.test, context);
  21228. if (test === true || test) {
  21229. const value = this.block(stmt.body, context);
  21230. if (value !== undefined) {
  21231. return value;
  21232. }
  21233. } else if (test === false) {
  21234. if (stmt.orelse) {
  21235. const value = this.block(stmt.orelse, context);
  21236. if (value !== undefined) {
  21237. return value;
  21238. }
  21239. }
  21240. } else {
  21241. throw new python.Error('Unsupported condition.');
  21242. }
  21243. } else if (stmt instanceof ast.For) {
  21244. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21245. const range = this.expression(stmt.iter, context);
  21246. const variable = stmt.target;
  21247. for (const current of range) {
  21248. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21249. const value = this.block(stmt.body.statements, context);
  21250. if (value !== undefined) {
  21251. return value;
  21252. }
  21253. }
  21254. } else {
  21255. throw new python.Error("Unsupported 'for' statement.");
  21256. }
  21257. } else if (stmt instanceof ast.While) {
  21258. const test = this.expression(stmt.test, context);
  21259. if (test) {
  21260. const value = this.block(stmt.body.statements, context);
  21261. if (value !== undefined) {
  21262. return value;
  21263. }
  21264. }
  21265. } else if (stmt instanceof ast.With) {
  21266. const items = [];
  21267. for (const item of stmt.items) {
  21268. items.push(this.expression(item.context_expr, context));
  21269. }
  21270. for (const item of items) {
  21271. if (item.__enter__ && item.__enter__.__call__) {
  21272. item.__enter__.__call__([item]);
  21273. }
  21274. }
  21275. const value = this.block(stmt.body, context);
  21276. for (const item of items) {
  21277. if (item.__exit__ && item.__exit__.__call__) {
  21278. item.__exit__.__call__([item]);
  21279. }
  21280. }
  21281. if (value !== undefined) {
  21282. return value;
  21283. }
  21284. } else if (stmt instanceof ast.Expr) {
  21285. this.expression(stmt.value, context);
  21286. } else if (stmt instanceof ast.Import) {
  21287. for (const alias of stmt.names) {
  21288. let module = this.__import__(alias.name, context);
  21289. if (alias.asname) {
  21290. const bits = alias.name.split('.').reverse();
  21291. bits.pop();
  21292. while (bits.length > 0) {
  21293. module = module[bits.pop()];
  21294. }
  21295. context.set(alias.asname, module);
  21296. } else {
  21297. context.set(alias.name.split('.')[0], module);
  21298. }
  21299. }
  21300. } else if (stmt instanceof ast.ImportFrom) {
  21301. const fromlist = stmt.names.map((name) => name.name);
  21302. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21303. for (const entry of stmt.names) {
  21304. const name = entry.name;
  21305. const asname = entry.asname ? entry.asname : null;
  21306. if (!module[name]) {
  21307. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21308. }
  21309. context.set(asname ? asname : name, module[name]);
  21310. }
  21311. } else {
  21312. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21313. }
  21314. return undefined;
  21315. }
  21316. expression(expr, context) {
  21317. const ast = this.ast;
  21318. const builtins = this.builtins;
  21319. const typing = this.typing;
  21320. const self = context.get('self');
  21321. switch (expr.__class__.__name__) {
  21322. case 'Assign': {
  21323. const [target] = expr.targets;
  21324. if (target instanceof ast.Name) {
  21325. const value = this.expression(expr.value, context);
  21326. context.set(target.id, value);
  21327. return undefined;
  21328. } else if (target instanceof ast.Subscript) {
  21329. if (target.value instanceof ast.Name &&
  21330. target.slice instanceof ast.List &&
  21331. target.slice.elts.length === 1) {
  21332. const index = this.expression(target.slice.elts[0], context);
  21333. const id = target.value.id;
  21334. if (id === '__annotations__') {
  21335. context.set(id, context.get(id) || {});
  21336. }
  21337. const obj = context.get(id);
  21338. const value = this.expression(expr.value, context);
  21339. if (obj instanceof Map) {
  21340. obj.set(index, value);
  21341. } else {
  21342. obj[index] = value;
  21343. }
  21344. return undefined;
  21345. }
  21346. } else if (target instanceof ast.Attribute) {
  21347. const obj = this.expression(target.value, context);
  21348. const value = this.expression(expr.value, context);
  21349. obj[target.attr] = value;
  21350. return undefined;
  21351. } else if (target instanceof ast.Tuple) {
  21352. context.target.push(target.elts);
  21353. const value = this.expression(expr.value, context);
  21354. context.target.pop();
  21355. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21356. if (target.elts.length < value.length) {
  21357. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21358. }
  21359. if (target.elts.length > value.length) {
  21360. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21361. }
  21362. for (let i = 0; i < value.length; i++) {
  21363. context.set(target.elts[i].id, value[i]);
  21364. }
  21365. return undefined;
  21366. }
  21367. }
  21368. break;
  21369. }
  21370. case 'List': {
  21371. return expr.elts.map((expr) => this.expression(expr, context));
  21372. }
  21373. case 'Constant': {
  21374. return expr.value;
  21375. }
  21376. case 'Subscript': {
  21377. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21378. const id = expr.value.id;
  21379. if (context.get(id)) {
  21380. const index = this.expression(expr.slice, context);
  21381. const target = context.get(id);
  21382. if (target instanceof Map) {
  21383. return target.get(index);
  21384. }
  21385. return target[index < 0 ? target.length + index : index];
  21386. }
  21387. }
  21388. const value = this.expression(expr.value, context);
  21389. if (value && expr.slice instanceof ast.List &&
  21390. (value.__class__ === typing._TupleType ||
  21391. value.__class__ === typing._SpecialGenericAlias ||
  21392. value.__class__ === typing._SpecialForm)) {
  21393. const type = { ...value };
  21394. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21395. return type;
  21396. }
  21397. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21398. const index = this.expression(expr.slice.elts[0], context);
  21399. if (value instanceof Map) {
  21400. return value.get(index);
  21401. }
  21402. return value[index < 0 ? value.length + index : index];
  21403. }
  21404. break;
  21405. }
  21406. case 'Attribute': {
  21407. const value = this.target(expr.value, context);
  21408. return value[expr.attr];
  21409. }
  21410. case 'Call': {
  21411. const func = expr.func;
  21412. if (func instanceof ast.Attribute) {
  21413. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21414. }
  21415. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21416. }
  21417. case 'Name': {
  21418. const id = expr.id;
  21419. if (id === 'self') {
  21420. return self;
  21421. }
  21422. const type = (value) => {
  21423. return value &&
  21424. (value.__class__ === builtins.type ||
  21425. value.__class__ === typing._TupleType ||
  21426. value.__class__ === typing._SpecialGenericAlias ||
  21427. value.__class__ === typing._SpecialForm);
  21428. };
  21429. const builtin = builtins[id];
  21430. if (type(builtin)) {
  21431. return builtin;
  21432. }
  21433. const value = context.get(id);
  21434. if (value === undefined) {
  21435. const value = typing[id];
  21436. if (type(value)) {
  21437. return value;
  21438. }
  21439. }
  21440. return value;
  21441. }
  21442. case 'Tuple': {
  21443. return expr.elts.map((expr) => this.expression(expr, context));
  21444. }
  21445. case 'Dict': {
  21446. const dict = {};
  21447. for (let i = 0; i < expr.keys.length; i++) {
  21448. const key = this.expression(expr.keys[i], context);
  21449. const value = this.expression(expr.values[i], context);
  21450. dict[key] = value;
  21451. }
  21452. return dict;
  21453. }
  21454. case 'UnaryOp': {
  21455. if (expr.op instanceof ast.USub) {
  21456. return -this.expression(expr.operand, context);
  21457. }
  21458. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21459. }
  21460. case 'binary': {
  21461. switch (expr.op) {
  21462. case '==': {
  21463. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21464. }
  21465. default: {
  21466. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21467. }
  21468. }
  21469. }
  21470. default: {
  21471. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21472. }
  21473. }
  21474. return undefined;
  21475. }
  21476. base(expr, context) {
  21477. return this.expression(expr, context);
  21478. }
  21479. identifier(expr) {
  21480. const ast = this.ast;
  21481. if (expr instanceof ast.Name) {
  21482. return expr.id;
  21483. }
  21484. if (expr instanceof ast.Attribute) {
  21485. return `${this.identifier(expr.value)}.${expr.attr}`;
  21486. }
  21487. return null;
  21488. }
  21489. target(expr, context) {
  21490. const ast = this.ast;
  21491. let current = expr;
  21492. let path = [];
  21493. for (;;) {
  21494. if (current instanceof ast.Attribute) {
  21495. path.push(current.attr);
  21496. current = current.value;
  21497. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21498. path.push(current.id);
  21499. break;
  21500. } else {
  21501. path = null;
  21502. break;
  21503. }
  21504. }
  21505. if (path) {
  21506. let target = null;
  21507. for (let i = path.length - 1; i >= 0; i--) {
  21508. const name = path[i];
  21509. if (target) {
  21510. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21511. } else {
  21512. target = context.get(name);
  21513. }
  21514. if (!target) {
  21515. break;
  21516. }
  21517. }
  21518. if (!target) {
  21519. path.reverse();
  21520. const name = path.join('.');
  21521. const file = `${path.join('/')}.py`;
  21522. if (this._sources.has(file)) {
  21523. target = this.import(name);
  21524. } else {
  21525. target = this.resolve(name);
  21526. }
  21527. }
  21528. return target;
  21529. }
  21530. return this.expression(expr, context);
  21531. }
  21532. add(name, source) {
  21533. this._sources.set(name, source);
  21534. }
  21535. on(event, listener) {
  21536. const value = this._events.get(event) || [];
  21537. value.push(listener);
  21538. this._events.set(event, value);
  21539. }
  21540. emit(event, ...args) {
  21541. if (this._events.has(event)) {
  21542. for (const callback of this._events.get(event)) {
  21543. callback(this, ...args);
  21544. }
  21545. }
  21546. }
  21547. register(name, value) {
  21548. if (!this._registry.has(name)) {
  21549. value = value || new (this._registry.get('builtins').module)(name);
  21550. this._registry.set(name, value);
  21551. let current = name;
  21552. for (;;) {
  21553. const index = current.lastIndexOf('.');
  21554. if (index === -1) {
  21555. break;
  21556. }
  21557. const child = current.substring(index + 1);
  21558. current = current.substring(0, index);
  21559. if (!value.__module__) {
  21560. value.__module__ = current;
  21561. }
  21562. const parent = this.register(current);
  21563. parent[child] = value;
  21564. value = parent;
  21565. }
  21566. }
  21567. return this._registry.get(name);
  21568. }
  21569. registerFunction(name, value) {
  21570. const builtins = this.builtins;
  21571. const index = name.lastIndexOf('.');
  21572. if (!value) {
  21573. value = () => {
  21574. throw new python.Error(`'${name}' is not implemented.`);
  21575. };
  21576. }
  21577. value.__class__ = builtins.function;
  21578. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21579. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21580. const module = this.register(value.__module__);
  21581. if (module[name]) {
  21582. throw new python.Error(`Function '${name}' is already registered.`);
  21583. }
  21584. module[value.__name__] = value;
  21585. return value;
  21586. }
  21587. registerOperator(name, value) {
  21588. this._operators.set(name, value);
  21589. }
  21590. _createType(name, value) {
  21591. const builtins = this.builtins;
  21592. const index = name.lastIndexOf('.');
  21593. value.__class__ = builtins.type;
  21594. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21595. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21596. value.prototype.__class__ = value;
  21597. return value;
  21598. }
  21599. registerType(name, value) {
  21600. value = this._createType(name, value);
  21601. const parts = name.split('.');
  21602. const memberName = parts.pop();
  21603. const moduleName = parts.join('.');
  21604. const module = this.register(moduleName);
  21605. if (module[memberName]) {
  21606. throw new python.Error(`Class '${memberName}' is already registered.`);
  21607. }
  21608. module[memberName] = value;
  21609. return value;
  21610. }
  21611. };
  21612. python.Execution.Context = class {
  21613. constructor(globals, locals) {
  21614. this.globals = globals;
  21615. this.locals = locals;
  21616. }
  21617. set(name, value) {
  21618. if (this.locals) {
  21619. this.locals[name] = value;
  21620. } else {
  21621. this.globals[name] = value;
  21622. }
  21623. }
  21624. get(name) {
  21625. if (this.locals && name in this.locals) {
  21626. return this.locals[name];
  21627. }
  21628. if (name in this.globals) {
  21629. return this.globals[name];
  21630. }
  21631. return undefined;
  21632. }
  21633. get target() {
  21634. this._target = this._target || [];
  21635. return this._target;
  21636. }
  21637. };
  21638. python.BinaryReader = class {
  21639. constructor(buffer) {
  21640. this._buffer = buffer;
  21641. this._length = buffer.length;
  21642. this._position = 0;
  21643. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21644. this._utf8Decoder = new TextDecoder('utf-8');
  21645. this._asciiDecoder = new TextDecoder('ascii');
  21646. }
  21647. get position() {
  21648. return this._position;
  21649. }
  21650. get length() {
  21651. return this._length;
  21652. }
  21653. seek(position) {
  21654. this._position = position >= 0 ? position : this._length + position;
  21655. if (this._position > this._buffer.length) {
  21656. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21657. }
  21658. }
  21659. skip(offset) {
  21660. this._position += offset;
  21661. if (this._position > this._buffer.length) {
  21662. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21663. }
  21664. }
  21665. stream(length) {
  21666. const buffer = this.read(length);
  21667. return new python.BinaryReader(buffer);
  21668. }
  21669. peek(length) {
  21670. const position = this._position;
  21671. length = length === undefined ? this._length - this._position : length;
  21672. this.skip(length);
  21673. const end = this._position;
  21674. this.skip(-length);
  21675. if (position === 0 && length === this._length) {
  21676. return this._buffer;
  21677. }
  21678. return this._buffer.subarray(position, end);
  21679. }
  21680. read(length) {
  21681. const position = this._position;
  21682. length = length === undefined ? this._length - this._position : length;
  21683. this.skip(length);
  21684. if (position === 0 && length === this._length) {
  21685. return this._buffer;
  21686. }
  21687. return this._buffer.subarray(position, this._position);
  21688. }
  21689. byte() {
  21690. const position = this._position;
  21691. this.skip(1);
  21692. return this._view.getUint8(position);
  21693. }
  21694. uint16() {
  21695. const position = this._position;
  21696. this.skip(2);
  21697. return this._view.getUint16(position, true);
  21698. }
  21699. int32() {
  21700. const position = this._position;
  21701. this.skip(4);
  21702. return this._view.getInt32(position, true);
  21703. }
  21704. uint32() {
  21705. const position = this._position;
  21706. this.skip(4);
  21707. return this._view.getUint32(position, true);
  21708. }
  21709. int64() {
  21710. const position = this._position;
  21711. this.skip(8);
  21712. return this._view.getBigInt64(position, true);
  21713. }
  21714. float64() {
  21715. const position = this._position;
  21716. this.skip(8);
  21717. return this._view.getFloat64(position, false);
  21718. }
  21719. string(size, encoding) {
  21720. const data = this.read(size);
  21721. return (encoding === 'utf-8') ?
  21722. this._utf8Decoder.decode(data) :
  21723. this._asciiDecoder.decode(data);
  21724. }
  21725. line() {
  21726. const index = this._buffer.indexOf(0x0A, this._position);
  21727. if (index === -1) {
  21728. throw new python.Error('Could not find end of line.');
  21729. }
  21730. const size = index - this._position;
  21731. const text = this.string(size, 'ascii');
  21732. this.skip(1);
  21733. return text;
  21734. }
  21735. };
  21736. python.StreamReader = class {
  21737. constructor(stream) {
  21738. this._stream = stream;
  21739. this._length = stream.length;
  21740. this._position = 0;
  21741. this._utf8Decoder = new TextDecoder('utf-8');
  21742. this._asciiDecoder = new TextDecoder('ascii');
  21743. }
  21744. get position() {
  21745. return this._position;
  21746. }
  21747. get length() {
  21748. return this._length;
  21749. }
  21750. seek(position) {
  21751. this._stream.seek(position);
  21752. this._position = this._stream.position;
  21753. }
  21754. skip(offset) {
  21755. this._position += offset;
  21756. if (this._position > this._length) {
  21757. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21758. }
  21759. }
  21760. stream(length) {
  21761. this._stream.seek(this._position);
  21762. this.skip(length);
  21763. return this._stream.stream(length);
  21764. }
  21765. peek(length) {
  21766. this._stream.seek(this._position);
  21767. return this._stream.peek(length);
  21768. }
  21769. read(length) {
  21770. this._stream.seek(this._position);
  21771. this.skip(length);
  21772. return this._stream.read(length);
  21773. }
  21774. byte() {
  21775. const position = this._fill(1);
  21776. return this._view.getUint8(position);
  21777. }
  21778. uint16() {
  21779. const position = this._fill(2);
  21780. return this._view.getUint16(position, true);
  21781. }
  21782. int32() {
  21783. const position = this._fill(4);
  21784. return this._view.getInt32(position, true);
  21785. }
  21786. uint32() {
  21787. const position = this._fill(4);
  21788. return this._view.getUint32(position, true);
  21789. }
  21790. int64() {
  21791. const position = this._fill(8);
  21792. return this._view.getBigInt64(position, true);
  21793. }
  21794. float64() {
  21795. const position = this._fill(8);
  21796. return this._view.getFloat64(position, false);
  21797. }
  21798. string(size, encoding) {
  21799. const data = this.read(size);
  21800. return (encoding === 'utf-8') ?
  21801. this._utf8Decoder.decode(data) :
  21802. this._asciiDecoder.decode(data);
  21803. }
  21804. line() {
  21805. let position = this._fill(0);
  21806. let index = this._buffer.indexOf(0x0A, position);
  21807. if (index === -1) {
  21808. const size = Math.min(0x20000000, this._stream.length - this._position);
  21809. this._fill(size);
  21810. this.skip(-size);
  21811. position = this._fill(0);
  21812. index = this._buffer.indexOf(0x0A, position);
  21813. if (index === -1) {
  21814. throw new python.Error('Could not find end of line.');
  21815. }
  21816. }
  21817. const size = index - position;
  21818. const text = this.string(size, 'ascii');
  21819. this.skip(1);
  21820. return text;
  21821. }
  21822. _fill(length) {
  21823. if (this._position + length > this._length) {
  21824. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21825. }
  21826. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21827. this._offset = this._position;
  21828. this._stream.seek(this._offset);
  21829. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21830. this._buffer = this._stream.read(size);
  21831. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21832. }
  21833. const position = this._position;
  21834. this._position += length;
  21835. return position - this._offset;
  21836. }
  21837. };
  21838. python.Error = class extends Error {
  21839. constructor(message) {
  21840. super(message);
  21841. this.name = 'Python Error';
  21842. }
  21843. };
  21844. export const Execution = python.Execution;