python.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834
  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 > 0 &&
  1385. (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') &&
  1386. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  1387. const op = literal.value < 0 ? new ast.Sub() : new ast.Add();
  1388. const left = stack.pop();
  1389. const right = new ast.Constant(Math.abs(literal.value));
  1390. node = new ast.BinOp(left, op, right);
  1391. stack.push(node);
  1392. } else if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1393. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1394. } else {
  1395. let value = literal.value;
  1396. if (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') {
  1397. switch (value) {
  1398. case 'inf': value = Infinity; break;
  1399. case '-inf': value = -Infinity; break;
  1400. default: value = Number(value); break;
  1401. }
  1402. } else if (literal.type === 'str') {
  1403. value = literal.value.substring(1, literal.value.length - 1);
  1404. } else {
  1405. throw new python.Error(`Invalid literal ${this._location()}`);
  1406. }
  1407. const node = new ast.Constant(value, literal.type);
  1408. this._mark(node, position);
  1409. stack.push(node);
  1410. }
  1411. continue;
  1412. }
  1413. if (this._eat('id', 'False')) {
  1414. const node = new ast.Constant(false, 'bool');
  1415. this._mark(node, position);
  1416. stack.push(node);
  1417. continue;
  1418. }
  1419. if (this._eat('id', 'True')) {
  1420. const node = new ast.Constant(true, 'bool');
  1421. this._mark(node, position);
  1422. stack.push(node);
  1423. continue;
  1424. }
  1425. if (this._eat('id', 'None')) {
  1426. const node = new ast.Constant(null);
  1427. this._mark(node, position);
  1428. stack.push(node);
  1429. continue;
  1430. }
  1431. if (this._tokenizer.peek().keyword) {
  1432. break;
  1433. }
  1434. if (this._eat('...')) {
  1435. const node = new ast.Ellipsis();
  1436. this._mark(node, position);
  1437. stack.push(node);
  1438. continue;
  1439. }
  1440. const name = this._parseName();
  1441. if (name) {
  1442. stack.push(name);
  1443. continue;
  1444. }
  1445. if (tuple === true && stack.length === 1 && this._tokenizer.accept(',')) {
  1446. if (stack[0] instanceof ast.Tuple) {
  1447. [node] = stack;
  1448. } else {
  1449. const position = this._position();
  1450. const elts = [stack.pop()];
  1451. node = new ast.Tuple(elts);
  1452. this._mark(node, position);
  1453. stack.push(node);
  1454. }
  1455. // for, bar, = <expr>
  1456. if (this._tokenizer.peek().type === '=') {
  1457. continue;
  1458. }
  1459. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1460. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1461. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1462. if (expression) {
  1463. node.elts.push(expression);
  1464. continue;
  1465. }
  1466. }
  1467. break;
  1468. }
  1469. break;
  1470. }
  1471. if (stack.length === 1) {
  1472. return stack.pop();
  1473. }
  1474. if (stack.length !== 0) {
  1475. throw new python.Error(`Unexpected expression ${this._location()}`);
  1476. }
  1477. return null;
  1478. }
  1479. _decorator() {
  1480. const list = [];
  1481. while (this._tokenizer.accept('@')) {
  1482. const value = this._parseExpression();
  1483. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1484. throw new python.Error(`Invalid decorator ${this._location()}`);
  1485. }
  1486. this._tokenizer.accept('\n');
  1487. list.push(value);
  1488. }
  1489. return list;
  1490. }
  1491. _parseGenerators() {
  1492. const generators = [];
  1493. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1494. const is_async = this._eat('id', 'async') ? 1 : 0;
  1495. this._tokenizer.expect('id', 'for');
  1496. const target = this._parseExpression(-1, ['in'], true);
  1497. this._tokenizer.expect('id', 'in');
  1498. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1499. const ifs = [];
  1500. while (this._tokenizer.accept('id', 'if')) {
  1501. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1502. }
  1503. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1504. generators.push(comprehension);
  1505. }
  1506. return generators;
  1507. }
  1508. _parseList() {
  1509. const elts = [];
  1510. this._tokenizer.expect('[');
  1511. if (!this._tokenizer.match(']')) {
  1512. const position = this._position();
  1513. const expr = this._parseExpression(-1, ['for']);
  1514. if (this._tokenizer.match('id', 'for')) {
  1515. const generators = this._parseGenerators();
  1516. this._tokenizer.expect(']');
  1517. const node = new ast.ListComp(expr, generators);
  1518. this._mark(node, position);
  1519. return node;
  1520. }
  1521. if (expr === null) {
  1522. throw new python.Error(`Expected expression ${this._location()}`);
  1523. }
  1524. elts.push(expr);
  1525. while (this._tokenizer.accept(',')) {
  1526. if (this._tokenizer.match(']')) {
  1527. break;
  1528. }
  1529. const expr = this._parseExpression(-1, ['for']);
  1530. if (!expr) {
  1531. throw new python.Error(`Expected expression ${this._location()}`);
  1532. }
  1533. elts.push(expr);
  1534. }
  1535. }
  1536. this._tokenizer.expect(']');
  1537. return new ast.List(elts);
  1538. }
  1539. _parseSlice() {
  1540. const elts = [];
  1541. let slice = [null, null, null];
  1542. let index = 0;
  1543. let valid = false;
  1544. this._tokenizer.expect('[');
  1545. while (true) {
  1546. if (this._tokenizer.accept(':')) {
  1547. index++;
  1548. valid = true;
  1549. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1550. if (!valid || index > 2) {
  1551. throw new python.Error(`Invalid slice at ${this._location()}`);
  1552. }
  1553. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1554. slice = [null, null, null];
  1555. index = 0;
  1556. if (this._tokenizer.accept(']')) {
  1557. break;
  1558. }
  1559. this._tokenizer.expect(',');
  1560. } else {
  1561. const expression = this._parseExpression();
  1562. if (expression === null) {
  1563. throw new python.Error(`Expected expression ${this._location()}`);
  1564. }
  1565. slice[index] = expression;
  1566. valid = true;
  1567. }
  1568. }
  1569. if (elts.length > 1) {
  1570. return new ast.Tuple(elts);
  1571. }
  1572. return elts[0];
  1573. }
  1574. _parseName(required) {
  1575. const token = this._tokenizer.peek();
  1576. if (token.type === 'id' && !token.keyword) {
  1577. const position = this._position();
  1578. this._tokenizer.read();
  1579. const node = new ast.Name(token.value);
  1580. return this._mark(node, position);
  1581. }
  1582. if (required) {
  1583. throw new python.Error(`Invalid syntax ${this._location()}`);
  1584. }
  1585. return null;
  1586. }
  1587. _parseDottedName() {
  1588. const list = [];
  1589. do {
  1590. const name = this._parseName(true);
  1591. list.push(name.id);
  1592. }
  1593. while (this._tokenizer.accept('.'));
  1594. return list.join('.');
  1595. }
  1596. _parseLiteral() {
  1597. const token = this._tokenizer.peek();
  1598. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1599. this._tokenizer.read();
  1600. return token;
  1601. }
  1602. return null;
  1603. }
  1604. _parseTypeArguments() {
  1605. const list = [];
  1606. this._tokenizer.expect('[');
  1607. while (!this._tokenizer.accept(']')) {
  1608. const type = this._parseType();
  1609. if (type === null) {
  1610. throw new python.Error(`Expected type ${this._location()}`);
  1611. }
  1612. list.push(type);
  1613. if (!this._tokenizer.accept(',')) {
  1614. this._tokenizer.expect(']');
  1615. break;
  1616. }
  1617. }
  1618. return list;
  1619. }
  1620. _parseType() {
  1621. const target = this._parseExpression(-1, ['[', '=']);
  1622. if (target) {
  1623. if (this._tokenizer.peek().value === '[') {
  1624. const list = this._parseList();
  1625. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1626. return new ast.Subscript(target, slice);
  1627. }
  1628. return target;
  1629. }
  1630. return null;
  1631. }
  1632. _parseArguments(terminal) {
  1633. let posonlyargs = [];
  1634. let args = [];
  1635. let vararg = null;
  1636. const kwonlyargs = [];
  1637. const kw_defaults = [];
  1638. let kwarg = null;
  1639. const defaults = [];
  1640. let is_slash = false;
  1641. let is_vararg = false; // '*'
  1642. let is_kwarg = false; // '**'
  1643. const read = (required) => {
  1644. const name = this._parseName(required);
  1645. if (name) {
  1646. const annotation = terminal !== ':' && this._tokenizer.accept(':') ? this._parseType() : null;
  1647. return new ast.arg(name.id, annotation, null);
  1648. }
  1649. return null;
  1650. };
  1651. while (!this._tokenizer.accept(terminal)) {
  1652. this._tokenizer.accept('\n');
  1653. if (this._tokenizer.accept('/')) {
  1654. if (is_slash || is_vararg || is_kwarg) {
  1655. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1656. }
  1657. is_slash = true;
  1658. } else if (this._tokenizer.accept('*')) {
  1659. if (is_vararg) {
  1660. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1661. }
  1662. is_vararg = true;
  1663. const arg = read(false);
  1664. vararg = arg ? arg : vararg;
  1665. } else if (this._tokenizer.accept('**')) {
  1666. if (is_kwarg) {
  1667. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1668. }
  1669. is_kwarg = true;
  1670. kwarg = read(true);
  1671. } else {
  1672. const arg = read(false);
  1673. if (!arg) {
  1674. this._tokenizer.expect(terminal);
  1675. break;
  1676. }
  1677. const default_value = this._tokenizer.accept('=') ? this._parseExpression() : null;
  1678. if (!is_vararg && !is_kwarg) {
  1679. if (is_slash) {
  1680. args.push(arg);
  1681. } else {
  1682. posonlyargs.push(arg);
  1683. }
  1684. if (default_value !== null) {
  1685. defaults.push(default_value);
  1686. }
  1687. } else if (is_vararg && !is_kwarg) {
  1688. kwonlyargs.push(arg);
  1689. kw_defaults.push(default_value);
  1690. } else {
  1691. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1692. }
  1693. }
  1694. this._tokenizer.accept('\n');
  1695. if (!this._tokenizer.accept(',')) {
  1696. this._tokenizer.expect(terminal);
  1697. break;
  1698. }
  1699. }
  1700. if (!is_slash) {
  1701. args = posonlyargs.concat(args);
  1702. posonlyargs = [];
  1703. }
  1704. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1705. }
  1706. _eat(type, value) {
  1707. if (this._tokenizer.match(type, value)) {
  1708. const position = this._position();
  1709. this._tokenizer.expect(type, value);
  1710. return position;
  1711. }
  1712. return null;
  1713. }
  1714. _mark(node, position) {
  1715. node.filename = position.filename;
  1716. node.lineno = position.lineno;
  1717. node.col_offset = position.col_offset;
  1718. node.end_lineno = this._tokenizer.lineno;
  1719. node.end_col_offset = this._tokenizer.col_offset;
  1720. return node;
  1721. }
  1722. _position() {
  1723. return {
  1724. filename: this._tokenizer.filename,
  1725. lineno: this._tokenizer.lineno,
  1726. col_offset: this._tokenizer.col_offset
  1727. };
  1728. }
  1729. _location() {
  1730. return this._tokenizer.location();
  1731. }
  1732. });
  1733. this.registerType('ast._Tokenizer', class {
  1734. constructor(text, file) {
  1735. this._text = text;
  1736. this.filename = file;
  1737. this.linepos = 0;
  1738. this.lineno = 1;
  1739. this._position = 0;
  1740. this._token = { type: '', value: '' };
  1741. this._brackets = 0;
  1742. this._indentation = [];
  1743. this._outdent = 0;
  1744. if (!ast._Tokenizer._whitespace) {
  1745. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1746. 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';
  1747. 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';
  1748. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1749. /* eslint-disable no-misleading-character-class */
  1750. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1751. /* eslint-enable no-misleading-character-class */
  1752. }
  1753. }
  1754. peek() {
  1755. if (!this._cache) {
  1756. this._tokenize();
  1757. this._cache = true;
  1758. }
  1759. return this._token;
  1760. }
  1761. read() {
  1762. if (!this._cache) {
  1763. this._tokenize();
  1764. }
  1765. const next = this._position + this._token.value.length;
  1766. while (this._position < next) {
  1767. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1768. this._position = this._newLine(this._position);
  1769. this.linepos = this._position;
  1770. this.lineno++;
  1771. } else {
  1772. this._position++;
  1773. }
  1774. }
  1775. this._cache = false;
  1776. return this._token;
  1777. }
  1778. match(type, value) {
  1779. const token = this.peek();
  1780. if (token.type === type && (!value || token.value === value)) {
  1781. return true;
  1782. }
  1783. return false;
  1784. }
  1785. accept(type, value) {
  1786. const token = this.peek();
  1787. if (token.type === type && (!value || token.value === value)) {
  1788. this.read();
  1789. return true;
  1790. }
  1791. return false;
  1792. }
  1793. expect(type, value) {
  1794. const token = this.peek();
  1795. if (token.type !== type) {
  1796. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1797. }
  1798. if (value && token.value !== value) {
  1799. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1800. }
  1801. this.read();
  1802. }
  1803. location() {
  1804. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1805. }
  1806. get col_offset() {
  1807. return this._position - this.linepos + 1;
  1808. }
  1809. static _isSpace(c) {
  1810. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1811. return true;
  1812. }
  1813. if (c.charCodeAt(0) >= 0x1680) {
  1814. return ast._Tokenizer._whitespace.test(c);
  1815. }
  1816. return false;
  1817. }
  1818. static _isNewline(c) {
  1819. switch (c) {
  1820. case '\n':
  1821. case '\r':
  1822. case '\u2028': // 8232
  1823. case '\u2029': // 8233
  1824. return true;
  1825. default:
  1826. return false;
  1827. }
  1828. }
  1829. static _isIdentifierStartChar(c) {
  1830. if (c < 'A') {
  1831. return c === '$';
  1832. }
  1833. if (c <= 'Z') {
  1834. return true;
  1835. }
  1836. if (c < 'a') {
  1837. return c === '_';
  1838. }
  1839. if (c <= 'z') {
  1840. return true;
  1841. }
  1842. const code = c.charCodeAt(0);
  1843. if (code >= 0xAA) {
  1844. return ast._Tokenizer._identifierStart.test(c);
  1845. }
  1846. return false;
  1847. }
  1848. static _isIdentifierChar(c) {
  1849. if (c < '0') {
  1850. return c === '$';
  1851. }
  1852. if (c <= '9') {
  1853. return true;
  1854. }
  1855. if (c < 'A') {
  1856. return false;
  1857. }
  1858. if (c <= 'Z') {
  1859. return true;
  1860. }
  1861. if (c < 'a') {
  1862. return c === '_';
  1863. }
  1864. if (c <= 'z') {
  1865. return true;
  1866. }
  1867. const code = c.charCodeAt(0);
  1868. if (code >= 0xAA) {
  1869. return ast._Tokenizer._identifierChar.test(c);
  1870. }
  1871. return false;
  1872. }
  1873. _get(position) {
  1874. return position >= this._text.length ? '\0' : this._text[position];
  1875. }
  1876. _skipLine() {
  1877. while (this._position < this._text.length) {
  1878. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1879. break;
  1880. }
  1881. this._position++;
  1882. }
  1883. }
  1884. _skipWhitespace() {
  1885. while (this._position < this._text.length) {
  1886. const c = this._text[this._position];
  1887. if (c === '#') {
  1888. this._skipLine();
  1889. } else if (ast._Tokenizer._isSpace(c)) {
  1890. this._position++;
  1891. } else if (c === '\\') {
  1892. // Explicit Line Continuation
  1893. this._position++;
  1894. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1895. this._position = this._newLine(this._position);
  1896. this.linepos = this._position;
  1897. this.lineno += 1;
  1898. } else {
  1899. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1900. }
  1901. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1902. // Implicit Line Continuation
  1903. this._position = this._newLine(this._position);
  1904. this.linepos = this._position;
  1905. this.lineno += 1;
  1906. } else {
  1907. break;
  1908. }
  1909. }
  1910. }
  1911. _newLine(position) {
  1912. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1913. return position + 2;
  1914. }
  1915. return position + 1;
  1916. }
  1917. _tokenize() {
  1918. if (this._token.type !== '\n') {
  1919. this._skipWhitespace();
  1920. }
  1921. if (this._token.type === 'dedent') {
  1922. this._indentation.pop();
  1923. this._outdent--;
  1924. if (this._outdent > 0) {
  1925. this._token = { type: 'dedent', value: '' };
  1926. return;
  1927. }
  1928. }
  1929. if (this._token.type === '\n') {
  1930. let indent = '';
  1931. let i = this._position;
  1932. while (i < this._text.length) {
  1933. const c = this._text[i];
  1934. if (ast._Tokenizer._isSpace(c)) {
  1935. indent += c;
  1936. i++;
  1937. } else if (ast._Tokenizer._isNewline(c)) {
  1938. indent = '';
  1939. i = this._newLine(i);
  1940. this._position = i;
  1941. this.linepos = i;
  1942. this.lineno += 1;
  1943. } else if (c === '#') {
  1944. indent = '';
  1945. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1946. i++;
  1947. }
  1948. continue;
  1949. } else {
  1950. break;
  1951. }
  1952. }
  1953. let type = null;
  1954. if (indent.length > 0) {
  1955. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1956. if (indent.length > current.length) {
  1957. type = 'indent';
  1958. this._indentation.push(indent);
  1959. } else if (indent.length > 0 && indent.length < current.length) {
  1960. type = 'dedent';
  1961. this._outdent = 0;
  1962. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1963. this._outdent++;
  1964. }
  1965. } else {
  1966. this._position += indent.length;
  1967. }
  1968. } else if (i >= this._text.length) {
  1969. this._token = { type: 'eof', value: '' };
  1970. return;
  1971. } else if (this._indentation.length > 0) {
  1972. type = 'dedent';
  1973. this._outdent = this._indentation.length;
  1974. }
  1975. if (type === 'indent' || type === 'dedent') {
  1976. this._token = { type, value: indent };
  1977. return;
  1978. }
  1979. }
  1980. if (this._position >= this._text.length) {
  1981. this._token = { type: 'eof', value: '' };
  1982. return;
  1983. }
  1984. const c = this._get(this._position);
  1985. const string = this._string();
  1986. if (string) {
  1987. this._token = string;
  1988. return;
  1989. }
  1990. switch (c) {
  1991. case '(':
  1992. case '[':
  1993. case '{':
  1994. this._brackets++;
  1995. this._token = { type: c, value: c };
  1996. return;
  1997. case ')':
  1998. case ']':
  1999. case '}':
  2000. if (this._brackets === 0) {
  2001. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  2002. }
  2003. this._brackets--;
  2004. this._token = { type: c, value: c };
  2005. return;
  2006. case ',':
  2007. case ';':
  2008. case '?':
  2009. this._token = { type: c, value: c };
  2010. return;
  2011. default: {
  2012. const number = this._number();
  2013. if (number) {
  2014. this._token = number;
  2015. return;
  2016. }
  2017. if (c === '.') {
  2018. let end = this._position + 1;
  2019. while (this._get(end) === '.') {
  2020. end++;
  2021. }
  2022. const text = this._text.substring(this._position, end);
  2023. this._token = { type: text, value: text };
  2024. return;
  2025. }
  2026. const identifier = this._identifier();
  2027. if (identifier) {
  2028. this._token = identifier;
  2029. return;
  2030. }
  2031. const operator = this._operator();
  2032. if (operator) {
  2033. this._token = operator;
  2034. return;
  2035. }
  2036. break;
  2037. }
  2038. }
  2039. if (c === '.') {
  2040. this._token = { type: c, value: c };
  2041. return;
  2042. }
  2043. if (c === '\\') {
  2044. this._token = { type: '\\', value: c };
  2045. return;
  2046. }
  2047. if (ast._Tokenizer._isNewline(c)) {
  2048. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2049. return;
  2050. }
  2051. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2052. }
  2053. _number() {
  2054. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2055. const binary = (c) => c === '0' || c === '1' || c === '_';
  2056. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2057. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2058. let c = this._get(this._position);
  2059. const sign = (c === '-' || c === '+') ? 1 : 0;
  2060. let i = this._position + sign;
  2061. c = this._get(i);
  2062. if (c === '0') {
  2063. let radix = 0;
  2064. const n = this._get(i + 1);
  2065. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2066. i += 2;
  2067. while (hex(this._get(i))) {
  2068. i += 1;
  2069. }
  2070. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2071. i += 1;
  2072. }
  2073. radix = 16;
  2074. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2075. i += 2;
  2076. while (binary(this._get(i))) {
  2077. i++;
  2078. }
  2079. radix = 2;
  2080. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2081. i += 2;
  2082. while (octal(this._get(i))) {
  2083. i++;
  2084. }
  2085. radix = 8;
  2086. } else if (n >= '0' && n <= '7') {
  2087. i++;
  2088. while (octal(this._get(i))) {
  2089. i += 1;
  2090. }
  2091. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2092. i += 1;
  2093. }
  2094. radix = 8;
  2095. }
  2096. if (radix > 0 && this._get(i) !== '.') {
  2097. const radixText = this._text.substring(this._position, i);
  2098. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2099. if (!isNaN(parseInt(radixParseText, radix))) {
  2100. return { type: 'int', value: radixText };
  2101. }
  2102. }
  2103. }
  2104. i = this._position + sign;
  2105. let isDecimal = false;
  2106. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2107. while (decimal(this._get(i))) {
  2108. i++;
  2109. }
  2110. c = this._get(i).toLowerCase();
  2111. isDecimal = c !== '.' && c !== 'e';
  2112. }
  2113. if (this._get(i) === '0') {
  2114. i++;
  2115. c = this._get(i).toLowerCase();
  2116. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2117. }
  2118. if (isDecimal) {
  2119. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2120. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2121. }
  2122. // if (this._get(i) === 'l' || this._get(i) === 'L') {
  2123. // Python 2 long integer
  2124. // }
  2125. const intText = this._text.substring(this._position, i);
  2126. if (!isNaN(parseInt(intText, 10))) {
  2127. return { type: 'int', value: intText };
  2128. }
  2129. }
  2130. i = this._position + sign;
  2131. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2132. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2133. while (decimal(this._get(i))) {
  2134. i++;
  2135. }
  2136. if (this._get(i) === '.') {
  2137. i++;
  2138. }
  2139. while (decimal(this._get(i))) {
  2140. i++;
  2141. }
  2142. if (i > (this._position + sign)) {
  2143. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2144. i++;
  2145. if (this._get(i) === '-' || this._get(i) === '+') {
  2146. i++;
  2147. }
  2148. if (decimal(this._get(i))) {
  2149. while (decimal(this._get(i))) {
  2150. i++;
  2151. }
  2152. } else {
  2153. i = this._position;
  2154. }
  2155. } else {
  2156. while (decimal(this._get(i))) {
  2157. i++;
  2158. }
  2159. }
  2160. }
  2161. if (i > (this._position + sign)) {
  2162. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2163. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2164. }
  2165. const floatText = this._text.substring(this._position, i);
  2166. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2167. if (!isNaN(parseFloat(floatParseText))) {
  2168. return { type: 'float', value: floatText };
  2169. }
  2170. }
  2171. }
  2172. return null;
  2173. }
  2174. _identifier() {
  2175. let i = this._position;
  2176. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2177. i++;
  2178. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2179. i++;
  2180. }
  2181. }
  2182. if (i > this._position) {
  2183. const text = this._text.substring(this._position, i);
  2184. let keyword = false;
  2185. switch (text) {
  2186. case 'and':
  2187. case 'as':
  2188. case 'else':
  2189. case 'For':
  2190. case 'If':
  2191. case 'Import':
  2192. case 'in':
  2193. case 'is':
  2194. case 'not':
  2195. case 'or':
  2196. keyword = true;
  2197. break;
  2198. default:
  2199. break;
  2200. }
  2201. return { type: 'id', value: text, keyword };
  2202. }
  2203. return null;
  2204. }
  2205. _operator() {
  2206. let length = 0;
  2207. const c0 = this._get(this._position);
  2208. const c1 = this._get(this._position + 1);
  2209. const c2 = this._get(this._position + 2);
  2210. switch (c0) {
  2211. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2212. length = c1 === '=' ? 2 : 1;
  2213. break;
  2214. case '-':
  2215. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2216. break;
  2217. case '*':
  2218. switch (c1) {
  2219. case '*': length = c2 === '=' ? 3 : 2; break;
  2220. case '=': length = 2; break;
  2221. default: length = 1; break;
  2222. }
  2223. break;
  2224. case '/':
  2225. switch (c1) {
  2226. case '/': length = c2 === '=' ? 3 : 2; break;
  2227. case '=': length = 2; break;
  2228. default: length = 1; break;
  2229. }
  2230. break;
  2231. case '<':
  2232. switch (c1) {
  2233. case '>': length = 2; break;
  2234. case '<': length = c2 === '=' ? 3 : 2; break;
  2235. case '=': length = 2; break;
  2236. default: length = 1; break;
  2237. }
  2238. break;
  2239. case '>':
  2240. switch (c1) {
  2241. case '>': length = c2 === '=' ? 3 : 2; break;
  2242. case '=': length = 2; break;
  2243. default: length = 1; break;
  2244. }
  2245. break;
  2246. case '@':
  2247. length = c1 === '=' ? 2 : 1;
  2248. break;
  2249. case ':':
  2250. length = c1 === '=' ? 2 : 1;
  2251. break;
  2252. default:
  2253. return null;
  2254. }
  2255. const text = this._text.substring(this._position, this._position + length);
  2256. return { type: text, value: text };
  2257. }
  2258. _string() {
  2259. let i = this._position;
  2260. let prefix = -1;
  2261. if (this._get(i) === "'" || this._get(i) === '"') {
  2262. prefix = '';
  2263. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2264. const c = this._get(i);
  2265. const cc = c.toLowerCase();
  2266. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2267. prefix = c;
  2268. }
  2269. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2270. const c = this._text.substring(this._position, this._position + 2);
  2271. const cc = c.toLowerCase();
  2272. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2273. prefix = c;
  2274. }
  2275. }
  2276. if (prefix.length >= 0) {
  2277. i += prefix.length;
  2278. let quote = '';
  2279. let count = 0;
  2280. const q0 = this._get(i);
  2281. const q1 = this._get(i + 1);
  2282. const q2 = this._get(i + 2);
  2283. switch (q0) {
  2284. case "'":
  2285. quote = q0;
  2286. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2287. break;
  2288. case '"':
  2289. quote = q0;
  2290. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2291. break;
  2292. default:
  2293. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2294. }
  2295. i += count;
  2296. if (count === 1) {
  2297. while (i < this._text.length) {
  2298. if (this._text[i] === quote) {
  2299. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2300. } else if (this._text[i] === '\\' &&
  2301. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2302. i += 2;
  2303. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2304. break;
  2305. } else {
  2306. i++;
  2307. }
  2308. }
  2309. } else if (count === 3) {
  2310. while (i < this._text.length) {
  2311. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2312. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2313. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2314. i += 2;
  2315. continue;
  2316. }
  2317. i++;
  2318. }
  2319. }
  2320. }
  2321. i = this._position;
  2322. if (this._get(i) === '`') {
  2323. i++;
  2324. while (i < this._text.length) {
  2325. if (this._text[i] === '`') {
  2326. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2327. }
  2328. i++;
  2329. }
  2330. }
  2331. return null;
  2332. }
  2333. });
  2334. this.registerType('builtins.dict', dict);
  2335. this.registerType('builtins.ellipsis', class {});
  2336. this.registerType('builtins.cell', class {});
  2337. this.registerType('builtins.list', class extends Array {
  2338. constructor(iterable) {
  2339. super();
  2340. if (Array.isArray(iterable)) {
  2341. this.push(...iterable);
  2342. }
  2343. }
  2344. });
  2345. this.registerType('builtins.number', class {});
  2346. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2347. return execution.__import__(name, globals, locals, fromlist, level);
  2348. });
  2349. this.registerType('builtins.bool', class extends Boolean {
  2350. constructor(value) {
  2351. if (value && value.__bool__) {
  2352. value = value.__bool__();
  2353. } else if (value && value.__len__) {
  2354. value = value.__len__() > 0;
  2355. } else {
  2356. value = value ? true : false;
  2357. }
  2358. super(value);
  2359. }
  2360. });
  2361. this.registerType('builtins.int', class extends Number {
  2362. constructor(value) {
  2363. if (value && value.__int__) {
  2364. value = value.__int__();
  2365. } else if (!Number.isInteger(value)) {
  2366. value = NaN;
  2367. }
  2368. super(value);
  2369. }
  2370. });
  2371. this.registerType('builtins.float', class extends Number {
  2372. constructor(value) {
  2373. if (value && value.__float__) {
  2374. value = value.__float__();
  2375. } else if (Number(value) !== value) {
  2376. value = NaN;
  2377. }
  2378. super(value);
  2379. }
  2380. });
  2381. this.registerType('builtins.long', class extends Number {
  2382. constructor(value) {
  2383. if (value && value.__int__) {
  2384. value = value.__int__();
  2385. } else if (!Number.isInteger(value)) {
  2386. value = NaN;
  2387. }
  2388. super(value);
  2389. }
  2390. });
  2391. this.registerType('builtins.str', class extends String {
  2392. constructor(value) {
  2393. if (value && value.__str__) {
  2394. value = value.__str__();
  2395. } else if (typeof value !== 'string') {
  2396. value = JSON.stringify(value);
  2397. }
  2398. super(value);
  2399. }
  2400. });
  2401. this.registerType('builtins.complex', class {
  2402. constructor(real, imaginary) {
  2403. this.real = real;
  2404. this.imag = imaginary;
  2405. }
  2406. });
  2407. this.registerType('builtins.NoneType', class {});
  2408. this.registerType('builtins.object', class {
  2409. static __new__(cls, ...args) {
  2410. return execution.invoke(cls, args);
  2411. }
  2412. static __setattr__(obj, name, value) {
  2413. builtins.setattr(obj, name, value);
  2414. }
  2415. });
  2416. this.registerType('builtins.tuple', class extends Array {
  2417. constructor(items) {
  2418. super(items ? items.length : 0);
  2419. if (items) {
  2420. for (let i = 0; i < items.length; i++) {
  2421. this[i] = items[i];
  2422. }
  2423. }
  2424. }
  2425. });
  2426. this.registerType('builtins.staticmethod', class {});
  2427. this.registerType('builtins.Warning', class {});
  2428. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2429. this.registerType('builtins.BaseException', class {});
  2430. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2431. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2432. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2433. this.registerFunction('builtins.print', () => {});
  2434. this.registerFunction('builtins.unicode');
  2435. builtins.Ellipsis = new builtins.ellipsis();
  2436. this.registerType('typing._Final', class {});
  2437. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2438. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2439. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2440. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2441. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2442. this.registerType('typing._CallableType', class {});
  2443. this.registerFunction('typing.cast');
  2444. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2445. typing.Callable = Reflect.construct(typing._CallableType, []);
  2446. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2447. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2448. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2449. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2450. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2451. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2452. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2453. this.registerType('enum.Enum', class {
  2454. // __reduce_ex__(proto) {
  2455. // return self.__class__, (self._value_, )
  2456. // }
  2457. });
  2458. this.registerFunction('operator.add');
  2459. this.registerFunction('operator.and_');
  2460. this.registerFunction('operator.and_');
  2461. this.registerFunction('operator.eq');
  2462. this.registerFunction('operator.floordiv');
  2463. this.registerFunction('operator.ge');
  2464. this.registerFunction('operator.getitem');
  2465. this.registerFunction('operator.gt');
  2466. this.registerFunction('operator.le');
  2467. this.registerFunction('operator.lt');
  2468. this.registerFunction('operator.mod');
  2469. this.registerFunction('operator.mul');
  2470. this.registerFunction('operator.ne');
  2471. this.registerFunction('operator.neg');
  2472. this.registerFunction('operator.or_');
  2473. this.registerFunction('operator.pos');
  2474. this.registerFunction('operator.pow');
  2475. this.registerFunction('operator.sub');
  2476. this.registerFunction('operator.truediv');
  2477. this.registerFunction('sys.path.append', () => {});
  2478. this.registerFunction('sys.path.insert', () => {});
  2479. this.registerType('argparse.Namespace', class {
  2480. constructor(args) {
  2481. this.args = args;
  2482. }
  2483. });
  2484. this.registerType('catboost._catboost._CatBoost', class {
  2485. _deserialize_model(/* serialized_model_str */) {
  2486. }
  2487. });
  2488. this.registerType('catboost.core._CatBoostBase', class {
  2489. constructor() {
  2490. this._object = new catboost._catboost._CatBoost();
  2491. }
  2492. __setstate__(state) {
  2493. for (const [key, value] of state) {
  2494. if (key === '__model') {
  2495. this._load_from_string(value);
  2496. continue;
  2497. }
  2498. this[key] = value;
  2499. }
  2500. }
  2501. _load_from_string(dump_model_str) {
  2502. this._deserialize_model(dump_model_str);
  2503. }
  2504. _deserialize_model(dump_model_str) {
  2505. this._object._deserialize_model(dump_model_str);
  2506. }
  2507. });
  2508. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2509. load_model(/* blob */) {
  2510. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2511. // this._load_from_string(blob);
  2512. }
  2513. });
  2514. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2515. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2516. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2517. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2518. catboost.CatBoost = catboost.core.CatBoost;
  2519. this.registerType('collections.deque', class extends Array {
  2520. constructor(iterable) {
  2521. super();
  2522. if (Array.isArray(iterable)) {
  2523. for (const value of iterable) {
  2524. this.push(value);
  2525. }
  2526. }
  2527. }
  2528. });
  2529. this.registerType('collections.OrderedDict', class extends dict {});
  2530. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2531. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2532. this.registerType('cuml.internals.array.CumlArray', class {});
  2533. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2534. this.registerType('cuml.raft.common.handle.Handle', class {
  2535. __setstate__(state) {
  2536. this._handle = state;
  2537. }
  2538. });
  2539. this.registerType('cuml.svm.svr.SVR', class {});
  2540. this.registerType('datetime.date', class {});
  2541. this.registerType('datetime.datetime', class extends datetime.date {});
  2542. this.registerType('datetime.timedelta', class {});
  2543. this.registerType('datetime.tzinfo', class {});
  2544. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2545. this.registerType('dnnlib.tflib.network.Network', class {});
  2546. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2547. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2548. constructor(dict) {
  2549. Object.assign(this, dict);
  2550. }
  2551. });
  2552. this.registerType('haiku._src.data_structures.frozendict', class {
  2553. constructor(obj) {
  2554. Object.assign(this, obj);
  2555. }
  2556. });
  2557. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2558. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2559. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2560. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2561. this.registerType('io.BytesIO', class {
  2562. constructor(buf, mode) {
  2563. this.mode = mode || 'r';
  2564. this._buf = this.mode === 'w' ? null : buf;
  2565. this._point = 0;
  2566. }
  2567. seek(offset) {
  2568. if (this._buf.seek) {
  2569. this._buf.seek(offset);
  2570. }
  2571. this._point = offset;
  2572. }
  2573. read(size, stream) {
  2574. if (this._buf.stream && stream) {
  2575. return this._buf.stream(size);
  2576. }
  2577. if (this._buf.peek) {
  2578. return this._buf.read(size);
  2579. }
  2580. if (this._buf instanceof Uint8Array) {
  2581. const start = this._point;
  2582. this._point = size === undefined ? this._buf.length : start + size;
  2583. return this._buf.subarray(start, this._point);
  2584. }
  2585. throw new python.Error('Unsupported buffer type.');
  2586. }
  2587. write(data) {
  2588. const src = this._buf || new Uint8Array();
  2589. const end = this._point + data.length;
  2590. const size = Math.max(src.length, end);
  2591. this._buf = new Uint8Array(size);
  2592. this._buf.set(src, 0);
  2593. this._buf.set(data, this._point);
  2594. this._point = end;
  2595. }
  2596. getbuffer() {
  2597. return new builtins.memoryview(this._buf);
  2598. }
  2599. });
  2600. this.registerType('io.StringIO', class {
  2601. constructor() {
  2602. this._buf = [];
  2603. }
  2604. write(text) {
  2605. this._buf.push(text);
  2606. }
  2607. toString() {
  2608. return this._buf.join('');
  2609. }
  2610. });
  2611. this.registerType('numpy.dtype', class {
  2612. constructor(obj, align, copy) {
  2613. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2614. this.kind = 'V';
  2615. this.byteorder = '|';
  2616. this.itemsize = obj.itemsize;
  2617. this.names = obj.names;
  2618. this.fields = new Map();
  2619. for (let i = 0; i < obj.names.length; i++) {
  2620. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2621. }
  2622. return;
  2623. }
  2624. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2625. this.byteorder = obj.substring(0, 1);
  2626. obj = obj.substring(1);
  2627. } else {
  2628. this.byteorder = '=';
  2629. }
  2630. switch (obj) {
  2631. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2632. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2633. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2634. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2635. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2636. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2637. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2638. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2639. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2640. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2641. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2642. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2643. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2644. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2645. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2646. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2647. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2648. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2649. default:
  2650. if (obj.startsWith('V')) {
  2651. this.itemsize = parseInt(obj.substring(1), 10);
  2652. this.kind = 'V';
  2653. } else if (obj.startsWith('O')) {
  2654. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2655. this.kind = 'O';
  2656. } else if (obj.startsWith('S')) {
  2657. this.itemsize = parseInt(obj.substring(1), 10);
  2658. this.kind = 'S';
  2659. } else if (obj.startsWith('U')) { // Unicode string
  2660. this.kind = 'U';
  2661. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2662. } else if (obj.startsWith('T')) {
  2663. this.kind = 'T';
  2664. this.itemsize = parseInt(obj.substring(1), 10);
  2665. } else {
  2666. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2667. }
  2668. break;
  2669. }
  2670. if (align) {
  2671. this.align = align;
  2672. }
  2673. if (copy) {
  2674. this.copy = copy;
  2675. }
  2676. }
  2677. get str() {
  2678. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2679. }
  2680. get name() {
  2681. switch (this.kind) {
  2682. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2683. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2684. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2685. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2686. case 'M': return 'datetime64';
  2687. case 'm': return 'timedelta64';
  2688. case 'b': return 'bool';
  2689. default: return this.__name__;
  2690. }
  2691. }
  2692. __setstate__(state) {
  2693. switch (state.length) {
  2694. case 8:
  2695. [
  2696. this.version, this.byteorder, this.subarray, this.names,
  2697. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2698. ] = state;
  2699. break;
  2700. case 9:
  2701. [
  2702. this.version, this.byteorder, this.subarray, this.names,
  2703. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2704. this.metadata
  2705. ] = state;
  2706. break;
  2707. default:
  2708. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2709. }
  2710. }
  2711. get __name__() {
  2712. switch (this.kind) {
  2713. case 'b':
  2714. switch (this.itemsize) {
  2715. case 1: return 'boolean';
  2716. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2717. }
  2718. case 'i':
  2719. switch (this.itemsize) {
  2720. case 1: return 'int8';
  2721. case 2: return 'int16';
  2722. case 4: return 'int32';
  2723. case 8: return 'int64';
  2724. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2725. }
  2726. case 'u':
  2727. switch (this.itemsize) {
  2728. case 1: return 'uint8';
  2729. case 2: return 'uint16';
  2730. case 4: return 'uint32';
  2731. case 8: return 'uint64';
  2732. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2733. }
  2734. case 'f':
  2735. switch (this.itemsize) {
  2736. case 1: return 'float8e5m2';
  2737. case 2: return 'float16';
  2738. case 4: return 'float32';
  2739. case 8: return 'float64';
  2740. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2741. }
  2742. case 'c':
  2743. switch (this.itemsize) {
  2744. case 8: return 'complex<float32>';
  2745. case 16: return 'complex<float64>';
  2746. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2747. }
  2748. case 'S':
  2749. case 'T':
  2750. return 'string';
  2751. case 'U':
  2752. return 'string';
  2753. case 'M':
  2754. return 'datetime';
  2755. case 'm':
  2756. return 'timedelta';
  2757. case 'O':
  2758. return 'object';
  2759. case 'V':
  2760. return 'void';
  2761. default:
  2762. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2763. }
  2764. }
  2765. });
  2766. this.registerType('numpy.generic', class {});
  2767. this.registerType('numpy.inexact', class {});
  2768. this.registerType('numpy.flexible', class extends numpy.generic {});
  2769. this.registerType('numpy.void', class extends numpy.flexible {});
  2770. this.registerType('numpy.bool_', class extends numpy.generic {});
  2771. this.registerType('numpy.number', class extends numpy.generic {});
  2772. this.registerType('numpy.integer', class extends numpy.number {});
  2773. this.registerType('numpy.floating', class extends numpy.inexact {});
  2774. this.registerType('numpy.float16', class extends numpy.floating {});
  2775. this.registerType('numpy.float32', class extends numpy.floating {});
  2776. this.registerType('numpy.float64', class extends numpy.floating {});
  2777. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2778. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2779. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2780. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2781. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2782. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2783. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2784. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2785. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2786. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2787. this.registerType('numpy.datetime64', class extends numpy.generic {
  2788. constructor(...args) {
  2789. super();
  2790. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2791. [this.buffer] = args;
  2792. }
  2793. }
  2794. toString() {
  2795. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2796. const value = view.getBigInt64(0, true);
  2797. if (value === -9223372036854775808n) {
  2798. return 'NaT';
  2799. }
  2800. const date = new Date(Number(value / 1000000n));
  2801. return date.toISOString().slice(0, -1);
  2802. }
  2803. });
  2804. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2805. constructor() {
  2806. super('|T16');
  2807. }
  2808. });
  2809. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2810. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2811. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2812. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2813. this.registerType('gensim.models.fasttext.FastText', class {});
  2814. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2815. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2816. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2817. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2818. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2819. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2820. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2821. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2822. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2823. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2824. this.registerFunction('gensim.models.phrases.original_scorer');
  2825. this.registerType('gensim.models.phrases.Phraser', class {});
  2826. this.registerType('gensim.models.phrases.Phrases', class {});
  2827. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2828. this.registerType('gensim.models.word2vec.Vocab', class {});
  2829. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2830. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2831. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2832. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2833. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2834. throw new builtins.AttributeError('This method should be called on a class object.');
  2835. });
  2836. this.registerFunction('gensim.utils.identity');
  2837. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2838. constructor(obj) {
  2839. Object.assign(this, obj);
  2840. }
  2841. });
  2842. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2843. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2844. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2845. __read__(unpickler) {
  2846. if (this.dtype.__name__ === 'object') {
  2847. return unpickler.load();
  2848. }
  2849. if (this.numpy_array_alignment_bytes) {
  2850. const [size] = unpickler.read(1);
  2851. unpickler.read(size);
  2852. }
  2853. if (this.order === 'F') {
  2854. throw new python.Error('Fortran order not implemented.');
  2855. }
  2856. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2857. this.data = unpickler.read(size);
  2858. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2859. }
  2860. });
  2861. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2862. __setstate__(state) {
  2863. this.subclass = state.get('subclass');
  2864. this.filename = state.get('state');
  2865. this.allow_mmap = state.get('allow_mmap');
  2866. }
  2867. __read__(/* unpickler */) {
  2868. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2869. }
  2870. });
  2871. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2872. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2873. this.registerType('keras.engine.sequential.Sequential', class {});
  2874. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2875. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2876. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2877. this.registerType('lasagne.layers.input.InputLayer', class {});
  2878. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2879. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2880. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2881. this.registerType('lightgbm.basic.Booster', class {
  2882. constructor() {
  2883. this.average_output = false;
  2884. this.models = [];
  2885. this.loaded_parameter = '';
  2886. }
  2887. __setstate__(state) {
  2888. const model_str = state.get('_handle', state.get('handle', null));
  2889. if (model_str) {
  2890. this.LoadModelFromString(model_str);
  2891. return;
  2892. }
  2893. for (const [key, value] of state) {
  2894. this[key] = value;
  2895. }
  2896. }
  2897. LoadModelFromString(model_str) {
  2898. const lines = model_str.split('\n');
  2899. const signature = lines.shift() || '?';
  2900. if (signature.trim() !== 'tree') {
  2901. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2902. }
  2903. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2904. const key_vals = new Map();
  2905. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2906. const cur_line = lines.shift().trim();
  2907. if (cur_line.length > 0) {
  2908. const strs = cur_line.split('=');
  2909. if (strs.length === 1) {
  2910. key_vals.set(strs[0], '');
  2911. } else if (strs.length === 2) {
  2912. key_vals.set(strs[0], strs[1]);
  2913. } else if (strs.length > 2) {
  2914. if (strs[0] === "feature_names") {
  2915. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2916. } else if (strs[0] === 'monotone_constraints') {
  2917. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2918. } else {
  2919. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2920. }
  2921. }
  2922. }
  2923. }
  2924. const atoi = (key, value) => {
  2925. if (key_vals.has(key)) {
  2926. return parseInt(key_vals.get(key), 10);
  2927. }
  2928. if (value !== undefined) {
  2929. return value;
  2930. }
  2931. throw new python.Error(`Model file does not specify ${key}.`);
  2932. };
  2933. const list = (key, size) => {
  2934. if (key_vals.has(key)) {
  2935. const value = key_vals.get(key).split(' ');
  2936. if (value.length !== size) {
  2937. throw new python.Error(`Wrong size of ${key}.`);
  2938. }
  2939. return value;
  2940. }
  2941. throw new python.Error(`Model file does not contain ${key}.`);
  2942. };
  2943. this.version = key_vals.get('version') || '';
  2944. this.num_class = atoi('num_class');
  2945. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2946. this.label_index = atoi('label_index');
  2947. this.max_feature_idx = atoi('max_feature_idx');
  2948. if (key_vals.has('average_output')) {
  2949. this.average_output = true;
  2950. }
  2951. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2952. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2953. if (key_vals.has('monotone_constraints')) {
  2954. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2955. }
  2956. if (key_vals.has('objective')) {
  2957. this.objective = key_vals.get('objective');
  2958. }
  2959. let tree = null;
  2960. while (lines.length > 0) {
  2961. const text = lines.shift();
  2962. const line = text.trim();
  2963. if (line.length === 0) {
  2964. continue;
  2965. }
  2966. if (line.startsWith('Tree=')) {
  2967. tree = { index: parseInt(line.split('=').pop(), 10) };
  2968. this.models.push(tree);
  2969. continue;
  2970. }
  2971. if (line === 'end of trees') {
  2972. break;
  2973. }
  2974. const param = line.split('=');
  2975. if (param.length !== 2) {
  2976. throw new python.Error(`Invalid property '${line}'.`);
  2977. }
  2978. const name = param[0].trim();
  2979. const value = param[1].trim();
  2980. tree[name] = value;
  2981. }
  2982. const ss = [];
  2983. let is_inparameter = false;
  2984. while (lines.length > 0) {
  2985. const text = lines.shift();
  2986. const line = text.trim();
  2987. if (line === 'parameters:') {
  2988. is_inparameter = true;
  2989. continue;
  2990. } else if (line === 'end of parameters') {
  2991. break;
  2992. } else if (is_inparameter) {
  2993. ss.push(line);
  2994. }
  2995. }
  2996. if (ss.length > 0) {
  2997. this.loaded_parameter = ss.join('\n');
  2998. }
  2999. }
  3000. });
  3001. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  3002. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  3003. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  3004. this.registerFunction('megengine.functional.nn.relu', () => {});
  3005. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3006. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3007. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3008. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3009. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3010. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3011. this.registerFunction('megengine.functional.tensor.full', () => {});
  3012. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3013. this.registerFunction('megengine.functional.tensor.split', () => {});
  3014. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3015. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3016. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3017. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3018. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3019. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3020. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3021. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3022. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3023. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3024. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3025. this.registerType('megengine.distributed.group.Group', class {});
  3026. this.registerType('megengine.module.activation.ReLU', class {});
  3027. this.registerType('megengine.module.activation.Softmax', class {});
  3028. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3029. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3030. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3031. this.registerType('megengine.module.conv.Conv2d', class {});
  3032. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3033. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3034. this.registerType('megengine.module.dropout.Dropout', class {});
  3035. this.registerType('megengine.module.identity.Identity', class {});
  3036. this.registerType('megengine.module.linear.Linear', class {});
  3037. this.registerType('megengine.module.module.Module', class {});
  3038. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3039. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3040. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3041. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3042. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3043. this.registerType('megengine.module.qat.concat.Concat', class {});
  3044. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3045. this.registerType('megengine.module.sequential.Sequential', class {});
  3046. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3047. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3048. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3049. this.registerType('megengine.quantization.utils.QParams', class {});
  3050. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3051. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3052. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3053. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3054. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3055. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3056. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3057. this.registerType('megengine.traced_module.expr.Apply', class {});
  3058. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3059. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3060. this.registerType('megengine.traced_module.expr.Constant', class {});
  3061. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3062. this.registerType('megengine.traced_module.expr.Input', class {});
  3063. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3064. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3065. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3066. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3067. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3068. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3069. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3070. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3071. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3072. this.registerType('megengine.tensor.Parameter', class {
  3073. constructor(data, dtype, device) {
  3074. this.data = data;
  3075. this.dtype = dtype;
  3076. this.device = device;
  3077. }
  3078. });
  3079. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3080. toString() {
  3081. let content = '';
  3082. for (const child of this.children_defs) {
  3083. content += `${child},`;
  3084. }
  3085. if (typeof this.type === "string") {
  3086. return `${this.type.split(".").slice(-1)}(${content})`;
  3087. }
  3088. return `${this.type.__name__}(${content})`;
  3089. }
  3090. });
  3091. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3092. toString() {
  3093. let content = '';
  3094. if (this.const_val === null) {
  3095. content += '[';
  3096. } else {
  3097. content += this.const_val;
  3098. }
  3099. for (const t of Object.values(this.type)) {
  3100. content += t.__name__;
  3101. }
  3102. content += ']';
  3103. return content;
  3104. }
  3105. });
  3106. this.registerType('megengine.tensor.Tensor', class {
  3107. constructor(data, dtype, device) {
  3108. this.data = data;
  3109. this.dtype = dtype;
  3110. this.device = device;
  3111. }
  3112. });
  3113. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3114. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3115. this.name = name;
  3116. this.cname = cname;
  3117. this.np_dtype = np_dtype;
  3118. this.qmin = qmin;
  3119. this.qmax = qmax;
  3120. this.is_signed = is_signed;
  3121. }
  3122. });
  3123. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3124. this.registerType('nolearn.lasagne.base.Layers', class {});
  3125. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3126. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3127. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3128. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3129. this.registerType('numpy.ndarray', class {
  3130. constructor(shape, dtype, buffer, offset, strides, order) {
  3131. this.shape = shape;
  3132. this.dtype = dtype;
  3133. this.data = buffer === undefined ? null : buffer;
  3134. this.offset = offset === undefined ? 0 : offset;
  3135. this._strides = strides === undefined ? null : strides;
  3136. this.order = order === undefined ? null : order;
  3137. this.flags = {};
  3138. this._read();
  3139. }
  3140. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3141. return new cls(shape, dtype, buffer, offset, strides, order);
  3142. }
  3143. __setstate__(state) {
  3144. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3145. this._read();
  3146. }
  3147. flatten() {
  3148. const size = this.shape.reduce((a, b) => a * b, 1);
  3149. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3150. value.flags = this.flags;
  3151. return value;
  3152. }
  3153. reshape(shape, order) {
  3154. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3155. }
  3156. tobytes() {
  3157. return this.data;
  3158. }
  3159. tolist() {
  3160. if (this.shape.length < 0 || this.shape.length > 1) {
  3161. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3162. }
  3163. const size = this.shape.reduce((a, b) => a * b, 1);
  3164. const list = new Array(size);
  3165. switch (this.dtype.kind) {
  3166. case 'U': {
  3167. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3168. const itemsize = this.dtype.itemsize >> 2;
  3169. let offset = 0;
  3170. for (let i = 0; i < size; i++) {
  3171. const buffer = data.subarray(offset, offset + itemsize);
  3172. const index = buffer.indexOf(0);
  3173. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3174. offset += itemsize;
  3175. }
  3176. return list;
  3177. }
  3178. case 'S': {
  3179. const data = this.data;
  3180. const itemsize = this.dtype.itemsize;
  3181. const decoder = new TextDecoder('utf-8');
  3182. let offset = 0;
  3183. for (let i = 0; i < size; i++) {
  3184. const buffer = data.subarray(offset, offset + itemsize);
  3185. const index = buffer.indexOf(0);
  3186. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3187. offset += itemsize;
  3188. }
  3189. return list;
  3190. }
  3191. case 'V': {
  3192. const itemsize = this.dtype.itemsize;
  3193. let offset = 0;
  3194. for (let i = 0; i < size; i++) {
  3195. list[i] = this.data.slice(offset, offset + itemsize);
  3196. offset += itemsize;
  3197. }
  3198. return list;
  3199. }
  3200. case 'M': {
  3201. const itemsize = this.dtype.itemsize;
  3202. let offset = 0;
  3203. for (let i = 0; i < size; i++) {
  3204. const buffer = this.data.slice(offset, offset + itemsize);
  3205. list[i] = new numpy.datetime64(buffer);
  3206. offset += itemsize;
  3207. }
  3208. return list;
  3209. }
  3210. case 'T': {
  3211. return this.data;
  3212. }
  3213. case 'O': {
  3214. return this.data;
  3215. }
  3216. default: {
  3217. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3218. }
  3219. }
  3220. }
  3221. get itemsize() {
  3222. return this.dtype.itemsize;
  3223. }
  3224. get size() {
  3225. return (this.shape || []).reduce((a, b) => a * b, 1);
  3226. }
  3227. get strides() {
  3228. if (!this._strides) {
  3229. const shape = this.shape;
  3230. const strides = new Array(shape.length);
  3231. let stride = this.itemsize;
  3232. for (let i = shape.length - 1; i >= 0; i--) {
  3233. strides[i] = stride;
  3234. stride *= shape[i];
  3235. }
  3236. return strides;
  3237. }
  3238. return this._strides;
  3239. }
  3240. _read() {
  3241. if (this.data) {
  3242. const length = this.dtype.itemsize * this.size;
  3243. if (typeof this.data === 'string') {
  3244. this.data = this._unescape(this.data, length);
  3245. if (this.data.length !== length) {
  3246. throw new python.Error('Invalid string array data size.');
  3247. }
  3248. } else if (this.data.length !== length) {
  3249. // throw new python.Error('Invalid array data size.');
  3250. }
  3251. }
  3252. }
  3253. _unescape(token, size) {
  3254. const length = token.length;
  3255. const a = new Uint8Array(length);
  3256. if (size && size === length) {
  3257. for (let p = 0; p < size; p++) {
  3258. a[p] = token.charCodeAt(p);
  3259. }
  3260. return a;
  3261. }
  3262. let i = 0;
  3263. let o = 0;
  3264. while (i < length) {
  3265. let c = token.charCodeAt(i++);
  3266. if (c !== 0x5C || i >= length) {
  3267. a[o++] = c;
  3268. } else {
  3269. c = token.charCodeAt(i++);
  3270. switch (c) {
  3271. case 0x27: a[o++] = 0x27; break; // '
  3272. case 0x5C: a[o++] = 0x5C; break; // \\
  3273. case 0x22: a[o++] = 0x22; break; // "
  3274. case 0x72: a[o++] = 0x0D; break; // \r
  3275. case 0x6E: a[o++] = 0x0A; break; // \n
  3276. case 0x74: a[o++] = 0x09; break; // \t
  3277. case 0x62: a[o++] = 0x08; break; // \b
  3278. case 0x58: // x
  3279. case 0x78: { // X
  3280. const xsi = i - 1;
  3281. const xso = o;
  3282. for (let xi = 0; xi < 2; xi++) {
  3283. if (i >= length) {
  3284. i = xsi;
  3285. o = xso;
  3286. a[o] = 0x5c;
  3287. break;
  3288. }
  3289. let c = token.charCodeAt(i++);
  3290. if (c >= 65 && c <= 70) {
  3291. c -= 55;
  3292. } else if (c >= 97 && c <= 102) {
  3293. c -= 87;
  3294. } else if (c >= 48 && c <= 57) {
  3295. c -= 48;
  3296. } else {
  3297. c = -1;
  3298. }
  3299. if (c === -1) {
  3300. i = xsi;
  3301. o = xso;
  3302. a[o] = 0x5c;
  3303. break;
  3304. }
  3305. a[o] = a[o] << 4 | c;
  3306. }
  3307. o++;
  3308. break;
  3309. }
  3310. default:
  3311. if (c < 48 || c > 57) { // 0-9
  3312. a[o++] = 0x5c;
  3313. a[o++] = c;
  3314. } else {
  3315. i--;
  3316. const osi = i;
  3317. const oso = o;
  3318. for (let oi = 0; oi < 3; oi++) {
  3319. if (i >= length) {
  3320. i = osi;
  3321. o = oso;
  3322. a[o] = 0x5c;
  3323. break;
  3324. }
  3325. const od = token.charCodeAt(i++);
  3326. if (od < 48 || od > 57) {
  3327. i = osi;
  3328. o = oso;
  3329. a[o] = 0x5c;
  3330. break;
  3331. }
  3332. a[o] = a[o] << 3 | od - 48;
  3333. }
  3334. o++;
  3335. }
  3336. break;
  3337. }
  3338. }
  3339. }
  3340. return a.slice(0, o);
  3341. }
  3342. });
  3343. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3344. static __new__(/* subtype, data, dtype, copy */) {
  3345. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3346. }
  3347. });
  3348. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3349. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3350. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3351. super(data.shape, data.dtype, data.data);
  3352. }
  3353. });
  3354. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3355. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3356. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3357. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3358. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3359. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', 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.timedeltas.TimedeltaArray', 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.period.PeriodArray', class {
  3372. __setstate__(state) {
  3373. [this._dtype, this._ndarray] = state;
  3374. Object.assign(this, Object.fromEntries(state[2]));
  3375. }
  3376. });
  3377. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3378. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3379. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3380. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3381. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3382. this.registerType('pandas.core.generic.Flags', class {});
  3383. this.registerType('pandas.core.generic.NDFrame', class {
  3384. constructor(data) {
  3385. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3386. this._metadata = [];
  3387. builtins.object.__setattr__(self, "_mgr", data);
  3388. builtins.object.__setattr__(self, "_attrs", {});
  3389. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3390. }
  3391. __setstate__(state) {
  3392. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3393. this._mgr = state;
  3394. } else if (state instanceof builtins.dict) {
  3395. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3396. state.__setitem__('_mgr', state.pop('_data'));
  3397. }
  3398. const typ = state.get('_typ');
  3399. if (typ) {
  3400. let attrs = state.get('_attrs', new builtins.dict());
  3401. if (!attrs) {
  3402. attrs = new builtins.dict();
  3403. }
  3404. builtins.object.__setattr__(this, '_attrs', attrs);
  3405. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3406. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3407. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3408. for (const k of meta) {
  3409. if (state.__contains__(k) && k !== '_flags') {
  3410. const v = state.__getitem__(k);
  3411. builtins.object.__setattr__(this, k, v);
  3412. }
  3413. }
  3414. for (const [k, v] of state) {
  3415. if (!meta.has(k)) {
  3416. builtins.object.__setattr__(this, k, v);
  3417. }
  3418. }
  3419. } else {
  3420. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3421. }
  3422. } else if (state.size === 2) {
  3423. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3424. }
  3425. }
  3426. });
  3427. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3428. });
  3429. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3430. return new cls(d);
  3431. });
  3432. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3433. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3434. this.registerType('pandas.core.indexes.base.Index', class {});
  3435. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3436. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3437. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3438. this.registerType('pandas.core.index.Int64Index', class {});
  3439. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3440. });
  3441. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3442. });
  3443. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3444. return pandas.core.internals.blocks.NumpyBlock;
  3445. });
  3446. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3447. return values;
  3448. });
  3449. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3450. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3451. return new klass(values, ndim, placement, refs);
  3452. });
  3453. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3454. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3455. this.registerType('pandas.core.series.Series', class {});
  3456. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3457. const obj = new cls();
  3458. if (state && obj.__setstate__) {
  3459. obj.__setstate__(state);
  3460. }
  3461. return obj;
  3462. });
  3463. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3464. const obj = new cls();
  3465. if (state && obj.__setstate__) {
  3466. obj.__setstate__(state);
  3467. }
  3468. return obj;
  3469. });
  3470. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3471. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3472. // if not isinstance(placement, BlockPlacement):
  3473. // placement = BlockPlacement(placement)
  3474. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3475. });
  3476. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3477. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3478. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3479. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3480. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3481. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3482. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3483. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3484. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3485. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3486. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3487. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3488. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3489. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3490. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3491. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3492. this.registerType('pathlib.Path', class {});
  3493. this.registerType('pathlib._local.PosixPath', class {});
  3494. this.registerType('pathlib._local.WindowsPath', class {});
  3495. const pathlib = this.register('pathlib');
  3496. pathlib.PosixPath = pathlib._local.PosixPath;
  3497. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3498. this.registerType('shap._serializable.Serializable', class {});
  3499. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3500. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3501. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3502. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3503. this.registerType('sklearn._loss.link.BaseLink', class {});
  3504. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3505. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3506. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3507. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3508. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3509. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3510. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3511. this.registerType('sklearn._loss.link.Interval', class {});
  3512. this.registerType('sklearn._loss.link.LogitLink', class {});
  3513. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3514. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3515. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3516. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3517. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3518. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3519. this.registerType('sklearn.base.BaseEstimator', class {});
  3520. this.registerType('sklearn.base.TransformerMixin', class {});
  3521. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3522. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3523. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3524. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3525. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3526. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3527. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3528. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3529. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3530. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3531. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3532. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3533. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3534. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3535. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3536. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3537. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3538. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3539. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3540. this.registerType('sklearn.decomposition.PCA', class {});
  3541. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3542. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3543. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3544. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3545. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3546. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3547. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3548. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3549. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3550. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3551. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3552. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3553. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3554. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3555. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3556. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3557. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3558. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3559. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3560. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3561. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3562. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3563. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3564. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3565. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3566. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3567. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3568. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3569. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3570. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3571. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3572. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3573. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3574. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3575. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3576. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3577. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3578. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3579. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3580. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3581. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3582. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3583. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3584. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3585. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3586. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3587. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3588. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3589. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3590. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3591. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3592. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3593. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3594. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3595. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3596. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3597. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3598. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3599. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3600. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3601. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3602. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3603. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3604. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3605. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3606. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3607. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3608. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3609. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3610. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3611. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3612. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3613. this.registerType('sklearn.impute.SimpleImputer', class {});
  3614. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3615. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3616. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3617. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3618. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3619. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3620. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3621. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3622. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3623. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3624. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3625. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3626. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3627. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3628. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3629. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3630. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3631. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3632. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3633. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3634. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3635. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3636. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3637. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3638. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3639. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3640. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3641. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3642. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3643. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3644. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3645. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3646. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3647. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3648. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3649. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3650. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3651. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3652. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3653. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3654. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3655. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3656. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3657. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3658. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3659. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3660. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3661. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3662. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3663. this.registerType('sklearn.model_selection._split.KFold', class {});
  3664. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3665. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3666. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3667. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3668. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3669. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3670. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3671. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3672. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3673. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3674. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3675. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3676. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3677. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3678. return obj.__new__(obj);
  3679. });
  3680. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3681. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3682. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3683. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3684. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3685. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3686. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3687. return obj.__new__(obj);
  3688. });
  3689. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3690. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3691. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3692. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3693. return obj.__new__(obj);
  3694. });
  3695. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3696. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3697. return obj.__new__(obj);
  3698. });
  3699. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3700. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3701. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3702. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3703. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3704. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3705. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3706. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3707. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3708. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3709. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3710. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3711. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3712. this.registerType('sklearn.pipeline.Pipeline', class {});
  3713. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3714. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3715. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3716. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3717. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3718. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3719. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3720. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3721. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3722. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3723. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3724. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3725. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3726. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3727. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3728. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3729. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3730. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3731. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3732. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3733. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3734. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3735. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3736. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3737. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3738. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3739. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3740. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3741. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3742. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3743. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3744. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3745. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3746. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3747. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3748. this.registerType('sklearn.svm._classes.SVC', class {});
  3749. this.registerType('sklearn.svm._classes.SVR', class {});
  3750. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3751. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3752. this.registerType('sklearn.svm.classes.SVC', class {});
  3753. this.registerType('sklearn.svm.classes.SVR', class {});
  3754. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3755. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3756. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3757. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3758. this.registerType('sklearn.tree._tree.Tree', class {
  3759. constructor(n_features, n_classes, n_outputs) {
  3760. this.n_features = n_features;
  3761. this.n_classes = n_classes;
  3762. this.n_outputs = n_outputs;
  3763. }
  3764. __setstate__(state) {
  3765. this.max_depth = state.get('max_depth');
  3766. this.node_count = state.get('node_count');
  3767. this.nodes = state.get('nodes');
  3768. this.values = state.get('values');
  3769. }
  3770. });
  3771. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3772. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3773. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3774. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3775. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3776. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3777. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3778. this.registerType('pickle.Unpickler', class {
  3779. constructor(data) {
  3780. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3781. this.persistent_load = () => {
  3782. throw new python.Error('Unsupported persistent id.');
  3783. };
  3784. }
  3785. load() {
  3786. const reader = this._reader;
  3787. const marker = [];
  3788. let stack = [];
  3789. const memo = {};
  3790. let size = 0;
  3791. while (reader.position < reader.length) {
  3792. const opcode = reader.byte();
  3793. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3794. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3795. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3796. switch (opcode) {
  3797. case 128: { // PROTO
  3798. const version = reader.byte();
  3799. if (version > 5) {
  3800. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3801. }
  3802. break;
  3803. }
  3804. case 99: { // GLOBAL 'c'
  3805. const module = reader.line();
  3806. const name = reader.line();
  3807. stack.push(this.find_class(module, name));
  3808. break;
  3809. }
  3810. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3811. const name = stack.pop();
  3812. const module = stack.pop();
  3813. stack.push(this.find_class(module, name));
  3814. break;
  3815. }
  3816. case 111: { // OBJ 'o'
  3817. const args = stack;
  3818. const cls = args.pop();
  3819. stack = marker.pop();
  3820. const obj = this._instantiate(cls, args);
  3821. stack.push(obj);
  3822. break;
  3823. }
  3824. case 112 : { // PUT 'p'
  3825. const index = parseInt(reader.line(), 10);
  3826. if (stack.length === 0) {
  3827. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3828. }
  3829. memo[index] = stack[stack.length - 1];
  3830. size++;
  3831. break;
  3832. }
  3833. case 103: { // GET 'g'
  3834. const index = parseInt(reader.line(), 10);
  3835. stack.push(memo[index]);
  3836. break;
  3837. }
  3838. case 48: // POP '0'
  3839. stack.pop();
  3840. break;
  3841. case 49: // POP_MARK '1'
  3842. stack = marker.pop();
  3843. break;
  3844. case 50: // DUP '2'
  3845. if (stack.length === 0) {
  3846. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3847. }
  3848. stack.push(stack[stack.length - 1]);
  3849. break;
  3850. case 80: // PERSID 'P'
  3851. stack.push(this.persistent_load(reader.line()));
  3852. break;
  3853. case 81: // BINPERSID 'Q'
  3854. stack.push(this.persistent_load(stack.pop()));
  3855. break;
  3856. case 82: { // REDUCE 'R'
  3857. const args = stack.pop();
  3858. const func = stack.pop();
  3859. stack.push(this._reduce(func, args));
  3860. break;
  3861. }
  3862. case 129: { // NEWOBJ
  3863. const args = stack.pop();
  3864. const cls = stack.pop();
  3865. const obj = this._newobj(cls, args);
  3866. stack.push(obj);
  3867. break;
  3868. }
  3869. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3870. const kwargs = stack.pop();
  3871. const args = stack.pop();
  3872. const cls = stack.pop();
  3873. if (Object.entries(kwargs).length > 0) {
  3874. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3875. }
  3876. const obj = this._newobj(cls, args);
  3877. stack.push(obj);
  3878. break;
  3879. }
  3880. case 104: // BINGET 'h'
  3881. stack.push(memo[reader.byte()]);
  3882. break;
  3883. case 105: { // INST 'i'
  3884. const module = reader.line();
  3885. const name = reader.line();
  3886. const args = stack;
  3887. const cls = `${module}.${name}`;
  3888. stack = marker.pop();
  3889. // cls = this.find_class(module, name)
  3890. const obj = this._instantiate(cls, args);
  3891. stack.push(obj);
  3892. break;
  3893. }
  3894. case 106: // LONG_BINGET 'j'
  3895. stack.push(memo[reader.uint32()]);
  3896. break;
  3897. case 113: // BINPUT 'q'
  3898. if (stack.length === 0) {
  3899. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3900. }
  3901. memo[reader.byte()] = stack[stack.length - 1];
  3902. size++;
  3903. break;
  3904. case 114: // LONG_BINPUT 'r'
  3905. if (stack.length === 0) {
  3906. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3907. }
  3908. memo[reader.uint32()] = stack[stack.length - 1];
  3909. size++;
  3910. break;
  3911. case 74: // BININT 'J'
  3912. stack.push(reader.int32());
  3913. break;
  3914. case 75: // BININT1 'K'
  3915. stack.push(reader.byte());
  3916. break;
  3917. case 76: // LONG 'L'
  3918. stack.push(parseInt(reader.line(), 10));
  3919. break;
  3920. case 77: // BININT2 'M'
  3921. stack.push(reader.uint16());
  3922. break;
  3923. case 66: // BINBYTES 'B' (Protocol 3)
  3924. stack.push(reader.read(reader.int32()));
  3925. break;
  3926. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3927. stack.push(reader.read(reader.byte()));
  3928. break;
  3929. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3930. stack.push(reader.read(reader.int64().toNumber()));
  3931. break;
  3932. case 70: // FLOAT 'F'
  3933. stack.push(parseFloat(reader.line()));
  3934. break;
  3935. case 71: // BINFLOAT 'G'
  3936. stack.push(reader.float64());
  3937. break;
  3938. case 73: { // INT 'I'
  3939. const value = reader.line();
  3940. if (value === '01') {
  3941. stack.push(true);
  3942. } else if (value === '00') {
  3943. stack.push(false);
  3944. } else {
  3945. stack.push(parseInt(value, 10));
  3946. }
  3947. break;
  3948. }
  3949. case 93: // EMPTY_LIST ']'
  3950. stack.push(new builtins.list());
  3951. break;
  3952. case 41: // EMPTY_TUPLE ')'
  3953. stack.push([]);
  3954. break;
  3955. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3956. stack.push([]);
  3957. break;
  3958. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3959. const items = stack;
  3960. stack = marker.pop();
  3961. const obj = stack[stack.length - 1];
  3962. for (let i = 0; i < items.length; i++) {
  3963. obj.push(items[i]);
  3964. }
  3965. break;
  3966. }
  3967. case 145: { // FROZENSET '\x91' (Protocol 4)
  3968. const items = stack;
  3969. stack = marker.pop();
  3970. stack.push(items);
  3971. break;
  3972. }
  3973. case 100: { // DICT 'd'
  3974. const items = stack;
  3975. stack = marker.pop();
  3976. const dict = new builtins.dict();
  3977. for (let i = 0; i < items.length; i += 2) {
  3978. dict.__setitem__(items[i], items[i + 1]);
  3979. }
  3980. stack.push(dict);
  3981. break;
  3982. }
  3983. case 108: { // LIST 'l'
  3984. const items = stack;
  3985. stack = marker.pop();
  3986. stack.push(items);
  3987. break;
  3988. }
  3989. case 116: { // TUPLE 't'
  3990. const items = stack;
  3991. stack = marker.pop();
  3992. stack.push(items);
  3993. break;
  3994. }
  3995. case 133: { // TUPLE1 // '\x85'
  3996. stack.push([stack.pop()]);
  3997. break;
  3998. }
  3999. case 134: { // TUPLE2 '\x86'
  4000. const b = stack.pop();
  4001. const a = stack.pop();
  4002. stack.push([a, b]);
  4003. break;
  4004. }
  4005. case 135: { // TUPLE3 '\x87'
  4006. const c = stack.pop();
  4007. const b = stack.pop();
  4008. const a = stack.pop();
  4009. stack.push([a, b, c]);
  4010. break;
  4011. }
  4012. case 115: { // SETITEM 's'
  4013. const value = stack.pop();
  4014. const key = stack.pop();
  4015. const obj = stack[stack.length - 1];
  4016. if (obj.__setitem__) {
  4017. obj.__setitem__(key, value);
  4018. } else {
  4019. obj[key] = value;
  4020. }
  4021. break;
  4022. }
  4023. case 117: { // SETITEMS 'u'
  4024. const items = stack;
  4025. stack = marker.pop();
  4026. const obj = stack[stack.length - 1];
  4027. if (obj.__setitem__) {
  4028. for (let i = 0; i < items.length; i += 2) {
  4029. obj.__setitem__(items[i], items[i + 1]);
  4030. }
  4031. } else {
  4032. for (let i = 0; i < items.length; i += 2) {
  4033. obj[items[i]] = items[i + 1];
  4034. }
  4035. }
  4036. break;
  4037. }
  4038. case 125: // EMPTY_DICT '}'
  4039. stack.push(new builtins.dict());
  4040. break;
  4041. case 97: { // APPEND 'a'
  4042. const append = stack.pop();
  4043. stack[stack.length - 1].push(append);
  4044. break;
  4045. }
  4046. case 101: { // APPENDS 'e'
  4047. const appends = stack;
  4048. stack = marker.pop();
  4049. const list = stack[stack.length - 1];
  4050. list.push(...appends);
  4051. break;
  4052. }
  4053. case 83: { // STRING 'S'
  4054. const str = reader.line();
  4055. stack.push(str.substring(1, str.length - 1));
  4056. break;
  4057. }
  4058. case 84: // BINSTRING 'T'
  4059. stack.push(reader.string(reader.uint32()));
  4060. break;
  4061. case 85 : // SHORT_BINSTRING 'U'
  4062. stack.push(reader.string(reader.byte()));
  4063. break;
  4064. case 86: // UNICODE 'V'
  4065. stack.push(reader.line());
  4066. break;
  4067. case 88: // BINUNICODE 'X
  4068. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4069. break;
  4070. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4071. stack.push(reader.string(reader.byte(), 'utf-8'));
  4072. break;
  4073. case 98: { // BUILD 'b'
  4074. const state = stack.pop();
  4075. let obj = stack.pop();
  4076. if (obj.__setstate__) {
  4077. if (obj.__setstate__.__call__) {
  4078. obj.__setstate__.__call__([obj, state]);
  4079. } else {
  4080. obj.__setstate__(state);
  4081. }
  4082. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4083. obj.__state__ = state;
  4084. } else if (obj instanceof Map && state instanceof Map) {
  4085. for (const [key, value] of state) {
  4086. obj.set(key, value);
  4087. }
  4088. } else if (obj instanceof Map) {
  4089. /* eslint-disable guard-for-in */
  4090. for (const key in state) {
  4091. obj.set(key, state[key]);
  4092. }
  4093. /* eslint-enable guard-for-in */
  4094. } else if (state instanceof Map) {
  4095. for (const [key, value] of state) {
  4096. obj[key] = value;
  4097. }
  4098. } else {
  4099. Object.assign(obj, state);
  4100. }
  4101. if (obj.__read__) {
  4102. obj = obj.__read__(this);
  4103. }
  4104. stack.push(obj);
  4105. break;
  4106. }
  4107. case 40: // MARK '('
  4108. marker.push(stack);
  4109. stack = [];
  4110. break;
  4111. case 136: // NEWTRUE '\x88'
  4112. stack.push(true);
  4113. break;
  4114. case 137: // NEWFALSE '\x89'
  4115. stack.push(false);
  4116. break;
  4117. case 138: { // LONG1 '\x8a'
  4118. const data = reader.read(reader.byte());
  4119. let number = 0;
  4120. switch (data.length) {
  4121. case 0: number = 0; break;
  4122. case 1: [number] = data; break;
  4123. case 2: number = data[1] << 8 | data[0]; break;
  4124. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4125. case 4: number = (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0; break;
  4126. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4127. default: number = Array.prototype.slice.call(data, 0); break;
  4128. }
  4129. stack.push(number);
  4130. break;
  4131. }
  4132. case 139: // LONG4 '\x8b'
  4133. // decode LONG4
  4134. stack.push(reader.read(reader.uint32()));
  4135. break;
  4136. case 148: // MEMOIZE '\x94' (Protocol 4)
  4137. memo[size++] = stack[stack.length - 1];
  4138. break;
  4139. case 149: // FRAME '\x95' (Protocol 4)
  4140. reader.read(8);
  4141. break;
  4142. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4143. stack.push(reader.read(reader.int64().toNumber()));
  4144. break;
  4145. }
  4146. case 78: // NONE 'N'
  4147. stack.push(null);
  4148. break;
  4149. case 46: // STOP '.'
  4150. return stack.pop();
  4151. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4152. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4153. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4154. default:
  4155. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4156. }
  4157. }
  4158. throw new python.Error('Unexpected end of file.');
  4159. }
  4160. find_class(module, name) {
  4161. execution.__import__(module);
  4162. return execution.resolve(`${module}.${name}`);
  4163. }
  4164. _instantiate(cls, args) {
  4165. return execution.invoke(cls, args);
  4166. }
  4167. _newobj(cls, args) {
  4168. // cls.__new__(cls, args)
  4169. return execution.invoke(cls, args);
  4170. }
  4171. _reduce(func, args) {
  4172. return execution.invoke(func, args);
  4173. }
  4174. read(size) {
  4175. return this._reader.read(size);
  4176. }
  4177. stream(size) {
  4178. return this._reader.stream(size);
  4179. }
  4180. });
  4181. this.registerType('random.Random', class {});
  4182. this.registerType('re.Pattern', class {
  4183. constructor(pattern, flags) {
  4184. this.pattern = pattern;
  4185. this.flags = flags;
  4186. }
  4187. });
  4188. this.registerType('spacy._ml.PrecomputableAffine', class {
  4189. __setstate__(state) {
  4190. Object.assign(this, new pickle.Unpickler(state).load());
  4191. }
  4192. });
  4193. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4194. __setstate__(state) {
  4195. Object.assign(this, new pickle.Unpickler(state).load());
  4196. }
  4197. });
  4198. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4199. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4200. this.registerType('theano.compile.function_module.Function', class {});
  4201. this.registerType('theano.compile.function_module.Supervisor', class {});
  4202. this.registerType('theano.compile.io.In', class {});
  4203. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4204. this.registerType('theano.compile.mode.Mode', class {});
  4205. this.registerType('theano.compile.ops.OutputGuard', class {});
  4206. this.registerType('theano.compile.ops.Shape', class {});
  4207. this.registerType('theano.compile.ops.Shape_i', class {});
  4208. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4209. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4210. this.registerType('theano.gof.graph.Apply', class {});
  4211. this.registerType('theano.gof.link.Container', class {});
  4212. this.registerType('theano.gof.opt._metadict', class {});
  4213. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4214. this.registerType('theano.gof.opt.MergeFeature', class {});
  4215. this.registerType('theano.gof.optdb.Query', class {});
  4216. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4217. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4218. this.registerType('theano.gof.utils.scratchpad', class {});
  4219. this.registerType('theano.misc.ordered_set.Link', class {});
  4220. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4221. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4222. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4223. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4224. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4225. this.registerType('theano.scalar.basic.Abs', class {});
  4226. this.registerType('theano.scalar.basic.Add', class {});
  4227. this.registerType('theano.scalar.basic.Cast', class {});
  4228. this.registerType('theano.scalar.basic.Composite', class {});
  4229. this.registerType('theano.scalar.basic.EQ', class {});
  4230. this.registerType('theano.scalar.basic.GE', class {});
  4231. this.registerType('theano.scalar.basic.Identity', class {});
  4232. this.registerType('theano.scalar.basic.IntDiv', class {});
  4233. this.registerType('theano.scalar.basic.Inv', class {});
  4234. this.registerType('theano.scalar.basic.LE', class {});
  4235. this.registerType('theano.scalar.basic.LT', class {});
  4236. this.registerType('theano.scalar.basic.Mul', class {});
  4237. this.registerType('theano.scalar.basic.Neg', class {});
  4238. this.registerType('theano.scalar.basic.Pow', class {});
  4239. this.registerType('theano.scalar.basic.Scalar', class {});
  4240. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4241. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4242. this.registerType('theano.scalar.basic.Second', class {});
  4243. this.registerType('theano.scalar.basic.Sgn', class {});
  4244. this.registerType('theano.scalar.basic.specific_out', class {});
  4245. this.registerType('theano.scalar.basic.Sub', class {});
  4246. this.registerType('theano.scalar.basic.Switch', class {});
  4247. this.registerType('theano.scalar.basic.Tanh', class {});
  4248. this.registerType('theano.scalar.basic.transfer_type', class {});
  4249. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4250. this.registerType('theano.tensor.basic.Alloc', class {});
  4251. this.registerType('theano.tensor.basic.Dot', class {});
  4252. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4253. this.registerType('theano.tensor.basic.Reshape', class {});
  4254. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4255. this.registerType('theano.tensor.blas.Dot22', class {});
  4256. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4257. this.registerType('theano.tensor.blas.Gemm', class {});
  4258. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4259. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4260. this.registerType('theano.tensor.elemwise.Sum', class {});
  4261. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4262. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4263. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4264. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4265. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4266. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4267. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4268. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4269. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4270. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4271. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4272. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4273. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4274. this.registerType('theano.tensor.opt.MakeVector', class {});
  4275. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4276. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4277. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4278. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4279. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4280. this.registerType('theano.tensor.type.TensorType', class {});
  4281. this.registerType('theano.tensor.var.TensorConstant', class {});
  4282. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4283. this.registerType('theano.tensor.var.TensorVariable', class {});
  4284. this.registerType('thinc.describe.Biases', class {});
  4285. this.registerType('thinc.describe.Dimension', class {});
  4286. this.registerType('thinc.describe.Gradient', class {});
  4287. this.registerType('thinc.describe.Weights', class {});
  4288. this.registerType('thinc.describe.Synapses', class {});
  4289. this.registerType('thinc.neural._classes.affine.Affine', class {
  4290. __setstate__(state) {
  4291. Object.assign(this, new pickle.Unpickler(state).load());
  4292. }
  4293. });
  4294. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4295. __setstate__(state) {
  4296. Object.assign(this, new pickle.Unpickler(state).load());
  4297. }
  4298. });
  4299. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4300. __setstate__(state) {
  4301. Object.assign(this, new pickle.Unpickler(state).load());
  4302. }
  4303. });
  4304. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4305. __setstate__(state) {
  4306. Object.assign(this, new pickle.Unpickler(state).load());
  4307. }
  4308. });
  4309. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4310. __setstate__(state) {
  4311. Object.assign(this, new pickle.Unpickler(state).load());
  4312. }
  4313. });
  4314. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4315. __setstate__(state) {
  4316. Object.assign(this, new pickle.Unpickler(state).load());
  4317. }
  4318. });
  4319. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4320. __setstate__(state) {
  4321. Object.assign(this, new pickle.Unpickler(state).load());
  4322. }
  4323. });
  4324. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4325. __setstate__(state) {
  4326. Object.assign(this, new pickle.Unpickler(state).load());
  4327. }
  4328. });
  4329. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4330. __setstate__(state) {
  4331. Object.assign(this, new pickle.Unpickler(state).load());
  4332. }
  4333. });
  4334. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4335. __setstate__(state) {
  4336. Object.assign(this, new pickle.Unpickler(state).load());
  4337. }
  4338. });
  4339. this.registerType('thinc.neural.mem.Memory', class {
  4340. });
  4341. this.registerType('thinc.neural.ops.NumpyOps', class {
  4342. });
  4343. this.registerType('__main__.BYOLState', class {
  4344. constructor(dict) {
  4345. Object.assign(this, dict);
  4346. }
  4347. });
  4348. const types = this.register('types');
  4349. this.registerType('types.GenericAlias', class {});
  4350. this.registerType('types.SimpleNamespace', class {});
  4351. this.registerType('types.BuiltinFunctionType', class {});
  4352. this.registerType('types.BuiltinMethodType', class {});
  4353. this.registerFunction('types.resolve_bases', (bases) => {
  4354. return bases;
  4355. });
  4356. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4357. if (kwds) {
  4358. kwds = new builtins.dict(kwds);
  4359. } else {
  4360. kwds = new builtins.dict();
  4361. }
  4362. let meta = null;
  4363. if (kwds.__contains__('metaclass')) {
  4364. meta = kwds.pop('metaclass');
  4365. } else if (bases && bases.length > 0) {
  4366. meta = builtins.type(bases[0]);
  4367. } else {
  4368. meta = builtins.type;
  4369. }
  4370. if (meta instanceof builtins.type) {
  4371. meta = types._calculate_meta(meta, bases);
  4372. }
  4373. let ns = null;
  4374. if (builtins.hasattr(meta, '__prepare__')) {
  4375. // ns = meta.__prepare__(name, bases, **kwds)
  4376. } else {
  4377. ns = new builtins.dict();
  4378. }
  4379. return [meta, ns, kwds];
  4380. });
  4381. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4382. const winner = meta;
  4383. return winner;
  4384. });
  4385. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4386. const resolved_bases = types.resolve_bases(bases);
  4387. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4388. if (exec_body) {
  4389. exec_body(ns);
  4390. }
  4391. return new meta(name, resolved_bases, ns);
  4392. });
  4393. types.ObjectType = builtins.object;
  4394. types.ModuleType = builtins.module;
  4395. types.MethodType = builtins.method;
  4396. types.FunctionType = builtins.function;
  4397. types.TypeType = builtins.type;
  4398. types.CodeType = builtins.code;
  4399. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4400. this.registerType('xgboost.core.Booster', class {
  4401. load_model(fname) {
  4402. if (fname instanceof Uint8Array) {
  4403. // XGBoosterLoadModel()
  4404. } else {
  4405. // XGBoosterUnserializeFromBuffer(handle) {
  4406. }
  4407. }
  4408. __setstate__(state) {
  4409. const handle = state.get('handle');
  4410. if (handle) {
  4411. this.handle = handle;
  4412. // XGBoosterLoadModelFromBuffer()
  4413. }
  4414. }
  4415. });
  4416. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4417. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4418. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4419. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4420. return new builtins.bytearray(obj, encoding);
  4421. });
  4422. this.registerType('builtins.bytearray', class extends Uint8Array {
  4423. constructor(source, encoding /*, errors */) {
  4424. source = builtins.bytes.__encode__(source, encoding);
  4425. super(Number.isInteger(source) ? source : source.length);
  4426. if (Array.isArray(source)) {
  4427. for (let i = 0; i < source.length; i++) {
  4428. this[i] = source;
  4429. }
  4430. } else if (source instanceof Uint8Array) {
  4431. this.set(source, 0);
  4432. } else if (typeof source === 'string') {
  4433. for (let i = 0; i < source.length; i++) {
  4434. this[i] = source.charCodeAt(i);
  4435. }
  4436. }
  4437. }
  4438. static __encode__(source, encoding) {
  4439. if (source === undefined) {
  4440. return 0;
  4441. }
  4442. if (Number.isInteger(source)) {
  4443. return source;
  4444. }
  4445. if (Array.isArray(source) || source instanceof Uint8Array) {
  4446. return source;
  4447. }
  4448. if (typeof source === 'string') {
  4449. switch (encoding) {
  4450. case 'latin1':
  4451. case 'latin-1':
  4452. return source;
  4453. case 'utf8':
  4454. case 'utf-8':
  4455. return new TextEncoder('utf-8').encode(source);
  4456. case undefined:
  4457. throw new python.Error('Unsupported string argument without an encoding.');
  4458. default:
  4459. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4460. }
  4461. }
  4462. throw new python.Error('Unsupported source.');
  4463. }
  4464. });
  4465. this.registerType('builtins.bytes', class extends Uint8Array {
  4466. constructor(source, encoding /*, errors */) {
  4467. source = builtins.bytes.__encode__(source, encoding);
  4468. super(Number.isInteger(source) ? source : source.length);
  4469. if (Array.isArray(source)) {
  4470. for (let i = 0; i < source.length; i++) {
  4471. this[i] = source;
  4472. }
  4473. } else if (source instanceof Uint8Array) {
  4474. this.set(source, 0);
  4475. } else if (typeof source === 'string') {
  4476. for (let i = 0; i < source.length; i++) {
  4477. this[i] = source.charCodeAt(i);
  4478. }
  4479. }
  4480. }
  4481. static __encode__(source, encoding) {
  4482. if (source === undefined) {
  4483. return 0;
  4484. }
  4485. if (Number.isInteger(source)) {
  4486. return source;
  4487. }
  4488. if (Array.isArray(source) || source instanceof Uint8Array) {
  4489. return source;
  4490. }
  4491. if (typeof source === 'string') {
  4492. switch (encoding) {
  4493. case 'latin1':
  4494. case 'latin-1':
  4495. return source;
  4496. case 'utf8':
  4497. case 'utf-8':
  4498. return new TextEncoder('utf-8').encode(source);
  4499. case undefined:
  4500. throw new python.Error('Unsupported string argument without an encoding.');
  4501. default:
  4502. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4503. }
  4504. }
  4505. throw new python.Error('Unsupported source.');
  4506. }
  4507. });
  4508. this.registerType('builtins.memoryview', class {
  4509. constructor(buf) {
  4510. this._buf = buf;
  4511. }
  4512. get nbytes() {
  4513. return this._buf.length;
  4514. }
  4515. });
  4516. this.registerType('builtins.frozenset', class extends Set {
  4517. constructor(iterable) {
  4518. super();
  4519. if (iterable) {
  4520. for (const item of iterable) {
  4521. this.add(item);
  4522. }
  4523. }
  4524. }
  4525. });
  4526. this.registerFunction('builtins.exec');
  4527. this.registerFunction('builtins.issubclass', (obj, type) => {
  4528. const name = `${type.__module__}.${type.__name__}`;
  4529. if (obj.__module__ && obj.__name__) {
  4530. if (name === `${obj.__module__}.${obj.__name__}`) {
  4531. return true;
  4532. }
  4533. }
  4534. if (obj.__bases__) {
  4535. for (const base of obj.__bases__) {
  4536. if (builtins.issubclass(base, type)) {
  4537. return true;
  4538. }
  4539. }
  4540. }
  4541. return false;
  4542. });
  4543. this.registerFunction('builtins.isinstance', (obj, type) => {
  4544. if (obj && type && obj instanceof type) {
  4545. return true;
  4546. }
  4547. if (obj && obj.__class__) {
  4548. return builtins.issubclass(obj.__class__, type);
  4549. }
  4550. return false;
  4551. });
  4552. this.registerFunction('builtins.hasattr', (obj, name) => {
  4553. if (obj instanceof Map && obj.__contains__) {
  4554. return obj.__contains__(name);
  4555. }
  4556. return Object.prototype.hasOwnProperty.call(obj, name);
  4557. });
  4558. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4559. if (obj && obj.__getattr__) {
  4560. return obj.__getattr__(name);
  4561. }
  4562. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4563. return obj[name];
  4564. }
  4565. return defaultValue;
  4566. });
  4567. this.registerFunction('builtins.len', (obj) => {
  4568. return obj.length;
  4569. });
  4570. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4571. if (obj && obj.__setattr__) {
  4572. obj.__setattr__(name, value);
  4573. } else {
  4574. obj[name] = value;
  4575. }
  4576. });
  4577. this.registerType('builtins.set', class extends Set {
  4578. __contains__(item) {
  4579. return this.has(item);
  4580. }
  4581. update(iterable) {
  4582. for (const item of iterable) {
  4583. this.add(item);
  4584. }
  4585. }
  4586. });
  4587. this.registerType('builtins.slice', class {
  4588. constructor(start, stop, step) {
  4589. this.start = start;
  4590. this.stop = stop;
  4591. this.step = step;
  4592. }
  4593. });
  4594. this.registerFunction('builtins.hash');
  4595. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4596. return name;
  4597. });
  4598. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4599. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4600. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4601. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4602. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4603. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4604. cell.cell_contents = value;
  4605. }
  4606. return cell;
  4607. });
  4608. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4609. // globals["__builtins__"] = __builtins__
  4610. return new types.FunctionType(code, globals, name, argdefs, closure);
  4611. });
  4612. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4613. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4614. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4615. if (class_tracker_id) {
  4616. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4617. }
  4618. return class_def;
  4619. });
  4620. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4621. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4622. const kwds = { 'metaclass': type_constructor };
  4623. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4624. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4625. });
  4626. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4627. return new builtins.cell();
  4628. });
  4629. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4630. [state] = state;
  4631. let registry = null;
  4632. for (const [attrname, attr] of state.items()) {
  4633. if (attrname === '_abc_impl') {
  4634. registry = attr;
  4635. } else {
  4636. builtins.setattr(obj, attrname, attr);
  4637. }
  4638. }
  4639. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4640. obj.__firstlineno__ = state.get('__firstlineno__');
  4641. }
  4642. if (registry) {
  4643. for (const subclass of registry) {
  4644. obj.register(subclass);
  4645. }
  4646. }
  4647. return obj;
  4648. });
  4649. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4650. const [, slotstate] = state;
  4651. [state] = state;
  4652. // obj.__dict__.update(state)
  4653. /* const obj_globals = */ slotstate.pop('__globals__');
  4654. const obj_closure = slotstate.pop('__closure__');
  4655. slotstate.pop('_cloudpickle_submodules');
  4656. if (obj.__globals__) {
  4657. // obj.__globals__.update(obj_globals);
  4658. // obj.__globals__.__builtins__ = __builtins__;
  4659. }
  4660. if (obj_closure) {
  4661. // let value = null;
  4662. for (let i = 0; i < obj_closure.length; i++) {
  4663. // const cell = obj_closure[i];
  4664. try {
  4665. // value = cell.cell_contents;
  4666. } catch {
  4667. // cell is empty
  4668. }
  4669. // obj.__closure__[i].cell_contents = value;
  4670. }
  4671. }
  4672. for (const [k, v] of slotstate.items()) {
  4673. builtins.setattr(obj, k, v);
  4674. }
  4675. });
  4676. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4677. execution.__import__(name);
  4678. return sys.modules.get(name);
  4679. });
  4680. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4681. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4682. const ray = this.register('ray');
  4683. this.register('ray.cloudpickle.cloudpickle');
  4684. this.register('ray.cloudpickle.cloudpickle_fast');
  4685. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4686. ray.cloudpickle.cloudpickle._fill_function = cloudpickle.cloudpickle._fill_function;
  4687. ray.cloudpickle.cloudpickle._make_cell = cloudpickle.cloudpickle._make_cell;
  4688. ray.cloudpickle.cloudpickle._make_function = cloudpickle.cloudpickle._make_function;
  4689. ray.cloudpickle.cloudpickle._make_skel_func = cloudpickle.cloudpickle._make_skel_func;
  4690. ray.cloudpickle.cloudpickle._make_skeleton_class = cloudpickle.cloudpickle._make_skeleton_class;
  4691. ray.cloudpickle.cloudpickle._make_empty_cell = cloudpickle.cloudpickle._make_empty_cell;
  4692. ray.cloudpickle.cloudpickle._empty_cell_value = cloudpickle.cloudpickle._empty_cell_value;
  4693. ray.cloudpickle.cloudpickle._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4694. ray.cloudpickle.cloudpickle._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4695. ray.cloudpickle.cloudpickle._lookup_class_or_track = cloudpickle.cloudpickle._lookup_class_or_track;
  4696. ray.cloudpickle.cloudpickle_fast._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4697. ray.cloudpickle.cloudpickle_fast._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4698. this.registerType('ray.rllib.algorithms.ppo.ppo.PPO', class {});
  4699. this.registerType('ray.rllib.algorithms.ppo.ppo.PPOConfig', class {});
  4700. this.registerType('ray.rllib.algorithms.algorithm_config.AlgorithmConfig', class {});
  4701. this.registerFunction('ray.rllib.algorithms.algorithm_config.AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN');
  4702. this.registerType('ray.rllib.algorithms.algorithm_config.TorchCompileWhatToCompile', class {});
  4703. this.registerType('ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector', class {});
  4704. this.registerType('ray.rllib.callbacks.callbacks.RLlibCallback', class {});
  4705. this.registerType('ray.rllib.core.learner.learner.TorchCompileWhatToCompile', class {});
  4706. this.registerType('ray.rllib.policy.policy.PolicySpec', class {});
  4707. this.registerType('ray.rllib.policy.sample_batch.SampleBatch', class {});
  4708. this.registerType('ray.rllib.utils.metrics.stats.mean.MeanStats', class {});
  4709. this.registerType('ray.rllib.utils.metrics.stats.ema.EmaStats', class {});
  4710. this.registerType('ray.rllib.utils.metrics.stats.min.MinStats', class {});
  4711. this.registerType('ray.rllib.utils.metrics.stats.max.MaxStats', class {});
  4712. this.registerType('ray.rllib.utils.metrics.stats.sum.SumStats', class {});
  4713. this.registerType('ray.rllib.utils.metrics.stats.lifetime_sum.LifetimeSumStats', class {});
  4714. this.registerType('ray.rllib.utils.metrics.stats.percentiles.PercentilesStats', class {});
  4715. this.registerType('ray.rllib.utils.metrics.stats.item.ItemStats', class {});
  4716. this.registerType('ray.rllib.utils.metrics.stats.item_series.ItemSeriesStats', class {});
  4717. this.registerType('collections.Counter', class {});
  4718. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4719. return {};
  4720. });
  4721. this.registerFunction('copy.deepcopy');
  4722. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4723. // copyreg._reconstructor in Python 3
  4724. if (base === '__builtin__.object' || base === builtins.object) {
  4725. return self.invoke(cls, []);
  4726. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4727. const obj = self.invoke(cls, []);
  4728. for (let i = 0; i < state.length; i++) {
  4729. obj[i] = state[i];
  4730. }
  4731. return obj;
  4732. }
  4733. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4734. });
  4735. this.registerFunction('copy.deepcopy', (/* x */) => {
  4736. throw new python.Error('Unsupported copy.deepcopy().');
  4737. });
  4738. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4739. const array = f(...args);
  4740. if (array.__setstate__) {
  4741. array.__setstate__(state);
  4742. }
  4743. if (npdict) {
  4744. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4745. }
  4746. return array;
  4747. });
  4748. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4749. return function() {
  4750. };
  4751. });
  4752. this.registerFunction('dill._dill._create_code', (args) => {
  4753. return self.invoke('types.CodeType', [args]);
  4754. });
  4755. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4756. return function() {
  4757. };
  4758. });
  4759. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4760. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4761. if (obj) {
  4762. return obj;
  4763. }
  4764. return undefined;
  4765. });
  4766. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4767. const [name, bases, dict] = args;
  4768. const type = class extends bases[0] {};
  4769. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4770. return self.registerType(identifier, Object.assign(type, dict));
  4771. });
  4772. this.registerFunction('dill._dill._eval_repr');
  4773. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4774. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4775. return self[name];
  4776. }
  4777. return undefined;
  4778. });
  4779. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4780. try {
  4781. if (import_name.startsWith('__runtime__.')) {
  4782. return execution.module(import_name);
  4783. } else if (import_name.indexOf('.') === -1) {
  4784. return execution.__import__(import_name);
  4785. }
  4786. return execution.resolve(import_name);
  4787. } catch (error) {
  4788. if (safe) {
  4789. return null;
  4790. }
  4791. throw error;
  4792. }
  4793. });
  4794. this.registerFunction('dill._dill._load_type', (name) => {
  4795. const _dill = self.register('dill._dill');
  4796. if (!_dill._reverse_typemap) {
  4797. _dill._reverse_typemap = new Map();
  4798. for (const name of ['__builtin__', 'types']) {
  4799. const module = self.register(name);
  4800. for (const [name, obj] of Object.entries(module)) {
  4801. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4802. _dill._reverse_typemap.set(name, obj);
  4803. }
  4804. }
  4805. }
  4806. _dill._reverse_typemap.set('PartialType', functools.partial);
  4807. _dill._reverse_typemap.set('CellType', builtins.cell);
  4808. }
  4809. if (!_dill._reverse_typemap.has(name)) {
  4810. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4811. }
  4812. return _dill._reverse_typemap.get(name);
  4813. });
  4814. this.registerFunction('dill._dill.loads');
  4815. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4816. const np_value = fun(...args);
  4817. np_value.__setstate__(arr_state);
  4818. const jnp_value = jax.device_put(np_value);
  4819. jnp_value.aval = jnp_value.aval.update(aval_state);
  4820. return jnp_value;
  4821. });
  4822. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4823. this.registerFunction('jax.device_put', (x) => {
  4824. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4825. return new jax.Array(aval, x.data);
  4826. });
  4827. this.registerType('jax._src.core.AbstractValue', class {});
  4828. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4829. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4830. constructor(shape, dtype, weak_type) {
  4831. super();
  4832. this.shape = shape;
  4833. this.dtype = dtype;
  4834. this.weak_type = weak_type || false;
  4835. }
  4836. update(dict) {
  4837. const shape = dict.get('shape') || this.shape;
  4838. const dtype = dict.get('dtype') || this.dtype;
  4839. const weak_type = dict.get('weak_type') || this.weak_type;
  4840. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4841. }
  4842. });
  4843. this.registerType('jax.Array', class {
  4844. constructor(aval, data) {
  4845. this.aval = aval;
  4846. this.data = data;
  4847. }
  4848. get dtype() {
  4849. return this.aval.dtype;
  4850. }
  4851. get shape() {
  4852. return this.aval.shape;
  4853. }
  4854. tobytes() {
  4855. return this.data;
  4856. }
  4857. });
  4858. jax.numpy.ndarray = jax.Array;
  4859. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4860. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4861. });
  4862. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4863. this.registerFunction('lasagne.nonlinearities.rectify');
  4864. this.registerFunction('lasagne.nonlinearities.softmax');
  4865. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4866. this.registerFunction('lasagne.updates.nesterov_momentum');
  4867. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4868. const BinaryReader = class {
  4869. constructor(buffer, ext_hook) {
  4870. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4871. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4872. this._buffer = buffer;
  4873. this._position = 0;
  4874. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4875. this._ext_hook = ext_hook;
  4876. }
  4877. value() {
  4878. const c = this._view.getUint8(this.skip(1));
  4879. if (c >= 0xe0) {
  4880. return c - 0x100;
  4881. }
  4882. if (c < 0xC0) {
  4883. if (c < 0x80) {
  4884. return c;
  4885. }
  4886. if (c < 0x90) {
  4887. return this.map(c - 0x80);
  4888. }
  4889. if (c < 0xa0) {
  4890. return this.array(c - 0x90);
  4891. }
  4892. return this.string(c - 0xa0);
  4893. }
  4894. switch (c) {
  4895. case 0xC0: return null;
  4896. case 0xC2: return false;
  4897. case 0xC3: return true;
  4898. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4899. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4900. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4901. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4902. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4903. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4904. case 0xCA: return this._view.getFloat32(this.skip(4));
  4905. case 0xCB: return this._view.getFloat64(this.skip(8));
  4906. case 0xCC: return this._view.getUint8(this.skip(1));
  4907. case 0xCD: return this._view.getUint16(this.skip(2));
  4908. case 0xCE: return this._view.getUint32(this.skip(4));
  4909. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4910. case 0xD0: return this._view.getInt8(this.skip(1));
  4911. case 0xD1: return this._view.getInt16(this.skip(2));
  4912. case 0xD2: return this._view.getInt32(this.skip(4));
  4913. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4914. case 0xD4: return this.extension(1);
  4915. case 0xD5: return this.extension(2);
  4916. case 0xD6: return this.extension(4);
  4917. case 0xD7: return this.extension(8);
  4918. case 0xD8: return this.extension(16);
  4919. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4920. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4921. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4922. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4923. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4924. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4925. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4926. default: throw new python.Error(`Invalid code '${c}'.`);
  4927. }
  4928. }
  4929. map(size) {
  4930. const map = {};
  4931. for (let i = 0; i < size; i++) {
  4932. const key = this.value();
  4933. const value = this.value();
  4934. map[key] = value;
  4935. }
  4936. return map;
  4937. }
  4938. array(size) {
  4939. const array = new Array(size);
  4940. for (let i = 0; i < size; i++) {
  4941. array[i] = this.value();
  4942. }
  4943. return array;
  4944. }
  4945. extension(size) {
  4946. const code = this._view.getUint8(this.skip(1));
  4947. const data = this.read(size);
  4948. return this._ext_hook(code, data);
  4949. }
  4950. skip(offset) {
  4951. const position = this._position;
  4952. this._position += offset;
  4953. if (this._position > this._buffer.length) {
  4954. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4955. }
  4956. return position;
  4957. }
  4958. read(size) {
  4959. const data = this._buffer.subarray(this._position, this._position + size);
  4960. this._position += size;
  4961. return data;
  4962. }
  4963. string(size) {
  4964. const buffer = this.read(size);
  4965. this._decoder = this._decoder || new TextDecoder('utf8');
  4966. return this._decoder.decode(buffer);
  4967. }
  4968. };
  4969. return new BinaryReader(packed, ext_hook).value();
  4970. });
  4971. this.registerFunction('nolearn.lasagne.base.objective');
  4972. this.registerFunction('numpy.core._DType_reconstruct');
  4973. this.registerFunction('numpy.core._ufunc_reconstruct');
  4974. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4975. return numpy.ndarray.__new__(subtype, shape, dtype);
  4976. });
  4977. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4978. const shape = [buf.length / dtype.itemsize];
  4979. return new numpy.ndarray(shape, dtype, buf);
  4980. });
  4981. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  4982. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  4983. });
  4984. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4985. return new numpy.dtypes.StringDType();
  4986. });
  4987. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4988. let data = rawData;
  4989. if (typeof rawData === 'string' || rawData instanceof String) {
  4990. data = new Uint8Array(rawData.length);
  4991. for (let i = 0; i < rawData.length; i++) {
  4992. data[i] = rawData.charCodeAt(i);
  4993. }
  4994. }
  4995. switch (dtype.kind) {
  4996. case 'b': {
  4997. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4998. switch (dtype.itemsize) {
  4999. case 1: return view.getInt8(0) ? true : false;
  5000. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  5001. }
  5002. }
  5003. case 'f': {
  5004. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5005. switch (dtype.itemsize) {
  5006. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  5007. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  5008. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  5009. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  5010. }
  5011. }
  5012. case 'i': {
  5013. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5014. switch (dtype.itemsize) {
  5015. case 1: return view.getInt8(0);
  5016. case 2: return view.getInt16(0, dtype.byteorder === '<');
  5017. case 4: return view.getInt32(0, dtype.byteorder === '<');
  5018. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  5019. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  5020. }
  5021. }
  5022. case 'u': {
  5023. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5024. switch (dtype.itemsize) {
  5025. case 1: return view.getUint8(0);
  5026. case 2: return view.getUint16(0, dtype.byteorder === '<');
  5027. case 4: return view.getUint32(0, dtype.byteorder === '<');
  5028. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5029. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5030. }
  5031. }
  5032. case 'U': {
  5033. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5034. const list = [];
  5035. for (let i = 0; i < dtype.itemsize; i += 4) {
  5036. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5037. }
  5038. return list.join('');
  5039. }
  5040. default: {
  5041. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5042. }
  5043. }
  5044. });
  5045. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5046. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5047. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5048. this.registerFunction('numpy.core._multiarray_umath.greater');
  5049. this.registerFunction('numpy.core._multiarray_umath.less');
  5050. this.registerFunction('numpy.core._multiarray_umath.log');
  5051. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5052. let data = rawData;
  5053. if (typeof rawData === 'string') {
  5054. data = new Uint8Array(rawData.length);
  5055. for (let i = 0; i < rawData.length; i++) {
  5056. data[i] = rawData.charCodeAt(i);
  5057. }
  5058. }
  5059. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5060. switch (dtype.__name__) {
  5061. case 'uint8':
  5062. return dataView.getUint8(0);
  5063. case 'float32':
  5064. return dataView.getFloat32(0, true);
  5065. case 'float64':
  5066. return dataView.getFloat64(0, true);
  5067. case 'int8':
  5068. return dataView.getInt8(0, true);
  5069. case 'int16':
  5070. return dataView.getInt16(0, true);
  5071. case 'int32':
  5072. return dataView.getInt32(0, true);
  5073. case 'int64':
  5074. return dataView.getBigInt64(0, true);
  5075. default:
  5076. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5077. }
  5078. });
  5079. this.registerFunction('numpy.core._multiarray_umath.sin');
  5080. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5081. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5082. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5083. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5084. this.register('numpy.core.numeric', numpy._core.numeric);
  5085. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5086. this.registerFunction('numpy.load', (file) => {
  5087. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5088. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5089. if (!file.read(6).every((v, i) => v === signature[i])) {
  5090. throw new python.Error('Invalid signature.');
  5091. }
  5092. const version = file.read(2);
  5093. const [major, minor] = version;
  5094. if (major > 3) {
  5095. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5096. }
  5097. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5098. let data = null;
  5099. switch (dtype.byteorder) {
  5100. case '|': {
  5101. data = file.read();
  5102. if (dtype.kind === 'O') {
  5103. const unpickler = new pickle.Unpickler(data);
  5104. return unpickler.load();
  5105. }
  5106. break;
  5107. }
  5108. case '>':
  5109. case '<': {
  5110. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5111. const stream = file.getbuffer().nbytes > 0x1000000;
  5112. data = file.read(dtype.itemsize * count, stream);
  5113. break;
  5114. }
  5115. default: {
  5116. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5117. }
  5118. }
  5119. if (fortran_order) {
  5120. data = null;
  5121. }
  5122. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5123. });
  5124. this.registerFunction('numpy.save', (file, arr) => {
  5125. const descr = arr.dtype.str;
  5126. if (descr[0] !== '<' && descr[0] !== '>') {
  5127. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5128. }
  5129. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5130. throw new python.Error(`Unsupported data type '${descr}'.`);
  5131. }
  5132. let shape = '';
  5133. switch (arr.shape.length) {
  5134. case 0: shape = '()'; break;
  5135. case 1: shape = `(${arr.shape[0]},)`; break;
  5136. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5137. }
  5138. const properties = [
  5139. `'descr': '${descr}'`,
  5140. "'fortran_order': False",
  5141. `'shape': ${shape}`
  5142. ];
  5143. let header = `{ ${properties.join(', ')} }`;
  5144. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5145. const encoder = new TextEncoder('ascii');
  5146. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5147. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5148. file.write(encoder.encode(header));
  5149. file.write(arr.tobytes());
  5150. });
  5151. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5152. const buffer = new Uint8Array([0, 0, 0, 0]);
  5153. const [major] = version;
  5154. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5155. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5156. let header = file.read(header_length);
  5157. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5158. header = decoder.decode(header).trim();
  5159. try {
  5160. header = ast.literal_eval(header);
  5161. } catch {
  5162. if (major <= 2) {
  5163. header = numpy.lib._format_impl._filter_header(header);
  5164. header = ast.literal_eval(header);
  5165. }
  5166. }
  5167. if (header.descr === undefined) {
  5168. throw new python.Error("Invalid 'descr'.");
  5169. }
  5170. if (!Array.isArray(header.shape)) {
  5171. throw new python.Error("Invalid 'shape'.");
  5172. }
  5173. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5174. return [header.shape, header.fortran_order, dtype];
  5175. });
  5176. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5177. if (typeof descr === 'string') {
  5178. return new numpy.dtype(descr);
  5179. } else if (descr instanceof builtins.tuple) {
  5180. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5181. return new numpy.dtype([dt, descr[1]]);
  5182. }
  5183. const titles = [];
  5184. const names = [];
  5185. const formats = [];
  5186. const offsets = [];
  5187. let offset = 0;
  5188. for (const field of descr) {
  5189. let name = null;
  5190. let dt = null;
  5191. let descr_str = null;
  5192. let shape = null;
  5193. let title = null;
  5194. if (field.length === 2) {
  5195. [name, descr_str] = field;
  5196. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5197. } else {
  5198. [name, descr_str, shape] = field;
  5199. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5200. }
  5201. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5202. if (!is_pad) {
  5203. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5204. titles.push(title);
  5205. names.push(name);
  5206. formats.push(dt);
  5207. offsets.push(offset);
  5208. }
  5209. offset += dt.itemsize;
  5210. }
  5211. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5212. });
  5213. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5214. const tokens = [];
  5215. const tokenizer = new ast._Tokenizer(s, '');
  5216. while (!tokenizer.match('eof')) {
  5217. const token = tokenizer.read();
  5218. if (token.type === 'int') {
  5219. const next = tokenizer.peek();
  5220. if (next.type === 'id' && next.value === 'L') {
  5221. tokenizer.read();
  5222. }
  5223. }
  5224. tokens.push(token.value);
  5225. }
  5226. return tokens.join('');
  5227. });
  5228. this.registerFunction('numpy.amin');
  5229. this.registerFunction('numpy.amax');
  5230. this.registerFunction('numpy.std');
  5231. this.registerFunction('numpy.asarray', (a, dtype) => {
  5232. const encode = (context, data, dim) => {
  5233. const size = context.shape[dim];
  5234. const littleendian = context.littleendian;
  5235. if (dim === context.shape.length - 1) {
  5236. for (let i = 0; i < size; i++) {
  5237. switch (context.dtype) {
  5238. case 'f2':
  5239. context.view.setFloat16(context.position, data[i], littleendian);
  5240. break;
  5241. case 'f4':
  5242. context.view.setFloat32(context.position, data[i], littleendian);
  5243. break;
  5244. case 'f8':
  5245. context.view.setFloat64(context.position, data[i], littleendian);
  5246. break;
  5247. case 'i1':
  5248. context.view.setInt8(context.position, data[i], littleendian);
  5249. break;
  5250. case 'i2':
  5251. context.view.setInt16(context.position, data[i], littleendian);
  5252. break;
  5253. case 'i4':
  5254. context.view.setInt32(context.position, data[i], littleendian);
  5255. break;
  5256. case 'i8':
  5257. context.view.setBigInt64(context.position, typeof data[i] === 'number' ? BigInt(data[i]) : data[i], littleendian);
  5258. break;
  5259. case 'u1':
  5260. context.view.setUint8(context.position, data[i], littleendian);
  5261. break;
  5262. case 'u2':
  5263. context.view.setUint16(context.position, data[i], littleendian);
  5264. break;
  5265. case 'u4':
  5266. context.view.setUint32(context.position, data[i], littleendian);
  5267. break;
  5268. case 'u8':
  5269. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5270. break;
  5271. case 'c8':
  5272. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5273. break;
  5274. case 'c16':
  5275. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5276. break;
  5277. case 'b1':
  5278. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5279. break;
  5280. default:
  5281. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5282. }
  5283. context.position += context.itemsize;
  5284. }
  5285. } else {
  5286. for (let j = 0; j < size; j++) {
  5287. encode(context, data[j], dim + 1);
  5288. }
  5289. }
  5290. };
  5291. const array_size = (value) => {
  5292. if (value.every((item) => Array.isArray(item))) {
  5293. const dims = value.map((item) => array_size(item));
  5294. const [dim] = dims;
  5295. for (let i = 1; i < dims.length; i++) {
  5296. if (dim.length === dims[i].length) {
  5297. if (!dims[i].every((value, i) => value === dim[i])) {
  5298. throw new python.Error('Invalid array shape.');
  5299. }
  5300. }
  5301. }
  5302. return [value.length].concat(dim);
  5303. }
  5304. return [value.length];
  5305. };
  5306. const shape = Array.isArray(a) ? array_size(a) : [];
  5307. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5308. const context = {
  5309. position: 0,
  5310. itemsize: dtype.itemsize,
  5311. dtype: dtype.str.substring(1),
  5312. littleendian: dtype.str[0],
  5313. shape,
  5314. data: new Uint8Array(size)
  5315. };
  5316. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5317. encode(context, a, 0);
  5318. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5319. });
  5320. this.registerFunction('numpy.max');
  5321. this.registerFunction('numpy.mean');
  5322. this.registerFunction('numpy.min');
  5323. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5324. const data = self.invoke(baseclass, [baseshape, basetype]);
  5325. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5326. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5327. return self.invoke(subtype, [data, mask, basetype]);
  5328. });
  5329. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5330. return {};
  5331. });
  5332. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5333. return {};
  5334. });
  5335. this.registerType('numpy.random.bit_generator.BitGenerator', class {});
  5336. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5337. __setstate__(/* state */) {
  5338. }
  5339. });
  5340. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5341. const obj = new cls();
  5342. if (state) {
  5343. obj.__setstate__(state);
  5344. }
  5345. return obj;
  5346. });
  5347. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5348. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5349. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5350. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5351. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5352. numpy.random._pickle.BitGenerators = {
  5353. 'MT19937': numpy.random._mt19937.MT19937,
  5354. 'PCG64': numpy.random._pcg64.PCG64,
  5355. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5356. 'Philox': numpy.random._philox.Philox,
  5357. 'SFC64': numpy.random._sfc64.SFC64,
  5358. };
  5359. this.registerType('numpy.random._generator.Generator', class {
  5360. constructor(bit_generator) {
  5361. this.bit_generator = bit_generator;
  5362. }
  5363. });
  5364. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5365. bit_generator = bit_generator || 'MT19937';
  5366. let bit_gen_class = null;
  5367. if (builtins.isinstance(bit_generator, builtins.type)) {
  5368. bit_gen_class = bit_generator;
  5369. } else {
  5370. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5371. }
  5372. if (bit_gen_class) {
  5373. return new bit_gen_class();
  5374. }
  5375. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5376. });
  5377. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5378. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5379. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5380. });
  5381. this.registerFunction('numpy.reshape');
  5382. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5383. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5384. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5385. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5386. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5387. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5388. this.registerFunction('sklearn.metrics._classification.f1_score');
  5389. this.registerFunction('sklearn.metrics._classification.log_loss');
  5390. this.registerFunction('sklearn.metrics._classification.precision_score');
  5391. this.registerFunction('sklearn.metrics._classification.recall_score');
  5392. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5393. return obj.__new__(obj);
  5394. });
  5395. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5396. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5397. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5398. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5399. this.registerFunction('sklearn.metrics._regression.r2_score');
  5400. sklearn.metrics.regression = sklearn.metrics._regression;
  5401. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5402. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5403. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5404. this.registerFunction('re._compile', (pattern, flags) => {
  5405. return self.invoke('re.Pattern', [pattern, flags]);
  5406. });
  5407. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5408. return function() {
  5409. return self.invoke(`types.${args[0]}`, args);
  5410. };
  5411. });
  5412. this.registerType('sympy.printing.defaults.Printable', class {});
  5413. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5414. constructor(...args) {
  5415. super();
  5416. this._args = args;
  5417. }
  5418. get args() {
  5419. return this._args;
  5420. }
  5421. });
  5422. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5423. });
  5424. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5425. });
  5426. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5427. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5428. __str__() {
  5429. return this._args.map((a) => a.__str__()).join('**');
  5430. }
  5431. });
  5432. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5433. __str__() {
  5434. return this._args.map((a) => a.__str__()).join(' + ');
  5435. }
  5436. });
  5437. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5438. __str__() {
  5439. return this._args.map((a) => a.__str__()).join('*');
  5440. }
  5441. });
  5442. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5443. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5444. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5445. constructor(value) {
  5446. super();
  5447. this.value = value;
  5448. this.is_Integer = true;
  5449. }
  5450. __int__() {
  5451. return this.value;
  5452. }
  5453. __str__() {
  5454. return this.value.toString();
  5455. }
  5456. });
  5457. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5458. constructor(name) {
  5459. super();
  5460. this.name = name;
  5461. }
  5462. __int__() {
  5463. throw new python.Error('Cannot convert symbols to int.');
  5464. }
  5465. __str__() {
  5466. return this.name;
  5467. }
  5468. });
  5469. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5470. constructor(lhs, rhs, op) {
  5471. super();
  5472. this._args = [lhs, rhs];
  5473. this._op = op;
  5474. }
  5475. __str__() {
  5476. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5477. }
  5478. });
  5479. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5480. });
  5481. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5482. });
  5483. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5484. constructor(lhs, rhs) {
  5485. super(lhs, rhs, '>=');
  5486. }
  5487. });
  5488. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5489. });
  5490. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5491. constructor(lhs, rhs) {
  5492. super(lhs, rhs, '<=');
  5493. }
  5494. });
  5495. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5496. constructor(lhs, rhs) {
  5497. super(lhs, rhs, '<');
  5498. }
  5499. });
  5500. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5501. constructor(lhs, rhs) {
  5502. super(lhs, rhs, '>');
  5503. }
  5504. });
  5505. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5506. constructor(lhs, rhs) {
  5507. super(lhs, rhs, '==');
  5508. }
  5509. });
  5510. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5511. });
  5512. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5513. __str__() {
  5514. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5515. }
  5516. });
  5517. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5518. if (a instanceof sympy.core.expr.Expr) {
  5519. return a;
  5520. }
  5521. const p = ast.parse(a);
  5522. const sympify = (node) => {
  5523. if (node instanceof ast.Call) {
  5524. switch (node.func.id) {
  5525. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5526. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5527. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5528. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5529. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5530. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5531. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5532. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5533. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5534. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5535. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5536. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5537. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5538. }
  5539. }
  5540. if (node instanceof ast.Name) {
  5541. return new sympy.core.symbol.Symbol(node.id);
  5542. }
  5543. if (node instanceof ast.Constant) {
  5544. if (node.type === 'int') {
  5545. return new sympy.core.numbers.Integer(node.value);
  5546. }
  5547. }
  5548. if (node instanceof ast.BinOp) {
  5549. if (node.op instanceof ast.Mult) {
  5550. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5551. }
  5552. if (node.op instanceof ast.Pow) {
  5553. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5554. }
  5555. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5556. }
  5557. if (node instanceof ast.Compare) {
  5558. const left = sympify(node.left);
  5559. const right = sympify(node.comparators[0]);
  5560. const [op] = node.ops;
  5561. if (op instanceof ast.Gt) {
  5562. return new sympy.core.relational.StrictGreaterThan(left, right);
  5563. }
  5564. if (op instanceof ast.GtE) {
  5565. return new sympy.core.relational.GreaterThan(left, right);
  5566. }
  5567. if (op instanceof ast.Lt) {
  5568. return new sympy.core.relational.StrictLessThan(left, right);
  5569. }
  5570. if (op instanceof ast.LtE) {
  5571. return new sympy.core.relational.LessThan(left, right);
  5572. }
  5573. if (op instanceof ast.Eq) {
  5574. return new sympy.core.relational.Equality(left, right);
  5575. }
  5576. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5577. }
  5578. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5579. };
  5580. return sympify(p.body[0].value);
  5581. });
  5582. this.registerFunction('theano.scalar.basic.same_out');
  5583. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5584. this.registerFunction('theano.scalar.basic.upcast_out');
  5585. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5586. this.registerFunction('theano.tensor.nnet.conv2d');
  5587. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5588. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5589. this.registerType('torch.nn.modules.module.Module', class {
  5590. constructor() {
  5591. this._modules = new collections.OrderedDict();
  5592. this._parameters = new collections.OrderedDict();
  5593. this._buffers = new collections.OrderedDict();
  5594. }
  5595. __setattr__(name, value) {
  5596. if (value instanceof torch.nn.modules.module.Module) {
  5597. this._modules.set(name, value);
  5598. } else {
  5599. this[name] = value;
  5600. }
  5601. }
  5602. __getattr__(name) {
  5603. if (this._modules.has(name)) {
  5604. return this._modules.get(name);
  5605. }
  5606. return this[name];
  5607. }
  5608. __delattr__(name) {
  5609. if (this._modules.has(name)) {
  5610. this._modules.delete(name);
  5611. }
  5612. }
  5613. children() {
  5614. return this._modules.values();
  5615. }
  5616. named_modules(memo, prefix, remove_duplicate) {
  5617. memo = memo || new Set();
  5618. prefix = prefix || '';
  5619. const modules = new builtins.dict();
  5620. if (!memo.has(this)) {
  5621. if (remove_duplicate) {
  5622. memo.add(this);
  5623. }
  5624. modules.set(prefix, this);
  5625. for (const [name, module] of this._modules.items()) {
  5626. if (module && module.named_modules) {
  5627. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5628. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5629. modules.set(k, v);
  5630. }
  5631. }
  5632. }
  5633. }
  5634. return modules;
  5635. }
  5636. named_children() {
  5637. return this._modules;
  5638. }
  5639. parameters() {
  5640. return this._parameters.values();
  5641. }
  5642. named_parameters(recurse) {
  5643. if (recurse) {
  5644. throw new python.Error('Named parameters with recurse not implemented.');
  5645. }
  5646. return this._parameters;
  5647. }
  5648. buffers() {
  5649. return this._buffers.values();
  5650. }
  5651. named_buffers(recurse) {
  5652. if (recurse) {
  5653. throw new python.Error('Named parameters with recurse not implemented.');
  5654. }
  5655. return this._buffers;
  5656. }
  5657. _get_name() {
  5658. return this.__class__.__name__;
  5659. }
  5660. add_module(name, module) {
  5661. this._modules.set(name, module);
  5662. }
  5663. register_module(name, module) {
  5664. this.add_module(name, module);
  5665. }
  5666. });
  5667. torch.nn.Module = torch.nn.modules.module.Module;
  5668. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5669. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5670. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5671. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5672. this.registerType('torch._C.SchemaParser', class {
  5673. constructor(str, allow_typevars) {
  5674. this.L = new torch._C.Lexer(str);
  5675. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5676. }
  5677. parseName() {
  5678. const L = this.L;
  5679. let name = L.expect('id').text();
  5680. if (L.nextIf(':')) {
  5681. L.expect(':');
  5682. name = `${name}::${L.expect('ident').text()}`;
  5683. }
  5684. let overload_name = '';
  5685. if (L.nextIf('.')) {
  5686. overload_name = L.expect('ident').text();
  5687. }
  5688. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5689. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5690. return new torch._C.OperatorName(name, overload_name);
  5691. }
  5692. parseDeclaration() {
  5693. const L = this.L;
  5694. const name = this.parseName();
  5695. if (L.cur().kind !== '(') {
  5696. return name;
  5697. }
  5698. throw new python.Error('Not implemented.');
  5699. }
  5700. parseExactlyOneDeclaration() {
  5701. // const L = this.L;
  5702. const result = this.parseDeclaration();
  5703. // L.nextIf(TK_NEWLINE);
  5704. // L.expect(TK_EOF);
  5705. return result;
  5706. }
  5707. parseArgument(idx, is_return, kwarg_only) {
  5708. const L = this.L;
  5709. const type_parser = this.type_parser;
  5710. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5711. let N = null;
  5712. if (L.nextIf('[')) {
  5713. fake_type = torch.ListType.create(fake_type);
  5714. real_type = torch.ListType.create(real_type);
  5715. if (L.cur().kind === '#') {
  5716. N = Number(L.cur().text());
  5717. L.next();
  5718. }
  5719. L.expect(']');
  5720. let container = type_parser.parseAliasAnnotation();
  5721. if (alias_info) {
  5722. if (!container) {
  5723. container = new torch._C.AliasInfo();
  5724. container.is_write = alias_info.is_write;
  5725. }
  5726. container.addContainedType(alias_info);
  5727. }
  5728. alias_info = container;
  5729. if (L.nextIf('?')) {
  5730. fake_type = torch.OptionalType.create(fake_type);
  5731. real_type = torch.OptionalType.create(real_type);
  5732. }
  5733. }
  5734. let name = null;
  5735. /* eslint-disable no-undef-init */
  5736. let default_value = undefined;
  5737. /* eslint-enable no-undef-init */
  5738. if (is_return) {
  5739. kwarg_only = false;
  5740. if (L.cur().kind === 'id') {
  5741. name = L.next().text();
  5742. } else {
  5743. name = '';
  5744. }
  5745. } else {
  5746. name = L.expect('id').text();
  5747. if (L.nextIf('=')) {
  5748. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5749. }
  5750. }
  5751. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5752. }
  5753. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5754. // auto range = L.cur().range;
  5755. const L = this.L;
  5756. const range = null;
  5757. switch (kind) {
  5758. case torch._C.TypeKind.StringType:
  5759. case torch._C.TypeKind.OptionalType:
  5760. case torch._C.TypeKind.NumberType:
  5761. case torch._C.TypeKind.IntType:
  5762. case torch._C.TypeKind.BoolType:
  5763. case torch._C.TypeKind.FloatType:
  5764. case torch._C.TypeKind.ComplexType:
  5765. return this.parseSingleConstant(arg_type, kind, real_type);
  5766. case torch._C.TypeKind.ListType: {
  5767. const elem_type = arg_type.containedType(0);
  5768. const real_elem_type = real_type.containedType(0);
  5769. if (L.cur().kind === 'id') {
  5770. return this.parseTensorDefault(range);
  5771. } else if (arg_N && L.cur().kind !== '[') {
  5772. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5773. const repeated = Array(arg_N).fill(v);
  5774. // std::vector<IValue> repeated(arg_N, v);
  5775. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5776. }
  5777. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5778. }
  5779. case torch._C.TypeKind.DynamicType:
  5780. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5781. default:
  5782. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5783. }
  5784. }
  5785. parseSingleConstant(type, kind, real_type) {
  5786. const L = this.L;
  5787. if (kind === torch._C.TypeKind.DynamicType) {
  5788. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5789. }
  5790. // const auto& str2dtype = c10::getStringToDtypeMap();
  5791. if (L.cur().kind === 'id') {
  5792. if (L.cur().text() === 'True') {
  5793. L.next();
  5794. return new torch._C.IValue(true);
  5795. }
  5796. if (L.cur().text() === 'False') {
  5797. L.next();
  5798. return new torch._C.IValue(false);
  5799. }
  5800. if (L.cur().text() === 'None') {
  5801. L.next();
  5802. return new torch._C.IValue();
  5803. }
  5804. } else if (L.cur().kind === 'string') {
  5805. const token = L.next();
  5806. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5807. } else if (L.cur().kind === '#') {
  5808. let n = '';
  5809. if (L.nextIf('-')) {
  5810. n = `-${L.expect('#').text()}`; // # .text();
  5811. } else {
  5812. n = L.expect('#').text(); // # .text();
  5813. }
  5814. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5815. throw new Error("Complex type not implemented.");
  5816. /*
  5817. const imag = std::stod(n.substr(0, n.size() - 1));
  5818. return c10::complex<double>(0, imag);
  5819. */
  5820. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5821. const v = parseFloat(n);
  5822. return new torch._C.IValue(v, 'Double');
  5823. } else {
  5824. const v = parseInt(n, 10);
  5825. return new torch._C.IValue(v, 'Int');
  5826. }
  5827. }
  5828. throw new python.Error('Not implemented.');
  5829. /*
  5830. switch (L.cur().kind) {
  5831. case TK_TRUE:
  5832. L.next();
  5833. return true;
  5834. case TK_FALSE:
  5835. L.next();
  5836. return false;
  5837. case TK_NONE:
  5838. L.next();
  5839. return IValue();
  5840. case TK_STRINGLITERAL: {
  5841. const token = L.next();
  5842. return parseStringLiteral(token.range, token.text());
  5843. }
  5844. case TK_IDENT: {
  5845. const tok = L.next();
  5846. const text_view = tok.text_view();
  5847. // NB: float/complex/long are here for BC purposes. Other dtypes
  5848. // are handled via str2dtype.
  5849. // Please don't add more cases to this if-else block.
  5850. if ("float" == text_view) {
  5851. return static_cast<int64_t>("at::kFloat");
  5852. } else if ("complex" == text_view) {
  5853. return static_cast<int64_t>("at::kComplexFloat");
  5854. } else if ("long" == text_view) {
  5855. return static_cast<int64_t>("at::kLong");
  5856. } else if ("strided" == text_view) {
  5857. return static_cast<int64_t>("at::kStrided");
  5858. } else if ("Mean" == text_view) {
  5859. return static_cast<int64_t>("at::Reduction::Mean");
  5860. } else if ("contiguous_format" == text_view) {
  5861. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5862. } else {
  5863. const text = tok.text();
  5864. if (isPossiblyOptionalScalarType(real_type) &&
  5865. str2dtype.count(text) > 0) {
  5866. return static_cast<int64_t>(str2dtype.at(text));
  5867. } else {
  5868. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5869. }
  5870. }
  5871. }
  5872. default: {
  5873. let n;
  5874. if (L.nextIf('-')) {
  5875. n = "-" + L.expect(TK_NUMBER).text();
  5876. }
  5877. else {
  5878. n = L.expect(TK_NUMBER).text();
  5879. }
  5880. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5881. throw new python.Error('Complex type not implemented.');
  5882. const imag = std::stod(n.substr(0, n.size() - 1));
  5883. return c10::complex<double>(0, imag);
  5884. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5885. throw new python.Error('Float type not implemented.');
  5886. return std::stod(n);
  5887. } else {
  5888. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5889. int64_t v = std::stoll(n);
  5890. return v;
  5891. }
  5892. }
  5893. }
  5894. */
  5895. }
  5896. parseConstantList(type, kind, real_type) {
  5897. const L = this.L;
  5898. const tok = L.expect('[');
  5899. const vs = [];
  5900. if (L.cur().kind !== ']') {
  5901. do {
  5902. vs.push(this.parseSingleConstant(type, kind, real_type));
  5903. } while (L.nextIf(','));
  5904. }
  5905. L.expect(']');
  5906. return this.convertToList(type, kind, tok.range, vs);
  5907. }
  5908. convertToList(type, kind, range, vs) {
  5909. switch (kind) {
  5910. case torch._C.TypeKind.ComplexType:
  5911. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5912. case torch._C.TypeKind.FloatType:
  5913. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5914. case torch._C.TypeKind.IntType:
  5915. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5916. case torch._C.TypeKind.BoolType:
  5917. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5918. case torch._C.TypeKindDynamicType:
  5919. return this.convertToList(type.dynamicKind(), range, vs);
  5920. default:
  5921. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5922. throw new python.Error('lists are only supported for float, int and complex types');
  5923. }
  5924. }
  5925. });
  5926. this.registerType('torch.FunctionSchema', class {
  5927. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5928. const index = name.indexOf('(');
  5929. if (index === -1) {
  5930. this._name = name;
  5931. this._overload_name = overload_name || '';
  5932. this._arguments = args || [];
  5933. this._returns = returns || [];
  5934. this._is_vararg = is_vararg || false;
  5935. this._is_varret = is_varret || false;
  5936. } else {
  5937. const value = name.substring(0, index).trim();
  5938. const dot = value.indexOf('.');
  5939. if (dot === -1) {
  5940. this._name = value;
  5941. this._overload_name = '';
  5942. } else {
  5943. this._name = value.substring(0, dot);
  5944. this._overload_name = value.substring(dot + 1, value.length);
  5945. }
  5946. this._buffer = name.substring(index, name.length);
  5947. }
  5948. }
  5949. static parse(schema) {
  5950. return new torch.FunctionSchema(schema);
  5951. }
  5952. get name() {
  5953. return this._name;
  5954. }
  5955. get overload_name() {
  5956. return this._overload_name;
  5957. }
  5958. get arguments() {
  5959. this._parse();
  5960. return this._arguments;
  5961. }
  5962. get returns() {
  5963. this._parse();
  5964. return this._returns;
  5965. }
  5966. get is_vararg() {
  5967. this._parse();
  5968. return this._is_vararg;
  5969. }
  5970. get is_varret() {
  5971. this._parse();
  5972. return this._is_varret;
  5973. }
  5974. argumentIndexWithName(name) {
  5975. const index = this.arguments.findIndex((arg) => arg.name === name);
  5976. return index === -1 ? null : index;
  5977. }
  5978. _parse() {
  5979. if (this._buffer) {
  5980. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  5981. const L = parser.L;
  5982. this._arguments = [];
  5983. this._is_vararg = false;
  5984. this._kwarg_only = false;
  5985. let idx = 0;
  5986. L.expect('(');
  5987. if (!L.nextIf(')')) {
  5988. while (true) {
  5989. if (this._is_vararg) {
  5990. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  5991. }
  5992. if (L.nextIf('*')) {
  5993. this._kwarg_only = true;
  5994. } else if (L.nextIf('...')) {
  5995. this._is_vararg = true;
  5996. } else {
  5997. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  5998. this._arguments.push(argument);
  5999. }
  6000. if (!L.nextIf(',')) {
  6001. break;
  6002. }
  6003. }
  6004. L.expect(')');
  6005. }
  6006. L.expect('->');
  6007. this._returns = [];
  6008. this._is_varret = false;
  6009. if (L.nextIf('...')) {
  6010. this._is_varret = true;
  6011. } else if (L.nextIf('(')) {
  6012. if (!L.nextIf(')')) {
  6013. while (true) {
  6014. if (this._is_varret) {
  6015. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6016. }
  6017. if (L.nextIf('...')) {
  6018. this._is_varret = true;
  6019. } else {
  6020. const argument = parser.parseArgument(idx++, true, false);
  6021. this._returns.push(argument);
  6022. }
  6023. if (!L.nextIf(',')) {
  6024. break;
  6025. }
  6026. }
  6027. L.expect(')');
  6028. }
  6029. } else {
  6030. this._returns.push(parser.parseArgument(0, true, false));
  6031. }
  6032. delete this._buffer;
  6033. }
  6034. }
  6035. __str__() {
  6036. const list = [this.name];
  6037. const overload_name = this.overload_name;
  6038. if (overload_name !== '' && overload_name !== 'default') {
  6039. list.push(`.${this.overload_name}`);
  6040. }
  6041. list.push('(');
  6042. let first = true;
  6043. let kwarg_only = false;
  6044. for (const argument of this.arguments) {
  6045. if (!first) {
  6046. list.push(', ');
  6047. }
  6048. if (argument.kwarg_only && !kwarg_only) {
  6049. list.push('*, ');
  6050. kwarg_only = true;
  6051. }
  6052. first = false;
  6053. list.push(argument.str());
  6054. }
  6055. if (this.is_vararg) {
  6056. if (!first) {
  6057. list.push(', ');
  6058. }
  6059. first = true;
  6060. list.push('...');
  6061. }
  6062. list.push(') -> ');
  6063. const returns = this.returns;
  6064. const braces = !this.is_varret &&
  6065. (returns.length !== 1 ||
  6066. returns[0].name ||
  6067. returns[0].real_type instanceof torch.TupleType ||
  6068. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6069. if (braces) {
  6070. list.push('(');
  6071. }
  6072. first = true;
  6073. for (const argument of this.returns) {
  6074. if (!first) {
  6075. list.push(', ');
  6076. }
  6077. first = false;
  6078. list.push(argument.str());
  6079. }
  6080. if (this.is_varret) {
  6081. if (!first) {
  6082. list.push(', ');
  6083. }
  6084. first = true;
  6085. list.push('...');
  6086. }
  6087. if (braces) {
  6088. list.push(')');
  6089. }
  6090. return list.join('');
  6091. }
  6092. aliasAnalysis() {
  6093. return this._alias_kind || 'CONSERVATIVE';
  6094. }
  6095. setAliasAnalysis(v) {
  6096. this._alias_kind = v;
  6097. }
  6098. hasAnyAliasInfo() {
  6099. for (const arg of this.arguments) {
  6100. if (arg.alias_info !== null) {
  6101. return true;
  6102. }
  6103. }
  6104. for (const ret of this.returns) {
  6105. if (ret.alias_info !== null) {
  6106. return true;
  6107. }
  6108. }
  6109. return false;
  6110. }
  6111. is_mutable() {
  6112. return this.arguments.some((arg) => {
  6113. const aliasInfo = arg.alias_info;
  6114. return aliasInfo && aliasInfo.is_write;
  6115. });
  6116. }
  6117. });
  6118. this.registerType('torch._C.SchemaInfo', class {
  6119. constructor(schema) {
  6120. this._schema = schema;
  6121. this._alias_maps_current = false;
  6122. this._has_init = false;
  6123. }
  6124. is_nondeterministic() {
  6125. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6126. //
  6127. }
  6128. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6129. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6130. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6131. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6132. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6133. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6134. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6135. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6136. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6137. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6138. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6139. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6140. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6141. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6142. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6143. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6144. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6145. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6146. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6147. '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',
  6148. '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',
  6149. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6150. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6151. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6152. ]);
  6153. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6154. return true;
  6155. }
  6156. /*
  6157. const auto& op = c10::Dispatcher::singleton().findOp(
  6158. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6159. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6160. */
  6161. return false;
  6162. }
  6163. });
  6164. this.registerType('torch._C.OperatorRegistry', class {
  6165. constructor() {
  6166. this.to_register = [];
  6167. this.operators = new Map();
  6168. }
  6169. registerPendingOperators() {
  6170. for (const op of this.to_register) {
  6171. const sym = op.schema().name;
  6172. if (!this.operators.has(sym)) {
  6173. this.operators.set(sym, []);
  6174. }
  6175. this.operators.get(sym).push(op);
  6176. }
  6177. this.to_register = [];
  6178. }
  6179. registerOperator(op) {
  6180. this.to_register.push(op);
  6181. }
  6182. getOperators(name) {
  6183. this.registerPendingOperators();
  6184. if (this.operators.has(name)) {
  6185. return this.operators.get(name);
  6186. }
  6187. return [];
  6188. }
  6189. });
  6190. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6191. return torch._C.getRegistry().getOperators(name);
  6192. });
  6193. this.registerType('torch._C.Operator', class {
  6194. constructor(schema) {
  6195. this._schema = schema;
  6196. }
  6197. schema() {
  6198. return this._schema;
  6199. }
  6200. getOperation(/* node */) {
  6201. return null;
  6202. }
  6203. aliasAnalysisKind() {
  6204. const schemaRef = this.schema();
  6205. const alias_analysis = schemaRef.aliasAnalysis();
  6206. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6207. return alias_analysis;
  6208. }
  6209. });
  6210. this.registerFunction('torch._C.getRegistry', () => {
  6211. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6212. return torch._C.r;
  6213. });
  6214. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6215. const operations = torch._C.getAllOperatorsFor(op_name);
  6216. for (const op of operations) {
  6217. if (op.schema().overload_name === overload_name) {
  6218. return op.schema();
  6219. }
  6220. }
  6221. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6222. });
  6223. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6224. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6225. });
  6226. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6227. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6228. if (sortedOps.length === 0) {
  6229. return [null, null];
  6230. }
  6231. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6232. return [{}, overload_names];
  6233. });
  6234. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6235. const operations = torch._C.getAllOperatorsFor(op_name);
  6236. for (const op of operations) {
  6237. if (op.schema().overload_name === overload_name) {
  6238. return [{}, {}, null];
  6239. }
  6240. }
  6241. return null;
  6242. });
  6243. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6244. return null;
  6245. });
  6246. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6247. });
  6248. this.registerType('torch._C.MatchedSchema', class {
  6249. constructor(inputs, return_types, return_field_names, schema_name) {
  6250. this.inputs = inputs;
  6251. this.return_types = return_types;
  6252. this.register_field_names = return_field_names;
  6253. this.schema_name = schema_name;
  6254. }
  6255. });
  6256. this.registerType('torch._C.Self', class {
  6257. });
  6258. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6259. return nvs.map((v) => v.value(g));
  6260. });
  6261. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6262. constructor(classType) {
  6263. super();
  6264. this._classType = classType;
  6265. }
  6266. makeSugared(v) {
  6267. v.setType(this._classType);
  6268. return new torch._C.SimpleValue(v);
  6269. }
  6270. getClassType() {
  6271. return this._classType;
  6272. }
  6273. });
  6274. this.registerType('torch._C.Function', class {
  6275. isGraphFunction() {
  6276. return false;
  6277. }
  6278. name() {
  6279. return this.qualname().name();
  6280. }
  6281. });
  6282. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6283. constructor(qualname, schema) {
  6284. super();
  6285. this._name = qualname;
  6286. this._schema = schema;
  6287. }
  6288. qualname() {
  6289. return this._name;
  6290. }
  6291. getSchema() {
  6292. return this._schema;
  6293. }
  6294. ensure_defined() {
  6295. }
  6296. });
  6297. this.registerType('torch._C.DeadCodeEliminator', class {
  6298. constructor(...args) {
  6299. this._aliasDb = null;
  6300. this._useAliasDb = false;
  6301. this._memo = new Map();
  6302. this._marked = new Set();
  6303. this._liveValues = new Set();
  6304. this._deleteCallback = () => {};
  6305. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6306. [this._graph, this._sideEffectPolicy] = args;
  6307. this._useAliasDb = true;
  6308. } else {
  6309. [this._sideEffectPolicy] = args;
  6310. }
  6311. }
  6312. run(block, recurse) {
  6313. this.eliminateDeadForkInputs(block, recurse);
  6314. this.mark(block.return_node());
  6315. this.mark(block);
  6316. this._deleteCallback(this._liveValues);
  6317. this.sweep(block, recurse);
  6318. }
  6319. setDeleteCallback(deleteCallback) {
  6320. this._deleteCallback = deleteCallback;
  6321. }
  6322. eliminateDeadForkInputs(block, recurse) {
  6323. for (const node of block.nodes()) {
  6324. if (recurse) {
  6325. for (const sb of node.blocks()) {
  6326. this.eliminateDeadForkInputs(sb, recurse);
  6327. }
  6328. }
  6329. if (node.kind() !== 'prim::fork') {
  6330. continue;
  6331. }
  6332. const g = node.g("Subgraph");
  6333. for (let i = 0; i < g.inputs().length; i++) {
  6334. if (!g.inputs()[i].hasUses()) {
  6335. g.eraseInput(i);
  6336. node.removeInput(i);
  6337. }
  6338. }
  6339. }
  6340. }
  6341. markReturnNode(node) {
  6342. if (this._marked.has(node)) {
  6343. return false;
  6344. }
  6345. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6346. const outerNode = node.owningBlock().owningNode();
  6347. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6348. return this.mark(node);
  6349. }
  6350. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6351. const loop = new torch._C.LoopView(outerNode);
  6352. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6353. if (outerNode.kind() === 'onnx::Loop') {
  6354. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6355. continue;
  6356. }
  6357. const innerInput = loop.bodyCarriedInputs()[i];
  6358. const innerOutput = loop.bodyCarriedOutputs()[i];
  6359. const outerOutput = loop.carriedOutputs()[i];
  6360. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6361. this._liveValues.add(innerOutput);
  6362. }
  6363. }
  6364. this._liveValues.add(loop.nextCond());
  6365. } else {
  6366. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6367. for (let i = 0; i < outerNode.outputs().length; i++) {
  6368. const innerOutput = node.inputs()[i];
  6369. const outerOutput = outerNode.outputs()[i];
  6370. if (!this._liveValues.has(outerOutput)) {
  6371. this._liveValues.add(innerOutput);
  6372. }
  6373. }
  6374. }
  6375. this._marked.add(node);
  6376. return true;
  6377. }
  6378. markLoop(node) {
  6379. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6380. let marked = false;
  6381. let anyMarked = false;
  6382. do {
  6383. marked = this.mark(node.blocks().at(0));
  6384. anyMarked = anyMarked || marked;
  6385. } while (marked);
  6386. return anyMarked;
  6387. }
  6388. mark(...args) {
  6389. if (args.length === 1 && args[0] instanceof torch.Block) {
  6390. const [block] = args;
  6391. let anyMarked = false;
  6392. for (const node of block.nodes()) {
  6393. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6394. const marked = this.mark(node);
  6395. anyMarked = anyMarked || marked;
  6396. }
  6397. }
  6398. const marked = this.markReturnNode(block.return_node());
  6399. anyMarked = anyMarked || marked;
  6400. for (const node of block.nodes()) {
  6401. if (node.kind() === 'prim::Loop') {
  6402. const marked = this.markLoop(node);
  6403. anyMarked = anyMarked || marked;
  6404. } else {
  6405. for (const subBlock of node.blocks()) {
  6406. const marked = this.mark(subBlock);
  6407. anyMarked = anyMarked || marked;
  6408. }
  6409. }
  6410. const marked = this.markIfLive(node);
  6411. anyMarked = anyMarked || marked;
  6412. }
  6413. return anyMarked;
  6414. }
  6415. if (args.length === 1 && args[0] instanceof torch.Node) {
  6416. const [node] = args;
  6417. if (this._marked.has(node)) {
  6418. return false;
  6419. }
  6420. this._marked.add(node);
  6421. let curNode = node;
  6422. while (curNode && curNode.owningBlock()) {
  6423. this.mark(curNode);
  6424. curNode = curNode.owningBlock().owningNode();
  6425. }
  6426. for (const input of node.inputs()) {
  6427. if (!this._liveValues.has(input)) {
  6428. this._liveValues.add(input);
  6429. }
  6430. }
  6431. return true;
  6432. }
  6433. throw new python.Error('Not implemented.');
  6434. }
  6435. markIfLive(node) {
  6436. for (const output of node.outputs()) {
  6437. if (this._liveValues.has(output)) {
  6438. return this.mark(node);
  6439. }
  6440. }
  6441. if (this._useAliasDb) {
  6442. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6443. return this.mark(node);
  6444. }
  6445. }
  6446. return false;
  6447. }
  6448. sweep(block, recurse) {
  6449. const nodes = Array.from(block.nodes()).reverse();
  6450. for (const node of nodes) {
  6451. this.removeDeadBlockOutputs(node);
  6452. this.removeDeadLoopOutputs(node);
  6453. if (recurse) {
  6454. for (const block of node.blocks()) {
  6455. this.sweep(block, true);
  6456. }
  6457. }
  6458. if (!this._marked.has(node) && !node.hasUses()) {
  6459. node.destroy();
  6460. }
  6461. }
  6462. }
  6463. hasUntrackedMutation(node) {
  6464. if (!this._useAliasDb) {
  6465. if (node.kind() === 'prim::SetAttr') {
  6466. return true;
  6467. }
  6468. const schema = node.maybeSchema();
  6469. return schema && schema.is_mutable();
  6470. }
  6471. return this.getOrCreateAliasDb().writesToWildcard(node);
  6472. }
  6473. hasSideEffects(node) {
  6474. const it = this._memo.get(node);
  6475. if (it) {
  6476. return it;
  6477. }
  6478. const has_side_effects = node.hasSideEffects() ||
  6479. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6480. this.hasUntrackedMutation(node);
  6481. this._memo.set(node, has_side_effects);
  6482. return has_side_effects;
  6483. }
  6484. removeDeadBlockOutputs(node) {
  6485. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6486. return;
  6487. }
  6488. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6489. const i = i_1 - 1;
  6490. if (!node.outputs()[i].hasUses()) {
  6491. node.eraseOutput(i);
  6492. for (const b of node.blocks()) {
  6493. b.eraseOutput(i);
  6494. }
  6495. }
  6496. }
  6497. }
  6498. removeDeadLoopOutputs() {
  6499. }
  6500. getOrCreateAliasDb() {
  6501. if (!this._aliasDb) {
  6502. this._aliasDb = new torch._C.AliasDb(this._graph);
  6503. }
  6504. return this._aliasDb;
  6505. }
  6506. });
  6507. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6508. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6509. const [graph] = args;
  6510. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6511. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6512. worker.run(graph.block(), /*recurse=*/true);
  6513. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6514. const [block] = args;
  6515. const recurse = false;
  6516. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6517. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6518. worker.run(block, recurse);
  6519. } else {
  6520. throw new python.Error('Not implemented.');
  6521. }
  6522. });
  6523. this.registerFunction('torch._C.removeTupleNodes', () => {
  6524. });
  6525. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6526. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6527. const [graph] = args;
  6528. torch._C.LowerSimpleTuples(graph.block());
  6529. torch._C.EliminateDeadCode(graph);
  6530. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6531. const [block] = args;
  6532. for (const n of block.nodes()) {
  6533. torch._C.removeTupleNodes(n, false);
  6534. for (const b of n.blocks()) {
  6535. torch._C.LowerSimpleTuples(b);
  6536. }
  6537. }
  6538. } else {
  6539. throw new python.Error('Not implemented.');
  6540. }
  6541. });
  6542. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6543. torch._C.AT_ASSERT(lhs !== null);
  6544. torch._C.AT_ASSERT(rhs !== null);
  6545. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6546. return false;
  6547. }
  6548. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6549. return true;
  6550. }
  6551. const lnames = lhs.attributeNames();
  6552. const rnames = rhs.attributeNames();
  6553. lnames.sort();
  6554. rnames.sort();
  6555. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6556. return false;
  6557. }
  6558. for (const name of lnames) {
  6559. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6560. return false;
  6561. }
  6562. const kind = lhs.kindOf(name);
  6563. switch (kind) {
  6564. case 'i':
  6565. case 'f':
  6566. case 's':
  6567. case 't': {
  6568. if (lhs[kind](name) !== rhs[kind](name)) {
  6569. return false;
  6570. }
  6571. break;
  6572. }
  6573. case 'ival': {
  6574. if (lhs[kind](name) !== rhs[kind](name)) {
  6575. return false;
  6576. }
  6577. break;
  6578. }
  6579. default: {
  6580. throw new python.Error('Not implemented.');
  6581. }
  6582. }
  6583. }
  6584. return true;
  6585. });
  6586. this.registerFunction('torch._C.get_hash', (...args) => {
  6587. let hash = 0;
  6588. for (const value of args) {
  6589. if (typeof value === 'number') {
  6590. hash += (value | 0);
  6591. } else if (typeof value === 'string') {
  6592. hash += (value.length | 0);
  6593. } else if (Array.isArray(value)) {
  6594. for (const item of value) {
  6595. hash += torch._C.get_hash(item);
  6596. }
  6597. }
  6598. }
  6599. return hash;
  6600. });
  6601. this.registerFunction('torch._C.HashNode', (k) => {
  6602. torch._C.AT_ASSERT(k !== null);
  6603. let constant_hash = 0;
  6604. if (k.kind() === 'prim::Constant') {
  6605. const type = k.output().type();
  6606. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6607. constant_hash = k.i('value');
  6608. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6609. constant_hash = k.f('value');
  6610. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6611. constant_hash = k.c('value');
  6612. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6613. constant_hash = k.i('value');
  6614. }
  6615. }
  6616. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6617. });
  6618. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6619. if (lhs === null && rhs === null) {
  6620. return true;
  6621. }
  6622. if (lhs === null || rhs === null) {
  6623. return false;
  6624. }
  6625. if (lhs.kind() !== rhs.kind()) {
  6626. return false;
  6627. }
  6628. const lhs_outputs = lhs.outputs();
  6629. const rhs_outputs = rhs.outputs();
  6630. if (lhs_outputs.length !== rhs_outputs.length) {
  6631. return false;
  6632. }
  6633. for (let i = 0; i < lhs_outputs.length; i++) {
  6634. const lt = lhs_outputs[i].type();
  6635. const rt = rhs_outputs[i].type();
  6636. if (!lt.equals(rt)) {
  6637. return false;
  6638. }
  6639. }
  6640. const lhs_inputs = lhs.inputs();
  6641. const rhs_inputs = rhs.inputs();
  6642. if (lhs_inputs.length !== rhs_inputs.length) {
  6643. return false;
  6644. }
  6645. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6646. return false;
  6647. }
  6648. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6649. return false;
  6650. }
  6651. if (lhs.blocks().length !== rhs.blocks().length) {
  6652. return false;
  6653. }
  6654. for (let i = 0; i < lhs.blocks().length; i++) {
  6655. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6656. return false;
  6657. }
  6658. }
  6659. return true;
  6660. });
  6661. this.registerType('torch._C.NodeSet', class {
  6662. constructor() {
  6663. this._nodes = new Map();
  6664. }
  6665. insert(n) {
  6666. const key = torch._C.HashNode(n);
  6667. if (this._nodes.has(key)) {
  6668. this._nodes.get(key).push(n);
  6669. } else {
  6670. this._nodes.set(key, [n]);
  6671. }
  6672. }
  6673. get(n) {
  6674. const key = torch._C.HashNode(n);
  6675. if (this._nodes.has(key)) {
  6676. const nodes = this._nodes.get(key);
  6677. for (const node of nodes) {
  6678. if (torch._C.EqualNode(node, n)) {
  6679. return node;
  6680. }
  6681. }
  6682. }
  6683. return null;
  6684. }
  6685. has(n) {
  6686. return this.get(n) !== null;
  6687. }
  6688. });
  6689. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6690. const ty = stack.pop().type();
  6691. for (const candidate of types) {
  6692. if (ty.isSubtypeOf(candidate)) {
  6693. stack.push(new torch._C.IValue(true, 'Bool'));
  6694. stack.push(true);
  6695. return;
  6696. }
  6697. }
  6698. stack.push(new torch._C.IValue(false, 'Bool'));
  6699. });
  6700. this.registerType('torch._C.Tuple', class {
  6701. constructor(elements) {
  6702. this._elements = elements;
  6703. }
  6704. static create(elements) {
  6705. return new torch._C.Tuple(elements);
  6706. }
  6707. elements() {
  6708. return this._elements;
  6709. }
  6710. });
  6711. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6712. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6713. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6714. const tuple = torch._C.Tuple.create(elems.reverse());
  6715. stack.push(new torch._C.IValue(tuple));
  6716. });
  6717. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6718. let stack = [];
  6719. for (const input of n.inputs()) {
  6720. const ival = torch._C.toIValue(input);
  6721. if (ival) {
  6722. stack.push(ival);
  6723. } else {
  6724. return null;
  6725. }
  6726. }
  6727. switch (n.kind()) {
  6728. case 'prim::ListUnpack': {
  6729. if (stack.back().toList().size() !== n.outputs().length) {
  6730. return null;
  6731. }
  6732. torch._C.listUnpack(stack, n.outputs().length);
  6733. break;
  6734. }
  6735. case 'prim::TupleConstruct': {
  6736. const tt = n.output().type().expect(torch.TupleType);
  6737. if (tt.name()) {
  6738. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6739. } else {
  6740. torch._C.tupleConstruct(stack, n.inputs().length);
  6741. }
  6742. break;
  6743. }
  6744. case 'prim::ListConstruct': {
  6745. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6746. break;
  6747. }
  6748. case 'prim::DictConstruct': {
  6749. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6750. break;
  6751. }
  6752. case 'prim::CreateObject': {
  6753. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6754. break;
  6755. }
  6756. case 'prim::GetAttr': {
  6757. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6758. torch._C.push(stack, attr);
  6759. break;
  6760. }
  6761. case 'prim::isinstance': {
  6762. torch._C.isinstance(stack, n.tys('types'));
  6763. break;
  6764. }
  6765. default: {
  6766. const maybe_schema = n.maybeSchema();
  6767. if (maybe_schema && maybe_schema.is_vararg) {
  6768. return null;
  6769. }
  6770. // try
  6771. // {
  6772. // const op = n.getOperation();
  6773. // op(stack);
  6774. const [module, name] = n.kind().split('::');
  6775. const obj = torch.ops[module];
  6776. if (!obj) {
  6777. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6778. }
  6779. const fn = torch.ops[module].__getattr__(name);
  6780. if (!fn || !fn.__call__) {
  6781. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6782. }
  6783. const args = stack.map((v) => v.value);
  6784. const result = fn.__call__(...args);
  6785. if (result === undefined) {
  6786. stack = [];
  6787. } else if (result instanceof torch._C.IValue) {
  6788. stack = [result];
  6789. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6790. stack = result;
  6791. } else {
  6792. stack = [new torch._C.IValue(result)];
  6793. }
  6794. // } catch {
  6795. // stack = [];
  6796. // return null;
  6797. // }
  6798. break;
  6799. }
  6800. }
  6801. for (const v of stack) {
  6802. if (v.isTensor()) {
  6803. const t = v.toTensor();
  6804. if (t.defined() && t.requires_grad()) {
  6805. return null;
  6806. }
  6807. }
  6808. if (ignore_custom_classes) {
  6809. if (v.isCustomClass()) {
  6810. return null;
  6811. }
  6812. }
  6813. if (v.isCustomClass()) {
  6814. if (v.toObject().is_weak_compilation_ref()) {
  6815. continue;
  6816. }
  6817. if (!db) {
  6818. continue;
  6819. }
  6820. const n_non_const = n;
  6821. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6822. continue;
  6823. }
  6824. const obj = v.toObject();
  6825. obj.unsafe_make_weak_compilation_ref();
  6826. }
  6827. if (v.isObject()) {
  6828. if (!v.toObject().is_weak_compilation_ref()) {
  6829. return null;
  6830. }
  6831. }
  6832. }
  6833. return stack;
  6834. });
  6835. this.registerType('torch._C.ConstantPropagator', class {
  6836. constructor(graph, aliasing_types, ignore_custom_classes) {
  6837. this._made_change = false;
  6838. this._graph = graph;
  6839. this._aliasing_types = aliasing_types;
  6840. this._ignore_custom_classes = ignore_custom_classes;
  6841. }
  6842. static NoAliasDb(graph) {
  6843. return new torch._C.ConstantPropagator(graph, false, false);
  6844. }
  6845. run() {
  6846. this.ConstantPropagation(this._graph.block());
  6847. return this._made_change;
  6848. }
  6849. propagateNode(n) {
  6850. let outputs = [];
  6851. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6852. if (outputs_opt) {
  6853. outputs = outputs_opt;
  6854. const graph = n.owningGraph();
  6855. const guard = new torch._C.WithInsertPoint(n);
  6856. for (let i = 0; i < outputs.length; i++) {
  6857. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6858. if (new_output) {
  6859. this._made_change = true;
  6860. if (outputs[i].isNone()) {
  6861. new_output.setType(n.outputs()[i].type());
  6862. }
  6863. n.outputs()[i].replaceAllUsesWith(new_output);
  6864. }
  6865. }
  6866. guard.dispose();
  6867. }
  6868. }
  6869. removeLoopNode(n) {
  6870. const loop_input_offset = 2;
  6871. for (let i = 0; i < n.outputs().length; i++) {
  6872. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6873. }
  6874. this._made_change = true;
  6875. n.destroy();
  6876. }
  6877. loopWillNotRun(node) {
  6878. const [trip_count, start_cond] = node.inputs();
  6879. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6880. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6881. const loop_might_run = cond_val && iter_len > 0;
  6882. return !loop_might_run;
  6883. }
  6884. inlineIfBody(body) {
  6885. const n = body.owningNode();
  6886. for (const body_node of body.nodes()) {
  6887. body_node.moveBefore(n);
  6888. }
  6889. for (let i = 0; i < n.outputs().length; i++) {
  6890. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6891. }
  6892. n.destroy();
  6893. }
  6894. inlineIf(n) {
  6895. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6896. torch._C.AT_ASSERT(input_bool !== null);
  6897. const block_index = input_bool ? 0 : 1;
  6898. this.ConstantPropagation(n.blocks().at(block_index));
  6899. this.inlineIfBody(n.blocks().at(block_index));
  6900. this._made_change = true;
  6901. }
  6902. replaceAndRemoveIfOutput(n, i, replacement) {
  6903. n.outputs()[i].replaceAllUsesWith(replacement);
  6904. n.eraseOutput(i);
  6905. n.blocks().at(0).eraseOutput(i);
  6906. n.blocks().at(1).eraseOutput(i);
  6907. }
  6908. removeExtraIfOutputs(n) {
  6909. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6910. const [true_block, false_block] = n.blocks();
  6911. const graph = n.owningGraph();
  6912. const initial_outputs = true_block.outputs().length;
  6913. const guard = new torch._C.WithInsertPoint(n);
  6914. for (let i = 0; i < true_block.outputs().length;) {
  6915. const t_out = true_block.outputs()[i];
  6916. const f_out = false_block.outputs()[i];
  6917. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6918. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6919. continue;
  6920. }
  6921. const maybe_const = torch._C.toIValue(t_out);
  6922. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6923. const new_const = graph.insertConstant(maybe_const);
  6924. this.replaceAndRemoveIfOutput(n, i, new_const);
  6925. continue;
  6926. }
  6927. i++;
  6928. }
  6929. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6930. guard.dispose();
  6931. }
  6932. removeExtraLoopOutputs(node) {
  6933. const initial_outputs = node.outputs().length;
  6934. const [loop_body] = node.blocks();
  6935. const loop_input_offset = 2;
  6936. const loop_body_offset = 1;
  6937. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6938. const i = i_1 - 1;
  6939. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6940. const node_input = node.inputs()[loop_input_offset + i];
  6941. node.outputs().at(i).replaceAllUsesWith(node_input);
  6942. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6943. node.eraseOutput(i);
  6944. node.removeInput(loop_input_offset + i);
  6945. loop_body.eraseInput(loop_body_offset + i);
  6946. loop_body.eraseOutput(loop_body_offset + i);
  6947. }
  6948. }
  6949. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6950. }
  6951. noMutableValues(values) {
  6952. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6953. }
  6954. getOrCreateAliasDb() {
  6955. if (!this._aliasDb) {
  6956. this._aliasDb = new torch._C.AliasDb(this._graph);
  6957. }
  6958. return this._aliasDb;
  6959. }
  6960. supportedNode(n) {
  6961. torch._C.skip_list = torch._C.skip_list || new Set([
  6962. 'prim::If',
  6963. 'prim::Loop',
  6964. 'prim::Closure',
  6965. 'prim::Constant',
  6966. 'prim::AutogradZero',
  6967. 'prim::Uninitialized',
  6968. 'prim::Guard',
  6969. 'prim::profile',
  6970. 'prim::profile_ivalue',
  6971. 'prim::unchecked_unwrap_optional',
  6972. 'prim::awaitable',
  6973. 'aten::dequantize'
  6974. ]);
  6975. let no_mutation = false;
  6976. if (this._aliasing_types) {
  6977. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  6978. } else {
  6979. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  6980. }
  6981. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  6982. }
  6983. ConstantPropagation(...args) {
  6984. if (args[0] instanceof torch.Graph) {
  6985. throw new python.Error('Not implemented.');
  6986. } else if (args[0] instanceof torch.Block) {
  6987. const [block] = args;
  6988. for (const n of block.nodes()) {
  6989. this.ConstantPropagation(n);
  6990. }
  6991. } else if (args[0] instanceof torch.Node) {
  6992. const [n] = args;
  6993. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  6994. if (n.kind() === 'prim::If') {
  6995. if (constant_inputs) {
  6996. this.inlineIf(n);
  6997. } else {
  6998. this.ConstantPropagation(n.blocks());
  6999. this.removeExtraIfOutputs(n);
  7000. }
  7001. } else if (n.kind() === 'prim::Loop') {
  7002. if (this.loopWillNotRun(n)) {
  7003. this.removeLoopNode(n);
  7004. } else {
  7005. this.ConstantPropagation(n.blocks());
  7006. this.removeExtraLoopOutputs(n);
  7007. }
  7008. } else if (constant_inputs && this.supportedNode(n)) {
  7009. this.propagateNode(n);
  7010. } else {
  7011. this.ConstantPropagation(n.blocks()); // not implemented
  7012. }
  7013. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7014. const [blocks] = args;
  7015. for (const block of blocks) {
  7016. this.ConstantPropagation(block);
  7017. }
  7018. } else {
  7019. throw new python.Error('Not implemented.');
  7020. }
  7021. }
  7022. });
  7023. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7024. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7025. const made_change = cp.run();
  7026. if (made_change) {
  7027. torch._C.EliminateDeadCode(graph);
  7028. }
  7029. return made_change;
  7030. });
  7031. this.registerType('torch._C.MutableTypePtrHelper', class {
  7032. constructor(mutable_type_cache) {
  7033. this._mutable_type_cache = mutable_type_cache;
  7034. }
  7035. mapTypeToAliasTypeSet(type) {
  7036. if (this._mutable_type_cache) {
  7037. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7038. if (result) {
  7039. return result;
  7040. }
  7041. }
  7042. return this.mapTypeToAliasTypeSetImpl(type);
  7043. }
  7044. mapTypeToAliasTypeSetImpl(type) {
  7045. if (type instanceof torch.ListType ||
  7046. type instanceof torch.DictType ||
  7047. type instanceof torch.ClassType ||
  7048. type instanceof torch.TensorType) {
  7049. return [torch._C.unshapedType(type)];
  7050. }
  7051. if (type instanceof torch.UnionType) {
  7052. const mutable_types = [];
  7053. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7054. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7055. if (maybe_inner_types) {
  7056. mutable_types.push(...maybe_inner_types);
  7057. }
  7058. }
  7059. if (mutable_types.length === 0) {
  7060. return null;
  7061. }
  7062. return mutable_types;
  7063. }
  7064. if (type instanceof torch.OptionalType) {
  7065. const inner = type.getElementType();
  7066. return this.mapTypeToAliasTypeSet(inner);
  7067. }
  7068. if (type instanceof torch.AnyType) {
  7069. return [torch._C.AliasTypeSet([type])];
  7070. }
  7071. if (type instanceof torch.FutureType) {
  7072. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7073. if (maybe_mut_types) {
  7074. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7075. }
  7076. return null;
  7077. }
  7078. if (type instanceof torch.AwaitType) {
  7079. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7080. if (maybe_mut_types) {
  7081. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7082. }
  7083. return null;
  7084. }
  7085. if (type instanceof torch.TupleType) {
  7086. const mutable_types = [];
  7087. for (const inner of type.elements()) {
  7088. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7089. if (maybe_inner_types) {
  7090. mutable_types.push(...maybe_inner_types);
  7091. }
  7092. }
  7093. if (mutable_types.length === 0) {
  7094. return null;
  7095. }
  7096. return [[torch.TupleType.create(mutable_types)]];
  7097. }
  7098. return null;
  7099. }
  7100. });
  7101. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7102. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7103. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7104. return true;
  7105. }
  7106. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7107. if (mutable_type_cache) {
  7108. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7109. }
  7110. return helper.mapTypeToAliasTypeSet(type) !== null;
  7111. });
  7112. this.registerType('torch._C.AliasDb', class {
  7113. constructor() {
  7114. this._writeIndex = new Map();
  7115. }
  7116. static isMutableType(...args) {
  7117. if (args[0] instanceof torch.Type) {
  7118. const [type] = args;
  7119. return torch._C.isMutableTypeImpl(type, null);
  7120. }
  7121. if (args[0] instanceof torch.Value) {
  7122. const [value] = args;
  7123. return torch._C.AliasDb.isMutableType(value.type());
  7124. }
  7125. throw new python.Error('Not implemented.');
  7126. }
  7127. writesToAlias(/* n, vs */) {
  7128. /*
  7129. const writtenTo = this.getWrites(n);
  7130. if (writtenTo.length === 0) {
  7131. return false;
  7132. }
  7133. MemoryLocations locs;
  7134. for (const v of vs) {
  7135. const it = elementMap_.find(v);
  7136. if (it != elementMap_.end()) {
  7137. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7138. if (writtenTo.intersects(vlocs)) {
  7139. return true;
  7140. }
  7141. }
  7142. }
  7143. */
  7144. return false;
  7145. }
  7146. writesToWildcard(n) {
  7147. if (!this._writeIndex.has(n)) {
  7148. return false;
  7149. }
  7150. const writes = this._writeIndex.get(n);
  7151. for (const pr of this._wildcardIndex) {
  7152. const [, wildcardElement] = pr;
  7153. if (writes.test(wildcardElement.index)) {
  7154. return true;
  7155. }
  7156. }
  7157. return false;
  7158. }
  7159. safeToChangeAliasingRelationship(a, b) {
  7160. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7161. return false;
  7162. }
  7163. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7164. }
  7165. });
  7166. this.registerFunction('torch._C.hasWriters', () => {
  7167. });
  7168. this.registerFunction('torch._C.escapesScope', () => {
  7169. });
  7170. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7171. constructor(graph) {
  7172. this._current = graph.block().nodes().front();
  7173. }
  7174. next() {
  7175. return null;
  7176. }
  7177. });
  7178. this.registerType('torch._C.ConcatCombiner', class {
  7179. constructor(graph) {
  7180. this._graph = graph;
  7181. this._aliasDb = new torch._C.AliasDb(graph);
  7182. this._combinable_concats = [];
  7183. }
  7184. collectOptimizableConcats() {
  7185. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7186. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7187. if (node.kind() === 'aten::cat') {
  7188. this.handleConcat(node);
  7189. }
  7190. }
  7191. }
  7192. combineConcats() {
  7193. if (this._combinable_concats.length === 0) {
  7194. return false;
  7195. }
  7196. const list_construct_inputs = this.getListConstructInputs();
  7197. for (const node_and_new_list of list_construct_inputs) {
  7198. const [node, inputs] = node_and_new_list;
  7199. const new_list_construct = this.createListConstruct(inputs);
  7200. const old_list_construct = node.input(0).node();
  7201. new_list_construct.output().setType(old_list_construct.output().type());
  7202. new_list_construct.insertBefore(node);
  7203. old_list_construct.replaceAllUsesWith(new_list_construct);
  7204. }
  7205. return true;
  7206. }
  7207. run() {
  7208. this.collectOptimizableConcats();
  7209. const changed = this.combineConcats();
  7210. if (changed) {
  7211. torch._C.EliminateDeadCode(this._graph);
  7212. }
  7213. return changed;
  7214. }
  7215. });
  7216. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7217. const changed = new torch._C.ConcatCombiner(graph).run();
  7218. return changed;
  7219. });
  7220. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7221. constructor(graph, disable_shape_peepholes) {
  7222. this._graph = graph;
  7223. this._shape_peepholes = !disable_shape_peepholes;
  7224. }
  7225. run() {
  7226. let changed = this.optimizeBlock(this._graph.block());
  7227. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7228. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7229. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7230. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7231. changed = changed || torch._C.CombineConcats(this._graph);
  7232. return changed;
  7233. }
  7234. optimizeBlock(block) {
  7235. let changed = false;
  7236. for (const node of block.nodes()) {
  7237. for (const sub_block of node.blocks()) {
  7238. changed = changed || this.optimizeBlock(sub_block);
  7239. }
  7240. if (node.kind() !== 'prim::Constant') {
  7241. const guard = new torch._C.WithInsertPoint(node);
  7242. for (const output of node.outputs()) {
  7243. if (output.type() instanceof torch.NoneType) {
  7244. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7245. changed = true;
  7246. }
  7247. }
  7248. guard.dispose();
  7249. }
  7250. if (node.kind() === 'prim::If') {
  7251. // throw new python.Error('Not implemented.');
  7252. /*
  7253. const n = new torch._C.IfView(node);
  7254. // this handles redundant short circuits like "x and True" or "x or
  7255. // False"
  7256. for (const auto i : c10::irange(n.outputs().length)) {
  7257. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7258. continue;
  7259. }
  7260. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7261. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7262. if (true_val && !false_val) {
  7263. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7264. changed = true;
  7265. }
  7266. }
  7267. for (let i = 0; i < n.outputs().length; ++i) {
  7268. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7269. const output_optional = n.outputs()[i].type();
  7270. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7271. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7272. if (unif) {
  7273. n.outputs()[i].setType(unif);
  7274. changed = true;
  7275. }
  7276. }
  7277. }
  7278. */
  7279. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7280. torch._C.AT_ASSERT(node.inputs().length === 2);
  7281. for (const check_none_index of [0, 1]) {
  7282. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7283. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7284. if (input_must_be_none && other_must_not_be_none) {
  7285. const guard = new torch._C.WithInsertPoint(node);
  7286. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7287. node.output().replaceAllUsesWith(output);
  7288. changed = true;
  7289. guard.dispose();
  7290. }
  7291. }
  7292. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7293. throw new python.Error('Not implemented.');
  7294. /*
  7295. // we are unwrapping an input that can't be None, remove the unwrap
  7296. const input = node.input();
  7297. if (input.mustNotBeNone()) {
  7298. node.output().replaceAllUsesWith(node.input());
  7299. changed = true;
  7300. }
  7301. */
  7302. } else if (node.kind() === 'prim::unchecked_cast') {
  7303. const input_type = torch._C.unshapedType(node.input().type());
  7304. const output_type = torch._C.unshapedType(node.output().type());
  7305. if (input_type.isSubtypeOf(output_type)) {
  7306. node.output().replaceAllUsesWith(node.input());
  7307. changed = true;
  7308. }
  7309. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7310. node.output().replaceAllUsesWith(node.input());
  7311. changed = true;
  7312. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7313. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7314. continue;
  7315. }
  7316. const inp_type = node.inputs()[0].type();
  7317. const immut_type = (type) => {
  7318. const kind = type.kind();
  7319. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7320. return handled_immutable_types.has(kind);
  7321. };
  7322. let non_throwing_type = false;
  7323. if (inp_type instanceof torch.ListType) {
  7324. non_throwing_type = immut_type(inp_type.getElementType());
  7325. } else if (inp_type instanceof torch.DictType) {
  7326. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7327. } else {
  7328. non_throwing_type = immut_type(inp_type);
  7329. }
  7330. if (non_throwing_type) {
  7331. const guard = new torch._C.WithInsertPoint(node);
  7332. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7333. changed = true;
  7334. guard.dispose();
  7335. }
  7336. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7337. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7338. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7339. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7340. }
  7341. }
  7342. return changed;
  7343. }
  7344. });
  7345. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7346. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7347. const changed = peephole.run();
  7348. if (changed) {
  7349. torch._C.EliminateDeadCode(graph.block());
  7350. }
  7351. return changed;
  7352. });
  7353. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7354. if (!cond) {
  7355. throw new python.Error('Assertion failed.');
  7356. }
  7357. });
  7358. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7359. if (!cond) {
  7360. throw new python.Error('Assertion failed.');
  7361. }
  7362. });
  7363. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7364. if (!cond) {
  7365. throw new python.Error('Assertion failed.');
  7366. }
  7367. });
  7368. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7369. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7370. for (let next_node = it.next(); next_node !== null;) {
  7371. const node = next_node;
  7372. next_node = it.next();
  7373. if (node.kind() === 'prim::EmptyListLiteral') {
  7374. if (node.hasUses()) {
  7375. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7376. }
  7377. const li = graph.createList(torch.TensorType.get(), []);
  7378. li.insertBefore(node);
  7379. node.replaceAllUsesWith(li);
  7380. }
  7381. node.destroy();
  7382. }
  7383. });
  7384. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7385. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7386. const [graph] = args;
  7387. const aliasDb = new torch._C.AliasDb(graph);
  7388. const constants = new torch._C.NodeSet();
  7389. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7390. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7391. const [block, constants, aliasDb] = args;
  7392. for (const node of block.nodes()) {
  7393. if (node.blocks().length > 0) {
  7394. for (const block of node.blocks()) {
  7395. torch._C.ConstantPooling(block, constants, aliasDb);
  7396. }
  7397. continue;
  7398. }
  7399. if (node.kind() !== 'prim::Constant') {
  7400. continue;
  7401. }
  7402. if (constants.has(node)) {
  7403. const existing = constants.get(node);
  7404. const old_ivalue = torch._C.toIValue(existing.output());
  7405. const new_ivalue = torch._C.toIValue(node.output());
  7406. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7407. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7408. continue;
  7409. }
  7410. node.replaceAllUsesWith(existing);
  7411. node.destroy();
  7412. continue;
  7413. } else {
  7414. constants.insert(node);
  7415. }
  7416. const [first_node] = node.owningGraph().block().nodes();
  7417. if (node !== first_node) {
  7418. node.moveBefore(first_node);
  7419. }
  7420. }
  7421. } else {
  7422. throw new python.Error('Not implemented.');
  7423. }
  7424. });
  7425. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7426. /*
  7427. const autocast_stack = [];
  7428. let incompatible_amp = null;
  7429. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7430. for (const node of block.nodes()) {
  7431. switch (node.kind()) {
  7432. case 'prim::CallFunction':
  7433. if (current_state() === initial_state) {
  7434. if (current_state()) {
  7435. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7436. }
  7437. break;
  7438. }
  7439. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7440. incompatible_amp = true;
  7441. break;
  7442. case 'prim::CallMethod':
  7443. if (current_state() === initial_state) {
  7444. if (current_state()) {
  7445. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7446. }
  7447. break;
  7448. }
  7449. if (node.input(0).type() instanceof torch.ClassType) {
  7450. const class_type = node.input(0).type();
  7451. const name = node.s('name');
  7452. const fn = class_type.getMethod(name);
  7453. if (!fn.isGraphFunction()) {
  7454. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7455. incompatible_amp = true;
  7456. }
  7457. } else {
  7458. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7459. incompatible_amp = true;
  7460. }
  7461. break;
  7462. case 'prim::Enter': {
  7463. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7464. if (autocast_scope) {
  7465. if (node.hasUses()) {
  7466. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7467. }
  7468. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7469. incompatible_amp = false;
  7470. autocast_stack.push(autocast_scope);
  7471. }
  7472. break;
  7473. }
  7474. case 'prim::Exit': {
  7475. if (torch._C.isAutocastNode(node.input(0))) {
  7476. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7477. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7478. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7479. incompatible_amp = false;
  7480. autocast_stack.pop();
  7481. }
  7482. break;
  7483. }
  7484. case 'aten::is_autocast_enabled': {
  7485. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7486. break;
  7487. }
  7488. case 'aten::is_autocast_cpu_enabled': {
  7489. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7490. break;
  7491. }
  7492. case 'aten::_convolution':
  7493. case 'aten::conv1d':
  7494. case 'aten::conv2d':
  7495. case 'aten::conv3d':
  7496. case 'aten::conv_tbc':
  7497. case 'aten::conv_transpose1d':
  7498. case 'aten::convolution':
  7499. case 'aten::cudnn_convolution':
  7500. case 'aten::cudnn_convolution_transpose':
  7501. case 'aten::prelu':
  7502. case 'aten::addmm':
  7503. case 'aten::addmv':
  7504. case 'aten::addr':
  7505. case 'aten::matmul':
  7506. case 'aten::mm':
  7507. case 'aten::mv':
  7508. case 'aten::linear':
  7509. case 'aten::addbmm':
  7510. case 'aten::baddbmm':
  7511. case 'aten::bmm':
  7512. case 'aten::chain_matmul':
  7513. case 'aten::_thnn_fused_lstm_cell':
  7514. case 'aten::_thnn_fused_gru_cell':
  7515. case 'aten::lstm_cell':
  7516. case 'aten::gru_cell':
  7517. case 'aten::rnn_tanh_cell':
  7518. case 'aten::rnn_relu_cell': {
  7519. if (!node.schema().is_mutable()) {
  7520. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7521. }
  7522. break;
  7523. }
  7524. case 'aten::native_layer_norm':
  7525. case 'aten::acos':
  7526. case 'aten::asin':
  7527. case 'aten::cosh':
  7528. case 'aten::erfinv':
  7529. case 'aten::exp':
  7530. case 'aten::expm1':
  7531. case 'aten::log':
  7532. case 'aten::log10':
  7533. case 'aten::log2':
  7534. case 'aten::log1p':
  7535. case 'aten::reciprocal':
  7536. case 'aten::rsqrt':
  7537. case 'aten::sinh':
  7538. case 'aten::tan':
  7539. case 'aten::pow':
  7540. case 'aten::softplus':
  7541. case 'aten::gelu':
  7542. case 'aten::layer_norm':
  7543. case 'aten::group_norm':
  7544. case 'aten::frobenius_norm':
  7545. case 'aten::nuclear_norm':
  7546. case 'aten::cosine_similarity':
  7547. case 'aten::cosine_embedding_loss':
  7548. case 'aten::nll_loss':
  7549. case 'aten::nll_loss2d':
  7550. case 'aten::hinge_embedding_loss':
  7551. case 'aten::kl_div':
  7552. case 'aten::l1_loss':
  7553. case 'aten::smooth_l1_loss':
  7554. case 'aten::mse_loss':
  7555. case 'aten::margin_ranking_loss':
  7556. case 'aten::multilabel_margin_loss':
  7557. case 'aten::soft_margin_loss':
  7558. case 'aten::triplet_margin_loss':
  7559. case 'aten::multi_margin_loss':
  7560. case 'aten::binary_cross_entropy_with_logits':
  7561. case 'aten::dist':
  7562. case 'aten::pdist':
  7563. case 'aten::cdist':
  7564. case 'aten::renorm':
  7565. case 'aten::logsumexp': {
  7566. if (!node.schema().is_mutable()) {
  7567. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7568. }
  7569. break;
  7570. }
  7571. case 'aten::prod':
  7572. case 'aten::log_softmax':
  7573. case 'aten::cumprod':
  7574. case 'aten::cumsum':
  7575. case 'aten::sum': {
  7576. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7577. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7578. }
  7579. break;
  7580. }
  7581. case 'aten::softmax': {
  7582. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7583. const context = current_state();
  7584. context.cpu_enabled = false;
  7585. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7586. }
  7587. break;
  7588. }
  7589. case 'aten::addcdiv':
  7590. case 'aten::addcmul':
  7591. case 'aten::atan2':
  7592. case 'aten::bilinear':
  7593. case 'aten::cat':
  7594. case 'aten::cross':
  7595. case 'aten::dot':
  7596. case 'aten::equal':
  7597. case 'aten::index_put':
  7598. case 'aten::stack':
  7599. case 'aten::tensordot':
  7600. case 'aten::add':
  7601. case 'aten::sub':
  7602. case 'aten::mul':
  7603. case 'aten::div': {
  7604. if (!node.schema().is_mutable()) {
  7605. torch._C.castInputsToWidestType(node, current_state());
  7606. }
  7607. break;
  7608. }
  7609. case 'aten::binary_cross_entropy': {
  7610. if (current_state()) {
  7611. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7612. }
  7613. break;
  7614. }
  7615. default: {
  7616. break;
  7617. }
  7618. }
  7619. for (const sub_block of node.blocks()) {
  7620. torch._C.handleBlock(sub_block, current_state());
  7621. }
  7622. }
  7623. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7624. */
  7625. });
  7626. this.registerFunction('torch._C.autocastEnabled', () => {
  7627. return true;
  7628. });
  7629. this.registerFunction('torch._C.Autocast', (graph) => {
  7630. if (torch._C.autocastEnabled()) {
  7631. const init = null;
  7632. /* AutocastContext init = {
  7633. at::autocast::is_autocast_enabled(at::kCUDA),
  7634. at::autocast::is_autocast_enabled(at::kCPU),
  7635. at::autocast::get_autocast_dtype(at::kCUDA),
  7636. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7637. torch._C.handleBlock(graph.block(), init);
  7638. }
  7639. });
  7640. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7641. disable_autocast = disable_autocast || false;
  7642. torch._C.Inline(graph);
  7643. torch._C.PeepholeOptimize(graph, true);
  7644. torch._C.ConstantPropagationImmutableTypes(graph);
  7645. if (!disable_autocast) {
  7646. torch._C.Autocast(graph);
  7647. }
  7648. torch._C.ConstantPooling(graph);
  7649. });
  7650. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7651. constructor(name, graph, function_creator, executor_execution_mode) {
  7652. super();
  7653. this._name = name;
  7654. this._graph = graph;
  7655. this._executor_execution_mode = executor_execution_mode || null;
  7656. this._function_creator = function_creator;
  7657. this._force_no_amp = false;
  7658. }
  7659. isGraphFunction() {
  7660. return true;
  7661. }
  7662. qualname() {
  7663. return this._name;
  7664. }
  7665. graph() {
  7666. return this._graph;
  7667. }
  7668. optimized_graph() {
  7669. const graph_ref = this._graph.copy();
  7670. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7671. return graph_ref;
  7672. }
  7673. ensure_defined() {
  7674. if (this._function_creator) {
  7675. const creator = this._function_creator;
  7676. this._function_creator = () => {
  7677. throw new python.Error('Recursive method call.');
  7678. };
  7679. creator(this);
  7680. this._function_creator = null;
  7681. }
  7682. this.check_single_output();
  7683. }
  7684. check_single_output() {
  7685. if (this.graph().outputs().length !== 1) {
  7686. throw new python.Error('Graph must have a single output.');
  7687. }
  7688. }
  7689. getSchema() {
  7690. this._schema = this._schema || this.defaultSchemaFor(this);
  7691. return this._schema;
  7692. }
  7693. setSchema(schema) {
  7694. this._schema = schema;
  7695. }
  7696. num_inputs() {
  7697. return this.graph().inputs().length;
  7698. }
  7699. unshapedType(type) {
  7700. if (type.isSubtypeOf(torch.TensorType.get())) {
  7701. return torch.TensorType.get();
  7702. }
  7703. const contained = type.containedTypes();
  7704. if (contained.length === 0) {
  7705. return type;
  7706. }
  7707. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7708. }
  7709. defaultSchemaFor(fn) {
  7710. const args = [];
  7711. const returns = [];
  7712. const g = fn.graph();
  7713. const num_inputs = fn.num_inputs();
  7714. for (let i = 0; i < num_inputs; i++) {
  7715. const v = g.inputs()[i];
  7716. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7717. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7718. args.push(argument);
  7719. }
  7720. const num_outputs = g.outputs().length;
  7721. for (let i = 0; i < num_outputs; i++) {
  7722. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7723. returns.push(argument);
  7724. }
  7725. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7726. }
  7727. });
  7728. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7729. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7730. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7731. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7732. __str__() {
  7733. return this._args.map((a) => a.__str__()).join('//');
  7734. }
  7735. });
  7736. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7737. this.registerType('torch.utils._sympy.functions.Where', class {});
  7738. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7739. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7740. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7741. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7742. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7743. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7744. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7745. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7746. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7747. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7748. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7749. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7750. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7751. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7752. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7753. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7754. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7755. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7756. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7757. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7758. static extract() {
  7759. }
  7760. });
  7761. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7762. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7763. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7764. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7765. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7766. this.registerType('torch.utils.data.dataset.Subset', class {});
  7767. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7768. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7769. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7770. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7771. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7772. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7773. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7774. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7775. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7776. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7777. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7778. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7779. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7780. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7781. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7782. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7783. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7784. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7785. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7786. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7787. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7788. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7789. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7790. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7791. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7792. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7793. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7794. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7795. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7796. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7797. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7798. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7799. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7800. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7801. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7802. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7803. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7804. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7805. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7806. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7807. this.registerType('torch._C._LegacyVariableBase', class {});
  7808. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7809. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7810. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7811. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7812. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7813. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7814. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7815. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7816. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7817. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7818. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7819. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7820. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7821. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7822. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7823. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7824. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7825. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7826. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7827. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7828. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7829. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7830. this.registerType('torch.distributions.beta.Beta', class {});
  7831. this.registerType('torch.distributions.binomial.Binomial', class {});
  7832. this.registerType('torch.distributions.categorical.Categorical', class {});
  7833. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7834. this.registerType('torch.distributions.constraints._Interval', class {});
  7835. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7836. this.registerType('torch.distributions.constraints._Real', class {});
  7837. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7838. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7839. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7840. this.registerType('torch.distributions.normal.Normal', class {});
  7841. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7842. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7843. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7844. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7845. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7846. this.registerType('torch.distributions.uniform.Uniform', class {});
  7847. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7848. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7849. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7850. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7851. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7852. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7853. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7854. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7855. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7856. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7857. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7858. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7859. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7860. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7861. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7862. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7863. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7864. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7865. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7866. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7867. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7868. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7869. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7870. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7871. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7872. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7873. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7874. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7875. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7876. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7877. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7878. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7879. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7880. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7881. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7882. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7883. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7884. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7885. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7886. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7887. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7888. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7889. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7890. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7891. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7892. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7893. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7894. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7895. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7896. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7897. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7898. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7899. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7900. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7901. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7902. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7903. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7904. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7905. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7906. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7907. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7908. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7909. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7911. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7912. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7913. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7914. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7915. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7916. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7917. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7918. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7920. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7921. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7922. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7923. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7924. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7925. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7926. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7927. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7928. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7929. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7930. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7931. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7932. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7933. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7934. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7935. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7936. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7937. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7938. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7939. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7940. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7941. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7942. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7943. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7944. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7945. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7946. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7947. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7948. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7949. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7950. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7951. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7952. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7953. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7954. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7955. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7956. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7957. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7958. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  7959. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7960. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  7961. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  7962. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  7963. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  7964. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  7965. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  7966. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  7967. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  7968. this.registerType('torch.nn.modules.module.PatchForward', class {});
  7969. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  7970. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  7971. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  7972. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  7973. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  7974. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  7975. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7976. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7977. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7978. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  7979. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7980. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7981. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7982. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  7983. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  7984. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  7985. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  7986. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  7987. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  7988. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  7989. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  7990. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  7991. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  7992. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7993. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7994. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7995. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  7996. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  7997. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  7998. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  7999. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8000. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8001. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8002. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8003. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8004. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8005. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8006. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8007. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8008. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8009. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8010. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8011. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8012. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8013. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8014. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8015. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8016. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8017. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8018. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8019. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8020. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8021. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8022. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8023. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8024. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8025. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8026. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8027. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8028. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8029. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8030. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8031. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8032. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8033. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8034. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8035. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8036. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8037. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8038. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8039. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8040. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8041. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8042. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8043. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8044. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8045. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8046. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8047. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8048. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8049. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8050. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8051. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8052. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8053. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8054. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8055. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8056. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8057. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8058. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8059. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8060. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8061. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8062. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8063. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8064. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8065. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8066. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8067. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8068. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8069. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8070. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8071. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8072. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8073. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8074. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8075. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8076. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8077. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8078. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8079. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8080. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8081. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8082. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8083. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8084. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8085. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8086. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8087. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8088. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8089. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8090. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8091. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8092. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8093. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8094. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8095. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8096. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8097. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8098. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8099. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8100. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8101. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8102. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8103. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8104. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8105. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8106. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8107. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8108. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8109. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8110. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8111. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8112. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8113. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8114. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8115. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8116. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8117. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8118. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8119. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8120. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8121. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8122. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8123. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8124. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8125. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8126. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8127. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8128. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8129. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8130. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8131. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8132. this.registerType('torch.optim.adamw.AdamW', class {});
  8133. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8134. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8135. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8136. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8137. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8138. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8139. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8140. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8141. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8142. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8143. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8144. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8145. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8146. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8147. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8148. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8149. this.registerType('torch.optim.sgd.SGD', class {});
  8150. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8151. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8152. torch.optim.RAdam = torch.optim.radam.RAdam;
  8153. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8154. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8155. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8156. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8157. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8158. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8159. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8160. this.registerFunction('torch.quantization.observer._with_args');
  8161. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8162. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8163. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8164. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8165. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8166. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8167. __enter__() {
  8168. return this;
  8169. }
  8170. __exit__(/* exc_type, exc_value, traceback */) {
  8171. }
  8172. });
  8173. this.registerFunction('torch.utils._pytree.tree_map');
  8174. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8175. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8176. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8177. this._expr = expr;
  8178. this.shape_env = shape_env;
  8179. this.pytype = pytype;
  8180. this._optimized_summation = optimized_summation;
  8181. this._hint = hint;
  8182. this.constant = constant;
  8183. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8184. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8185. }
  8186. __str__() {
  8187. return this._expr.__str__();
  8188. }
  8189. });
  8190. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8191. constructor() {
  8192. this.var_to_val = new Map();
  8193. this.var_to_stack = new Map();
  8194. }
  8195. add_var_to_val(expr, val) {
  8196. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8197. }
  8198. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8199. }
  8200. create_symintnode(sym, hint, source) {
  8201. let out = null;
  8202. let fx_node = null;
  8203. if (this._translation_validation_enabled && source !== null) {
  8204. throw new python.Error('Not implemented.');
  8205. } else {
  8206. fx_node = null;
  8207. }
  8208. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8209. out = builtins.int(sym);
  8210. if (hint !== null && out !== hint) {
  8211. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8212. }
  8213. } else {
  8214. // if free_unbacked_symbols(sym):
  8215. // hint = None
  8216. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8217. }
  8218. return out;
  8219. }
  8220. create_symboolnode(sym) {
  8221. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8222. }
  8223. });
  8224. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8225. /*
  8226. assert isinstance(sym, sympy.Symbol)
  8227. const name_str = sym.name.toLowerCase();
  8228. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8229. return name_str.startsWith(prefix_str[prefix])
  8230. }
  8231. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8232. */
  8233. return false;
  8234. });
  8235. this.registerType('torch.fx.proxy.TracerBase', class {
  8236. constructor() {
  8237. this.traced_func_name = 'forward';
  8238. }
  8239. });
  8240. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8241. trace(root /*, concrete_args */) {
  8242. let fn = null;
  8243. if (root instanceof torch.nn.Module) {
  8244. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8245. this.root = root;
  8246. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8247. this.root_module_name = root._get_name();
  8248. this.submodule_paths = new builtins.dict(root.named_modules());
  8249. } else {
  8250. this.root = new torch.nn.Module();
  8251. fn = root;
  8252. }
  8253. const tracer_cls = builtins.getattr(this, '__class__', null);
  8254. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8255. if (builtins.hasattr(this, '__code__')) {
  8256. const code = fn.__code__;
  8257. this.graph._co_fields = {
  8258. co_name: code.co_name,
  8259. co_filename: code.co_filename,
  8260. co_firstlineno: code.co_firstlineno,
  8261. };
  8262. }
  8263. return this.graph;
  8264. }
  8265. is_leaf_module(m /*, module_qualified_name */) {
  8266. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8267. }
  8268. });
  8269. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8270. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8271. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8272. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8273. return new graph_module_cls(...args);
  8274. });
  8275. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8276. let tracer_cls = body.get('_tracer_cls');
  8277. if (!tracer_cls) {
  8278. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8279. }
  8280. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8281. const cls_tracer = tracer_cls;
  8282. const KeepModules = class extends cls_tracer {
  8283. is_leaf_module() {
  8284. return true;
  8285. }
  8286. };
  8287. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8288. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8289. const graph = new KeepModules().trace(com, tracer_extras);
  8290. graph._tracer_cls = tracer_cls;
  8291. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8292. for (const [k, v] of body.items()) {
  8293. if (!builtins.hasattr(gm, k)) {
  8294. builtins.setattr(gm, k, v);
  8295. }
  8296. }
  8297. return gm;
  8298. });
  8299. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8300. globals = { ...globals };
  8301. const context = new python.Execution.Context(globals, null);
  8302. execution.exec(src, context);
  8303. const forward_fn = globals.forward;
  8304. delete globals.forward;
  8305. return forward_fn;
  8306. });
  8307. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8308. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8309. let fn_src = null;
  8310. if (body.has('_code')) {
  8311. fn_src = body.get('_code');
  8312. } else if (body.has('code')) {
  8313. fn_src = body.get('code');
  8314. } else {
  8315. fn_src = body._code || body.code;
  8316. }
  8317. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8318. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8319. });
  8320. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8321. const forward = importer.import_module(generated_module_name).forward;
  8322. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8323. });
  8324. this.registerType('torch.fx.graph.CodeGen', class {});
  8325. this.registerType('torch.fx.graph._Namespace', class {
  8326. constructor() {
  8327. this._obj_to_name = new Map();
  8328. this._unassociated_names = new Set();
  8329. this._used_names = new Set();
  8330. this._base_count = {};
  8331. }
  8332. create_name(candidate, obj) {
  8333. if (obj && this._obj_to_name.has(obj)) {
  8334. return self._obj_to_name.get(obj);
  8335. }
  8336. candidate = candidate || '_unnamed';
  8337. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8338. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8339. const match = candidate.match(/(.*)_(\d+)$"/);
  8340. let base = candidate;
  8341. let num = null;
  8342. if (match) {
  8343. [, base] = match;
  8344. num = parseInt(match[2], 10);
  8345. }
  8346. candidate = num ? `${base}_${num}` : base;
  8347. if (!num) {
  8348. num = this._base_count[base] || 0;
  8349. }
  8350. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8351. num += 1;
  8352. candidate = `${base}_${num}`;
  8353. }
  8354. this._used_names.add(candidate);
  8355. this._base_count[base] = num;
  8356. if (obj) {
  8357. this._obj_to_name[obj] = candidate;
  8358. } else {
  8359. this._unassociated_names.add(candidate);
  8360. }
  8361. return candidate;
  8362. }
  8363. _is_illegal_name(/* name, obj */) {
  8364. /*
  8365. if name in keyword.kwlist:
  8366. return True
  8367. if name in builtins.__dict__:
  8368. return obj is not builtins.__dict__[name]
  8369. if name in _custom_builtins:
  8370. return obj is not _custom_builtins[name].obj
  8371. */
  8372. return false;
  8373. }
  8374. associate_name_with_obj() {
  8375. }
  8376. });
  8377. this.registerType('torch.fx.node.Node', class {
  8378. constructor(graph, name, op, target, args, kwargs, return_type) {
  8379. this.graph = graph;
  8380. this.name = name;
  8381. this.op = op;
  8382. this.target = target;
  8383. this._input_nodes = new builtins.dict();
  8384. this.__update_args_kwargs(args, kwargs);
  8385. this.users = new builtins.dict();
  8386. this.type = return_type;
  8387. this._prev = this;
  8388. this._next = this;
  8389. this._erased = false;
  8390. this._repr_fn = null;
  8391. this.meta = new builtins.dict();
  8392. }
  8393. get args() {
  8394. return this._args;
  8395. }
  8396. get kwargs() {
  8397. return this._kwargs;
  8398. }
  8399. get next() {
  8400. return this._next;
  8401. }
  8402. prepend(x) {
  8403. x._remove_from_list();
  8404. const p = this._prev;
  8405. [p._next, x._prev] = [x, p];
  8406. [x._next, this._prev] = [this, x];
  8407. }
  8408. _remove_from_list() {
  8409. const [p, n] = [this._prev, this._next];
  8410. [p._next, n._prev] = [n, p];
  8411. }
  8412. __update_args_kwargs(new_args, new_kwargs) {
  8413. const update_users_and_input_nodes = (n) => {
  8414. if (n instanceof torch.fx.node.Node) {
  8415. this._input_nodes.setdefault(n);
  8416. n.users.setdefault(this);
  8417. }
  8418. return n;
  8419. };
  8420. const map_aggregate = (a, fn) => {
  8421. if (a instanceof builtins.tuple) {
  8422. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8423. if (!builtins.hasattr(a, '_fields')) {
  8424. return t;
  8425. }
  8426. throw new python.Error('Not implemented.');
  8427. // return type(a)(*t);
  8428. } else if (Array.isArray(a)) {
  8429. return a.map((elem) => map_aggregate(elem, fn));
  8430. } else if (a instanceof builtins.dict) {
  8431. const rv = new builtins.dict();
  8432. for (const [k, v] of a) {
  8433. rv.__setitem__(k, map_aggregate(v, fn));
  8434. }
  8435. return rv;
  8436. } else if (a instanceof builtins.slice) {
  8437. throw new python.Error('Not implemented.');
  8438. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8439. }
  8440. return fn(a);
  8441. };
  8442. for (const old_use of this._input_nodes.keys()) {
  8443. old_use.users.pop(this);
  8444. }
  8445. // object.__setattr__(self, "_input_nodes", {})
  8446. this._input_nodes = new builtins.dict();
  8447. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8448. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8449. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8450. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8451. }
  8452. });
  8453. torch.fx.Node = torch.fx.node.Node;
  8454. torch.fx.graph.Node = torch.fx.node.Node;
  8455. this.registerType('torch.fx.graph.Graph', class {
  8456. constructor(owning_module, tracer_cls, tracer_extras) {
  8457. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8458. this._used_names = new Map();
  8459. this._len = 0;
  8460. this._graph_namespace = new torch.fx.graph._Namespace();
  8461. this._owning_module = owning_module;
  8462. this._tracer_cls = tracer_cls;
  8463. this._tracer_extras = tracer_extras;
  8464. // this._codegen = CodeGen()
  8465. // this._co_fields = {}
  8466. }
  8467. get nodes() {
  8468. const array = new Array(this._len);
  8469. let node = this._root.next;
  8470. for (let i = 0; node !== this._root; i++) {
  8471. array[i] = node;
  8472. node = node.next;
  8473. }
  8474. return array;
  8475. }
  8476. placeholder(name, type_expr /*, default_value */) {
  8477. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8478. const kwargs = new builtins.dict();
  8479. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8480. }
  8481. create_node(op, target, args, kwargs, name, type_expr) {
  8482. args = args || new builtins.tuple();
  8483. kwargs = kwargs || new builtins.dict();
  8484. const candidate = name || this._target_to_str(target);
  8485. name = this._graph_namespace.create_name(candidate, null);
  8486. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8487. this._graph_namespace.associate_name_with_obj(name, n);
  8488. this._insert(n);
  8489. this._len += 1;
  8490. return n;
  8491. }
  8492. _insert(n) {
  8493. this._root.prepend(n);
  8494. }
  8495. output(result, type_expr) {
  8496. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8497. }
  8498. _target_to_str(target) {
  8499. if (typeof target === 'string') {
  8500. if (target.startsWith('__') && target.endsWith('__')) {
  8501. target = target.substring(2, target.length - 2);
  8502. }
  8503. } else {
  8504. target = target.__name__;
  8505. }
  8506. return this._snake_case(target);
  8507. }
  8508. _snake_case(s) {
  8509. const chars = [];
  8510. let prev_lower = false;
  8511. for (const c of s) {
  8512. const x = c.toLowerCase();
  8513. if (prev_lower && x !== c) {
  8514. chars.push('_');
  8515. } else {
  8516. prev_lower = true;
  8517. }
  8518. chars.push(x);
  8519. }
  8520. return chars.join('');
  8521. }
  8522. });
  8523. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8524. constructor(body) {
  8525. super();
  8526. for (const [k, v] of body.items()) {
  8527. builtins.setattr(this, k, v);
  8528. }
  8529. }
  8530. });
  8531. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8532. const parts = target.split('.');
  8533. const field = parts.pop();
  8534. for (const item of parts) {
  8535. const f = builtins.getattr(from_module, item);
  8536. let t = builtins.getattr(to_module, item, null);
  8537. if (f === t) {
  8538. return;
  8539. }
  8540. if (t === null) {
  8541. t = new torch.nn.modules.module.Module();
  8542. builtins.setattr(to_module, item, t);
  8543. }
  8544. from_module = f;
  8545. to_module = t;
  8546. }
  8547. const orig = builtins.getattr(from_module, field);
  8548. builtins.setattr(to_module, field, orig);
  8549. });
  8550. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8551. constructor(root, graph, class_name) {
  8552. super();
  8553. this.__class__.__name__ = class_name || 'GraphModule';
  8554. this.graph = graph;
  8555. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8556. for (const node of graph.nodes) {
  8557. if (node.op === 'get_attr' || node.op === 'call_module') {
  8558. torch.fx.graph_module._copy_attr(root, this, node.target);
  8559. }
  8560. }
  8561. }
  8562. }
  8563. });
  8564. torch.fx.Graph = torch.fx.graph.Graph;
  8565. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8566. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8567. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8568. return fn_or_name;
  8569. });
  8570. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8571. this.registerFunction('torchvision.datasets.folder.default_loader');
  8572. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8573. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8574. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8575. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8576. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8577. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8578. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8579. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8580. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8581. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8582. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8583. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8584. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8585. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8586. this.registerType('torchvision.ops.misc.Permute', class {});
  8587. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8588. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8589. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8590. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8591. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8592. this.registerType('torchvision.models._api.Weights', class {});
  8593. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8594. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8595. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8596. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8597. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8598. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8599. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8600. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8601. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8602. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8603. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8604. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8605. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8606. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8607. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8608. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8609. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8610. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8611. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8612. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8613. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8614. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8615. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8616. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8617. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8618. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8619. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8620. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8621. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8622. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8623. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8624. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8625. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8626. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8627. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8628. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8629. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8630. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8631. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8632. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8633. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8634. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8635. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8636. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8637. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8638. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8639. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8640. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8641. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8642. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8643. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8644. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8645. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8646. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8647. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8648. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8649. this.registerType('torchvision.models.googlenet.Inception', class {});
  8650. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8651. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8652. this.registerType('torchvision.models.inception.Inception3', class {});
  8653. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8654. this.registerType('torchvision.models.inception.InceptionA', class {});
  8655. this.registerType('torchvision.models.inception.InceptionB', class {});
  8656. this.registerType('torchvision.models.inception.InceptionC', class {});
  8657. this.registerType('torchvision.models.inception.InceptionD', class {});
  8658. this.registerType('torchvision.models.inception.InceptionE', class {});
  8659. this.registerFunction('torchvision.models.inception.inception_v3');
  8660. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8661. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8662. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8663. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8664. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8665. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8666. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8667. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8668. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8669. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8670. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8671. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8672. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8673. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8674. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8675. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8676. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8677. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8678. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8679. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8680. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8681. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8682. this.registerType('torchvision.models.regnet.RegNet', class {});
  8683. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8684. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8685. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8686. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8687. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8688. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8689. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8690. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8691. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8692. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8693. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8694. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8695. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8696. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8697. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8698. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8699. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8700. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8701. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8702. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8703. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8704. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8705. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8706. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8707. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8708. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8709. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8710. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8711. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8712. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8713. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8714. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8715. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8716. this.registerType('torchvision.models.resnet.ResNet', class {});
  8717. this.registerType('torchvision.models.vgg.VGG', class {});
  8718. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8719. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8720. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8721. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8722. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8723. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8724. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8725. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8726. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8727. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8728. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8729. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8730. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8731. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8732. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8733. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8734. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8735. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8736. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8737. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8738. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8739. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8740. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8741. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8742. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8743. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8744. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8745. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8746. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8747. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8748. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8749. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8750. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8751. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8752. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8753. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8754. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8755. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8756. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8757. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8758. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8759. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8760. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8761. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8762. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8763. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8764. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8765. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8766. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8767. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8768. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8769. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8770. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8771. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8772. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8773. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8774. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8775. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8776. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8777. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8778. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8779. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8780. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8781. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8782. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8783. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8784. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8785. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8786. this.registerFunction('torchvision.ops.boxes.box_iou');
  8787. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8788. this.registerFunction('builtins.annotate', (type, value) => {
  8789. if (type === builtins.int) {
  8790. return Number.isInteger(value) ? value : NaN;
  8791. }
  8792. if (type === builtins.float) {
  8793. return typeof value === 'number' ? value : NaN;
  8794. }
  8795. if (type === builtins.number) {
  8796. // if (pytorch.Utility.isTensor(value)) {
  8797. // value.resize_([]);
  8798. // }
  8799. }
  8800. return value;
  8801. });
  8802. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8803. return undefined;
  8804. });
  8805. this.registerFunction('builtins.range', (start, stop, step) => {
  8806. if (stop === undefined && step === undefined) {
  8807. if (Number.isInteger(start)) {
  8808. return Array(start).keys();
  8809. }
  8810. if (isNaN(start)) {
  8811. return [];
  8812. }
  8813. }
  8814. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8815. });
  8816. this.registerFunction('math.trunc');
  8817. builtins.xrange = builtins.range;
  8818. this.registerFunction('torch._C._nn.gelu');
  8819. this.registerFunction('torch._C._nn.avg_pool2d');
  8820. this.registerFunction('torch._C._nn.avg_pool3d');
  8821. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8822. this.registerFunction('torch._C._nn.softplus');
  8823. this.registerFunction('torch._native_multi_head_attention');
  8824. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8825. if (layout === torch.sparse_coo) {
  8826. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8827. }
  8828. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8829. });
  8830. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8831. return device;
  8832. });
  8833. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8834. device = torch._utils._get_restore_location(device);
  8835. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8836. });
  8837. this.registerFunction('torch.from_numpy', (obj) => {
  8838. const dtypes = new Map([
  8839. ['<f2', torch.float16],
  8840. ['<f4', torch.float32],
  8841. ['<f8', torch.float64],
  8842. ['<i2', torch.int16],
  8843. ['<i4', torch.int32],
  8844. ['<i8', torch.int64],
  8845. ]);
  8846. if (!dtypes.has(obj.dtype.str)) {
  8847. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8848. }
  8849. const dtype = dtypes.get(obj.dtype.str);
  8850. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8851. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8852. storage._set_cdata(obj.data);
  8853. const tensor = new torch.Tensor();
  8854. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8855. return tensor;
  8856. });
  8857. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8858. const tensor = torch.from_numpy(data);
  8859. // tensor = tensor.to(dtype, device)
  8860. tensor.requires_grad = requires_grad;
  8861. return tensor;
  8862. });
  8863. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  8864. const tensor = self.invoke('torch.Tensor', []);
  8865. tensor._layout = torch.sparse_coo;
  8866. tensor._indices = indices;
  8867. tensor._values = values;
  8868. tensor._shape = size;
  8869. return tensor;
  8870. });
  8871. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  8872. torch._C._set_tensor_metadata(tensor, metadata);
  8873. });
  8874. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  8875. return tensor;
  8876. });
  8877. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  8878. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  8879. });
  8880. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  8881. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  8882. const [, storage_type, , ,size] = storage;
  8883. storage = new storage_type(size);
  8884. }
  8885. const tensor = new torch.Tensor();
  8886. tensor.__setstate__([storage, storage_offset, size, stride]);
  8887. return tensor;
  8888. });
  8889. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  8890. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  8891. tensor.requires_grad = requires_grad;
  8892. if (metadata) {
  8893. torch._utils.set_tensor_metadata(tensor, metadata);
  8894. }
  8895. tensor.backward_hooks = backward_hooks;
  8896. return tensor;
  8897. });
  8898. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  8899. const t = new torch.Tensor(null, null, dtype);
  8900. t.set_(storage, storage_offset, size, stride);
  8901. if (metadata) {
  8902. torch._utils.set_tensor_metadata(t, metadata);
  8903. }
  8904. t._backward_hooks = backward_hooks;
  8905. return torch._utils._restore_device_fake_mode(t);
  8906. });
  8907. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  8908. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8909. param.backward_hooks = backward_hooks;
  8910. return param;
  8911. });
  8912. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  8913. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8914. param.backward_hooks = backward_hooks;
  8915. torch._utils._set_obj_state(param, state);
  8916. return param;
  8917. });
  8918. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  8919. const _set_obj_state = (obj, state) => {
  8920. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  8921. if (dict_state) {
  8922. for (const [k, v] of Object.entries(dict_state)) {
  8923. builtins.setattr(obj, k, v);
  8924. }
  8925. }
  8926. if (slots_state) {
  8927. for (const [k, v] of Object.entries(slots_state)) {
  8928. builtins.setattr(obj, k, v);
  8929. }
  8930. }
  8931. };
  8932. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8933. param._backward_hooks = backward_hooks;
  8934. _set_obj_state(param, state);
  8935. return param;
  8936. });
  8937. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  8938. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  8939. tensor.quantizer_params = quantizer_params;
  8940. return tensor;
  8941. });
  8942. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  8943. let dict_state = state;
  8944. let slots_state = null;
  8945. if (state instanceof self.builtins.tuple) {
  8946. if (state.length !== 2) {
  8947. throw new python.Error(`Invalid serialized state: '${state}'.`);
  8948. }
  8949. [dict_state, slots_state] = state;
  8950. }
  8951. if (dict_state) {
  8952. for (const [name, value] of Object.entries(dict_state)) {
  8953. builtins.setattr(obj, name, value);
  8954. }
  8955. }
  8956. if (slots_state) {
  8957. for (const [name, value] of Object.entries(slots_state)) {
  8958. builtins.setattr(obj, name, value);
  8959. }
  8960. }
  8961. return obj;
  8962. });
  8963. this.registerFunction('torch._set_item', (dict, key, value) => {
  8964. dict[key] = value;
  8965. });
  8966. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  8967. let ret = func(...args);
  8968. if (ret.__class__ !== new_type) {
  8969. // ret = ret.as_subclass(new_type);
  8970. }
  8971. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  8972. if (setstate === torch.Tensor.__setstate__) {
  8973. ret = torch._utils._set_obj_state(ret, state);
  8974. } else {
  8975. ret.__setstate__(state);
  8976. }
  8977. return ret;
  8978. });
  8979. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  8980. if (step === 0) {
  8981. throw new python.Error('range() arg 3 must not be zero');
  8982. }
  8983. if (step > 0 && lo < hi) {
  8984. return 1 + (hi - 1 - lo) / step;
  8985. } else if (step < 0 && lo > hi) {
  8986. return 1 + (lo - 1 - hi) / (0 - step);
  8987. }
  8988. return 0;
  8989. });
  8990. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  8991. this.registerOperator('aten::_unwrap_optional', (value) => {
  8992. return value;
  8993. });
  8994. this.registerFunction('torch.get_default_dtype', () => {
  8995. torch._default_type = torch._default_type || torch.float32;
  8996. return torch._default_type;
  8997. });
  8998. this.registerFunction('torch.set_default_dtype', (value) => {
  8999. torch._default_type = value;
  9000. });
  9001. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9002. return value || torch.get_default_dtype();
  9003. });
  9004. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9005. const shape = size;
  9006. dtype = torch._prims_common.dtype_or_default(dtype);
  9007. let storage = null;
  9008. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9009. const size = shape.reduce((a, b) => a * b, 1);
  9010. storage = new torch.storage.TypedStorage(size, dtype);
  9011. }
  9012. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9013. tensor.__setstate__([storage, 0, shape, stride]);
  9014. return tensor;
  9015. });
  9016. this.registerFunction('torch.all', (input) => {
  9017. if (Array.isArray(input) && input.length === 0) {
  9018. return true;
  9019. }
  9020. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9021. });
  9022. this.registerFunction('torch.append', (list, value) => {
  9023. list.push(value);
  9024. return value;
  9025. });
  9026. this.registerFunction('torch.clear', (value) => {
  9027. if (value instanceof torch.Value) {
  9028. throw new python.Error('Invalid value.');
  9029. }
  9030. if (Object(value) === value) {
  9031. for (const key of Object.keys(value)) {
  9032. delete value[key];
  9033. }
  9034. }
  9035. });
  9036. this.registerFunction('torch.dict', (args) => {
  9037. const obj = {};
  9038. if (args) {
  9039. if (Array.isArray(args)) {
  9040. for (const [key, value] of args) {
  9041. obj[key] = value;
  9042. }
  9043. } else {
  9044. throw new python.Error("'torch.dict' arguments not supported.");
  9045. }
  9046. }
  9047. return obj;
  9048. });
  9049. this.registerOperator('aten::cosine_similarity', () => {
  9050. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9051. });
  9052. this.registerOperator('aten::extend', (list, value) => {
  9053. list.push(...value);
  9054. });
  9055. this.registerOperator('aten::insert', (list, index, value) => {
  9056. list.splice(index, 0, value);
  9057. return value;
  9058. });
  9059. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9060. return value.replace(oldvalue, newvalue);
  9061. });
  9062. this.registerOperator('aten::add', (left, right) => {
  9063. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9064. return left + right;
  9065. }
  9066. if (Array.isArray(left) && Array.isArray(right)) {
  9067. return left.concat(right);
  9068. }
  9069. if (typeof left === 'string' && typeof right === 'string') {
  9070. return left + right;
  9071. }
  9072. throw new python.Error('Unsupported aten::add expression type.');
  9073. });
  9074. this.registerOperator('aten::log', (x) => {
  9075. if (typeof x === 'number' || x instanceof Number) {
  9076. return Math.log(x);
  9077. }
  9078. throw new python.Error('Unsupported aten::log expression type.');
  9079. });
  9080. this.registerOperator('aten::dim', (tensor) => {
  9081. if (tensor && tensor.size) {
  9082. const size = tensor.size();
  9083. if (size) {
  9084. return size.length;
  9085. }
  9086. }
  9087. return NaN;
  9088. });
  9089. this.registerOperator('aten::numel', (tensor) => {
  9090. if (tensor && tensor.size) {
  9091. const size = tensor.size();
  9092. if (size) {
  9093. return size.reduce((a, b) => a * b, 1);
  9094. }
  9095. }
  9096. return NaN;
  9097. });
  9098. this.registerOperator('aten::eq', (left, right) => {
  9099. if (typeof left === 'string' && typeof right === 'string') {
  9100. return left === right;
  9101. }
  9102. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9103. if (isNaN(left) && isNaN(right)) {
  9104. return true;
  9105. }
  9106. return left === right;
  9107. }
  9108. if (left === undefined || right === undefined) {
  9109. return true;
  9110. }
  9111. if (Array.isArray(left) && Array.isArray(right)) {
  9112. return left.length === right.length && left.every((item, index) => item === right[index]);
  9113. }
  9114. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9115. });
  9116. this.registerOperator('aten::floor', (value) => {
  9117. return Math.floor(value);
  9118. });
  9119. this.registerOperator('aten::ceil', (value) => {
  9120. return Math.ceil(value);
  9121. });
  9122. this.registerOperator('aten::floordiv', (left, right) => {
  9123. return Math.floor(left / right);
  9124. });
  9125. this.registerOperator('aten::format', (...args) => {
  9126. const list = args.shift().split(/({}D?)/);
  9127. return list.map((text) => {
  9128. if (text === '{}' || text === '{}D') {
  9129. const arg = args.shift();
  9130. if (Array.isArray(arg)) {
  9131. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9132. }
  9133. return arg ? arg.toString() : '?';
  9134. }
  9135. return text;
  9136. }).join('');
  9137. });
  9138. this.registerOperator('aten::strip', (self, chars) => {
  9139. chars = chars || '\\n\\t\\f\\v';
  9140. const regex = new RegExp(`[${chars}]`, 'g');
  9141. return self.replace(regex, '');
  9142. });
  9143. this.registerOperator('aten::gt', (left, right) => {
  9144. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9145. if (!isNaN(left) && !isNaN(right)) {
  9146. return left > right;
  9147. }
  9148. }
  9149. if (isNaN(left) && !isNaN(right)) {
  9150. return true;
  9151. }
  9152. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9153. });
  9154. this.registerOperator('aten::ge', (left, right) => {
  9155. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9156. if (!isNaN(left) && !isNaN(right)) {
  9157. return left > right;
  9158. }
  9159. }
  9160. if (isNaN(left) && !isNaN(right)) {
  9161. return true;
  9162. }
  9163. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9164. });
  9165. this.registerOperator('aten::is_floating_point', (tensor) => {
  9166. const type = tensor.dtype.scalar_type();
  9167. return (type === 5 || type === 6 || type === 7);
  9168. });
  9169. this.registerOperator('aten::is_grad_enabled', () => {
  9170. return false;
  9171. });
  9172. this.registerOperator('aten::is_autocast_enabled', () => {
  9173. return false;
  9174. });
  9175. this.registerOperator('aten::isfinite');
  9176. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9177. });
  9178. this.registerFunction('torch.serialization._get_layout', (name) => {
  9179. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9180. return value instanceof torch.layout ? value : null;
  9181. });
  9182. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9183. return torch.load(b);
  9184. });
  9185. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9186. return data;
  9187. });
  9188. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9189. return data;
  9190. });
  9191. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9192. return data;
  9193. });
  9194. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9195. return data;
  9196. });
  9197. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9198. return self.builtins.CONSTANTS[`c${data}`];
  9199. });
  9200. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9201. return value;
  9202. });
  9203. this.registerOperator('aten::keys', (dict) => {
  9204. return Object.keys(dict);
  9205. });
  9206. this.registerOperator('aten::len', (value) => {
  9207. if (Array.isArray(value)) {
  9208. return value.length;
  9209. }
  9210. if (value && value.shape && value.__len__) {
  9211. return value.__len__();
  9212. }
  9213. return NaN;
  9214. });
  9215. this.registerOperator('aten::le', (left, right) => {
  9216. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9217. if (isNaN(left) || isNaN(right)) {
  9218. return false;
  9219. }
  9220. return left <= right;
  9221. }
  9222. if (left === undefined || right === undefined) {
  9223. return true;
  9224. }
  9225. throw new python.Error("Unsupported 'torch.le' expression type.");
  9226. });
  9227. this.registerOperator('aten::list', (args) => {
  9228. return args;
  9229. });
  9230. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9231. return size;
  9232. });
  9233. this.registerType('torch.PyTorchFileReader', class {
  9234. constructor(entries) {
  9235. let prefix = 0;
  9236. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9237. for (let set = new Set(); set && paths.length > 0;) {
  9238. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9239. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9240. prefix += set ? set.keys().next().value.length + 1 : 0;
  9241. }
  9242. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9243. this._version = 0;
  9244. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  9245. if (stream) {
  9246. const decoder = new TextDecoder('utf-8');
  9247. const buffer = stream.peek();
  9248. const text = decoder.decode(buffer);
  9249. this._version = Number(text.split('\n').shift().trim());
  9250. }
  9251. }
  9252. has_record(name) {
  9253. return this._records.has(name);
  9254. }
  9255. get_record(name) {
  9256. return this._records.get(name);
  9257. }
  9258. get_all_records() {
  9259. return Array.from(this._records.keys());
  9260. }
  9261. version() {
  9262. return this._version;
  9263. }
  9264. });
  9265. this.registerFunction('torch.load', (f) => {
  9266. const legacy_load = (entries) => {
  9267. const deserialized_objects = {};
  9268. if (entries.has('storages')) {
  9269. const data = entries.get('storages');
  9270. const unpickler = new pickle.Unpickler(data);
  9271. const num_storages = unpickler.load();
  9272. for (let i = 0; i < num_storages; i++) {
  9273. const args = unpickler.load();
  9274. const [key, , storage_type] = args;
  9275. const obj = storage_type._new_with_file(unpickler);
  9276. deserialized_objects[key] = obj;
  9277. }
  9278. /*
  9279. let storage_views = unpickler.load();
  9280. for target_cdata, root_cdata, offset, size in storage_views:
  9281. root = deserialized_objects[root_cdata]
  9282. deserialized_objects[target_cdata] = root[offset:offset + size]
  9283. */
  9284. }
  9285. if (entries.has('tensors')) {
  9286. const data = entries.get('tensors');
  9287. const unpickler = new pickle.Unpickler(data);
  9288. const num_tensors = unpickler.load();
  9289. const int32 = (unpickler) => {
  9290. const buffer = unpickler.read(4);
  9291. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9292. };
  9293. const int64 = (unpickler) => {
  9294. const buffer = unpickler.read(8);
  9295. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9296. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9297. }
  9298. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9299. };
  9300. for (let i = 0; i < num_tensors; i++) {
  9301. const args = unpickler.load();
  9302. const [key, storage_id] = args;
  9303. const storage = deserialized_objects[storage_id];
  9304. const ndim = int32(unpickler);
  9305. unpickler.read(4);
  9306. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9307. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9308. const storage_offset = int64(unpickler);
  9309. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9310. deserialized_objects[key] = tensor;
  9311. }
  9312. }
  9313. const data = entries.get('pickle');
  9314. const unpickler = new pickle.Unpickler(data);
  9315. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9316. return unpickler.load();
  9317. };
  9318. const _legacy_load = () => {
  9319. const unpickler = new pickle.Unpickler(f);
  9320. unpickler.load(); // magic_number
  9321. const protocol_version = unpickler.load();
  9322. if (protocol_version !== 1001) {
  9323. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9324. }
  9325. const sys_info = unpickler.load();
  9326. if (sys_info.get('protocol_version') !== 1001) {
  9327. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9328. }
  9329. if (sys_info.get('little_endian') === false) {
  9330. throw new python.Error("Unsupported big-endian storage data.");
  9331. }
  9332. const module_source_map = new Map();
  9333. const deserialized_objects = new Map();
  9334. unpickler.persistent_load = (saved_id) => {
  9335. switch (saved_id[0]) {
  9336. case 'module': {
  9337. const [, module, ,source] = saved_id;
  9338. module_source_map.set(module, source);
  9339. return saved_id[1];
  9340. }
  9341. case 'storage': {
  9342. const [, storage_type, key, , size, view_metadata] = saved_id;
  9343. if (!deserialized_objects.has(key)) {
  9344. const obj = new storage_type(size);
  9345. deserialized_objects.set(key, obj);
  9346. }
  9347. if (view_metadata) {
  9348. const view_key = view_metadata.shift();
  9349. view_metadata.shift(); // view_offset
  9350. view_metadata.shift(); // view_size
  9351. if (!deserialized_objects.has(view_key)) {
  9352. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9353. deserialized_objects.set(view_key, view);
  9354. }
  9355. return deserialized_objects.get(view_key);
  9356. }
  9357. return deserialized_objects.get(key);
  9358. }
  9359. default: {
  9360. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9361. }
  9362. }
  9363. };
  9364. const obj = unpickler.load();
  9365. const deserialized_storage_keys = unpickler.load();
  9366. for (const deserialized_storage_key of deserialized_storage_keys) {
  9367. const storage = deserialized_objects.get(deserialized_storage_key);
  9368. storage._set_from_file(unpickler);
  9369. }
  9370. if (!obj) {
  9371. throw new python.Error('File format is not PyTorch.');
  9372. }
  9373. if (obj === 'None') {
  9374. throw new python.Error("File contains 'None' root object.");
  9375. }
  9376. return obj;
  9377. };
  9378. const _load = (entries) => {
  9379. if (f.has('constant.pkl')) {
  9380. throw python.Error("TorchScript 'torch.load' not supported.");
  9381. }
  9382. const loaded_storages = new Map();
  9383. const persistent_load = (saved_id) => {
  9384. switch (saved_id[0]) {
  9385. case 'storage': {
  9386. const [, storage_type, key, , numel] = saved_id;
  9387. if (!loaded_storages.has(key)) {
  9388. const storage = new storage_type(numel);
  9389. if (!storage._set_cdata) {
  9390. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9391. }
  9392. const name = `data/${key}`;
  9393. const stream = entries.get(name);
  9394. storage._set_cdata(stream);
  9395. loaded_storages.set(key, storage);
  9396. }
  9397. return loaded_storages.get(key);
  9398. }
  9399. default: {
  9400. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9401. }
  9402. }
  9403. };
  9404. const data_file = entries.get('data.pkl');
  9405. const unpickler = new pickle.Unpickler(data_file);
  9406. unpickler.persistent_load = persistent_load;
  9407. const result = unpickler.load();
  9408. return result;
  9409. };
  9410. if (f instanceof Map) {
  9411. const reader = new torch.PyTorchFileReader(f);
  9412. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9413. f = new Map(records);
  9414. if (f.has('pickle')) {
  9415. return legacy_load(f);
  9416. }
  9417. if (f.has('data.pkl')) {
  9418. return _load(f);
  9419. }
  9420. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9421. }
  9422. return _legacy_load(f);
  9423. });
  9424. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9425. return value;
  9426. });
  9427. this.registerOperator('prim::data', (tensor) => {
  9428. return tensor;
  9429. });
  9430. this.registerOperator('prim::device', (tensor) => {
  9431. return tensor.device;
  9432. });
  9433. this.registerOperator('prim::dtype', (tensor) => {
  9434. return tensor.dtype.scalar_type();
  9435. });
  9436. this.registerOperator('prim::is_quantized', (tensor) => {
  9437. return tensor.is_quantized;
  9438. });
  9439. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9440. return false;
  9441. });
  9442. this.registerOperator('prim::is_nested', (tensor) => {
  9443. return tensor.is_nested;
  9444. });
  9445. this.registerOperator('prim::is_sparse', (tensor) => {
  9446. return tensor.is_sparse;
  9447. });
  9448. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9449. return value;
  9450. });
  9451. this.registerOperator('prim::NumToTensor', (value) => {
  9452. const tensor = self.invoke('torch.Tensor', []);
  9453. tensor.value = value;
  9454. return tensor;
  9455. });
  9456. this.registerOperator('prim::min', (...args) => {
  9457. if (Array.isArray(args[0])) {
  9458. return Math.min.apply(null, args[0]);
  9459. }
  9460. return Math.min.apply(null, args);
  9461. });
  9462. this.registerOperator('prim::max', (...args) => {
  9463. if (Array.isArray(args[0])) {
  9464. return Math.max.apply(null, args[0]);
  9465. }
  9466. return Math.max.apply(null, args);
  9467. });
  9468. this.registerOperator('prim::shape', (tensor) => {
  9469. return tensor && tensor.size ? tensor.size() : undefined;
  9470. });
  9471. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9472. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9473. params.weight = weight;
  9474. params.bias = bias;
  9475. params.stride = stride;
  9476. params.padding = padding;
  9477. params.dilation = dilation;
  9478. params.groups = groups;
  9479. return params;
  9480. });
  9481. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9482. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9483. params.weight = weight;
  9484. params.bias = bias;
  9485. params.stride = stride;
  9486. params.padding = padding;
  9487. params.dilation = dilation;
  9488. params.groups = groups;
  9489. return params;
  9490. });
  9491. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9492. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9493. params.weight = weight;
  9494. params.bias = bias;
  9495. params.stride = stride;
  9496. params.padding = padding;
  9497. params.dilation = dilation;
  9498. params.groups = groups;
  9499. return params;
  9500. });
  9501. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9502. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9503. params.weight = weight;
  9504. params.bias = bias;
  9505. params.stride = stride;
  9506. params.padding = padding;
  9507. params.dilation = dilation;
  9508. params.groups = groups;
  9509. return params;
  9510. });
  9511. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9512. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9513. params.weight = weight;
  9514. params.bias = bias;
  9515. params.stride = stride;
  9516. params.padding = padding;
  9517. params.output_padding = output_padding;
  9518. params.dilation = dilation;
  9519. params.groups = groups;
  9520. return params;
  9521. });
  9522. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9523. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9524. params.weight = weight;
  9525. params.bias = bias;
  9526. params.stride = stride;
  9527. params.padding = padding;
  9528. params.output_padding = output_padding;
  9529. params.dilation = dilation;
  9530. params.groups = groups;
  9531. return params;
  9532. });
  9533. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9534. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9535. params.weight = weight;
  9536. params.bias = bias;
  9537. return params;
  9538. });
  9539. this.registerOperator('prim::RaiseException', (message) => {
  9540. throw new python.Error(message);
  9541. });
  9542. this.registerOperator('prim::TupleIndex', (t, i) => {
  9543. return t.elements()[i];
  9544. });
  9545. this.registerOperator('prim::TupleUnpack', (t) => {
  9546. return t.elements();
  9547. });
  9548. this.registerOperator('aten::is_scripting', () => {
  9549. return true;
  9550. });
  9551. this.registerOperator('aten::__and__', (left, right) => {
  9552. return left && right;
  9553. });
  9554. this.registerOperator('aten::__contains__', (dict, key) => {
  9555. return builtins.hasattr(dict, key);
  9556. });
  9557. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9558. return start + index * step;
  9559. });
  9560. this.registerOperator('aten::__is__', (left, right) => {
  9561. return left === right;
  9562. });
  9563. this.registerOperator('aten::__isnot__', (left, right) => {
  9564. return left !== right;
  9565. });
  9566. this.registerOperator('aten::__not__', (value) => {
  9567. if (Number.isInteger(value)) {
  9568. value = Boolean(value);
  9569. }
  9570. if (typeof value === 'boolean') {
  9571. return !value;
  9572. }
  9573. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9574. });
  9575. this.registerOperator('aten::log10', (value) => {
  9576. return Math.log10(value);
  9577. });
  9578. this.registerOperator('aten::device', (type, index) => {
  9579. return new torch.device(type, index);
  9580. });
  9581. this.registerOperator('aten::lt', (left, right) => {
  9582. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9583. return left < right;
  9584. }
  9585. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9586. });
  9587. this.registerOperator('aten::mul', (left, right) => {
  9588. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9589. return left * right;
  9590. }
  9591. if (isNaN(left) || isNaN(right)) {
  9592. return NaN;
  9593. }
  9594. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9595. return left.map((value) => value * right);
  9596. }
  9597. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9598. });
  9599. this.registerOperator('aten::div', (left, right) => {
  9600. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9601. return left / right;
  9602. }
  9603. if (isNaN(left) || isNaN(right)) {
  9604. return NaN;
  9605. }
  9606. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9607. });
  9608. this.registerFunction('torch.round', (value) => {
  9609. if (typeof value === 'number' || value instanceof Number) {
  9610. return Math.round(value);
  9611. }
  9612. if (isNaN(value)) {
  9613. return value;
  9614. }
  9615. throw new python.Error("Unsupported 'torch.round' expression type.");
  9616. });
  9617. this.registerOperator('aten::remainder', (left, right) => {
  9618. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9619. return left % right;
  9620. }
  9621. if (isNaN(left) || isNaN(right)) {
  9622. return NaN;
  9623. }
  9624. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9625. });
  9626. this.registerOperator('aten::ne', (left, right) => {
  9627. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9628. return left !== right;
  9629. }
  9630. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9631. if (isNaN(left) || isNaN(right)) {
  9632. return false;
  9633. }
  9634. return left !== right;
  9635. }
  9636. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9637. return false;
  9638. }
  9639. if (typeof left === 'string' && typeof right === 'string') {
  9640. return left !== right;
  9641. }
  9642. if (left === undefined || right === undefined) {
  9643. return true;
  9644. }
  9645. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9646. });
  9647. this.registerOperator('aten::neg', (value) => {
  9648. if (typeof value === 'number') {
  9649. return -value;
  9650. }
  9651. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9652. });
  9653. this.registerOperator('aten::pow', (left, right) => {
  9654. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9655. return Math.pow(left, right);
  9656. }
  9657. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9658. });
  9659. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9660. return -1;
  9661. });
  9662. this.registerFunction('torch.t', (tensor) => {
  9663. return tensor;
  9664. });
  9665. this.registerOperator('aten::size', (tensor, dim) => {
  9666. if (tensor && tensor.size) {
  9667. const size = tensor.size();
  9668. if (Array.isArray(size)) {
  9669. if (dim === undefined) {
  9670. return size;
  9671. }
  9672. if (Number.isInteger(dim)) {
  9673. if (dim >= 0 && dim < size.length) {
  9674. return size[dim];
  9675. }
  9676. if (dim < 0 && -dim < size.length) {
  9677. return size[size.length + dim];
  9678. }
  9679. }
  9680. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9681. }
  9682. }
  9683. if (Number.isInteger(dim)) {
  9684. return NaN;
  9685. }
  9686. return [];
  9687. });
  9688. this.registerFunction('aten::sqrt', (x) => {
  9689. return Math.sqrt(x);
  9690. });
  9691. this.registerOperator('aten::slice', (l, start, end, step) => {
  9692. if (!Array.isArray(l)) {
  9693. throw new python.Error('Slicing expected array');
  9694. }
  9695. step = step || 1;
  9696. if (step !== 1) {
  9697. throw new python.Error('Slicing only supports step=1');
  9698. }
  9699. start = Math.max(0, start >= 0 ? start : l.length + start);
  9700. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9701. return l.slice(start, end);
  9702. });
  9703. this.registerOperator('aten::sub', (left, right) => {
  9704. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9705. return left - right;
  9706. }
  9707. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9708. });
  9709. this.registerFunction('torch.sym_int');
  9710. this.registerFunction('torch.sym_float');
  9711. this.registerFunction('torch.sym_ite');
  9712. this.registerFunction('torch.sym_max');
  9713. this.registerFunction('torch.sym_min');
  9714. this.registerFunction('torch.sym_not');
  9715. this.registerFunction('torch.sym_sqrt');
  9716. this.registerFunction('torch.sym_sqrt');
  9717. this.registerFunction('torch.functional.einsum');
  9718. this.registerFunction('torch.functional.norm');
  9719. this.registerFunction('torch.functional.split');
  9720. this.registerFunction('torch.nn.init.constant_');
  9721. this.registerFunction('torch.nn.init.normal_');
  9722. this.registerFunction('torch.nn.init.xavier_uniform_');
  9723. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9724. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9725. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9726. this.registerFunction('torch.nn.functional.cross_entropy');
  9727. this.registerFunction('torch.nn.functional.elu');
  9728. this.registerFunction('torch.nn.functional.gelu');
  9729. this.registerFunction('torch.nn.functional.hardsigmoid');
  9730. this.registerFunction('torch.nn.functional.hardswish');
  9731. this.registerFunction('torch.nn.functional.hardtanh');
  9732. this.registerFunction('torch.nn.functional.interpolate');
  9733. this.registerFunction('torch.nn.functional.leaky_relu');
  9734. this.registerFunction('torch.nn.functional.l1_loss');
  9735. this.registerFunction('torch.nn.functional.linear');
  9736. this.registerFunction('torch.nn.functional.log_softmax');
  9737. this.registerFunction('torch.nn.functional._max_pool2d');
  9738. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9739. this.registerFunction('torch.nn.functional.mse_loss');
  9740. this.registerFunction('torch.nn.functional.pad');
  9741. this.registerFunction('torch.nn.functional.relu');
  9742. this.registerFunction('torch.nn.functional.relu6');
  9743. this.registerFunction('torch.nn.functional.sigmoid');
  9744. this.registerFunction('torch.nn.functional.silu');
  9745. this.registerFunction('torch.nn.functional.softmax');
  9746. this.registerFunction('torch.nn.functional.tanh');
  9747. this.registerFunction('torch.values', (dict) => {
  9748. return Object.values(dict);
  9749. });
  9750. this.registerFunction('torch.warn', () => {
  9751. });
  9752. this.registerType('torch._ops.OperatorBase', class {
  9753. constructor() {
  9754. this.functorch_table = {};
  9755. }
  9756. });
  9757. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9758. constructor(name, cacheable) {
  9759. super();
  9760. this._name = name;
  9761. this.__name__ = name;
  9762. this._ns = 'higher_order';
  9763. this.__module__ = 'torch.ops.higher_order';
  9764. this._cacheable = cacheable;
  9765. }
  9766. get namespace() {
  9767. return this._ns;
  9768. }
  9769. get name() {
  9770. return this._name;
  9771. }
  9772. });
  9773. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9774. constructor(name) {
  9775. super(name, false);
  9776. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9777. }
  9778. });
  9779. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9780. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9781. constructor(name) {
  9782. super(name, false);
  9783. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9784. }
  9785. });
  9786. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9787. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9788. constructor(name) {
  9789. super(name, false);
  9790. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9791. }
  9792. });
  9793. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  9794. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9795. constructor(name) {
  9796. super(name, false);
  9797. }
  9798. });
  9799. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  9800. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9801. constructor(name) {
  9802. super(name, false);
  9803. }
  9804. });
  9805. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  9806. this.registerType('torch.Type', class {
  9807. constructor(kind, annotation_str) {
  9808. this._kind = kind;
  9809. if (annotation_str) {
  9810. this._annotation_str = annotation_str;
  9811. }
  9812. }
  9813. static get(kind, annotation_str) {
  9814. torch.Type.cache = torch.Type.cache || new Map();
  9815. if (!annotation_str) {
  9816. if (!torch.Type.cache.has(kind)) {
  9817. torch.Type.cache.set(kind, new torch.Type(kind));
  9818. }
  9819. return torch.Type.cache.get(kind);
  9820. }
  9821. return new torch.Type(kind, annotation_str);
  9822. }
  9823. kind() {
  9824. return this._kind;
  9825. }
  9826. get annotation_str() {
  9827. return this._annotation_str;
  9828. }
  9829. equals(rhs) {
  9830. return this.kind() === rhs.kind();
  9831. }
  9832. isSubtypeOf(rhs) {
  9833. if (rhs.kind() === 'AnyType' || this === rhs) {
  9834. return true;
  9835. }
  9836. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  9837. return this.isSubtypeOf(rhs.getElementType());
  9838. }
  9839. if (rhs instanceof torch.UnionType) {
  9840. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  9841. }
  9842. if (rhs instanceof torch._C.DynamicType) {
  9843. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  9844. }
  9845. return this.equals(rhs);
  9846. }
  9847. containedTypes() {
  9848. return [];
  9849. }
  9850. containedType(i) {
  9851. return this.containedTypes()[i];
  9852. }
  9853. withContained(contained_types) {
  9854. const current_contained = this.containedTypes();
  9855. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  9856. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  9857. return this;
  9858. }
  9859. return this.createWithContained(contained_types);
  9860. }
  9861. createWithContained(/* createWithContained */) {
  9862. throw new python.Error('Not implemented.');
  9863. }
  9864. isUnionType() {
  9865. return false;
  9866. }
  9867. hasFreeVariables() {
  9868. return false;
  9869. }
  9870. is_module() {
  9871. return false;
  9872. }
  9873. expect(type) {
  9874. torch._C.AT_ASSERT(this instanceof type);
  9875. return this;
  9876. }
  9877. str() {
  9878. if (this instanceof torch._C.VarType && this._annotation_str) {
  9879. return this._annotation_str;
  9880. } else if (this._kind === 'ScalarTypeType') {
  9881. return 'ScalarType';
  9882. } else if (this._kind === 'QSchemeType') {
  9883. return 'QScheme';
  9884. } else if (this._kind) {
  9885. return this._kind;
  9886. }
  9887. throw new python.Error(`Not implemented '${this.kind()}'.`);
  9888. }
  9889. __str__() {
  9890. return this.str();
  9891. }
  9892. toString() {
  9893. return this.__str__();
  9894. }
  9895. });
  9896. this.registerType('torch.ClassType', class extends torch.Type {
  9897. constructor(qualified_name, cu, is_module) {
  9898. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  9899. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  9900. this._is_module = is_module;
  9901. this._attributes = [];
  9902. this._attributeTypes = [];
  9903. this._methods = [];
  9904. this._staticmethods = new Map();
  9905. this._forward_hooks = [];
  9906. this._forward_pre_hooks = [];
  9907. this._properties = [];
  9908. this._constants = new Map();
  9909. }
  9910. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  9911. return new torch.ClassType(qualifiedName, cu, is_module);
  9912. }
  9913. qualified_name() {
  9914. return this.annotation_str;
  9915. }
  9916. name() {
  9917. return this._name;
  9918. }
  9919. is_module() {
  9920. return this._is_module;
  9921. }
  9922. is_parameter(slot) {
  9923. return this._attributes[slot].is_parameter === true;
  9924. }
  9925. is_buffer(slot) {
  9926. return this._attributes[slot].is_buffer === true;
  9927. }
  9928. addMethod(method) {
  9929. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  9930. this._methods.push(method);
  9931. }
  9932. findMethod(name) {
  9933. for (const method of this._methods) {
  9934. if (name === method.name()) {
  9935. return method;
  9936. }
  9937. }
  9938. return null;
  9939. }
  9940. getMethod(name) {
  9941. const method = this.findMethod(name);
  9942. if (!method) {
  9943. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  9944. }
  9945. return method;
  9946. }
  9947. methods() {
  9948. return this._methods;
  9949. }
  9950. addStaticMethod(func) {
  9951. this._staticmethods.set(func.name, func);
  9952. }
  9953. findStaticMethod(name) {
  9954. return this._staticmethods.get(name);
  9955. }
  9956. findHook(name) {
  9957. let hook = this.findForwardHook(name);
  9958. if (hook === null) {
  9959. hook = this.findForwardPreHook(name);
  9960. }
  9961. return hook;
  9962. }
  9963. findForwardHook(name) {
  9964. for (const hook of this._forward_hooks) {
  9965. if (name === hook.name()) {
  9966. return hook;
  9967. }
  9968. }
  9969. return null;
  9970. }
  9971. findForwardPreHook(name) {
  9972. for (const pre_hook of this._forward_pre_hooks) {
  9973. if (name === pre_hook.name()) {
  9974. return pre_hook;
  9975. }
  9976. }
  9977. return null;
  9978. }
  9979. numAttributes() {
  9980. return this._attributes.length;
  9981. }
  9982. addAttribute(name, type, is_parameter, is_buffer) {
  9983. is_parameter = is_parameter || false;
  9984. is_buffer = is_buffer || false;
  9985. const slot = this._attributes.length;
  9986. this._attributes.push({ name, type, is_parameter, is_buffer });
  9987. this._attributeTypes.push(type);
  9988. return slot;
  9989. }
  9990. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  9991. is_parameter = is_parameter || false;
  9992. is_buffer = is_buffer || false;
  9993. const slot_idx = this.findAttributeSlot(name);
  9994. if (slot_idx === null) {
  9995. return this.addAttribute(name, ty, is_parameter, is_buffer);
  9996. }
  9997. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  9998. // const TypePtr& atype = getAttribute(*slot_idx);
  9999. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10000. return slot_idx;
  10001. }
  10002. findAttributeSlot(name) {
  10003. for (let pos = 0; pos < this._attributes.length; pos++) {
  10004. if (name === this._attributes[pos].name) {
  10005. return pos;
  10006. }
  10007. }
  10008. return null;
  10009. }
  10010. findAttribute(name) {
  10011. const slot = this.findAttributeSlot(name);
  10012. if (slot !== null) {
  10013. return this._attributes[slot].type;
  10014. }
  10015. return null;
  10016. }
  10017. hasAttribute(name) {
  10018. return this._attributes.find((attr) => attr.name === name);
  10019. }
  10020. getAttribute(arg) {
  10021. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10022. return this._attributes[slot].type;
  10023. }
  10024. getAttributeName(slot) {
  10025. return this._attributes[slot].name;
  10026. }
  10027. addConstant(name, value) {
  10028. this._constants.set(name, value);
  10029. }
  10030. hasConstant(name) {
  10031. return this._constants.has(name);
  10032. }
  10033. getProperty(name) {
  10034. for (const prop of this._properties) {
  10035. if (name === prop.name) {
  10036. return prop;
  10037. }
  10038. }
  10039. return null;
  10040. }
  10041. containedTypes() {
  10042. return this._attributeTypes;
  10043. }
  10044. createWithContained(contained_types) {
  10045. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10046. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10047. for (let i = 0; i < this._attributes.length; i++) {
  10048. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10049. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10050. }
  10051. for (const method of this.methods()) {
  10052. ptr.addMethod(method);
  10053. }
  10054. return ptr;
  10055. }
  10056. str() {
  10057. return this.qualified_name();
  10058. }
  10059. });
  10060. this.registerType('torch.EnumType', class extends torch.Type {
  10061. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10062. super('EnumType', qualified_class_name);
  10063. this._name = qualified_class_name;
  10064. this._value_type = value_type;
  10065. this._enum_names_values = enum_names_values;
  10066. this._cu = cu;
  10067. }
  10068. static create(qualified_class_name, value, enum_names_values, cu) {
  10069. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10070. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10071. }
  10072. torch._C.TORCH_CHECK(false);
  10073. return null;
  10074. }
  10075. name() {
  10076. return this._name;
  10077. }
  10078. get annotation_str() {
  10079. return this._name.qualifiedName();
  10080. }
  10081. enumNamesValues() {
  10082. return this._enum_names_values;
  10083. }
  10084. compilation_unit() {
  10085. return this._cu;
  10086. }
  10087. getValueType() {
  10088. return this._value_type;
  10089. }
  10090. equals(rhs) {
  10091. if (rhs instanceof torch.EnumType) {
  10092. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10093. }
  10094. return false;
  10095. }
  10096. isSubtypeOf(rhs) {
  10097. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10098. return true;
  10099. }
  10100. return super.isSubtypeOf(rhs);
  10101. }
  10102. });
  10103. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10104. if (args.length === 1) {
  10105. const [to_flatten] = args;
  10106. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10107. const to_fill = [];
  10108. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10109. to_flatten.splice(0, to_flatten.length);
  10110. to_flatten.push(...to_fill);
  10111. } else if (args.length === 2) {
  10112. const [reference, to_fill] = args;
  10113. for (const type of reference) {
  10114. torch._C.flattenUnion(type, to_fill);
  10115. }
  10116. torch._C.filterDuplicateSubtypes(to_fill);
  10117. torch._C.sortUnion(to_fill);
  10118. } else {
  10119. throw new python.Error('Not implemented.');
  10120. }
  10121. });
  10122. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10123. if (type instanceof torch.UnionType) {
  10124. for (const inner of type.containedTypes()) {
  10125. torch._C.flattenUnion(inner, to_fill);
  10126. }
  10127. } else if (type instanceof torch.OptionalType) {
  10128. const inner = type.getElementType();
  10129. torch._C.flattenUnion(inner, to_fill);
  10130. to_fill.push(torch.NoneType.get());
  10131. } else if (type instanceof torch.NumberType) {
  10132. to_fill.push(torch.IntType.get());
  10133. to_fill.push(torch.FloatType.get());
  10134. to_fill.push(torch.ComplexType.get());
  10135. } else {
  10136. to_fill.push(type);
  10137. }
  10138. });
  10139. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10140. if (types.length === 0) {
  10141. // return;
  10142. }
  10143. /*
  10144. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10145. // We don't want nested Optionals. Also, prematurely unifying to
  10146. // `Optional` could prevent us from coalescing other types
  10147. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10148. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10149. return null;
  10150. } else {
  10151. return unifyTypes(t1, t2, default_to_union=false);
  10152. }
  10153. };
  10154. size_t end_idx = types->size()-1;
  10155. for (size_t i = types->size()-1; i > 0; --i) {
  10156. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10157. std::optional<TypePtr> unified;
  10158. unified = get_supertype((*types)[i], (*types)[j]);
  10159. if (unified) {
  10160. (*types)[j] = *unified;
  10161. (*types)[i] = (*types)[end_idx];
  10162. --end_idx;
  10163. break;
  10164. }
  10165. if (j == 0) {
  10166. break;
  10167. }
  10168. }
  10169. }
  10170. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10171. */
  10172. });
  10173. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10174. /*
  10175. std::sort(types->begin(), types->end(),
  10176. [](const TypePtr& a, const TypePtr& b) -> bool {
  10177. if (a->kind() != b->kind()) {
  10178. return a->kind() < b->kind();
  10179. }
  10180. return a->str() < b->str();
  10181. });
  10182. */
  10183. });
  10184. this.registerType('torch.UnionType', class extends torch.Type {
  10185. constructor(reference, kind) {
  10186. super(kind || 'UnionType');
  10187. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10188. this._types = [];
  10189. torch._C.standardizeVectorForUnion(reference, this._types);
  10190. if (this._types.length === 1) {
  10191. throw new python.Error('Invalid union type reference.');
  10192. }
  10193. this._can_hold_none = false;
  10194. this._has_free_variables = false;
  10195. for (const type of this._types) {
  10196. if (type instanceof torch.NoneType) {
  10197. this._can_hold_none = true;
  10198. }
  10199. if (type.hasFreeVariables()) {
  10200. this._has_free_variables = true;
  10201. }
  10202. }
  10203. }
  10204. static create(reference) {
  10205. const union_type = new torch.UnionType(reference);
  10206. /*
  10207. bool int_found = false;
  10208. bool float_found = false;
  10209. bool complex_found = false;
  10210. bool nonetype_found = false;
  10211. const update_is_opt_flags = [&](const TypePtr& t) {
  10212. if (t == IntType::get()) {
  10213. int_found = true;
  10214. } else if (t == FloatType::get()) {
  10215. float_found = true;
  10216. } else if (t == ComplexType::get()) {
  10217. complex_found = true;
  10218. } else if (t == NoneType::get()) {
  10219. nonetype_found = true;
  10220. }
  10221. };
  10222. for (const auto& t : union_type->containedTypes()) {
  10223. update_is_opt_flags(t);
  10224. }
  10225. bool numbertype_found = int_found && float_found && complex_found;
  10226. if (nonetype_found) {
  10227. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10228. return OptionalType::create(NumberType::get());
  10229. }
  10230. if (union_type->containedTypes().size() == 2) {
  10231. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10232. ? union_type->containedTypes()[0]
  10233. : union_type->containedTypes()[1];
  10234. return OptionalType::create(not_none);
  10235. }
  10236. }
  10237. */
  10238. return union_type;
  10239. }
  10240. containedTypes() {
  10241. return this._types;
  10242. }
  10243. isUnionType() {
  10244. return true;
  10245. }
  10246. hasFreeVariables() {
  10247. return this._has_free_variables;
  10248. }
  10249. equals(rhs) {
  10250. if (rhs instanceof torch.UnionType) {
  10251. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10252. return false;
  10253. }
  10254. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10255. } else if (rhs instanceof torch.OptionalType) {
  10256. if (rhs.getElementType() === torch.NumberType.get()) {
  10257. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10258. }
  10259. const optional_lhs = this.toOptional();
  10260. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10261. } else if (rhs instanceof torch.NumberType) {
  10262. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10263. }
  10264. return false;
  10265. }
  10266. isSubtypeOf(rhs) {
  10267. const rhs_types = [];
  10268. if (rhs instanceof torch.UnionType) {
  10269. if (this.containedTypes() === rhs.containedTypes()) {
  10270. return true;
  10271. }
  10272. for (const typePtr of rhs.containedTypes()) {
  10273. rhs_types.push(typePtr);
  10274. }
  10275. } else if (rhs instanceof torch.OptionalType) {
  10276. rhs_types.push(torch.NoneType.get());
  10277. if (rhs.getElementType() === torch.NumberType.get()) {
  10278. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10279. rhs_types.push(...number_types);
  10280. } else {
  10281. rhs_types.push(rhs.getElementType());
  10282. }
  10283. } else if (rhs instanceof torch.NumberType) {
  10284. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10285. rhs_types.push(...number_types);
  10286. } else {
  10287. rhs_types.push(rhs);
  10288. }
  10289. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10290. }
  10291. });
  10292. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10293. constructor(contained) {
  10294. super([contained, torch.NoneType.get()], 'OptionalType');
  10295. let is_numbertype = false;
  10296. if (contained instanceof torch.UnionType) {
  10297. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10298. }
  10299. if (super.containedTypes().length === 2) {
  10300. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10301. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10302. this._contained = torch.NumberType.get();
  10303. this._types.splice(0, this._types.length);
  10304. this._types.push(torch.NumberType.get());
  10305. this._types.push(torch.NoneType.get());
  10306. } else {
  10307. const to_subtract = [torch.NoneType.get()];
  10308. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10309. this._contained = torch.UnionType.create([without_none]);
  10310. }
  10311. this._has_free_variables = contained.hasFreeVariables();
  10312. }
  10313. static create(elem) {
  10314. return new torch.OptionalType(elem);
  10315. }
  10316. getElementType() {
  10317. return this._contained;
  10318. }
  10319. equals(rhs) {
  10320. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10321. }
  10322. isSubtypeOf(rhs) {
  10323. if (rhs instanceof torch.OptionalType) {
  10324. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10325. } else if (rhs instanceof torch.UnionType) {
  10326. throw new python.Error('Not implemented.');
  10327. }
  10328. // return super.isSubtypeOf(rhs);
  10329. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10330. }
  10331. containedTypes() {
  10332. return [this._contained];
  10333. }
  10334. createWithContained(contained_types) {
  10335. torch._C.AT_ASSERT(contained_types.length === 1);
  10336. return torch.OptionalType.create(contained_types[0]);
  10337. }
  10338. subtractTypeSetFrom(to_subtract, from) {
  10339. const types = [];
  10340. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10341. for (const t of from) {
  10342. if (!should_subtract(t)) {
  10343. types.push(t);
  10344. }
  10345. }
  10346. if (types.length === 0) {
  10347. return null;
  10348. } else if (types.length === 1) {
  10349. return types[0];
  10350. }
  10351. return torch.UnionType.create(types);
  10352. }
  10353. str() {
  10354. return `${this.getElementType().str()}?`;
  10355. }
  10356. __str__() {
  10357. return `Optional[${this.getElementType().__str__()}]`;
  10358. }
  10359. });
  10360. this.registerType('torch.ListType', class extends torch.Type {
  10361. constructor(elem) {
  10362. super('ListType');
  10363. this._elem = elem;
  10364. }
  10365. static create(elem) {
  10366. return new torch.ListType(elem);
  10367. }
  10368. getElementType() {
  10369. return this._elem;
  10370. }
  10371. equals(rhs) {
  10372. if (rhs instanceof torch.ListType) {
  10373. return this.getElementType().equals(rhs.getElementType());
  10374. }
  10375. return false;
  10376. }
  10377. isSubtypeOf(rhs) {
  10378. if (super.isSubtypeOf(rhs)) {
  10379. return true;
  10380. }
  10381. if (rhs.kind() === 'AnyListType') {
  10382. return true;
  10383. }
  10384. return false;
  10385. }
  10386. containedTypes() {
  10387. return [this._elem];
  10388. }
  10389. createWithContained(contained_types) {
  10390. return new torch.ListType(contained_types[0]);
  10391. }
  10392. hasFreeVariables() {
  10393. return this.getElementType().hasFreeVariables();
  10394. }
  10395. str() {
  10396. return `${this.getElementType().str()}[]`;
  10397. }
  10398. __str__() {
  10399. return `List[${this.getElementType().__str__()}]`;
  10400. }
  10401. });
  10402. this.registerType('torch.FutureType', class extends torch.Type {
  10403. constructor(elem) {
  10404. super('FutureType');
  10405. this._elem = elem;
  10406. }
  10407. static create(elem) {
  10408. return new torch.FutureType(elem);
  10409. }
  10410. getElementType() {
  10411. return this._elem;
  10412. }
  10413. containedTypes() {
  10414. throw new python.Error('Not implemented.');
  10415. }
  10416. str() {
  10417. return `Future(${this.getElementType().str()})`;
  10418. }
  10419. __str__() {
  10420. return `Future[${this.getElementType().__str__()}]`;
  10421. }
  10422. });
  10423. this.registerType('torch.RRefType', class extends torch.Type {
  10424. constructor(elem) {
  10425. super('RRefType');
  10426. this._elem = elem;
  10427. }
  10428. static create(elem) {
  10429. return new torch.RRefType(elem);
  10430. }
  10431. getElementType() {
  10432. return this._elem;
  10433. }
  10434. containedTypes() {
  10435. throw new python.Error('Not implemented.');
  10436. }
  10437. str() {
  10438. return `RRef(${this.getElementType().str()})`;
  10439. }
  10440. __str__() {
  10441. return `RRef[${this.getElementType().__str__()}]`;
  10442. }
  10443. });
  10444. this.registerType('torch.AwaitType', class extends torch.Type {
  10445. constructor(elem) {
  10446. super('AwaitType');
  10447. this._elem = elem;
  10448. }
  10449. static get(elem) {
  10450. return new torch.AwaitType(elem);
  10451. }
  10452. getElementType() {
  10453. return this._elem;
  10454. }
  10455. containedTypes() {
  10456. throw new python.Error('Not implemented.');
  10457. }
  10458. str() {
  10459. return `Await(${this.getElementType().str()})`;
  10460. }
  10461. __str__() {
  10462. return `Await[${this.getElementType().__str__()}]`;
  10463. }
  10464. });
  10465. this.registerType('torch.TupleType', class extends torch.Type {
  10466. constructor(elements, annotation_str, schema) {
  10467. super('TupleType', annotation_str);
  10468. this._elements = elements;
  10469. this._has_free_variables = elements.some((v) => {
  10470. if (!v) {
  10471. throw new python.Error('Can not create tuple with None type');
  10472. }
  10473. return v.hasFreeVariables();
  10474. });
  10475. this._schema = schema;
  10476. }
  10477. static create(elements) {
  10478. return new torch.TupleType(elements, null, null);
  10479. }
  10480. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10481. const args = [];
  10482. for (let i = 0; i < field_names.length; i++) {
  10483. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10484. args.push(arg);
  10485. }
  10486. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10487. return new torch.TupleType(field_types, qualified_name, schema);
  10488. }
  10489. elements() {
  10490. return this._elements;
  10491. }
  10492. name() {
  10493. return this.annotation_str;
  10494. }
  10495. containedTypes() {
  10496. return this._elements;
  10497. }
  10498. createWithContained(createWithContained) {
  10499. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10500. }
  10501. hasFreeVariables() {
  10502. return this._has_free_variables;
  10503. }
  10504. schema() {
  10505. return this._schema;
  10506. }
  10507. str() {
  10508. if (this._schema) {
  10509. return `NamedTuple(...)`;
  10510. }
  10511. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10512. }
  10513. __str__() {
  10514. if (this.annotation_str) {
  10515. return this.annotation_str;
  10516. }
  10517. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10518. }
  10519. });
  10520. this.registerType('torch.AnyType', class extends torch.Type {
  10521. constructor() {
  10522. super('AnyType');
  10523. }
  10524. static get() {
  10525. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10526. return torch.AnyType.value;
  10527. }
  10528. str() {
  10529. return 'Any';
  10530. }
  10531. __str__() {
  10532. return 'Any';
  10533. }
  10534. });
  10535. this.registerType('torch.NoneType', class extends torch.Type {
  10536. constructor() {
  10537. super('NoneType');
  10538. }
  10539. static get() {
  10540. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10541. return torch.NoneType.value;
  10542. }
  10543. equals(rhs) {
  10544. return this.kind() === rhs.kind();
  10545. }
  10546. isSubtypeOf(rhs) {
  10547. if (rhs.kind() === 'OptionalType') {
  10548. return true;
  10549. }
  10550. return super.isSubtypeOf(rhs);
  10551. }
  10552. str() {
  10553. return 'NoneType';
  10554. }
  10555. __str__() {
  10556. return 'NoneType';
  10557. }
  10558. });
  10559. this.registerType('torch.TensorType', class extends torch.Type {
  10560. constructor() {
  10561. super('TensorType');
  10562. this._is_inferred = false;
  10563. }
  10564. static get() {
  10565. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10566. return torch.TensorType.value;
  10567. }
  10568. equals(rhs) {
  10569. return this.kind() === rhs.kind();
  10570. }
  10571. isInferredType() {
  10572. return this._is_inferred;
  10573. }
  10574. str() {
  10575. return 'Tensor';
  10576. }
  10577. __str__() {
  10578. return 'Tensor';
  10579. }
  10580. });
  10581. this.registerType('torch.NumberType', class extends torch.Type {
  10582. constructor() {
  10583. super('NumberType');
  10584. }
  10585. static get() {
  10586. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10587. return torch.NumberType.value;
  10588. }
  10589. str() {
  10590. return 'Scalar';
  10591. }
  10592. __str__() {
  10593. return 'number';
  10594. }
  10595. });
  10596. this.registerType('torch.BoolType', class extends torch.Type {
  10597. constructor() {
  10598. super('BoolType');
  10599. }
  10600. static get() {
  10601. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10602. return torch.BoolType.value;
  10603. }
  10604. equals(rhs) {
  10605. return this.kind() === rhs.kind();
  10606. }
  10607. str() {
  10608. return 'bool';
  10609. }
  10610. __str__() {
  10611. return 'bool';
  10612. }
  10613. });
  10614. this.registerType('torch.IntType', class extends torch.Type {
  10615. constructor() {
  10616. super('IntType');
  10617. }
  10618. static get() {
  10619. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10620. return torch.IntType.value;
  10621. }
  10622. equals(rhs) {
  10623. return this.kind() === rhs.kind();
  10624. }
  10625. isSubtypeOf(rhs) {
  10626. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10627. }
  10628. str() {
  10629. return 'int';
  10630. }
  10631. __str__() {
  10632. return 'int';
  10633. }
  10634. });
  10635. this.registerType('torch.SymIntType', class extends torch.Type {
  10636. constructor() {
  10637. super('SymIntType');
  10638. }
  10639. static get() {
  10640. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10641. return torch.SymIntType.value;
  10642. }
  10643. equals(rhs) {
  10644. return this.kind() === rhs.kind();
  10645. }
  10646. str() {
  10647. return 'SymInt';
  10648. }
  10649. __str__() {
  10650. return 'int';
  10651. }
  10652. });
  10653. this.registerType('torch.FloatType', class extends torch.Type {
  10654. constructor() {
  10655. super('FloatType');
  10656. }
  10657. static get() {
  10658. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10659. return torch.FloatType.value;
  10660. }
  10661. equals(rhs) {
  10662. return this.kind() === rhs.kind();
  10663. }
  10664. isSubtypeOf(rhs) {
  10665. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10666. }
  10667. str() {
  10668. return 'float';
  10669. }
  10670. __str__() {
  10671. return 'float';
  10672. }
  10673. });
  10674. this.registerType('torch.StringType', class extends torch.Type {
  10675. constructor() {
  10676. super('StringType');
  10677. }
  10678. static get() {
  10679. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10680. return torch.StringType.value;
  10681. }
  10682. equals(rhs) {
  10683. return this.kind() === rhs.kind();
  10684. }
  10685. str() {
  10686. return 'str';
  10687. }
  10688. __str__() {
  10689. return 'str';
  10690. }
  10691. });
  10692. this.registerType('torch.ComplexType', class extends torch.Type {
  10693. constructor() {
  10694. super('ComplexType');
  10695. }
  10696. static get() {
  10697. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10698. return torch.ComplexType.value;
  10699. }
  10700. equals(rhs) {
  10701. return this.kind() === rhs.kind();
  10702. }
  10703. isSubtypeOf(rhs) {
  10704. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10705. }
  10706. str() {
  10707. return 'complex';
  10708. }
  10709. __str__() {
  10710. return 'complex';
  10711. }
  10712. });
  10713. this.registerType('torch.DictType', class extends torch.Type {
  10714. constructor(key, value) {
  10715. super('DictType');
  10716. this.types = [key, value];
  10717. }
  10718. static create(key, value) {
  10719. let kind = key.kind();
  10720. if (key instanceof torch._C.DynamicType) {
  10721. kind = key.dynamicKind();
  10722. }
  10723. switch (kind) {
  10724. case 'AnyType':
  10725. case 'IntType':
  10726. case 'BoolType':
  10727. case 'FloatType':
  10728. case 'ComplexType':
  10729. case 'StringType':
  10730. case 'TensorType':
  10731. case 'DeviceObjType':
  10732. return new torch.DictType(key, value);
  10733. default:
  10734. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10735. }
  10736. }
  10737. createWithContained(contained_types) {
  10738. if (contained_types.length !== 2) {
  10739. throw new python.Error('Expected 2 contained types.');
  10740. }
  10741. return torch.DictType.create(contained_types[0], contained_types[1]);
  10742. }
  10743. getKeyType() {
  10744. return this.types[0];
  10745. }
  10746. getValueType() {
  10747. return this.types[1];
  10748. }
  10749. hasFreeVariables() {
  10750. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10751. }
  10752. containedTypes() {
  10753. return this.types;
  10754. }
  10755. equals(rhs) {
  10756. if (rhs instanceof torch.DictType) {
  10757. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10758. }
  10759. return false;
  10760. }
  10761. str() {
  10762. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10763. }
  10764. __str__() {
  10765. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10766. }
  10767. });
  10768. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10769. constructor() {
  10770. super('DeviceObjType');
  10771. }
  10772. static get() {
  10773. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10774. return torch.DeviceObjType.value;
  10775. }
  10776. str() {
  10777. return 'Device';
  10778. }
  10779. __str__() {
  10780. return 'Device';
  10781. }
  10782. });
  10783. this.registerType('torch.StreamObjType', class extends torch.Type {
  10784. constructor() {
  10785. super('StreamObjType');
  10786. }
  10787. str() {
  10788. return 'Stream';
  10789. }
  10790. __str__() {
  10791. return 'Stream';
  10792. }
  10793. });
  10794. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10795. constructor() {
  10796. super('GeneratorType');
  10797. }
  10798. static get() {
  10799. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10800. return torch._C._GeneratorType.value;
  10801. }
  10802. str() {
  10803. return 'Generator';
  10804. }
  10805. __str__() {
  10806. return 'Generator';
  10807. }
  10808. });
  10809. this.registerType('torch.InterfaceType', class extends torch.Type {
  10810. constructor() {
  10811. super('InterfaceType');
  10812. }
  10813. });
  10814. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10815. constructor() {
  10816. super('DynamicType');
  10817. }
  10818. });
  10819. this.registerType('torch._C.FunctionType', class extends torch.Type {
  10820. constructor(func) {
  10821. super('FunctionType');
  10822. this._func = func;
  10823. }
  10824. static create(func) {
  10825. return new torch._C.FunctionType(func);
  10826. }
  10827. function() {
  10828. return this._func;
  10829. }
  10830. });
  10831. this.registerType('torch._C.VarType', class extends torch.Type {
  10832. constructor(name) {
  10833. super('VarType', name);
  10834. }
  10835. static create(name) {
  10836. return new torch._C.VarType(name);
  10837. }
  10838. name() {
  10839. return this._annotation_str;
  10840. }
  10841. hasFreeVariables() {
  10842. return true;
  10843. }
  10844. });
  10845. this.registerType('torch._C.AliasInfo', class {
  10846. constructor() {
  10847. this.is_write = false;
  10848. this.before_set = [];
  10849. this.after_set = [];
  10850. this.containedTypes = [];
  10851. }
  10852. addBeforeSet(value) {
  10853. this.before_set.push(value);
  10854. }
  10855. addAfterSet(value) {
  10856. this.after_set.push(value);
  10857. }
  10858. addContainedType(alias_info) {
  10859. this.containedTypes.push(alias_info);
  10860. }
  10861. str() {
  10862. const list = ['('];
  10863. list.push(this.before_set.join('|'));
  10864. if (this.after_set.length > 0) {
  10865. list.push(' -> ');
  10866. list.push(this.after_set.join('|'));
  10867. }
  10868. if (this.is_write) {
  10869. list.push('!');
  10870. }
  10871. list.push(')');
  10872. return list.join('');
  10873. }
  10874. });
  10875. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  10876. if (str.startsWith('"') && str.endsWith('"')) {
  10877. return str.slice(1, -1);
  10878. }
  10879. if (str.startsWith("'") && str.endsWith("'")) {
  10880. return str.slice(1, -1);
  10881. }
  10882. throw new python.Error(`Invalid string literal '${str}'.`);
  10883. // inline std::string parseStringLiteral(
  10884. });
  10885. this.registerType('torch._C.Token', class {
  10886. constructor() {
  10887. this.kind = '';
  10888. this.value = '';
  10889. }
  10890. text() {
  10891. return this.value;
  10892. }
  10893. });
  10894. this.registerType('torch._C.Lexer', class {
  10895. constructor(buffer) {
  10896. this.buffer = buffer;
  10897. this.position = 0;
  10898. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  10899. this.next();
  10900. }
  10901. cur() {
  10902. return this.next_tokens[0];
  10903. }
  10904. lookahead() {
  10905. if (!this.next_tokens[1].kind) {
  10906. this.position += this.cur().text().length;
  10907. this.lex(this.next_tokens[1]);
  10908. }
  10909. return this.next_tokens[1];
  10910. }
  10911. next() {
  10912. const [cur] = this.next_tokens;
  10913. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  10914. this.next_tokens[1].kind = '';
  10915. this.next_tokens[3] = cur;
  10916. const [token] = this.next_tokens;
  10917. if (token.kind) {
  10918. return cur;
  10919. }
  10920. this.position += cur.text().length;
  10921. this.lex(token);
  10922. return cur;
  10923. }
  10924. nextIf(kind) {
  10925. if (this.cur().kind !== kind) {
  10926. return false;
  10927. }
  10928. this.next();
  10929. return true;
  10930. }
  10931. expect(kind) {
  10932. if (this.cur().kind !== kind) {
  10933. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  10934. }
  10935. return this.next();
  10936. }
  10937. lex(token) {
  10938. while (this.buffer[this.position] === ' ') {
  10939. this.position += 1;
  10940. }
  10941. let i = this.position;
  10942. if (i >= this.buffer.length) {
  10943. token.kind = '\0';
  10944. token.value = '';
  10945. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  10946. token.kind = '...';
  10947. token.value = '...';
  10948. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  10949. this.kind = '[]';
  10950. this.value = '[]'; */
  10951. } 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] === '|') {
  10952. token.kind = this.buffer[i];
  10953. token.value = this.buffer[i];
  10954. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  10955. i += 1;
  10956. 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] === '_')) {
  10957. i += 1;
  10958. }
  10959. token.kind = 'id';
  10960. token.value = this.buffer.slice(this.position, i);
  10961. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  10962. token.kind = '->';
  10963. token.value = '->';
  10964. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  10965. i += 1;
  10966. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  10967. i += 1;
  10968. }
  10969. token.kind = '#';
  10970. token.value = this.buffer.slice(this.position, i);
  10971. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  10972. const quote = this.buffer[i];
  10973. i += 1;
  10974. while (i < this.buffer.length && this.buffer[i] !== quote) {
  10975. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  10976. }
  10977. i += 1;
  10978. token.kind = 'string';
  10979. token.value = this.buffer.slice(this.position, i);
  10980. } else {
  10981. throw new python.Error(`Unsupported token at '${this.position}'.`);
  10982. }
  10983. }
  10984. });
  10985. this.registerType('torch._C.SchemaTypeParser', class {
  10986. constructor(L, complete_tensor_types, allow_typevars) {
  10987. this.L = L;
  10988. this.complete_tensor_types = complete_tensor_types;
  10989. this._allow_typevars = allow_typevars;
  10990. }
  10991. parseType() {
  10992. const r = this.parseFakeAndRealType();
  10993. return { first: r[0], second: r[2] };
  10994. }
  10995. parseBaseType() {
  10996. const L = this.L;
  10997. const tok = L.cur();
  10998. const text = tok.text();
  10999. L.next();
  11000. switch (text) {
  11001. case 'Tensor': return torch.TensorType.get();
  11002. case 'bool': return torch.BoolType.get();
  11003. case 'int': return torch.IntType.get();
  11004. case 'float': return torch.FloatType.get();
  11005. case 'complex': return torch.ComplexType.get();
  11006. case 'str': return torch.StringType.get();
  11007. case 'SymInt': return torch.SymIntType.get();
  11008. case 'Scalar': return torch.NumberType.get();
  11009. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11010. case 'Device': return torch.DeviceObjType.get();
  11011. case 'Layout': return torch.Type.get('Layout');
  11012. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11013. case 'Generator': return torch._C._GeneratorType.get();
  11014. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11015. case 'Any': return torch.AnyType.get();
  11016. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11017. case 'Dimname': return torch.StringType.get();
  11018. case 'QScheme': return torch.Type.get('QSchemeType');
  11019. case 'Stream': return torch.StreamObjType.get();
  11020. case 'Storage': return torch.Type.get('Storage');
  11021. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11022. case 'NoneType': return torch.NoneType.get();
  11023. default: throw new python.Error(`Unsupported type '${text}'.`);
  11024. }
  11025. }
  11026. parseFakeAndRealType() {
  11027. const L = this.L;
  11028. let fake_value = null;
  11029. let real_value = null;
  11030. let alias_info = null;
  11031. if (L.nextIf('(')) {
  11032. const types = [];
  11033. while (!L.nextIf(')')) {
  11034. const r = this.parseType();
  11035. types.push(r.first);
  11036. if (alias_info && r.second) {
  11037. alias_info.addContainedType(r.second);
  11038. }
  11039. L.nextIf(',');
  11040. }
  11041. real_value = torch.TupleType.create(types);
  11042. fake_value = real_value;
  11043. } else if (L.cur().text() === 'Future') {
  11044. L.next();
  11045. L.expect('(');
  11046. const p = this.parseType();
  11047. const subtype = p.first;
  11048. // const subalias = p.second;
  11049. L.expect(')');
  11050. real_value = torch.FutureType.create(subtype);
  11051. fake_value = real_value;
  11052. } else if (L.cur().text() === 'Await') {
  11053. L.next();
  11054. L.expect('(');
  11055. const p = this.parseType();
  11056. const subtype = p.first;
  11057. // const subalias = p.second;
  11058. L.expect(')');
  11059. real_value = torch.AwaitType.get(subtype);
  11060. fake_value = real_value;
  11061. } else if (L.cur().text() === 'RRef') {
  11062. L.next();
  11063. L.expect('(');
  11064. const p = this.parseType();
  11065. const subtype = p.first;
  11066. // const subalias = p.second;
  11067. L.expect(')');
  11068. real_value = torch.RRefType.create(subtype);
  11069. fake_value = real_value;
  11070. } else if (L.cur().text() === 'Tensor') {
  11071. L.next();
  11072. real_value = torch.TensorType.get();
  11073. fake_value = real_value;
  11074. alias_info = this.parseAliasAnnotation();
  11075. } else if (L.cur().text() === 'Dict') {
  11076. L.next();
  11077. L.expect('(');
  11078. const key_type = this.parseType().first;
  11079. L.expect(',');
  11080. const value_type = this.parseType().first;
  11081. L.expect(')');
  11082. alias_info = this.parseAliasAnnotation();
  11083. real_value = torch.DictType.create(key_type, value_type);
  11084. fake_value = real_value;
  11085. } else if (L.nextIf('Union')) {
  11086. L.next();
  11087. L.expect('(');
  11088. const types = [];
  11089. types.push(this.parseType().first);
  11090. while (L.cur().kind !== ')') {
  11091. L.expect(',');
  11092. types.push(this.parseType().first);
  11093. }
  11094. L.expect(')');
  11095. alias_info = this.parseAliasAnnotation();
  11096. real_value = new torch.UnionType(types);
  11097. fake_value = real_value;
  11098. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11099. fake_value = real_value = parseRefinedTensor();
  11100. alias_info = parseAliasAnnotation(); */
  11101. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11102. L.next();
  11103. L.expect('.');
  11104. const torch_tok = L.expect('id');
  11105. if (torch_tok.text() !== 'torch') {
  11106. throw new python.Error('Expected classes namespace.');
  11107. }
  11108. L.expect('.');
  11109. const classes_tok = L.expect('id');
  11110. if (classes_tok.text() !== 'classes') {
  11111. throw new python.Error('Expected classes namespace.');
  11112. }
  11113. L.expect('.');
  11114. const ns_tok = L.expect('id');
  11115. L.expect('.');
  11116. const class_tok = L.expect('id');
  11117. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11118. fake_value = real_value;
  11119. if (!fake_value) {
  11120. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11121. }
  11122. } else {
  11123. real_value = this.parseBaseType();
  11124. fake_value = real_value;
  11125. if (real_value.kind() === 'ScalarTypeType' ||
  11126. real_value.kind() === 'MemoryFormat' ||
  11127. real_value.kind() === 'Layout' ||
  11128. real_value.kind() === 'SymIntType') {
  11129. fake_value = torch.IntType.get();
  11130. }
  11131. alias_info = this.parseAliasAnnotation();
  11132. }
  11133. while (true) {
  11134. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11135. L.expect('[');
  11136. L.expect(']');
  11137. fake_value = torch.ListType.create(fake_value);
  11138. real_value = torch.ListType.create(real_value);
  11139. let container = this.parseAliasAnnotation();
  11140. if (alias_info) {
  11141. if (!container) {
  11142. container = new torch._C.AliasInfo();
  11143. container.is_write = alias_info.is_write;
  11144. }
  11145. container.addContainedType(alias_info);
  11146. }
  11147. alias_info = container;
  11148. } else if (L.nextIf('?')) {
  11149. fake_value = torch.OptionalType.create(fake_value);
  11150. real_value = torch.OptionalType.create(real_value);
  11151. } else {
  11152. break;
  11153. }
  11154. }
  11155. return [fake_value, real_value, alias_info];
  11156. }
  11157. parseAliasAnnotation() {
  11158. const L = this.L;
  11159. let alias_info = null;
  11160. if (L.nextIf('(')) {
  11161. alias_info = new torch._C.AliasInfo();
  11162. do {
  11163. alias_info.addBeforeSet(L.cur().text());
  11164. L.next();
  11165. if (L.nextIf('!')) {
  11166. alias_info.is_write = true;
  11167. }
  11168. }
  11169. while (L.nextIf('|'));
  11170. if (L.nextIf('->')) {
  11171. do {
  11172. alias_info.addAfterSet(L.cur().text());
  11173. L.next();
  11174. }
  11175. while (L.nextIf('|'));
  11176. }
  11177. L.expect(')');
  11178. }
  11179. return alias_info;
  11180. }
  11181. });
  11182. this.registerType('torch.Argument', class {
  11183. constructor(...args) {
  11184. // torch/aten/src/ATen/core/function_schema.h
  11185. this.N = null;
  11186. this.default_value = null;
  11187. this.kwarg_only = false;
  11188. this.alias_info = null;
  11189. if (args.length === 2) {
  11190. [this.name, this.type] = args;
  11191. this.real_type = this.type;
  11192. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11193. [this.name, this.type, this.real_type] = args;
  11194. } else if (args.length === 6) {
  11195. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11196. } else if (args.length === 7) {
  11197. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11198. } else {
  11199. throw new python.Error('Invalid arguments.');
  11200. }
  11201. const is_alias = this.alias_info && this.alias_info.is_write;
  11202. this.is_out = this.kwarg_only && is_alias;
  11203. }
  11204. has_default_value() {
  11205. return this.default_value !== undefined;
  11206. }
  11207. is_inferred_type() {
  11208. if (this.type instanceof torch.TensorType) {
  11209. return this.type.isInferredType();
  11210. }
  11211. return false;
  11212. }
  11213. str() {
  11214. const list = [];
  11215. const type = this.real_type;
  11216. const is_opt = type instanceof torch.OptionalType;
  11217. const unopt_type = is_opt ? type.getElementType() : type;
  11218. if (unopt_type instanceof torch.ListType) {
  11219. list.push(unopt_type.getElementType().str());
  11220. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11221. list.push(this.alias_info.containedTypes[0].str());
  11222. }
  11223. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11224. } else {
  11225. list.push(unopt_type.str());
  11226. }
  11227. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11228. list.push(this.alias_info.str());
  11229. }
  11230. if (is_opt) {
  11231. list.push('?');
  11232. }
  11233. if (this.name) {
  11234. list.push(' ');
  11235. list.push(this.name);
  11236. }
  11237. if (this.default_value !== undefined) {
  11238. const value = this.default_value;
  11239. if (value === null) {
  11240. list.push('=None');
  11241. } else if (typeof value === 'boolean') {
  11242. list.push('=');
  11243. list.push(value ? 'True' : 'False');
  11244. } else if (typeof value === 'string') {
  11245. list.push(`="${value}"`);
  11246. } else if (typeof value === 'number') {
  11247. list.push(`=${value}`);
  11248. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11249. list.push(`.`);
  11250. }
  11251. } else if (Array.isArray(value)) {
  11252. list.push(`=[${value.join(', ')}]`);
  11253. }
  11254. }
  11255. return list.join('');
  11256. }
  11257. });
  11258. torch._C.TypeKind = {
  11259. StringType: 'StringType',
  11260. NumberType: 'NumberType',
  11261. IntType: 'IntType',
  11262. BoolType: 'BoolType',
  11263. DynamicType: 'DynamicType',
  11264. OptionalType: 'OptionalType',
  11265. FloatType: 'FloatType',
  11266. ComplexType: 'ComplexType',
  11267. ListType: 'ListType',
  11268. };
  11269. this.registerType('torch._C.List', class extends Array {
  11270. constructor(type, elements) {
  11271. super(elements ? elements.length : 0);
  11272. if (Array.isArray(elements)) {
  11273. for (let i = 0; i < elements.length; i++) {
  11274. this[i] = elements[i];
  11275. }
  11276. }
  11277. this.type = type;
  11278. }
  11279. elementType() {
  11280. return this.type;
  11281. }
  11282. });
  11283. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11284. return new Map();
  11285. });
  11286. this.registerFunction('torch._C.string_to_type_lut', () => {
  11287. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11288. const map = new Map();
  11289. map.set('Tensor', torch.TensorType.get());
  11290. map.set('int', torch.IntType.get());
  11291. map.set('float', torch.FloatType.get());
  11292. map.set('bool', torch.BoolType.get());
  11293. map.set('complex', torch.ComplexType.get());
  11294. map.set('str', torch.StringType.get());
  11295. map.set('Device', torch.DeviceObjType.get());
  11296. map.set('number', torch.NumberType.get());
  11297. map.set('None', torch.NoneType.get());
  11298. map.set('NoneType', torch.NoneType.get());
  11299. map.set('Any', torch.AnyType.get());
  11300. map.set('list', torch.Type.get('AnyListType'));
  11301. map.set('tuple', torch.Type.get('AnyTupleType'));
  11302. torch._C.string_to_type_lut.basePythonTypes = map;
  11303. }
  11304. return torch._C.string_to_type_lut.basePythonTypes;
  11305. });
  11306. this.registerType('torch._C.ScriptTypeParser', class {
  11307. constructor(resolver) {
  11308. this._resolver = resolver;
  11309. }
  11310. parseSchemaFromDef(def, skip_self) {
  11311. const name = def.name;
  11312. const args = this.parseArgsFromDecl(def, skip_self);
  11313. const returns = this.parseReturnFromDecl(def);
  11314. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11315. }
  11316. parseArgsFromDecl(decl, skip_self) {
  11317. const retval = [];
  11318. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11319. throw new python.Error('Unsupported function argument.');
  11320. }
  11321. const params = decl.args.args.slice();
  11322. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11323. const start = skip_self ? 1 : 0;
  11324. for (let i = start; i < params.length; i++) {
  11325. const decl_arg = params[i];
  11326. const N = null;
  11327. const default_value = undefined;
  11328. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11329. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11330. retval.push(arg);
  11331. }
  11332. return retval;
  11333. }
  11334. parseReturnFromDecl(decl) {
  11335. if (!decl.returns) {
  11336. return [];
  11337. }
  11338. if (this.parseBroadcastList(decl.returns)) {
  11339. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11340. }
  11341. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11342. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11343. }
  11344. parseTypeFromExpr(expr) {
  11345. if (this._resolver) {
  11346. if (expr instanceof ast.Name) {
  11347. const type = this._resolver.resolveType(expr.id);
  11348. if (type) {
  11349. return type;
  11350. }
  11351. }
  11352. }
  11353. return this.parseTypeFromExprImpl(expr);
  11354. }
  11355. parseTypeFromExprImpl(expr) {
  11356. if (expr instanceof ast.Subscript) {
  11357. const value_name = this.parseBaseTypeName(expr.value);
  11358. if (!value_name) {
  11359. throw new python.Error('Subscripted type must be a type identifier.');
  11360. }
  11361. return this.subscriptToType(value_name, expr);
  11362. }
  11363. const name = this.parseBaseTypeName(expr);
  11364. if (name) {
  11365. const itr = torch._C.string_to_type_lut().get(name);
  11366. if (itr) {
  11367. return itr;
  11368. }
  11369. if (this._resolver) {
  11370. const typePtr = this._resolver.resolveType(name, expr);
  11371. if (typePtr) {
  11372. return typePtr;
  11373. }
  11374. }
  11375. }
  11376. throw new python.Error(`Unknown type name '${name}'.`);
  11377. }
  11378. parseBaseTypeName(expr) {
  11379. if (expr instanceof ast.Name) {
  11380. return expr.id;
  11381. } else if (expr instanceof ast.Constant && expr.value === null) {
  11382. return 'None';
  11383. } else if (expr instanceof ast.Attribute) {
  11384. const name = expr.attr;
  11385. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11386. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11387. return name;
  11388. }
  11389. return torch._C.collectQualname(expr);
  11390. }
  11391. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11392. }
  11393. parseBroadcastList(/* expr */) {
  11394. return null;
  11395. }
  11396. parseType(str) {
  11397. const expr = ast.parse(str);
  11398. return this.parseTypeFromExpr(expr.body[0].value);
  11399. }
  11400. subscriptToType(typeName, subscript) {
  11401. if (typeName === 'Tuple' || typeName === 'tuple') {
  11402. const subscript_expr_types = [];
  11403. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11404. for (const expr of elts) {
  11405. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11406. }
  11407. return torch.TupleType.create(subscript_expr_types);
  11408. } else if (typeName === 'List' || typeName === 'list') {
  11409. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11410. throw new python.Error('List type must have exactly one element type.');
  11411. }
  11412. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11413. return torch.ListType.create(elem_type);
  11414. } else if (typeName === 'Optional') {
  11415. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11416. throw new python.Error('Optional type must have exactly one element type.');
  11417. }
  11418. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11419. return torch.OptionalType.create(elem_type);
  11420. } else if (typeName === 'Union') {
  11421. const subscript_expr_types = [];
  11422. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11423. for (const expr of elts) {
  11424. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11425. }
  11426. return torch.UnionType.create(subscript_expr_types);
  11427. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11428. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11429. if (elts.length !== 1) {
  11430. throw new python.Error('Future type must have exactly one element type.');
  11431. }
  11432. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11433. return torch.FutureType.create(elem_type);
  11434. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11435. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11436. if (elts.length !== 1) {
  11437. throw new python.Error('Await type must have exactly one element type.');
  11438. }
  11439. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11440. return torch.AwaitType.create(elem_type);
  11441. } else if (typeName === 'RRef') {
  11442. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11443. if (elts.length !== 1) {
  11444. throw new python.Error('RRef type must have exactly one element type.');
  11445. }
  11446. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11447. return torch.RRefType.create(elem_type);
  11448. } else if (typeName === 'Dict' || typeName === 'dict') {
  11449. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11450. if (elts.length !== 2) {
  11451. throw new python.Error('Dict type must have exactly two element types.');
  11452. }
  11453. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11454. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11455. return torch.DictType.create(key_type, value_type);
  11456. }
  11457. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11458. }
  11459. });
  11460. this.registerFunction('torch._C.isTorch', (expr) => {
  11461. return expr instanceof ast.Name && expr.id === 'torch';
  11462. });
  11463. this.registerFunction('torch._C.collectQualname', (select) => {
  11464. const base = select.value;
  11465. if (base instanceof ast.Name) {
  11466. return `${base.id}.${select.attr}`;
  11467. }
  11468. const basename = torch._C.collectQualname(base);
  11469. return `${basename}.${select.attr}`;
  11470. });
  11471. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11472. constructor(overloadpacket, op, op_dk, schema, tags) {
  11473. super();
  11474. this._op = op;
  11475. this._op_dk = op_dk;
  11476. this._schema = schema;
  11477. this._overloadpacket = overloadpacket;
  11478. this._tags = tags;
  11479. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11480. this._name = this._schema.name;
  11481. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11482. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11483. this.__module__ = overloadpacket.__module__;
  11484. op.__module__ = overloadpacket.__module__;
  11485. this.__qualname__ = self._name;
  11486. this.__annotations__ = {};
  11487. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11488. let is_write = null;
  11489. for (const a of this._schema.arguments) {
  11490. if (a.alias_info) {
  11491. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11492. }
  11493. }
  11494. this.is_view = is_write !== null && !is_write;
  11495. }
  11496. name() {
  11497. return this._name;
  11498. }
  11499. });
  11500. this.registerType('torch._ops.OpOverloadPacket', class {
  11501. constructor(qualified_op_name, op_name, op, overload_names) {
  11502. this._qualified_op_name = qualified_op_name;
  11503. this.__name__ = op_name;
  11504. this._op = op;
  11505. this._overload_names = overload_names;
  11506. this._dir = [];
  11507. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11508. }
  11509. get _schemas() {
  11510. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11511. }
  11512. __getattr__(key) {
  11513. key = key === 'default' ? '' : key;
  11514. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11515. const [op_, op_dk_, tags] = op_dk_tags;
  11516. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11517. const overload = this._has_script_object_arg(schema) ?
  11518. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11519. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11520. builtins.setattr(self, key, overload);
  11521. this._dir.push(key);
  11522. return overload;
  11523. }
  11524. _has_script_object_arg(schema) {
  11525. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11526. }
  11527. __call__(...args) {
  11528. const fn = execution._operators.get(this._qualified_op_name);
  11529. if (!fn) {
  11530. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11531. }
  11532. return fn(...args);
  11533. }
  11534. });
  11535. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11536. constructor(name) {
  11537. super(`torch.ops.${name}`);
  11538. this.name = name;
  11539. this._dir = [];
  11540. }
  11541. __getattr__(op_name) {
  11542. const namespace_name = this.name;
  11543. const qualified_op_name = `${namespace_name}::${op_name}`;
  11544. const module_name = `${this.__module__}.${namespace_name}`;
  11545. let op = null;
  11546. let overload_names = null;
  11547. try {
  11548. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11549. } catch {
  11550. // continue regardless of error
  11551. }
  11552. if (!op) {
  11553. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11554. }
  11555. op.__module__ = module_name;
  11556. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11557. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11558. builtins.setattr(this, op_name, opoverloadpacket);
  11559. this._dir.push(op_name);
  11560. return opoverloadpacket;
  11561. }
  11562. _get_packet(qualname, op_module) {
  11563. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11564. if (op) {
  11565. // torch.jit._builtins._register_builtin(op, qualname);
  11566. }
  11567. op.__module__ = op_module;
  11568. return [op, overload_names];
  11569. }
  11570. });
  11571. this.registerType('torch._C.graph_node_list', class {
  11572. constructor(head) {
  11573. this.head = head;
  11574. }
  11575. front() {
  11576. return this.head.next;
  11577. }
  11578. end() {
  11579. return this.head.prev;
  11580. }
  11581. [Symbol.iterator]() {
  11582. let current = this.head.next;
  11583. const prev = this.head.prev;
  11584. return {
  11585. next() {
  11586. if (current !== prev) {
  11587. const value = current;
  11588. current = current.next;
  11589. return { value, done: false };
  11590. }
  11591. return { done: true };
  11592. }
  11593. };
  11594. }
  11595. });
  11596. this.registerType('torch.Graph', class {
  11597. constructor() {
  11598. this._next_unique = 0;
  11599. this._unique_names = new Map();
  11600. this._name_base_suffix = new Map();
  11601. this.all_nodes = new Set();
  11602. this.all_values = new Set();
  11603. this.all_blocks = new Set();
  11604. this._block = new torch.Block(this, null);
  11605. this._insert_before = this.return_node();
  11606. }
  11607. insert(opname, args, kwargs, range) {
  11608. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11609. }
  11610. create(kind, ...args) {
  11611. let inputs = null;
  11612. let num_outputs = 1;
  11613. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11614. [inputs, num_outputs] = args;
  11615. } else if (args.length === 1) {
  11616. if (typeof args[0] === 'number') {
  11617. [num_outputs] = args;
  11618. } else if (Array.isArray(args[0])) {
  11619. [inputs] = args;
  11620. }
  11621. }
  11622. const n = new torch.Node(this, kind);
  11623. if (inputs) {
  11624. for (const i of inputs) {
  11625. n.addInput(i);
  11626. }
  11627. }
  11628. for (let i = 0; i < num_outputs; i++) {
  11629. n.addOutput();
  11630. }
  11631. return n;
  11632. }
  11633. createClone(n, value_map, copy_blocks) {
  11634. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11635. const r = n.allocNewInstance(this);
  11636. for (const o of n.outputs()) {
  11637. r.addOutput().copyMetadata(o);
  11638. }
  11639. r.cloneFrom(n);
  11640. for (const i of n.inputs()) {
  11641. r.addInput(value_map(i));
  11642. }
  11643. if (copy_blocks) {
  11644. for (const b of n.blocks()) {
  11645. r.addBlock().cloneFrom(b, value_map);
  11646. }
  11647. }
  11648. return r;
  11649. }
  11650. createNone() {
  11651. const n = this.create('prim::Constant');
  11652. n.output().setType(torch.NoneType.get());
  11653. return n;
  11654. }
  11655. createUninitialized(typ) {
  11656. const n = this.create('prim::Uninitialized');
  11657. n.output().setType(typ);
  11658. return n;
  11659. }
  11660. createEnumValue(e) {
  11661. const enum_type = e.type().expect(torch.EnumType);
  11662. const n = this.create('prim::EnumValue', [e]);
  11663. n.output().setType(enum_type.getValueType());
  11664. return n;
  11665. }
  11666. createList(contained_type, values) {
  11667. const n = this.create('prim::ListConstruct', values);
  11668. for (const v of values) {
  11669. if (!v.type().isSubtypeOf(contained_type)) {
  11670. throw new python.Error('Invalid list item.');
  11671. }
  11672. }
  11673. n.output().setType(torch.ListType.create(contained_type));
  11674. return n;
  11675. }
  11676. createListUnpack(v, size) {
  11677. const list_type = v.type().expect(torch.ListType);
  11678. const elem_type = list_type.getElementType();
  11679. const n = this.create('prim::ListUnpack', [v], 0);
  11680. for (let i = 0; i < size; i++) {
  11681. n.addOutput().setType(elem_type);
  11682. }
  11683. return n;
  11684. }
  11685. createTuple(values, tuple_type) {
  11686. if (!tuple_type) {
  11687. const types = values.map((v) => v.type());
  11688. tuple_type = torch.TupleType.create(types);
  11689. }
  11690. const n = this.create('prim::TupleConstruct', values);
  11691. n.output().setType(tuple_type);
  11692. return n;
  11693. }
  11694. createTupleUnpack(v) {
  11695. const tt = v.type().expect(torch.TupleType);
  11696. const n = this.create('prim::TupleUnpack', [v], 0);
  11697. for (const element of tt.elements()) {
  11698. n.addOutput().setType(element);
  11699. }
  11700. return n;
  11701. }
  11702. createTupleIndex(tup, idx, output_type) {
  11703. const n = this.create('prim::TupleIndex', [tup, idx]);
  11704. n.output().setType(output_type);
  11705. return n;
  11706. }
  11707. createTupleSlice(tup, beg, step_size, num_values) {
  11708. const new_vals = [];
  11709. const tt = tup.type().expect(torch.TupleType);
  11710. let i = beg;
  11711. for (let j = 0; j < num_values; j++) {
  11712. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11713. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11714. new_vals.push(tupleIndex.output());
  11715. i += step_size;
  11716. }
  11717. const n = this.createTuple(new_vals);
  11718. return n;
  11719. }
  11720. createDict(key_type, value_type, keys, values) {
  11721. if (keys.length !== values.length) {
  11722. throw new python.Error('Invalid dictionary size.');
  11723. }
  11724. const n = this.create('prim::DictConstruct');
  11725. const length = keys.length;
  11726. for (let i = 0; i < length; i++) {
  11727. if (!keys[i].type().isSubtypeOf(key_type)) {
  11728. throw new python.Error('Invalid key.');
  11729. }
  11730. if (!values[i].type().isSubtypeOf(value_type)) {
  11731. throw new python.Error('Invalid value.');
  11732. }
  11733. n.addInput(keys[i]);
  11734. n.addInput(values[i]);
  11735. }
  11736. n.output().setType(torch.DictType.create(key_type, value_type));
  11737. return n;
  11738. }
  11739. createObject(type) {
  11740. const node = this.create('prim::CreateObject');
  11741. node.output().setType(type);
  11742. return node;
  11743. }
  11744. createIsInstance(v, types) {
  11745. const n = this.create('prim::isinstance', [v], 1);
  11746. n.tys_('types', types);
  11747. n.output().setType(torch.BoolType.get());
  11748. return n;
  11749. }
  11750. createSetAttr(obj, field, newValue) {
  11751. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11752. n.s_('name', field);
  11753. return n;
  11754. }
  11755. createGetAttr(obj, field) {
  11756. const n = this.create('prim::GetAttr', [obj]);
  11757. n.s_('name', field);
  11758. const classType = obj.type();
  11759. const outputType = classType.getAttribute(field);
  11760. n.output().setType(outputType);
  11761. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11762. return n;
  11763. }
  11764. createLoad(name, type) {
  11765. const n = this.create('prim::Load', [], 1);
  11766. n.s_('name', name);
  11767. n.output().setType(type);
  11768. return n;
  11769. }
  11770. createStore(name, v) {
  11771. const n = this.create('prim::Store', [v], 0);
  11772. n.s_('name', name);
  11773. return n;
  11774. }
  11775. inputs() {
  11776. return this._block.inputs();
  11777. }
  11778. outputs() {
  11779. return this._block.outputs();
  11780. }
  11781. nodes() {
  11782. return this._block.nodes();
  11783. }
  11784. param_node() {
  11785. return this._block.param_node();
  11786. }
  11787. return_node() {
  11788. return this._block.return_node();
  11789. }
  11790. block() {
  11791. return this._block;
  11792. }
  11793. addInput(name) {
  11794. return this._block.addInput(name);
  11795. }
  11796. insertNode(node) {
  11797. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11798. return node.insertBefore(this._insert_before);
  11799. }
  11800. insertConstant(val, loc, scope) {
  11801. return torch._C.insertConstant(this, val, loc, scope);
  11802. }
  11803. insertMethodCall(method_name, matched) {
  11804. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11805. .s_('name', method_name)
  11806. .output().setType(matched.return_types[0]);
  11807. return result;
  11808. }
  11809. insertUncheckedCast(v, type) {
  11810. const n = this.create('prim::unchecked_cast', [v]);
  11811. this.insertNode(n);
  11812. n.output().setType(type);
  11813. return n.output();
  11814. }
  11815. insertToList(v, type) {
  11816. let dim = 0;
  11817. let ptr = type;
  11818. while (ptr instanceof torch.ListType) {
  11819. ptr = ptr.getElementType();
  11820. dim += 1;
  11821. }
  11822. let elem_ty = 0;
  11823. if (ptr instanceof torch.IntType) {
  11824. elem_ty = 0;
  11825. } else if (ptr instanceof torch.FloatType) {
  11826. elem_ty = 1;
  11827. } else if (ptr instanceof torch.BoolType) {
  11828. elem_ty = 2;
  11829. } else if (ptr instanceof torch.ComplexType) {
  11830. elem_ty = 3;
  11831. } else {
  11832. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  11833. }
  11834. const dim_val = this.insertConstant(dim);
  11835. const elem_ty_val = this.insertConstant(elem_ty);
  11836. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  11837. n.output().setType(type);
  11838. return n.output();
  11839. }
  11840. insertFunctionCall(callee, matched) {
  11841. const func_name = callee.name();
  11842. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  11843. const inputs = [fn_constant, ...matched.inputs];
  11844. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  11845. return result;
  11846. }
  11847. insertPoint() {
  11848. return this._insert_before;
  11849. }
  11850. setInsertPoint(node) {
  11851. if (node instanceof torch.Block) {
  11852. node = node.return_node();
  11853. }
  11854. this._insert_before = node;
  11855. }
  11856. freeNode(n) {
  11857. this.all_nodes.delete(n);
  11858. }
  11859. freeValue(v) {
  11860. v.setDebugName('');
  11861. this.all_values.delete(v);
  11862. }
  11863. freeBlock(b) {
  11864. this.all_blocks.delete(b);
  11865. }
  11866. copy() {
  11867. const new_g = new torch.Graph();
  11868. new_g.cloneFrom(this);
  11869. return new_g;
  11870. }
  11871. cloneFrom(src) {
  11872. const env = (v) => {
  11873. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  11874. };
  11875. this.block().cloneFrom(src.block(), env);
  11876. }
  11877. set_op_version(version) {
  11878. this._op_version = version;
  11879. }
  11880. get_op_version() {
  11881. return this._op_version;
  11882. }
  11883. print(out, print_source_locations) {
  11884. out.write('graph(');
  11885. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  11886. out.write('):\n');
  11887. const groups = [];
  11888. for (const node of this.nodes()) {
  11889. node.print(out, 1, groups, print_source_locations);
  11890. }
  11891. out.write(' return (');
  11892. torch._C.printValueRefs(out, this.outputs());
  11893. out.write(')\n');
  11894. for (let i = 0; i < groups.length; i++) {
  11895. const fg = groups[i];
  11896. out.write('with ');
  11897. out.write(fg.kind());
  11898. out.write(`_${i} = `);
  11899. out.write(fg.g('Subgraph'));
  11900. }
  11901. return out;
  11902. }
  11903. toString() {
  11904. const out = new io.StringIO();
  11905. this.print(out, true);
  11906. return out.toString();
  11907. }
  11908. });
  11909. this.registerType('torch.Block', class {
  11910. constructor(graph, node) {
  11911. this._graph = graph;
  11912. this._input = graph.create('prim::Param', 0);
  11913. this._output = graph.create('prim::Return', 0);
  11914. this._owning_node = node;
  11915. this._input.next = this._output;
  11916. this._input.prev = this._output;
  11917. this._output.next = this._input;
  11918. this._output.prev = this._input;
  11919. this._graph.all_blocks.add(this);
  11920. this._output._owning_block = this;
  11921. // output_.topo_position_ = kUpperBound;
  11922. this._input._owning_block = this;
  11923. // input_.topo_position_ = kLowerBound;
  11924. }
  11925. inputs() {
  11926. return this._input.outputs();
  11927. }
  11928. outputs() {
  11929. return this._output.inputs();
  11930. }
  11931. nodes() {
  11932. return new torch._C.graph_node_list(this._input);
  11933. }
  11934. return_node() {
  11935. return this._output;
  11936. }
  11937. param_node() {
  11938. return this._input;
  11939. }
  11940. owningNode() {
  11941. return this._owning_node;
  11942. }
  11943. owningGraph() {
  11944. return this._graph;
  11945. }
  11946. addInput(name) {
  11947. const value = this._input.addOutput();
  11948. value.setDebugName(name || '');
  11949. return value;
  11950. }
  11951. registerOutput(value) {
  11952. this._output.addInput(value);
  11953. return this.outputs().length - 1;
  11954. }
  11955. appendNode(n) {
  11956. if (n._graph !== this._graph || n.inBlockList()) {
  11957. throw new python.Error('Node not in graph.');
  11958. }
  11959. n.insertBefore(this._output);
  11960. return n;
  11961. }
  11962. cloneFrom(src, value_map) {
  11963. const local_map = new Map();
  11964. const env = (v) => {
  11965. if (local_map.has(v)) {
  11966. return local_map.get(v);
  11967. }
  11968. return value_map(v);
  11969. };
  11970. const graph = this.owningGraph();
  11971. for (const input of src.inputs()) {
  11972. local_map.set(input, this.addInput().copyMetadata(input));
  11973. }
  11974. for (const node of src.nodes()) {
  11975. const new_node = this.appendNode(graph.createClone(node, env));
  11976. for (let i = 0; i < node.outputs().length; i++) {
  11977. const oo = node.outputs()[i];
  11978. const no = new_node.outputs()[i];
  11979. local_map.set(oo, no);
  11980. no.copyMetadata(oo);
  11981. }
  11982. }
  11983. for (const output of src.outputs()) {
  11984. this.registerOutput(env(output));
  11985. }
  11986. }
  11987. eraseOutput(i) {
  11988. this._output.removeInput(i);
  11989. }
  11990. destroy() {
  11991. this._output.removeAllInputs();
  11992. for (const n of this.nodes()) {
  11993. n.destroy();
  11994. }
  11995. this._output.destroy();
  11996. this._input.destroy();
  11997. this._graph.freeBlock(this);
  11998. }
  11999. });
  12000. this.registerType('torch.Node', class {
  12001. constructor(graph, kind) {
  12002. this._kind = kind;
  12003. this._graph = graph;
  12004. this._owning_block = null;
  12005. this._values = new Map();
  12006. this._inputs = [];
  12007. this._outputs = [];
  12008. this._blocks = [];
  12009. this._graph.all_nodes.add(this);
  12010. this._prev = null;
  12011. this._next = null;
  12012. this._source_range = null;
  12013. this._op = null;
  12014. }
  12015. owningGraph() {
  12016. return this._graph;
  12017. }
  12018. owningBlock() {
  12019. return this._owning_block;
  12020. }
  12021. kind() {
  12022. return this._kind;
  12023. }
  12024. schema() {
  12025. if (this._op) {
  12026. return this._op.schema();
  12027. }
  12028. // Node::schema() throws while torch.Node.schema() does not.
  12029. const op = this.maybeOperator();
  12030. if (op) {
  12031. return op.schema();
  12032. }
  12033. return null;
  12034. // return this.getOperator().schema();
  12035. }
  12036. hasNamedInput(name) {
  12037. for (const argument of this.schema().arguments) {
  12038. if (argument.name === name) {
  12039. return true;
  12040. }
  12041. }
  12042. return false;
  12043. }
  12044. matches(schema) {
  12045. if (torch._C.isBlockListedSchema(schema)) {
  12046. return false;
  12047. }
  12048. if (this.kind() !== schema.name) {
  12049. return false;
  12050. }
  12051. const actuals = this.inputs();
  12052. const formals = schema.arguments;
  12053. if (actuals.length < formals.length) {
  12054. return false;
  12055. }
  12056. const type_env = new Map();
  12057. for (let i = 0; i < formals.length; i++) {
  12058. let formal = formals[i].type;
  12059. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12060. if (!matched_type.success()) {
  12061. return false;
  12062. }
  12063. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12064. if (resolved) {
  12065. formal = resolved;
  12066. }
  12067. if (!actuals[i].type().isSubtypeOf(formal)) {
  12068. return false;
  12069. }
  12070. }
  12071. if (!schema.is_vararg && actuals.length !== formals.length) {
  12072. return false;
  12073. }
  12074. return true;
  12075. }
  12076. mustBeNone() {
  12077. return this._kind === 'prim::AutogradZero' ||
  12078. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12079. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12080. }
  12081. maybeSchema() {
  12082. const op = this.maybeOperator();
  12083. if (op) {
  12084. return op.schema();
  12085. }
  12086. return null;
  12087. }
  12088. maybeOperator() {
  12089. if (!this._op) {
  12090. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12091. for (const candidate of candidates) {
  12092. if (this.matches(candidate.schema())) {
  12093. this._op = candidate;
  12094. break;
  12095. }
  12096. }
  12097. }
  12098. return this._op;
  12099. }
  12100. getOperator() {
  12101. const maybe = this.maybeOperator();
  12102. if (maybe) {
  12103. return maybe;
  12104. }
  12105. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12106. }
  12107. getOperation() {
  12108. return this.getOperator().getOperation(this);
  12109. }
  12110. isNondeterministic() {
  12111. const schema = this.maybeSchema();
  12112. if (!this.kind().startsWith('aten::')) {
  12113. return false;
  12114. }
  12115. if (!schema) {
  12116. return false;
  12117. }
  12118. const schema_info = new torch._C.SchemaInfo(schema);
  12119. if (this.hasNamedInput('train')) {
  12120. throw new python.Error('Not Implemented.');
  12121. // const value = constant_as<bool>(this.namedInput("train"));
  12122. // if (value) {
  12123. // schema_info.addArgumentValue('train', value);
  12124. // }
  12125. }
  12126. return schema_info.is_nondeterministic();
  12127. }
  12128. hasSideEffects() {
  12129. switch (this._kind) {
  12130. case 'prim::PythonOp':
  12131. case 'prim::IgnoredPythonOp':
  12132. case 'prim::Print':
  12133. case 'prim::RaiseException':
  12134. case 'aten::warn':
  12135. case 'aten::save':
  12136. case 'aten::manual_seed':
  12137. case 'prim::AddStatValue':
  12138. case 'prim::TimePoint':
  12139. case 'prim::CallFunction':
  12140. case 'prim::CallMethod':
  12141. case 'prim::BailoutTemplate':
  12142. case 'prim::BailOut':
  12143. case 'prim::rpc_async':
  12144. case 'prim::rpc_sync':
  12145. case 'prim::rpc_remote':
  12146. case 'aten::wait':
  12147. case 'cuda::set_stream':
  12148. case 'cuda::_set_device':
  12149. case 'cuda::_current_device':
  12150. case 'cuda::synchronize':
  12151. case 'prim::Enter':
  12152. case 'prim::Exit':
  12153. return true;
  12154. default:
  12155. break;
  12156. }
  12157. const op = this.maybeOperator();
  12158. if (!op) {
  12159. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12160. return false;
  12161. }
  12162. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12163. torch._C.TORCH_INTERNAL_ASSERT(
  12164. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12165. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12166. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12167. }
  12168. switch (op.aliasAnalysisKind()) {
  12169. case 'PURE_FUNCTION':
  12170. case 'FROM_SCHEMA':
  12171. case 'INTERNAL_SPECIAL_CASE':
  12172. return false;
  12173. case 'CONSERVATIVE':
  12174. return true;
  12175. default:
  12176. break;
  12177. }
  12178. torch._C.TORCH_INTERNAL_ASSERT(false);
  12179. return false;
  12180. }
  12181. inputs() {
  12182. return this._inputs;
  12183. }
  12184. outputs() {
  12185. return this._outputs;
  12186. }
  12187. input(i) {
  12188. if (i === undefined) {
  12189. torch._C.AT_ASSERT(this._inputs.length === 1);
  12190. return this._inputs[0];
  12191. }
  12192. return this._inputs[i];
  12193. }
  12194. output(i) {
  12195. if (i === undefined) {
  12196. torch._C.AT_ASSERT(this._outputs.length === 1);
  12197. return this._outputs[0];
  12198. }
  12199. return this._outputs[i];
  12200. }
  12201. hasUses() {
  12202. for (const o of this.outputs()) {
  12203. if (o.uses().length > 0) {
  12204. return true;
  12205. }
  12206. }
  12207. return false;
  12208. }
  12209. blocks() {
  12210. return this._blocks;
  12211. }
  12212. insertInput(i, value) {
  12213. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12214. this._op = null;
  12215. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12216. const use = this.findUseForInput(use_itr);
  12217. use.offset += 1;
  12218. }
  12219. this._inputs.splice(i, 0, value);
  12220. value._uses.push(new torch.Use(this, i));
  12221. return value;
  12222. }
  12223. addInput(value) {
  12224. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12225. this._op = null;
  12226. const use = new torch.Use(this, this._inputs.length);
  12227. value.uses().push(use);
  12228. this._inputs.push(value);
  12229. return value;
  12230. }
  12231. addOutput() {
  12232. const value = new torch.Value(this, this._outputs.length);
  12233. this._outputs.push(value);
  12234. return value;
  12235. }
  12236. addBlock() {
  12237. this._op = null;
  12238. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12239. return this._blocks[this._blocks.length - 1];
  12240. }
  12241. get prev() {
  12242. return this._prev;
  12243. }
  12244. set prev(value) {
  12245. this._prev = value;
  12246. }
  12247. get next() {
  12248. return this._next;
  12249. }
  12250. set next(value) {
  12251. this._next = value;
  12252. }
  12253. insertBefore(n) {
  12254. if (!n.inBlockList()) {
  12255. throw new python.Error('Node not in block.');
  12256. }
  12257. this.insertAfter(n.prev);
  12258. return this;
  12259. }
  12260. insertAfter(n) {
  12261. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12262. torch._C.AT_ASSERT(n.owningBlock());
  12263. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12264. this._owning_block = n.owningBlock();
  12265. const next = n.next;
  12266. n.next = this;
  12267. this.prev = n;
  12268. this.next = next;
  12269. next.prev = this;
  12270. // this.assignTopoPosition();
  12271. return this;
  12272. }
  12273. allocNewInstance(g) {
  12274. return new torch.Node(g, this.kind());
  12275. }
  12276. cloneFrom(s) {
  12277. this._source_range = s._source_range;
  12278. if (s._scope && !s._scope.isBlank()) {
  12279. this._scope = s._scope;
  12280. }
  12281. this.copyAttributes(s);
  12282. this._callstack = s._callstack;
  12283. }
  12284. copyAttributes(rhs) {
  12285. this._values = new Map(rhs._values);
  12286. return this;
  12287. }
  12288. dropInput(i) {
  12289. torch._C.AT_ASSERT(i < this._inputs.length);
  12290. const input_node = this._inputs[i];
  12291. const use_it = this.findUseForInput(i);
  12292. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12293. this._inputs[i] = null;
  12294. return input_node;
  12295. }
  12296. eraseOutput(i) {
  12297. torch._C.AT_ASSERT(i < this._outputs.length);
  12298. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12299. this._op = null;
  12300. const n = this._outputs[i];
  12301. this._outputs.splice(i, 1);
  12302. this.owningGraph().freeValue(n);
  12303. for (let j = i; j < this._outputs.length; j++) {
  12304. this._outputs[j]._offset--;
  12305. }
  12306. }
  12307. eraseBlock(i) {
  12308. this._op = null;
  12309. const n = this._blocks[i];
  12310. this._blocks.splice(i, 1);
  12311. n.destroy();
  12312. }
  12313. findUseForInput(i) {
  12314. const input_uses = this._inputs[i]._uses;
  12315. for (const use_it of input_uses) {
  12316. if (use_it.user === this && use_it.offset === i) {
  12317. return use_it;
  12318. }
  12319. }
  12320. throw new python.Error('Input use not found.');
  12321. }
  12322. moveBefore(n) {
  12323. this.removeFromList();
  12324. this.insertBefore(n);
  12325. }
  12326. removeInput(i) {
  12327. this._op = null;
  12328. this.dropInput(i);
  12329. for (let j = i + 1; j < this._inputs.length; j++) {
  12330. const it = this.findUseForInput(j);
  12331. it.offset--;
  12332. }
  12333. this._inputs.splice(i, 1);
  12334. }
  12335. removeAllInputs() {
  12336. this._op = null;
  12337. for (let i = 0; i < this._inputs.length; i++) {
  12338. this.dropInput(i);
  12339. }
  12340. this._inputs = [];
  12341. }
  12342. inBlockList() {
  12343. return this.next !== null;
  12344. }
  12345. removeFromList() {
  12346. this._owning_block = null;
  12347. const next = this.next;
  12348. const prev = this.prev;
  12349. prev.next = next;
  12350. next.prev = prev;
  12351. this.next = null;
  12352. this.prev = null;
  12353. }
  12354. destroy() {
  12355. while (this.outputs().length > 0) {
  12356. this.eraseOutput(this.outputs().length - 1);
  12357. }
  12358. while (this.blocks().length > 0) {
  12359. this.eraseBlock(this.blocks().length - 1);
  12360. }
  12361. this.removeAllInputs();
  12362. if (this.inBlockList()) {
  12363. this.removeFromList();
  12364. }
  12365. this._graph.freeNode(this);
  12366. }
  12367. replaceAllUsesWith(n) {
  12368. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12369. const nOutputs = this.outputs().length;
  12370. for (let i = 0; i < nOutputs; i++) {
  12371. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12372. }
  12373. }
  12374. s_(name, value) {
  12375. this._values.set(name, [value, 's']);
  12376. return this;
  12377. }
  12378. s(name) {
  12379. return this._values.get(name)[0];
  12380. }
  12381. ss_(name, value) {
  12382. this._values.set(name, [value, 'ss']);
  12383. return this;
  12384. }
  12385. ss(name) {
  12386. return this._values.get(name)[0];
  12387. }
  12388. i_(name, value) {
  12389. this._values.set(name, [value, 'i']);
  12390. return this;
  12391. }
  12392. i(name) {
  12393. return this._values.get(name)[0];
  12394. }
  12395. f_(name, value) {
  12396. this._values.set(name, [value, 'f']);
  12397. return this;
  12398. }
  12399. f(name) {
  12400. return this._values.get(name)[0];
  12401. }
  12402. t_(name, value) {
  12403. this._values.set(name, [value, 't']);
  12404. return this;
  12405. }
  12406. t(name) {
  12407. return this._values.get(name)[0];
  12408. }
  12409. tys_(name, value) {
  12410. this._values.set(name, [value, 'tys']);
  12411. return this;
  12412. }
  12413. tys(name) {
  12414. return this._values.get(name)[0];
  12415. }
  12416. ival_(name, value) {
  12417. this._values.set(name, [value, 'ival']);
  12418. return this;
  12419. }
  12420. ival(name) {
  12421. return this._values.get(name)[0];
  12422. }
  12423. hasAttribute(name) {
  12424. return this._values.has(name);
  12425. }
  12426. hasAttributes() {
  12427. return this._values.size > 0;
  12428. }
  12429. attributeNames() {
  12430. return Array.from(this._values.keys());
  12431. }
  12432. kindOf(name) {
  12433. return this._values.get(name)[1];
  12434. }
  12435. setSourceRange(r) {
  12436. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12437. this._source_range = r;
  12438. return this;
  12439. }
  12440. sourceRange() {
  12441. if (this._source_range) {
  12442. return this._source_range;
  12443. }
  12444. return new torch._C.SourceRange();
  12445. }
  12446. print_attributes(out, ignore_subgraph) {
  12447. ignore_subgraph = ignore_subgraph || false;
  12448. out.write('[');
  12449. const names = this.attributeNames();
  12450. for (let i = 0; i < names.length; i++) {
  12451. const name = names[i];
  12452. if (ignore_subgraph && name === 'Subgraph') {
  12453. continue;
  12454. }
  12455. if (i > 0) {
  12456. out.write(', ');
  12457. }
  12458. out.write(`${name}=`);
  12459. this.printAttrValue(out, name);
  12460. }
  12461. out.write(']');
  12462. }
  12463. printTypeList(out, items) {
  12464. out.write('[');
  12465. for (let i = 0; i < items.length; i++) {
  12466. const item = items[i];
  12467. if (i++ > 0) {
  12468. out.write(', ');
  12469. }
  12470. out.write(item.str());
  12471. }
  12472. out.write(']');
  12473. }
  12474. printAttrValue(out, name) {
  12475. const kind = this.kindOf(name);
  12476. switch (kind) {
  12477. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12478. case 'ss': case 'ival': case 'ty':
  12479. out.write(this[kind](name));
  12480. break;
  12481. case 's':
  12482. out.write(`"${this.s(name)}"`);
  12483. break;
  12484. case 't':
  12485. out.write(`"{}"`);
  12486. break;
  12487. case 'ts': out.write('[<Tensors>]'); break;
  12488. case 'g': out.write('[<Graph>]'); break;
  12489. case 'gs': out.write('[<Graphs>]'); break;
  12490. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12491. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12492. }
  12493. }
  12494. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12495. print_source_locations = print_source_locations === false ? false : true;
  12496. print_attributes = print_attributes === false ? false : true;
  12497. print_scopes = print_scopes === false ? false : true;
  12498. print_body = print_body === false ? false : true;
  12499. const outs = this.outputs();
  12500. torch._C.indent(out, level);
  12501. torch._C.const_value_list_with_types(out, outs, ', ');
  12502. out.write(' = ');
  12503. if (this.kind() === 'prim::PythonOp') {
  12504. throw new python.Error('Not implemented.');
  12505. } else if (this.hasAttribute('Subgraph') && groups) {
  12506. throw new python.Error('Not implemented.');
  12507. } else {
  12508. out.write(this.kind());
  12509. if (print_attributes && this.hasAttributes()) {
  12510. this.print_attributes(out);
  12511. }
  12512. }
  12513. out.write('(');
  12514. torch._C.printValueRefs(out, this.inputs());
  12515. out.write(')');
  12516. if (print_scopes) {
  12517. //
  12518. }
  12519. if (print_source_locations) {
  12520. let r = this.sourceRange();
  12521. if (r.source()) {
  12522. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12523. if (orig) {
  12524. r = orig;
  12525. }
  12526. }
  12527. const file_line_col = r.file_line_col();
  12528. if (file_line_col !== null) {
  12529. const [filename, line, col] = file_line_col;
  12530. out.write(` # ${filename}:${line}:${col}`);
  12531. }
  12532. }
  12533. if (!print_body) {
  12534. return out;
  12535. }
  12536. out.write('\n');
  12537. for (let i = 0; i < this.blocks().length; i++) {
  12538. const b = this.blocks().at(i);
  12539. torch._C.indent(out, level + 1);
  12540. out.write(`block${i}(`);
  12541. torch._C.const_value_list_with_types(out, b.inputs());
  12542. out.write('):\n');
  12543. for (const nested of b.nodes()) {
  12544. nested.print(out, level + 2, groups);
  12545. }
  12546. torch._C.indent(out, level + 2);
  12547. out.write('-> (');
  12548. torch._C.printValueRefs(out, b.outputs());
  12549. out.write(')\n');
  12550. }
  12551. return out;
  12552. }
  12553. toString() {
  12554. const out = new io.StringIO();
  12555. this.print(out, 0, true);
  12556. return out.toString();
  12557. }
  12558. });
  12559. this.registerType('torch.Value', class {
  12560. constructor(node, offset) {
  12561. this._node = node;
  12562. this._offset = offset;
  12563. this._unique = node._graph._next_unique++;
  12564. this._uses = [];
  12565. this._node._graph.all_values.add(this);
  12566. }
  12567. unique() {
  12568. return this._unique;
  12569. }
  12570. node() {
  12571. return this._node;
  12572. }
  12573. owningGraph() {
  12574. return this._node.owningGraph();
  12575. }
  12576. uses() {
  12577. return this._uses;
  12578. }
  12579. hasUses() {
  12580. return this._uses.length > 0;
  12581. }
  12582. mustBeNone() {
  12583. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12584. }
  12585. mustNotBeNone() {
  12586. return this._node.kind() !== 'prim::AutogradAdd' &&
  12587. this.type() !== torch.NoneType.get() &&
  12588. !(this.type() instanceof torch.OptionalType) &&
  12589. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12590. }
  12591. isValidName(name) {
  12592. if (name.length === 0) {
  12593. return true;
  12594. }
  12595. if (torch._C.isNumber(name)) {
  12596. return false;
  12597. }
  12598. return true;
  12599. }
  12600. hasDebugName() {
  12601. return this._unique_name && this._unique_name.length > 0;
  12602. }
  12603. setDebugName(name) {
  12604. if (!this.isValidName(name)) {
  12605. throw new python.Error(`Invalid name '${name}'.`);
  12606. }
  12607. const names = this.node().owningGraph()._unique_names;
  12608. if (this.hasDebugName()) {
  12609. names.delete(this._unique_name);
  12610. this._unique_name = '';
  12611. }
  12612. if (!name) {
  12613. return this;
  12614. }
  12615. const old_owner_of_name = names.get(name);
  12616. if (old_owner_of_name) {
  12617. let suffix = 1;
  12618. let name_base = name;
  12619. const last_dot_pos = name.lastIndexOf('.');
  12620. if (last_dot_pos !== -1) {
  12621. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12622. suffix = Number(name.substring(last_dot_pos + 1));
  12623. name_base = name.substring(0, last_dot_pos);
  12624. }
  12625. }
  12626. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12627. if (names_suffixes.has(name_base)) {
  12628. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12629. }
  12630. let replacement_name = null;
  12631. do {
  12632. replacement_name = `${name_base}.${suffix++}`;
  12633. } while (names.has(replacement_name));
  12634. names_suffixes.set(name_base, suffix);
  12635. old_owner_of_name.setDebugName(replacement_name);
  12636. }
  12637. names.set(name, this);
  12638. this._unique_name = name;
  12639. return this;
  12640. }
  12641. debugName() {
  12642. if (this.hasDebugName()) {
  12643. return this._unique_name;
  12644. }
  12645. return this.unique().toString();
  12646. }
  12647. type() {
  12648. return this._type;
  12649. }
  12650. setType(type) {
  12651. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12652. if (type instanceof torch._C.DynamicType) {
  12653. type = type.fallback();
  12654. }
  12655. this._type = type;
  12656. for (const use of this._uses) {
  12657. use.user._op = null;
  12658. }
  12659. return this;
  12660. }
  12661. set value(value) { // remove
  12662. if (value instanceof torch.Value) {
  12663. throw new python.Error('Value cannot be a value.');
  12664. }
  12665. this._value = value;
  12666. }
  12667. get value() { // remove
  12668. return this._value;
  12669. }
  12670. replaceFirstUseWith(newValue) {
  12671. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12672. const [u] = this.uses();
  12673. u.user._inputs[u.offset] = newValue;
  12674. newValue._uses.push(u);
  12675. this._uses.shift();
  12676. }
  12677. replaceAllUsesWith(newValue) {
  12678. while (this.uses().length > 0) {
  12679. this.replaceFirstUseWith(newValue);
  12680. }
  12681. }
  12682. copyMetadata(from) {
  12683. this.setType(from.type());
  12684. if (from.hasDebugName()) {
  12685. this.setDebugName(from.debugName());
  12686. }
  12687. return this;
  12688. }
  12689. toString() {
  12690. return `${this.debugName()} : ${this.type().toString()}`;
  12691. }
  12692. });
  12693. this.registerType('torch.Use', class {
  12694. constructor(user, offset) {
  12695. this.user = user;
  12696. this.offset = offset;
  12697. }
  12698. });
  12699. this.registerType('torch._C.IValue', class {
  12700. constructor(value, tag) {
  12701. this.value = value;
  12702. if (tag) {
  12703. this.tag = tag;
  12704. } else if (value === undefined) {
  12705. this.tag = 'None';
  12706. this.value = null;
  12707. } else if (typeof value === 'boolean') {
  12708. this.tag = 'Bool';
  12709. } else if (typeof value === 'string') {
  12710. this.tag = 'String';
  12711. } else if (value instanceof torch.Tensor) {
  12712. this.tag = 'Tensor';
  12713. } else if (value instanceof torch.ScriptObject) {
  12714. this.tag = 'Object';
  12715. } else if (Array.isArray(value)) {
  12716. this.tag = 'GenericList';
  12717. } else if (value instanceof torch._C.Tuple) {
  12718. this.tag = 'Tuple';
  12719. } else if (value instanceof torch.device) {
  12720. this.tag = 'Device';
  12721. } else if (Number.isInteger(value)) {
  12722. this.tag = 'Int';
  12723. } else if (typeof value === 'number') {
  12724. this.tag = 'Double';
  12725. } else if (value instanceof torch._C.EnumHolder) {
  12726. this.tag = 'Enum';
  12727. } else {
  12728. throw new python.Error('Unsupported type.');
  12729. }
  12730. }
  12731. isNone() {
  12732. return this.tag === 'None';
  12733. }
  12734. isBool() {
  12735. return this.tag === 'Bool';
  12736. }
  12737. toBool() {
  12738. return this.value;
  12739. }
  12740. isObject() {
  12741. return this.tag === 'Object';
  12742. }
  12743. toObject() {
  12744. return this.value;
  12745. }
  12746. isTensor() {
  12747. return this.tag === 'Tensor';
  12748. }
  12749. toTensor() {
  12750. return this.value;
  12751. }
  12752. isDouble() {
  12753. return this.tag === 'Double';
  12754. }
  12755. toDouble() {
  12756. return this.value;
  12757. }
  12758. isComplexDouble() {
  12759. return this.tag === 'ComplexDouble';
  12760. }
  12761. isInt() {
  12762. return this.tag === 'Int';
  12763. }
  12764. toInt() {
  12765. if (this.isInt()) {
  12766. return this.value;
  12767. } else if (this.isSymInt()) {
  12768. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12769. }
  12770. throw new python.Error('Expected int.');
  12771. }
  12772. isString() {
  12773. return this.tag === 'String';
  12774. }
  12775. toStringRef() {
  12776. return this.value;
  12777. }
  12778. isList() {
  12779. return this.tag === 'GenericList';
  12780. }
  12781. toList() {
  12782. return this.value;
  12783. }
  12784. toListRef() {
  12785. return this.value;
  12786. }
  12787. isBoolList() {
  12788. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12789. }
  12790. isIntList() {
  12791. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12792. }
  12793. isDoubleList() {
  12794. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12795. }
  12796. isDevice() {
  12797. return this.tag === 'Device';
  12798. }
  12799. toDevice() {
  12800. return this.value;
  12801. }
  12802. isGenerator() {
  12803. return this.tag === 'Generator';
  12804. }
  12805. isStream() {
  12806. return this.tag === 'Stream';
  12807. }
  12808. isGenericDict() {
  12809. return this.tag === 'GenericDict';
  12810. }
  12811. isEnum() {
  12812. return this.tag === 'Enum';
  12813. }
  12814. toEnumHolder() {
  12815. return this.value;
  12816. }
  12817. isTuple() {
  12818. return this.tag === 'Tuple';
  12819. }
  12820. toTupleRef() {
  12821. return this.value;
  12822. }
  12823. isCustomClass() {
  12824. return torch._C.isCustomClass(this);
  12825. }
  12826. equals(rhs) {
  12827. switch (this.tag) {
  12828. case 'None': return rhs.isNone();
  12829. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  12830. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  12831. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  12832. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  12833. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  12834. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  12835. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  12836. case 'GenericList': {
  12837. if (rhs.isList()) {
  12838. const a = this.toList();
  12839. const b = rhs.toList();
  12840. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  12841. }
  12842. return false;
  12843. }
  12844. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  12845. }
  12846. }
  12847. is(rhs) {
  12848. return this.equals(rhs);
  12849. }
  12850. type() {
  12851. switch (this.tag) {
  12852. case 'None': return torch.NoneType.get();
  12853. case 'Bool': return torch.BoolType.get();
  12854. case 'Int': return torch.IntType.get();
  12855. case 'Double': return torch.FloatType.get();
  12856. case 'String': return torch.StringType.get();
  12857. case 'Device': return torch.DeviceObjType.get();
  12858. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  12859. case 'Enum': return this.toEnumHolder().type();
  12860. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  12861. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  12862. }
  12863. }
  12864. });
  12865. this.registerFunction('torch._C.indent', (out, level) => {
  12866. for (let i = 0; i < level; i++) {
  12867. out.write(' ');
  12868. }
  12869. return out;
  12870. });
  12871. this.registerFunction('torch._C.printValueRef', (out, n) => {
  12872. out.write(`%${n.debugName()}`);
  12873. });
  12874. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  12875. for (let i = 0; i < nodes.length; i++) {
  12876. const n = nodes[i];
  12877. if (i > 0) {
  12878. out.write(', ');
  12879. }
  12880. torch._C.printValueRef(out, n);
  12881. }
  12882. return out;
  12883. });
  12884. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  12885. for (let i = 0; i < values.length; i++) {
  12886. const n = values[i];
  12887. if (i > 0) {
  12888. out.write(delim);
  12889. }
  12890. torch._C.printValueRef(out, n);
  12891. out.write(' : ');
  12892. out.write(n.type().str());
  12893. }
  12894. });
  12895. this.register('torch.jit._script');
  12896. this.register('torch.jit._trace');
  12897. this.registerType('torch._C.Parser', class {
  12898. constructor(source) {
  12899. this.L = source;
  12900. }
  12901. parse() {
  12902. const p = ast.parse(this.L.text_str(), this.L.filename());
  12903. return p;
  12904. }
  12905. parseExp() {
  12906. const expr = ast.parse(this.L.text_str());
  12907. return expr.body[0].value;
  12908. }
  12909. });
  12910. this.registerType('torch._C.StringCordView', class {
  12911. });
  12912. this.registerType('torch._C.Source', class {
  12913. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  12914. if (text_view instanceof Uint8Array) {
  12915. const decoder = new TextDecoder('utf-8');
  12916. this._text_view = decoder.decode(text_view);
  12917. } else if (typeof text_view === 'string') {
  12918. this._text_view = text_view;
  12919. } else {
  12920. throw new python.Error('Invalid text view.');
  12921. }
  12922. this._filename = filename;
  12923. this._starting_line_no = starting_line_no;
  12924. this._gen_ranges = gen_ranges;
  12925. this.calc_line_start_offsets();
  12926. }
  12927. text_str() {
  12928. return this._text_view;
  12929. }
  12930. size() {
  12931. return this._text_view.length;
  12932. }
  12933. filename() {
  12934. return this._filename;
  12935. }
  12936. calc_line_start_offsets() {
  12937. let pos = 0;
  12938. this._line_starting_offsets = [0];
  12939. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  12940. pos += 1;
  12941. this._line_starting_offsets.push(pos);
  12942. }
  12943. }
  12944. offset_for_line(line) {
  12945. return this._line_starting_offsets[line];
  12946. }
  12947. lineno_for_offset(offset) {
  12948. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  12949. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  12950. }
  12951. lineno_to_source_lineno(lineno) {
  12952. if (this._filename) {
  12953. return lineno + this._starting_line_no;
  12954. }
  12955. return lineno;
  12956. }
  12957. findSourceRangeThatGenerated(range) {
  12958. if (!this._gen_ranges) {
  12959. return null;
  12960. }
  12961. return this._gen_ranges.findSourceRangeThatGenerated(range);
  12962. }
  12963. });
  12964. this.registerType('torch._C.SourceRange', class {
  12965. constructor(...args) {
  12966. if (args.length === 0) {
  12967. this._source_view = null;
  12968. } else if (args.length === 2) {
  12969. let node = null;
  12970. [this._source_view, node] = args;
  12971. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  12972. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  12973. } else if (args.length === 3) {
  12974. [this._source_view, this._start, this._end] = args;
  12975. } else {
  12976. throw new python.Error('Not implemented.');
  12977. }
  12978. }
  12979. source() {
  12980. return this._source_view;
  12981. }
  12982. file_line_col() {
  12983. if (!this._source_view || this.source().filename() === null) {
  12984. return null;
  12985. }
  12986. const lineno = this._source_view.lineno_for_offset(this._start);
  12987. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  12988. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  12989. }
  12990. start() {
  12991. return this._start;
  12992. }
  12993. toString() {
  12994. const loc = this.file_line_col();
  12995. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  12996. }
  12997. });
  12998. this.registerType('torch._C.QualifiedName', class {
  12999. constructor(...args) {
  13000. let name = null;
  13001. if (args.length === 1 && typeof args[0] === 'string') {
  13002. [name] = args;
  13003. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13004. name = args[0].join('.');
  13005. } else {
  13006. name = `${args[0].qualifiedName()}.${args[1]}`;
  13007. }
  13008. const index = name.lastIndexOf('.');
  13009. this._qualifiedName = name;
  13010. this._prefix = index === -1 ? '' : name.substring(0, index);
  13011. this._name = index === -1 ? name : name.substring(index + 1);
  13012. }
  13013. qualifiedName() {
  13014. return this._qualifiedName; // "foo.bar.baz"
  13015. }
  13016. prefix() {
  13017. return this._prefix; // "foo.bar"
  13018. }
  13019. name() {
  13020. return this._name; // "baz"
  13021. }
  13022. atoms() {
  13023. return this._qualifiedName.split('.');
  13024. }
  13025. });
  13026. this.registerType('torch._C.Resolver', class {
  13027. resolveValue() {
  13028. throw new python.Error('Not implemented.');
  13029. }
  13030. resolveType() {
  13031. throw new python.Error('Not implemented.');
  13032. }
  13033. });
  13034. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13035. torch._C.customClasses = torch._C.customClasses || new Map();
  13036. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13037. const name = class_type.name().qualifiedName();
  13038. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13039. torch._C.customClasses.set(name, class_type);
  13040. });
  13041. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13042. torch._C.customClasses = torch._C.customClasses || new Map();
  13043. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13044. return ret;
  13045. });
  13046. this.registerFunction('torch._C.isCustomClass', (v) => {
  13047. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13048. });
  13049. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13050. constructor(cu, constant_table, source_loader, version) {
  13051. super();
  13052. this._cu = cu;
  13053. this._constant_table = constant_table;
  13054. this._source_loader = source_loader;
  13055. this._version = version;
  13056. this._loaded_sources = new Set();
  13057. this._sources = new Map();
  13058. const sources = this._sources;
  13059. ast.AST.prototype.range = function() {
  13060. if (!this._range) {
  13061. if (sources.has(this.filename)) {
  13062. const source_view = sources.get(this.filename);
  13063. this._range = new torch._C.SourceRange(source_view, this);
  13064. } else {
  13065. this._range = new torch._C.SourceRange();
  13066. }
  13067. }
  13068. return this._range;
  13069. };
  13070. this._to_be_defined = new Map();
  13071. this._env = new Map([
  13072. ['torch', new torch._C.BuiltinModule('aten', version)],
  13073. ['ops', new torch._C.OpsValue(version)],
  13074. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13075. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13076. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13077. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13078. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13079. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13080. ]);
  13081. }
  13082. loadType(name) {
  13083. const type_parser = new torch._C.ScriptTypeParser(this);
  13084. return type_parser.parseType(name.qualifiedName());
  13085. }
  13086. resolveType(name) {
  13087. name = new torch._C.QualifiedName(name);
  13088. return this.findNamedType(name);
  13089. }
  13090. resolveValue(name, m, loc) {
  13091. if (this._env.has(name)) {
  13092. return this._env.get(name);
  13093. }
  13094. const graph = m.graph();
  13095. switch (name) {
  13096. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13097. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13098. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13099. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13100. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13101. default: return null;
  13102. }
  13103. }
  13104. findNamedType(name) {
  13105. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13106. if (custom_class) {
  13107. return custom_class;
  13108. }
  13109. this.parseSourceIfNeeded(name.prefix());
  13110. const key = name.qualifiedName();
  13111. const it = this._to_be_defined.get(key);
  13112. if (it && it instanceof ast.ClassDef) {
  13113. this._to_be_defined.delete(key);
  13114. this.importNamedType(name.prefix(), it);
  13115. }
  13116. return this._cu.get_type(name);
  13117. }
  13118. importNamedType(qualifier, class_def) {
  13119. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13120. if (class_def.bases.length === 0) {
  13121. this.importClass(qualified_name, class_def, false);
  13122. return;
  13123. }
  13124. const superclass_name = class_def.bases[0].id;
  13125. if (superclass_name === 'Module') {
  13126. this.importClass(qualified_name, class_def, true);
  13127. } else if (superclass_name === 'NamedTuple') {
  13128. this.importNamedTuple(qualified_name, class_def);
  13129. } else if (superclass_name === 'Interface') {
  13130. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13131. } else if (superclass_name === 'ModuleInterface') {
  13132. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13133. } else if (superclass_name === 'Enum') {
  13134. this.importEnum(qualified_name, class_def);
  13135. } else {
  13136. throw new python.Error('TorchScript does not support class inheritance.');
  13137. }
  13138. }
  13139. importClass(qualified_classname, class_def, is_module) {
  13140. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13141. return;
  13142. }
  13143. const parameter_names = new Set();
  13144. const buffer_names = new Set();
  13145. const methods = [];
  13146. const method_resolvers = [];
  13147. const attributes = [];
  13148. const constants = [];
  13149. const pre_hook_names = new Set();
  13150. const pre_hook_def_map = new Map();
  13151. const hook_names = new Set();
  13152. const hook_def_map = new Map();
  13153. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13154. for (const stmt of class_def.body) {
  13155. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13156. let target = null;
  13157. let annotation = null;
  13158. let value = null;
  13159. if (stmt instanceof ast.Assign) {
  13160. [target] = stmt.targets;
  13161. value = stmt.value;
  13162. } else {
  13163. target = stmt.target;
  13164. annotation = stmt.annotation;
  13165. value = stmt.value;
  13166. }
  13167. if (target instanceof ast.Name) {
  13168. const name = this._cu.execution.identifier(target);
  13169. switch (name) {
  13170. case '__annotations__': {
  13171. continue;
  13172. }
  13173. case '__parameters__': {
  13174. for (const elt of value.elts) {
  13175. parameter_names.add(elt.value);
  13176. }
  13177. break;
  13178. }
  13179. case '__buffers__': {
  13180. for (const elt of value.elts) {
  13181. buffer_names.add(elt.value);
  13182. }
  13183. break;
  13184. }
  13185. case '__forward_pre_hooks__': {
  13186. for (const elt of value.elts) {
  13187. pre_hook_names.add(elt.value);
  13188. }
  13189. break;
  13190. }
  13191. case '__forward_hooks__': {
  13192. for (const elt of value.elts) {
  13193. hook_names.add(elt.value);
  13194. }
  13195. break;
  13196. }
  13197. default: {
  13198. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13199. if (fixed_up) {
  13200. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13201. } else if (value) {
  13202. constants.push({ name, value, annotation });
  13203. } else {
  13204. attributes.push({ name, value, annotation });
  13205. }
  13206. break;
  13207. }
  13208. }
  13209. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13210. const name = target.slice.value;
  13211. attributes.push({ name, value, annotation: stmt.value });
  13212. continue;
  13213. } else {
  13214. throw new python.Error('Unexpected statement kind in module metadata.');
  13215. }
  13216. } else if (stmt instanceof ast.FunctionDef) {
  13217. const def = stmt;
  13218. const def_name = def.name;
  13219. if (pre_hook_names.has(def_name)) {
  13220. pre_hook_def_map.set(def_name, def);
  13221. } else if (hook_names.has(def_name)) {
  13222. hook_def_map.set(def_name, def);
  13223. } else {
  13224. methods.push(def);
  13225. method_resolvers.push(this);
  13226. }
  13227. } else {
  13228. throw new python.Error('Unexpected statement kind in class body.');
  13229. }
  13230. }
  13231. const type_parser = new torch._C.ScriptTypeParser(this);
  13232. for (const assign of attributes) {
  13233. const name = assign.name;
  13234. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13235. const is_parameter = parameter_names.has(name);
  13236. const is_buffer = buffer_names.has(name);
  13237. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13238. }
  13239. for (const constant of constants) {
  13240. class_type.addConstant(constant.name, constant.value);
  13241. }
  13242. this._cu.register_type(class_type);
  13243. const self = new torch._C.SimpleSelf(class_type);
  13244. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13245. }
  13246. importEnum(qualified_name, enum_def) {
  13247. const names_values = [];
  13248. let value_type = null;
  13249. const set_or_check_type = (t) => {
  13250. if (!value_type) {
  13251. value_type = t;
  13252. } else if (value_type !== t) {
  13253. throw new python.Error('Enum class with varying value types are not supported.');
  13254. }
  13255. };
  13256. for (const stmt of enum_def.body) {
  13257. if (stmt instanceof ast.Assign === false) {
  13258. throw new python.Error('Unexpected statement in Enum class body.');
  13259. }
  13260. const assign = stmt;
  13261. const name = assign.targets[0].id;
  13262. let ivalue = null;
  13263. const rhs = assign.value;
  13264. switch (rhs.type) {
  13265. case 'str':
  13266. ivalue = new torch._C.IValue(rhs.value, 'String');
  13267. set_or_check_type(torch.StringType.get());
  13268. break;
  13269. case 'int':
  13270. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13271. set_or_check_type(torch.IntType.get());
  13272. break;
  13273. case 'float':
  13274. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13275. set_or_check_type(torch.FloatType.get());
  13276. break;
  13277. default:
  13278. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13279. }
  13280. names_values.push([name, ivalue]);
  13281. }
  13282. if (!value_type) {
  13283. throw new python.Error('No enum values defined.');
  13284. }
  13285. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13286. this._cu.register_type(enum_type);
  13287. }
  13288. importNamedTuple(qualified_name, named_tuple_def) {
  13289. const type_parser = new torch._C.ScriptTypeParser(this);
  13290. const field_names = [];
  13291. const field_types = [];
  13292. const field_defaults = [];
  13293. for (const stmt of named_tuple_def.body) {
  13294. if (stmt instanceof ast.AnnAssign === false) {
  13295. throw new python.Error('Unexpected statement in NamedTuple body.');
  13296. }
  13297. const assign = stmt;
  13298. const target = this._cu.execution.identifier(stmt.target);
  13299. // const annotation = this._cu.execution.type(stmt.annotation);
  13300. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13301. field_names.push(target);
  13302. // field_types.push(annotation);
  13303. field_types.push(type);
  13304. }
  13305. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13306. this._cu.register_type(tt);
  13307. }
  13308. importFunction(qualifier, def) {
  13309. const definitions = [def];
  13310. const resolvers = [this];
  13311. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13312. }
  13313. parseSourceIfNeeded(qualifier) {
  13314. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13315. return;
  13316. }
  13317. this._loaded_sources.add(qualifier);
  13318. const src = this._source_loader(qualifier);
  13319. if (!src) {
  13320. return;
  13321. }
  13322. this._sources.set(src.filename(), src);
  13323. const p = new torch._C.Parser(src);
  13324. const L = p.parse();
  13325. this.parsePossibleVersionNumber(p);
  13326. for (const stmt of L.body) {
  13327. if (stmt instanceof ast.ClassDef) {
  13328. const name = `${qualifier}.${stmt.name}`;
  13329. this._to_be_defined.set(name, stmt);
  13330. } else if (stmt instanceof ast.FunctionDef) {
  13331. const name = `${qualifier}.${stmt.name}`;
  13332. this._to_be_defined.set(name, stmt);
  13333. }
  13334. }
  13335. }
  13336. parsePossibleVersionNumber(/* p */) {
  13337. }
  13338. parseImports(/* p */) {
  13339. }
  13340. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13341. const replacements = new Map([
  13342. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13343. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13344. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13345. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13346. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13347. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13348. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13349. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13350. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13351. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13352. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13353. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13354. ]);
  13355. const mangleRe = /\.___torch_mangle_\d+/g;
  13356. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13357. if (replacements.has(demangled_classname)) {
  13358. const lhs = assign.target;
  13359. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13360. return null;
  13361. }
  13362. const type = assign.annotation.id;
  13363. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13364. if (lhs.id === attr_name && type === expected_type) {
  13365. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13366. const typename_expr = p.parseExp();
  13367. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13368. }
  13369. }
  13370. return null;
  13371. }
  13372. LEGACY_import_methods(mod, src) {
  13373. const self = new torch._C.SimpleSelf(mod.type());
  13374. const prefix = mod.type().name();
  13375. const p = new torch._C.Parser(src);
  13376. const L = p.parse();
  13377. this.parsePossibleVersionNumber(L);
  13378. this.parseImports(L);
  13379. const definitions = [];
  13380. const resolvers = [];
  13381. for (const def of L.body) {
  13382. if (def instanceof ast.FunctionDef) {
  13383. definitions.push(def);
  13384. resolvers.push(this);
  13385. }
  13386. }
  13387. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13388. }
  13389. findFunction(name) {
  13390. this.parseSourceIfNeeded(name.prefix());
  13391. const key = name.qualifiedName();
  13392. const it = this._to_be_defined.get(key);
  13393. if (it && it instanceof ast.FunctionDef) {
  13394. this._to_be_defined.delete(key);
  13395. this.importFunction(name.prefix(), it);
  13396. }
  13397. return this._cu.find_function(name);
  13398. }
  13399. });
  13400. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13401. constructor(otherResolver, functionTable) {
  13402. super();
  13403. this._otherResolver = otherResolver;
  13404. this._functionTable = functionTable;
  13405. }
  13406. resolveValue(name, m, loc) {
  13407. const it = this._functionTable.get(name);
  13408. if (it) {
  13409. return new torch._C.FunctionValue(it);
  13410. }
  13411. return this._otherResolver.resolveValue(name, m, loc);
  13412. }
  13413. resolveType(name, loc) {
  13414. return this._otherResolver.resolveType(name, loc);
  13415. }
  13416. });
  13417. this.registerType('torch._C.SourceRangeDeserializer', class {
  13418. constructor(text_table) {
  13419. this.cached_sources = new Map();
  13420. this._text_table = text_table || [];
  13421. }
  13422. deserialize(iv) {
  13423. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13424. const [file, start, end] = iv;
  13425. const source = this.deserialize_source(file);
  13426. return new torch._C.SourceRange(source, start, end);
  13427. }
  13428. deserialize_source(iv) {
  13429. const tup = iv;
  13430. if (this.cached_sources.has(tup)) {
  13431. return this.cached_sources.get(tup);
  13432. }
  13433. let source = null;
  13434. const tup_elems = tup;
  13435. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13436. if (this._text_table.length > 0) {
  13437. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13438. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13439. const filename = this._text_table[fnameIndex];
  13440. const pieces = [];
  13441. const strs = [];
  13442. for (const i of textIndex) {
  13443. pieces.push(this._text_table[i]);
  13444. strs.push(this._text_table[i]);
  13445. }
  13446. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13447. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13448. } else {
  13449. const [text, filename, starting_line_no] = tup_elems;
  13450. source = new torch._C.Source(text, filename, starting_line_no);
  13451. }
  13452. this.cached_sources.set(tup, source);
  13453. return source;
  13454. }
  13455. });
  13456. this.registerType('torch._C.SourceRangeUnpickler', class {
  13457. });
  13458. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13459. constructor (data) {
  13460. super();
  13461. this.data = data;
  13462. this.deserializer = null;
  13463. this.unpickled_records = null;
  13464. }
  13465. unpickle() {
  13466. if (this.unpickled_records) {
  13467. return;
  13468. }
  13469. const unpickler = new pickle.Unpickler(this.data);
  13470. const ivalues = unpickler.load();
  13471. torch._C.TORCH_CHECK(ivalues.length > 0);
  13472. this.unpickled_records = [];
  13473. let lines = null;
  13474. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13475. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13476. lines = ivalues[2];
  13477. } else {
  13478. this.deserializer = new torch._C.SourceRangeDeserializer();
  13479. lines = ivalues;
  13480. }
  13481. for (const tup_elems of lines) {
  13482. const [offset, range] = tup_elems;
  13483. const source_range = this.deserializer.deserialize(range);
  13484. this.unpickled_records.push([offset, source_range]);
  13485. }
  13486. }
  13487. findSourceRangeThatGenerated(range) {
  13488. this.unpickle();
  13489. const start = range.start();
  13490. const records = this.unpickled_records;
  13491. for (let i = 0; i < records.length; i++) {
  13492. const [offset, target] = records[i];
  13493. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13494. if (start >= offset && start < next) {
  13495. return target;
  13496. }
  13497. }
  13498. return null;
  13499. }
  13500. });
  13501. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13502. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13503. });
  13504. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13505. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13506. if (!reader.has_record(path)) {
  13507. return null;
  13508. }
  13509. const stream = reader.get_record(path);
  13510. let gen_ranges = null;
  13511. const debug_file = `${path}.debug_pkl`;
  13512. if (reader.has_record(debug_file)) {
  13513. const debug_stream = reader.get_record(debug_file);
  13514. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13515. }
  13516. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13517. });
  13518. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13519. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13520. this._compilation_unit = cu;
  13521. this._reader = reader;
  13522. this._storage_context = storage_context;
  13523. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13524. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13525. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13526. this._constant_table = [];
  13527. const SourceLoader = (qualifier) => {
  13528. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13529. };
  13530. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13531. }
  13532. deserialize() {
  13533. const execution = this._compilation_unit.execution;
  13534. const code_prefix = this._code_prefix;
  13535. for (const name of this._reader.get_all_records()) {
  13536. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13537. const file = name.substring(code_prefix.length);
  13538. const stream = this._reader.get_record(name);
  13539. const buffer = stream.peek();
  13540. execution.add(file, buffer);
  13541. }
  13542. }
  13543. const torch = execution.import('torch');
  13544. execution.builtins.torch = torch;
  13545. execution.builtins.Tensor = torch.Tensor;
  13546. execution.builtins.ops = torch.ops;
  13547. execution.builtins.inf = torch.inf;
  13548. execution.builtins.CONSTANTS = {};
  13549. execution._resolver = this._source_importer;
  13550. if (this._reader.has_record('model.json')) {
  13551. return this.LEGACY_deserialize();
  13552. }
  13553. const constants = this.readArchive('constants');
  13554. for (let i = 0; i < constants.length; i++) {
  13555. let val = constants[i];
  13556. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13557. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13558. const obj = torch.ScriptObject.create(type);
  13559. obj._ivalue = val;
  13560. val = obj;
  13561. }
  13562. execution.builtins.CONSTANTS[`c${i}`] = val;
  13563. this._constant_table.push(val);
  13564. }
  13565. const obj = this.readArchive('data');
  13566. const convertObject = (obj) => {
  13567. if (obj.__class__) {
  13568. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13569. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13570. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13571. for (let i = 0; i < type.numAttributes(); i++) {
  13572. const k = type.getAttributeName(i);
  13573. const t = type.getAttribute(i);
  13574. const v = obj[k];
  13575. if (t instanceof torch.ClassType) {
  13576. module.__setattr__(k, convertObject(v));
  13577. } else {
  13578. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13579. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13580. type._attributes[i].type = this._source_importer.resolveType(name);
  13581. }
  13582. module.__setattr__(k, obj[k]);
  13583. }
  13584. }
  13585. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13586. if (value && value.__class__ === builtins.method) {
  13587. module[key] = value;
  13588. }
  13589. }
  13590. return module;
  13591. }
  13592. throw new python.Error('Module class not found.');
  13593. };
  13594. return convertObject(obj);
  13595. }
  13596. LEGACY_deserialize() {
  13597. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13598. const execution = this._compilation_unit.execution;
  13599. const caffe2 = execution.proto.caffe2;
  13600. const torch = execution.import('torch');
  13601. const stream = this._reader.get_record('model.json');
  13602. const buffer = stream.peek();
  13603. const decoder = new TextDecoder('utf-8');
  13604. const content = decoder.decode(buffer);
  13605. const obj = JSON.parse(content);
  13606. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13607. const tensorTypeMap = new Map([
  13608. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13609. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13610. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13611. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13612. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13613. [caffe2.TensorProto.DataType.INT64, 'Long']
  13614. ]);
  13615. const tensor_table = (model.tensors || []).map((constant) => {
  13616. const key = constant.data.key;
  13617. if (!tensorTypeMap.has(constant.data_type)) {
  13618. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13619. }
  13620. const type = tensorTypeMap.get(constant.data_type);
  13621. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13622. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13623. const storage_type = execution.resolve(`torch.${type}Storage`);
  13624. const size = (shape || []).reduce((a, b) => a * b, 1);
  13625. const offset = parseInt(constant.offset, 10) || 0;
  13626. const storage = new storage_type(size);
  13627. const itemsize = storage.dtype.itemsize();
  13628. const stream = this._reader.get_record(key);
  13629. if (stream) {
  13630. const buffer = stream.peek();
  13631. const length = size * itemsize;
  13632. const data = buffer.slice(offset, offset + length);
  13633. storage._set_cdata(data);
  13634. }
  13635. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13636. tensor.name = key;
  13637. return tensor;
  13638. });
  13639. execution.builtins.CONSTANTS = {};
  13640. for (let i = 0; i < tensor_table.length; i++) {
  13641. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13642. }
  13643. const attributes = [];
  13644. if (this._reader.has_record('attributes.pkl')) {
  13645. const stream = this._reader.get_record('attributes.pkl');
  13646. const buffer = stream.peek();
  13647. const unpickler = new pickle.Unpickler(buffer);
  13648. const obj = unpickler.load();
  13649. attributes.push(...obj);
  13650. }
  13651. this._LEGACY_moduleStack = ['__torch__'];
  13652. const module_def = model.main_module;
  13653. for (const tensor of tensor_table) {
  13654. this._constant_table.push(tensor);
  13655. }
  13656. return this.LEGACY_convertModule(module_def);
  13657. }
  13658. LEGACY_convertModule(module_def) {
  13659. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13660. const numPushed = atoms.length;
  13661. for (const atom of atoms) {
  13662. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13663. this._LEGACY_moduleStack.push(sanitized);
  13664. }
  13665. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13666. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13667. for (const sub_def of module_def.submodules || []) {
  13668. const submodule = this.LEGACY_convertModule(sub_def);
  13669. module.register_module(sub_def.name, submodule);
  13670. }
  13671. for (const param_def of module_def.parameters || []) {
  13672. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13673. if (param_def.isBuffer) {
  13674. module.register_buffer(param_def.name, tensor);
  13675. } else {
  13676. module.register_parameter(param_def.name, tensor, false);
  13677. }
  13678. }
  13679. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13680. for (const attr_def of module_def.attributes || []) {
  13681. if (module.hasattr(attr_def.name)) {
  13682. continue;
  13683. }
  13684. throw new python.Error('Not implemented.');
  13685. // IValue ivalue;
  13686. // if (attr_def.id() >= 0) {
  13687. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13688. // }
  13689. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13690. }
  13691. if (module_def.torchscript_arena) {
  13692. const key = module_def.torchscript_arena.key;
  13693. const file = key.substring('code/'.length);
  13694. const name = file.replace(/\.py$/, '').split('/').join('.');
  13695. const code = execution.import(name);
  13696. if (code.forward.__class__ === execution.builtins.function) {
  13697. module.forward = code.forward;
  13698. }
  13699. }
  13700. // let gen_ranges = null;
  13701. if (module_def.torchscript_debug_arena) {
  13702. throw new python.Error('Not implemented.');
  13703. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13704. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13705. }
  13706. if (module_def.torchscript_arena) {
  13707. const filename = module_def.torchscript_arena.key;
  13708. const stream = this._reader.get_record(filename);
  13709. const data = stream.peek();
  13710. const src = new torch._C.Source(data, filename);
  13711. this._source_importer.LEGACY_import_methods(module, src);
  13712. }
  13713. if (module_def.get_state_attribute_id) {
  13714. throw new python.Error('Not implemented.');
  13715. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13716. }
  13717. /*
  13718. const module_type = module._ivalue().type();
  13719. const N = module_type.numAttributes();
  13720. for (let i = 0; i < N; ++i) {
  13721. const v = module._ivalue().getSlot(i);
  13722. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13723. torch._C.TORCH_CHECK(!v.isNone());
  13724. }
  13725. }
  13726. */
  13727. for (let i = 0; i < numPushed; i++) {
  13728. this._LEGACY_moduleStack.pop();
  13729. }
  13730. return module;
  13731. }
  13732. readArchive(archive_name) {
  13733. const type_resolver = (qn) => {
  13734. const cls = this._source_importer.loadType(qn);
  13735. return cls;
  13736. };
  13737. const ObjLoaderFunc = (/* type, ivalue */) => {
  13738. };
  13739. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13740. }
  13741. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13742. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13743. const stream = stream_reader.get_record(picklename);
  13744. if (!stream) {
  13745. throw new python.Error(`File '${picklename}' is not found.`);
  13746. }
  13747. const buffer = stream.peek();
  13748. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13749. const read_record = (name) => {
  13750. const stream = stream_reader.get_record(tensor_dir_path + name);
  13751. return stream.length <= 0x40000 ? stream.peek() : stream;
  13752. };
  13753. const execution = this._compilation_unit.execution;
  13754. const pickle = execution.__import__('pickle');
  13755. const Unpickler = class extends pickle.Unpickler {
  13756. find_class(module, name) {
  13757. return super.find_class(module, name);
  13758. }
  13759. };
  13760. const unpickler = new Unpickler(buffer);
  13761. unpickler.persistent_load = (saved_id) => {
  13762. if (saved_id[0] !== 'storage') {
  13763. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13764. }
  13765. const [, storage_type, key, , size] = saved_id;
  13766. if (storage_context && storage_context.has_storage(key)) {
  13767. return storage_context.get_storage(key);
  13768. }
  13769. const storage = new storage_type(size);
  13770. if (!storage._set_cdata) {
  13771. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  13772. }
  13773. const storage_ptr = read_record(key);
  13774. storage._set_cdata(storage_ptr);
  13775. if (storage_context) {
  13776. storage_context.add_storage(key);
  13777. }
  13778. return storage;
  13779. };
  13780. return unpickler.load();
  13781. }
  13782. });
  13783. this.registerType('torch._C.WithInsertPoint', class {
  13784. constructor(...args) {
  13785. let n = null;
  13786. if (args.length === 1 && args[0] instanceof torch.Block) {
  13787. const [b] = args;
  13788. n = b.return_node();
  13789. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13790. [n] = args;
  13791. } else {
  13792. throw new python.Error('Invalid arguments.');
  13793. }
  13794. this._prev = n.owningGraph().insertPoint();
  13795. n.owningGraph().setInsertPoint(n);
  13796. }
  13797. dispose() {
  13798. this._prev.owningGraph().setInsertPoint(this._prev);
  13799. }
  13800. });
  13801. this.registerType('torch._C.Environment', class {
  13802. constructor(method, resolver, b, next) {
  13803. this.method = method;
  13804. this.resolver = resolver;
  13805. this.b = b;
  13806. this.next = next;
  13807. this.value_table = new Map();
  13808. this.type_table = new Map();
  13809. this.error_messages = new Map();
  13810. }
  13811. setVariableTypeError(name, msg) {
  13812. /* eslint-disable consistent-this */
  13813. let runner = this;
  13814. /* eslint-enable consistent-this */
  13815. while (runner.next) {
  13816. runner = runner.next;
  13817. }
  13818. runner.error_messages.set(name, msg);
  13819. }
  13820. insertLoad(name, type) {
  13821. const g = this.b.owningGraph();
  13822. const load = g.insertNode(g.createLoad(name, type));
  13823. if (torch._C.meaningfulName(name)) {
  13824. load.output().setDebugName(name);
  13825. }
  13826. return new torch._C.SimpleValue(load.output());
  13827. }
  13828. insertStore(name, loc, v, type) {
  13829. const g = this.b.owningGraph();
  13830. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  13831. this.type_table.set(name, type);
  13832. }
  13833. findInThisFrame(name) {
  13834. if (this.value_table.has(name)) {
  13835. return this.value_table.get(name);
  13836. }
  13837. if (this.type_table.has(name)) {
  13838. return this.insertLoad(name, this.type_table.get(name));
  13839. }
  13840. return null;
  13841. }
  13842. findInParentFrame(name) {
  13843. return this.next ? this.next.findInAnyFrame(name) : null;
  13844. }
  13845. setType(name, type) {
  13846. this.type_table.set(name, type);
  13847. }
  13848. findInAnyFrame(name) {
  13849. /* eslint-disable consistent-this */
  13850. const self = this;
  13851. /* eslint-enable consistent-this */
  13852. for (let runner = self; runner; runner = runner.next) {
  13853. const r = runner.findInThisFrame(name);
  13854. if (r) {
  13855. return r;
  13856. }
  13857. }
  13858. return null;
  13859. }
  13860. block() {
  13861. return this.b;
  13862. }
  13863. setVar(loc, name, value) {
  13864. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  13865. }
  13866. setSugaredVar(loc, name, value, annotated_type) {
  13867. let as_simple_value = torch._C.asSimple(value);
  13868. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  13869. as_simple_value.setDebugName(name);
  13870. }
  13871. const parent = this.findInParentFrame(name);
  13872. if (parent) {
  13873. if (annotated_type) {
  13874. throw new python.Error('Type already defined in an outer block.');
  13875. }
  13876. if (!as_simple_value) {
  13877. throw new python.Error('Only reassignments to first-class values are allowed.');
  13878. }
  13879. const simple_parent = torch._C.asSimple(parent);
  13880. if (!simple_parent) {
  13881. throw new python.Error('Only reassignments to first-class values are allowed.');
  13882. }
  13883. const parent_type = torch._C.unshapedType(simple_parent.type());
  13884. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  13885. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  13886. throw new python.Error('Incompatible types.');
  13887. }
  13888. }
  13889. if (as_simple_value) {
  13890. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  13891. throw new python.Error('Invalid type.');
  13892. }
  13893. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  13894. this.insertStore(name, loc, as_simple_value, value_store_type);
  13895. } else {
  13896. this.value_table.set(name, value);
  13897. }
  13898. }
  13899. getSugaredVar(ident, range, required) {
  13900. required = required || true;
  13901. let retval = this.findInAnyFrame(ident);
  13902. if (!retval) {
  13903. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  13904. ['print', new torch._C.PrintValue()],
  13905. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  13906. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  13907. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  13908. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  13909. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  13910. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  13911. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  13912. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  13913. ['range', torch._C.SpecialFormValue.create('prim::range')],
  13914. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  13915. ]);
  13916. if (torch._C.Environment.globals.has(ident)) {
  13917. retval = torch._C.Environment.globals.get(ident);
  13918. }
  13919. }
  13920. if (!retval) {
  13921. const type = this.resolver.resolveType(ident, range);
  13922. if (type instanceof torch.TupleType) {
  13923. retval = new torch.jit.NamedTupleConstructor(type);
  13924. }
  13925. }
  13926. if (!retval) {
  13927. retval = this.resolver.resolveValue(ident, this.method, range);
  13928. }
  13929. if (!retval) {
  13930. const type = this.resolver.resolveType(ident, range);
  13931. if (type instanceof torch.ClassType) {
  13932. retval = new torch.jit.ClassValue(type);
  13933. }
  13934. }
  13935. if (!retval && required) {
  13936. throw new python.Error(`The name '${ident}' is not defined.`);
  13937. }
  13938. return retval;
  13939. }
  13940. getVar(ident, range) {
  13941. return this.getSugaredVar(ident, range).asValue(range, this.method);
  13942. }
  13943. definedVariables() {
  13944. return Array.from(this.type_table.keys());
  13945. }
  13946. });
  13947. this.registerType('torch._C.Refinement', class {
  13948. constructor(identifier, type) {
  13949. this._identifier = identifier;
  13950. this._type = type;
  13951. }
  13952. identifier() {
  13953. return this._identifier;
  13954. }
  13955. type() {
  13956. return this._type;
  13957. }
  13958. });
  13959. this.registerType('torch._C.RefinementSet', class {
  13960. constructor(...args) {
  13961. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  13962. this._true_refinements = [args[0]];
  13963. this._false_refinements = [];
  13964. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  13965. this._true_refinements = [args[0]];
  13966. this._false_refinements = [args[1]];
  13967. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  13968. [this._true_refinements, this._false_refinements] = args;
  13969. } else {
  13970. throw new python.Error('Not implemented.');
  13971. }
  13972. }
  13973. Not() {
  13974. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  13975. }
  13976. activeRefinements() {
  13977. return this._true_refinements;
  13978. }
  13979. });
  13980. this.registerFunction('torch._C.CondValue', class {
  13981. constructor(...args) {
  13982. if (args.length === 3) {
  13983. [this._value, this._refinements, this._static_if] = args;
  13984. } else if (args.length === 4) {
  13985. const [g, loc, static_value, refinements] = args;
  13986. this._value = g.insertConstant(static_value, loc);
  13987. this._refinements = refinements;
  13988. this._static_if = static_value;
  13989. } else {
  13990. throw new python.Error('Invalid number of arguments.');
  13991. }
  13992. }
  13993. value() {
  13994. return this._value;
  13995. }
  13996. staticIf() {
  13997. return this._static_if;
  13998. }
  13999. refinements() {
  14000. return this._refinements;
  14001. }
  14002. });
  14003. this.registerFunction('torch._C.asSimple', (value) => {
  14004. if (value instanceof torch._C.SimpleValue) {
  14005. return value.getValue();
  14006. }
  14007. return null;
  14008. });
  14009. this.registerFunction('torch._C.isNumber', (str) => {
  14010. return /^[0-9]+$/.test(str);
  14011. });
  14012. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14013. if (torch._C.isNumber(field)) {
  14014. return `_${field}`;
  14015. }
  14016. return field;
  14017. });
  14018. this.registerFunction('torch._C.meaningfulName', (name) => {
  14019. if (name.length === 0) {
  14020. return false;
  14021. }
  14022. if (name[0] === '$') {
  14023. return false;
  14024. }
  14025. if (name[0] !== '_') {
  14026. return true;
  14027. }
  14028. return !/\d+/.test(name.slice(1));
  14029. });
  14030. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14031. const key = `${val.value}:${val.tag}`;
  14032. const existing_constant = map.get(key);
  14033. if (existing_constant) {
  14034. return existing_constant;
  14035. }
  14036. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14037. const new_constant = graph.insertConstant(val, r);
  14038. map.set(key, new_constant);
  14039. guard.dispose();
  14040. return new_constant;
  14041. });
  14042. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14043. if (schema.overload_name) {
  14044. return `${schema.name}.${schema.overload_name}`;
  14045. }
  14046. return schema.name;
  14047. });
  14048. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14049. const value_map_func = (v) => value_map.get(v);
  14050. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14051. for (let i = 0; i < inputs.length; i++) {
  14052. value_map.set(callee.inputs()[i], inputs[i]);
  14053. }
  14054. for (const node of callee.nodes()) {
  14055. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14056. for (let i = 0; i < node.outputs().length; i++) {
  14057. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14058. }
  14059. }
  14060. const outputs = [];
  14061. for (const output of callee.outputs()) {
  14062. outputs.push(value_map_func(output));
  14063. }
  14064. return outputs;
  14065. });
  14066. this.registerType('TemplateEnv', class {
  14067. });
  14068. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14069. constructor() {
  14070. this.state = 'UNINITIALIZED';
  14071. this._builtins_by_name = new Map();
  14072. }
  14073. getAllBuiltinFunctionsFor(name) {
  14074. if (this.state === 'UNINITIALIZED') {
  14075. this.loadBuiltinFunctions();
  14076. this.state = 'INITIALIZED';
  14077. }
  14078. if (!this._builtins_by_name.has(name)) {
  14079. return [];
  14080. }
  14081. return this._builtins_by_name.get(name);
  14082. }
  14083. loadBuiltinFunctions() {
  14084. /*
  14085. for (const scalar of ['float', 'int', 'complex']) {
  14086. const env = new torch.C.TemplateEnv();
  14087. env.s('Scalar', scalar);
  14088. this.loadSource(scalar_operators_source.format(env), 'aten');
  14089. }
  14090. for (const scalar of ['float', 'int']) {
  14091. const env = new torch.C.TemplateEnv();
  14092. env.s('Scalar', scalar);
  14093. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14094. }
  14095. using str_pair = std::pair<std::string, std::string>;
  14096. const std::vector<str_pair> name_len = {
  14097. str_pair('single', '1'),
  14098. str_pair('pair', '2'),
  14099. str_pair('triple', '3'),
  14100. str_pair('quadruple', '4'),
  14101. };
  14102. for (const auto scalar : {'float', 'int'}) {
  14103. for (const auto& pair : name_len) {
  14104. const env = new torch.C.TemplateEnv();
  14105. env.s('Scalar', scalar);
  14106. env.s('name', pair.first);
  14107. env.s('Length', pair.second);
  14108. this.loadSource(_ntuple_ops.format(env), 'aten');
  14109. }
  14110. }
  14111. for (auto rhs : {'number', 'Tensor'}) {
  14112. at::jit::TemplateEnv env;
  14113. env.s('Rhs_Type', rhs);
  14114. this.loadSource(floordiv.format(env), 'aten');
  14115. }
  14116. this.loadSource(aten_ops, 'aten');
  14117. this.loadSource(aten_ops_additional, 'aten');
  14118. this.loadSource(tensor_properties, 'prim');
  14119. */
  14120. }
  14121. loadSource(/* source, the_namespace */) {
  14122. }
  14123. });
  14124. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14125. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14126. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14127. });
  14128. this.registerFunction('torch._C.get_operator_version_map', () => {
  14129. return new Map();
  14130. });
  14131. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14132. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14133. let arg_type = arg.type;
  14134. if (arg_type instanceof torch._C.DynamicType) {
  14135. arg_type = arg_type.fallback();
  14136. }
  14137. const argument_is_list = arg_type instanceof torch.ListType;
  14138. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14139. const arg_is_broadcasting_list = arg.N > 0;
  14140. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14141. });
  14142. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14143. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14144. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14145. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14146. return true;
  14147. }
  14148. return false;
  14149. });
  14150. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14151. if (opt_type instanceof torch._C.DynamicType) {
  14152. return torch._C.unwrapOptional(opt_type.fallback());
  14153. }
  14154. if (opt_type instanceof torch.OptionalType) {
  14155. return opt_type.getElementType();
  14156. }
  14157. return opt_type;
  14158. });
  14159. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14160. const possibleSchemas = [];
  14161. if (version === undefined) {
  14162. return possibleSchemas;
  14163. }
  14164. for (const entry of torch._C.get_operator_version_map()) {
  14165. const old_symbol_name = entry.first;
  14166. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14167. if (base_name === name) {
  14168. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14169. if (possibleUpgrader.has_value()) {
  14170. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14171. }
  14172. }
  14173. }
  14174. return possibleSchemas;
  14175. });
  14176. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14177. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14178. return current_version < latest_update;
  14179. });
  14180. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14181. const it = torch._C.get_operator_version_map().get(name);
  14182. if (it) {
  14183. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14184. }
  14185. return true;
  14186. });
  14187. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14188. if (values.length === 1) {
  14189. return values[0];
  14190. }
  14191. let named_tuple = null;
  14192. if (field_names) {
  14193. const types = values.map((v) => v.type());
  14194. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14195. }
  14196. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14197. });
  14198. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14199. const v_type = value.type();
  14200. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14201. return false;
  14202. }
  14203. const arg_type = torch._C.unwrapOptional(arg.type);
  14204. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14205. });
  14206. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14207. const list_type = list_type_;
  14208. if (list_type instanceof torch.ListType === false) {
  14209. return false;
  14210. }
  14211. if (type.isSubtypeOf(list_type_)) {
  14212. return true;
  14213. }
  14214. if (type instanceof torch.TupleType) {
  14215. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14216. }
  14217. return false;
  14218. });
  14219. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14220. for (let i = 0; i < kwargs.length; i++) {
  14221. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14222. return i;
  14223. }
  14224. if (kwargs[i].name() === name) {
  14225. return i;
  14226. }
  14227. }
  14228. return null;
  14229. });
  14230. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14231. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14232. const list_elements = [];
  14233. for (const named_value of varargs) {
  14234. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14235. if (!matched_value) {
  14236. return null;
  14237. }
  14238. list_elements.push(matched_value);
  14239. }
  14240. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14241. });
  14242. this.registerType('torch._C.MatchTypeReturn', class {
  14243. constructor(reason) {
  14244. this._reason = reason;
  14245. }
  14246. static Success() {
  14247. return new torch._C.MatchTypeReturn(null);
  14248. }
  14249. success() {
  14250. return this._reason === null;
  14251. }
  14252. });
  14253. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14254. if (!formal.hasFreeVariables()) {
  14255. if (formal instanceof torch._C.DynamicType) {
  14256. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14257. }
  14258. return torch._C.MatchTypeReturn.Success();
  14259. }
  14260. if (formal instanceof torch._C.VarType) {
  14261. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14262. if (it === null) {
  14263. type_env.set(formal.name(), actual);
  14264. return torch._C.MatchTypeReturn.Success();
  14265. } else if (torch._C.unifyTypes(it, actual)) {
  14266. return torch._C.MatchTypeReturn.Success();
  14267. }
  14268. return new torch._C.MatchTypeReturn('Cannot match var.');
  14269. } else if (formal instanceof torch.ListType) {
  14270. if (actual instanceof torch.ListType) {
  14271. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14272. if (!innerMatch.success()) {
  14273. return innerMatch;
  14274. }
  14275. return torch._C.MatchTypeReturn.Success();
  14276. } else if (actual instanceof torch.TupleType) {
  14277. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14278. if (maybe_tuple_unified) {
  14279. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14280. }
  14281. }
  14282. return new torch._C.MatchTypeReturn('Cannot match list.');
  14283. } else if (formal instanceof torch.TupleType) {
  14284. if (actual instanceof torch.TupleType) {
  14285. if (formal.elements().length !== actual.elements().length) {
  14286. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14287. }
  14288. for (let i = 0; i < formal.elements().length; i++) {
  14289. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14290. if (!result.success()) {
  14291. return result;
  14292. }
  14293. }
  14294. return torch._C.MatchTypeReturn.Success();
  14295. }
  14296. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14297. } else if (formal instanceof torch.FutureType) {
  14298. if (actual instanceof torch.FutureType) {
  14299. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14300. if (!innerMatch.success()) {
  14301. return innerMatch;
  14302. }
  14303. return torch._C.MatchTypeReturn.Success();
  14304. }
  14305. return new torch._C.MatchTypeReturn('Cannot match future.');
  14306. } else if (formal instanceof torch.AwaitType) {
  14307. if (actual instanceof torch.AwaitType) {
  14308. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14309. if (!innerMatch.success()) {
  14310. return innerMatch;
  14311. }
  14312. return torch._C.MatchTypeReturn.Success();
  14313. }
  14314. return new torch._C.MatchTypeReturn('Cannot match await.');
  14315. } else if (formal instanceof torch.RRefType) {
  14316. if (actual instanceof torch.RRefType) {
  14317. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14318. if (!innerMatch.success()) {
  14319. return innerMatch;
  14320. }
  14321. return torch._C.MatchTypeReturn.Success();
  14322. }
  14323. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14324. } else if (formal instanceof torch.OptionalType) {
  14325. if (actual instanceof torch.OptionalType) {
  14326. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14327. if (!optionedMatch.success()) {
  14328. return optionedMatch;
  14329. }
  14330. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14331. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14332. }
  14333. return torch._C.MatchTypeReturn.Success();
  14334. } else if (formal instanceof torch.DictType) {
  14335. if (actual instanceof torch.DictType) {
  14336. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14337. if (!key_match.success()) {
  14338. return key_match;
  14339. }
  14340. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14341. if (!value_match.success()) {
  14342. return value_match;
  14343. }
  14344. return torch._C.MatchTypeReturn.Success();
  14345. }
  14346. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14347. }
  14348. throw new python.Error('Unhandled free variable container.');
  14349. });
  14350. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14351. let value = named_value.value(graph);
  14352. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14353. const repeated = Array(arg.N).fill(value);
  14354. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14355. }
  14356. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14357. if (!matched.success()) {
  14358. if (failure_messages) {
  14359. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14360. }
  14361. return null;
  14362. }
  14363. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14364. if (!concrete_type) {
  14365. if (failure_messages) {
  14366. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14367. }
  14368. return null;
  14369. }
  14370. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14371. if (!value.type().isSubtypeOf(concrete_type)) {
  14372. if (failure_messages) {
  14373. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14374. }
  14375. return null;
  14376. }
  14377. return value;
  14378. });
  14379. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14380. if (concrete_type instanceof torch.OptionalType) {
  14381. const op = concrete_type;
  14382. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14383. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14384. }
  14385. }
  14386. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14387. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14388. }
  14389. if (value.type() instanceof torch.TupleType) {
  14390. const value_tuple = value.type();
  14391. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14392. const unpacked = torch._C.createTupleUnpack(value);
  14393. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14394. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14395. }
  14396. if (concrete_type instanceof torch.TupleType) {
  14397. const concrete_tuple = concrete_type;
  14398. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14399. concrete_tuple.elements().length === value_tuple.elements().length) {
  14400. const unpacked = torch._C.createTupleUnpack(value);
  14401. const converted = [];
  14402. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14403. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14404. }
  14405. value = graph.insertNode(graph.createTuple(converted)).output();
  14406. }
  14407. }
  14408. }
  14409. if (allow_conversions) {
  14410. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14411. const value_equals_number = value.type() === torch.NumberType.get();
  14412. const concrete_float = concrete_type === torch.FloatType.get();
  14413. const concrete_complex = concrete_type === torch.ComplexType.get();
  14414. const concrete_int = concrete_type === torch.IntType.get();
  14415. const concrete_number = concrete_type === torch.NumberType.get();
  14416. if (value_isa_tensor) {
  14417. if (concrete_float) {
  14418. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14419. } else if (concrete_complex) {
  14420. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14421. } else if (concrete_int) {
  14422. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14423. } else if (concrete_number) {
  14424. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14425. }
  14426. } else if (value_equals_number) {
  14427. if (concrete_float) {
  14428. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14429. } else if (concrete_complex) {
  14430. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14431. } else if (concrete_int) {
  14432. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14433. }
  14434. } else if (value.type() === torch.BoolType.get()) {
  14435. if (concrete_float) {
  14436. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14437. } else if (concrete_int || concrete_number) {
  14438. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14439. }
  14440. }
  14441. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14442. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14443. }
  14444. }
  14445. return value;
  14446. });
  14447. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14448. if (!type.hasFreeVariables()) {
  14449. if (type instanceof torch._C.DynamicType) {
  14450. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14451. }
  14452. return type;
  14453. }
  14454. if (type instanceof torch._C.VarType) {
  14455. return type_env.get(type.annotation_str);
  14456. }
  14457. const contained = type.containedTypes();
  14458. if (contained.length === 0) {
  14459. return type;
  14460. }
  14461. const new_contained = [];
  14462. for (const t of contained) {
  14463. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14464. if (!r) {
  14465. return null;
  14466. }
  14467. new_contained.push(r);
  14468. }
  14469. return type.withContained(new_contained);
  14470. });
  14471. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14472. if (torch._C.isBlockListedSchema(schema)) {
  14473. return null;
  14474. }
  14475. const err = null;
  14476. const type_env = new Map();
  14477. const positional_inputs = [];
  14478. const used_kwarg = kwargs.map(() => false);
  14479. const is_aten = schema.name.startsWith('aten::');
  14480. let used_args = 0;
  14481. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14482. const arg = schema.arguments[schema_i];
  14483. let actual_named_value = null;
  14484. if (arg.name === 'self' && self) {
  14485. actual_named_value = self;
  14486. self = null;
  14487. } else if (!arg.kwarg_only && used_args < args.length) {
  14488. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14489. const value = args[used_args].value(graph);
  14490. const actual_type = value.type();
  14491. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14492. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14493. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14494. if (!list) {
  14495. return null;
  14496. }
  14497. used_args = args.length;
  14498. positional_inputs.push(list);
  14499. continue;
  14500. }
  14501. }
  14502. actual_named_value = args[used_args];
  14503. used_args++;
  14504. } else {
  14505. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14506. if (Number.isInteger(kwarg_idx)) {
  14507. const nv = kwargs[kwarg_idx];
  14508. if (used_kwarg[kwarg_idx]) {
  14509. if (failure_messages) {
  14510. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14511. }
  14512. return null;
  14513. }
  14514. used_kwarg[kwarg_idx] = true;
  14515. actual_named_value = nv;
  14516. } else if (arg.has_default_value()) {
  14517. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14518. } else {
  14519. if (failure_messages) {
  14520. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14521. }
  14522. return null;
  14523. }
  14524. }
  14525. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14526. if (!positional) {
  14527. return null;
  14528. }
  14529. positional_inputs.push(positional);
  14530. }
  14531. if (self !== null) {
  14532. if (failure_messages) {
  14533. throw new python.Error('Provided self argument not used in schema.');
  14534. }
  14535. return null;
  14536. }
  14537. if (schema.is_vararg) {
  14538. for (; used_args < args.length; used_args++) {
  14539. positional_inputs.push(args[used_args].value(graph));
  14540. }
  14541. }
  14542. if (used_args < args.length) {
  14543. if (failure_messages) {
  14544. throw new python.Error('Too many positional arguments.');
  14545. }
  14546. return null;
  14547. }
  14548. for (let i = 0; i < kwargs.length; i++) {
  14549. const nv = kwargs[i];
  14550. if (!used_kwarg[i]) {
  14551. if (failure_messages) {
  14552. if (schema.argumentIndexWithName(nv.name()) === null) {
  14553. throw new python.Error('Keyword argument unknown.');
  14554. } else {
  14555. throw new python.Error('Keyword argument specified twice.');
  14556. }
  14557. }
  14558. return null;
  14559. }
  14560. }
  14561. const returns = schema.returns;
  14562. const return_types = returns.map((r) => {
  14563. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14564. if (!result) {
  14565. throw new python.Error('Unbound type variable.');
  14566. }
  14567. return result;
  14568. });
  14569. const return_has_field_names = returns.every((r) => !r.name);
  14570. let return_field_names = null;
  14571. if (return_has_field_names) {
  14572. return_field_names = returns.map((r) => r.name);
  14573. }
  14574. const schema_name = torch._C.getFullSchemaName(schema);
  14575. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14576. });
  14577. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14578. self = self || null;
  14579. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14580. if (result) {
  14581. return result;
  14582. }
  14583. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14584. });
  14585. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14586. self = self || null;
  14587. render_errors = render_errors || false;
  14588. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14589. if (schemas.length === 1) {
  14590. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14591. }
  14592. for (const allow_conversions of [false, true]) {
  14593. for (let i = 0; i < schemas.length; i++) {
  14594. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14595. if (matched_schema) {
  14596. return [i, matched_schema];
  14597. }
  14598. }
  14599. }
  14600. if (!render_errors) {
  14601. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14602. }
  14603. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14604. });
  14605. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14606. const variants = torch._C.getAllOperatorsFor(name);
  14607. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14608. const graph_version = graph.get_op_version();
  14609. const schemas = [];
  14610. const upgrader_schemas = [];
  14611. for (const op of variants) {
  14612. let found_upgrader = false;
  14613. const op_name = torch._C.getFullSchemaName(op.schema());
  14614. if (Number.isInteger(graph_version)) {
  14615. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14616. if (version_entry) {
  14617. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14618. if (old_schema_entry.has_value()) {
  14619. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14620. upgrader_schemas.push(old_schema);
  14621. found_upgrader = true;
  14622. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14623. throw new python.Error('Valid upgrader must be present.');
  14624. }
  14625. }
  14626. }
  14627. if (!found_upgrader) {
  14628. schemas.push(op.schema());
  14629. }
  14630. }
  14631. if (variants.length === 0) {
  14632. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14633. for (const old_schema_entry of oldSchemas) {
  14634. const old_schema = torch._C.parseSchema(old_schema_entry);
  14635. upgrader_schemas.push(old_schema);
  14636. }
  14637. }
  14638. for (const schema of upgrader_schemas) {
  14639. schemas.push(schema);
  14640. }
  14641. for (const method of builtin_functions) {
  14642. method.ensure_defined();
  14643. schemas.push(method.getSchema());
  14644. }
  14645. if (schemas.length === 0) {
  14646. const user_function_name = name;
  14647. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  14648. }
  14649. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14650. if (matched[0] < variants.length + upgrader_schemas.length) {
  14651. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14652. }
  14653. const fn = builtin_functions[matched.first - variants.size()];
  14654. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14655. });
  14656. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14657. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14658. for (const ret of matched_schema.return_types) {
  14659. n.addOutput().setType(ret);
  14660. }
  14661. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14662. n.getOperation();
  14663. } else {
  14664. n.setHistoricSchemaName(matched_schema.schema_name);
  14665. }
  14666. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14667. });
  14668. this.registerFunction('torch._C.unshapedType', (type) => {
  14669. if (type.isSubtypeOf(torch.TensorType.get())) {
  14670. return torch.TensorType.get();
  14671. }
  14672. const contained = type.containedTypes();
  14673. if (contained.length === 0) {
  14674. return type;
  14675. }
  14676. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14677. });
  14678. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14679. default_to_union = default_to_union || false;
  14680. type_hint = type_hint || null;
  14681. if (t1.isSubtypeOf(t2)) {
  14682. return t2;
  14683. } else if (t2.isSubtypeOf(t1)) {
  14684. return t1;
  14685. }
  14686. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14687. return t1.merge(t2);
  14688. }
  14689. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14690. return torch.OptionalType.create(t2);
  14691. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14692. return torch.OptionalType.create(t1);
  14693. }
  14694. if (t1 instanceof torch.OptionalType) {
  14695. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14696. if (elem) {
  14697. return torch.OptionalType.create(elem);
  14698. }
  14699. } else if (t2 instanceof torch.OptionalType) {
  14700. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14701. if (elem) {
  14702. return torch.OptionalType.create(elem);
  14703. }
  14704. }
  14705. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14706. if (t1.elements().size() !== t2.elements().size()) {
  14707. return null;
  14708. }
  14709. const elements = [];
  14710. for (let i = 0; i < t1.elements().length; i++) {
  14711. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14712. if (elem) {
  14713. elements.push(elem);
  14714. } else {
  14715. return null;
  14716. }
  14717. }
  14718. return torch.TupleType.create(elements);
  14719. }
  14720. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14721. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14722. if (elem) {
  14723. return torch.FutureType.create(elem);
  14724. }
  14725. }
  14726. const t1_unshaped = torch._C.unshapedType(t1);
  14727. const t2_unshaped = torch._C.unshapedType(t2);
  14728. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14729. return t2_unshaped;
  14730. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14731. return t1_unshaped;
  14732. }
  14733. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14734. return type_hint;
  14735. }
  14736. return null;
  14737. });
  14738. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14739. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14740. if (default_to_union && !unified) {
  14741. return torch.UnionType.create([t1, t2]);
  14742. }
  14743. return unified;
  14744. });
  14745. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14746. if (elements.length === 0) {
  14747. return null;
  14748. }
  14749. let [ret_type] = elements;
  14750. for (let i = 1; i < elements.length && ret_type; i++) {
  14751. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14752. if (!maybe_unified) {
  14753. return null;
  14754. }
  14755. ret_type = maybe_unified;
  14756. }
  14757. return ret_type;
  14758. });
  14759. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14760. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14761. });
  14762. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14763. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14764. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14765. ivalue.isDevice() || ivalue.isEnum()) {
  14766. return true;
  14767. }
  14768. if (ivalue.isTensor()) {
  14769. return torch._C.insertableTensor(ivalue.toTensor());
  14770. }
  14771. if (ivalue.isList() || ivalue.isTuple()) {
  14772. let elems = [];
  14773. if (ivalue.isTuple()) {
  14774. elems = ivalue.toTupleRef().elements();
  14775. } else {
  14776. elems = ivalue.toListRef();
  14777. }
  14778. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14779. }
  14780. if (ivalue.isGenericDict()) {
  14781. const dict = ivalue.toGenericDict();
  14782. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14783. }
  14784. return false;
  14785. });
  14786. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14787. loc = loc || null;
  14788. scope = scope || null;
  14789. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14790. if (value !== undefined) {
  14791. return value;
  14792. }
  14793. throw new python.Error('Unsupported value kind.');
  14794. });
  14795. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14796. if (val instanceof torch._C.IValue) {
  14797. const n = g.create('prim::Constant');
  14798. if (val.isTensor()) {
  14799. const ref = val.toTensor();
  14800. if (!torch._C.insertableTensor(val.toTensor())) {
  14801. n.destroy();
  14802. return null;
  14803. }
  14804. if (!ref.defined()) {
  14805. n.destroy();
  14806. return g.insertNode(g.createNone()).output();
  14807. }
  14808. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  14809. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  14810. n.t_('value', ref);
  14811. } else if (val.isInt()) {
  14812. n.i_('value', val.toInt());
  14813. n.output().setType(torch.IntType.get());
  14814. } else if (val.isDouble()) {
  14815. n.f_('value', val.toDouble());
  14816. n.output().setType(torch.FloatType.get());
  14817. } else if (val.isComplexDouble()) {
  14818. n.c_('value', val.toComplexDouble());
  14819. n.output().setType(torch.ComplexType.get());
  14820. } else if (val.isBool()) {
  14821. n.i_('value', val.toBool());
  14822. n.output().setType(torch.BoolType.get());
  14823. } else if (val.isList()) {
  14824. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  14825. if (fast_path_list || torch._C.insertableIValue(val)) {
  14826. n.ival_('value', val);
  14827. n.output().setType(val.type());
  14828. } else {
  14829. n.destroy();
  14830. return null;
  14831. }
  14832. } else if (val.isString()) {
  14833. n.s_('value', val.toStringRef());
  14834. n.output().setType(torch.StringType.get());
  14835. } else if (val.isDevice()) {
  14836. n.s_('value', val.toDevice().__str__());
  14837. n.output().setType(torch.DeviceObjType.get());
  14838. } else if (val.isGenerator()) {
  14839. n.ival_('value', val.toGenerator());
  14840. n.output().setType(torch._C_._GeneratorType.get());
  14841. } else if (val.isStream()) {
  14842. n.ival_('value', val);
  14843. n.output().setType(torch.StreamObjType.get());
  14844. } else if (val.isNone()) {
  14845. n.output().setType(torch.NoneType.get());
  14846. // n.ival_('value', null); // remove
  14847. } else if (val.isTuple()) {
  14848. if (torch._C.insertableIValue(val)) {
  14849. n.ival_('value', val);
  14850. n.output().setType(val.type());
  14851. } else {
  14852. n.destroy();
  14853. return null;
  14854. }
  14855. } else if (val.isObject()) {
  14856. const ref = val.toObjectRef();
  14857. // see: [Constant Object Weak CompilationUnit Reference]
  14858. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  14859. n.ival_('value', val);
  14860. n.output().setType(val.type());
  14861. } else {
  14862. n.destroy();
  14863. return null;
  14864. }
  14865. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  14866. n.ival_('value', val);
  14867. n.output().setType(val.type());
  14868. } else {
  14869. n.destroy();
  14870. return null;
  14871. }
  14872. if (loc) {
  14873. n.setSourceRange(loc);
  14874. }
  14875. if (scope) {
  14876. n.setScope(scope);
  14877. }
  14878. return g.insertNode(n).output();
  14879. }
  14880. const n = g.create('prim::Constant');
  14881. let type = null;
  14882. if (val === null) {
  14883. n.ival_('value', val);
  14884. type = torch.NoneType.get();
  14885. } else if (typeof val === 'string') {
  14886. n.s_('value', val);
  14887. type = torch.StringType.get();
  14888. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  14889. n.ss_('value', val);
  14890. type = torch.ListType.create(torch.StringType.get());
  14891. } else if (typeof val === 'boolean') {
  14892. n.i_('value', val === true ? 1 : 0);
  14893. type = torch.BoolType.get();
  14894. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  14895. n.i_('value', val);
  14896. type = torch.IntType.get();
  14897. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  14898. n.f_('value', val);
  14899. type = torch.FloatType.get();
  14900. } else if (val instanceof torch.Tensor) {
  14901. n.t_('value', val);
  14902. type = torch.TensorType.get();
  14903. } else if (val instanceof torch.ScriptObject) {
  14904. n.ival_('value', val);
  14905. type = val.type();
  14906. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  14907. n.ival_('value', val);
  14908. type = torch.ListType.create(torch.IntType.get());
  14909. } else {
  14910. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  14911. }
  14912. if (type) {
  14913. n.output().setType(type);
  14914. }
  14915. if (loc) {
  14916. n.setSourceRange(loc);
  14917. }
  14918. if (scope) {
  14919. n.setScope(scope);
  14920. }
  14921. return g.insertNode(n).output();
  14922. });
  14923. this.registerFunction('torch._C.toIValue', (v) => {
  14924. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  14925. return null;
  14926. }
  14927. const node = v.node();
  14928. const type = v.type();
  14929. if (type.isSubtypeOf(torch.TensorType.get())) {
  14930. return new torch._C.IValue(node.t('value'), 'Tensor');
  14931. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  14932. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  14933. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  14934. return new torch._C.IValue(node.i('value'), 'Int');
  14935. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  14936. return new torch._C.IValue(node.f('value'), 'Double');
  14937. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'c') {
  14938. return new torch._C.IValue(node.c('value'), 'Complex');
  14939. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  14940. let list = node.ival('value');
  14941. list = list.isList ? list : new torch._C.IValue(list); // remove
  14942. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  14943. return list;
  14944. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  14945. const dict = node.ival('value');
  14946. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  14947. return dict;
  14948. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  14949. const tup = node.ival('value');
  14950. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  14951. return tup;
  14952. } else if (type === torch.StringType.get()) {
  14953. const s = new torch._C.IValue(node.s('value'), 'String');
  14954. return s;
  14955. } else if (type === torch.DeviceObjType.get()) {
  14956. const d = new torch.device(node.s('value'));
  14957. return new torch._C.IValue(d);
  14958. } else if (type === torch._C._GeneratorType.get()) {
  14959. throw new python.Error('Not implemented.');
  14960. // const generator = node.ival('value').toGenerator();
  14961. // return generator;
  14962. } else if (type === torch.StreamObjType.get()) {
  14963. throw new python.Error('Not implemented.');
  14964. // const s = node.ival('value').toStream();
  14965. // return s;
  14966. } else if (node.mustBeNone()) {
  14967. return new torch._C.IValue();
  14968. } else if (type.kind() === 'EnumType') {
  14969. const enum_val = node.ival('value');
  14970. return enum_val;
  14971. } else if (type instanceof torch.ClassType && !type.is_module()) {
  14972. const class_val = node.ival('value');
  14973. return new torch._C.IValue(class_val, 'Object');
  14974. }
  14975. throw new python.Error('Unsupported constant literal.');
  14976. });
  14977. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  14978. const ivalue = torch._C.toIValue(v);
  14979. if (ivalue) {
  14980. return ivalue[target]();
  14981. }
  14982. return default_value === undefined ? null : default_value;
  14983. });
  14984. this.registerType('torch._C.NamedValue', class {
  14985. constructor(...args) {
  14986. if (args.length === 1) {
  14987. if (args[0] instanceof torch.Value) {
  14988. [this._value] = args;
  14989. } else {
  14990. [this._ivalue] = args;
  14991. }
  14992. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  14993. [this._loc, this._name, this._value] = args;
  14994. } else {
  14995. throw new python.Error('Invalid argument.');
  14996. }
  14997. }
  14998. name() {
  14999. return this._name;
  15000. }
  15001. value(g) {
  15002. if (!this._value) {
  15003. return torch._C.insertConstant(g, this._ivalue);
  15004. }
  15005. return this._value;
  15006. }
  15007. type() {
  15008. if (this._value) {
  15009. return this._value.type();
  15010. }
  15011. return this._ivalue.type();
  15012. }
  15013. });
  15014. this.registerType('torch._C.SugaredValue', class {
  15015. kind() {
  15016. throw new python.Error('Not implemented.');
  15017. }
  15018. shouldEmitUnrolled() {
  15019. return this.staticLen() !== null;
  15020. }
  15021. });
  15022. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15023. constructor(value) {
  15024. super();
  15025. this._value = value;
  15026. }
  15027. kind() {
  15028. return `value of type '${this._value.type().annotation_str}'`;
  15029. }
  15030. asValue(/* range, m */) {
  15031. return this._value;
  15032. }
  15033. getValue() {
  15034. return this._value;
  15035. }
  15036. asTuple(loc, m, size_hint) {
  15037. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15038. if (this._value.type() instanceof torch.TupleType) {
  15039. const outputs = torch._C.createTupleUnpack(this._value);
  15040. return outputs.map((v) => make_simple_value(v));
  15041. } else if (this._value.type() instanceof torch.ListType) {
  15042. if (!size_hint) {
  15043. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15044. }
  15045. const graph = this._value.owningGraph();
  15046. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15047. return unpack.outputs().map((v) => make_simple_value(v));
  15048. } else if (this._value.type().kind() === 'AnyTupleType') {
  15049. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15050. }
  15051. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15052. }
  15053. attr(loc, m, field) {
  15054. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15055. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15056. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15057. }
  15058. }
  15059. if (this._value.type() instanceof torch.TupleType) {
  15060. throw new python.Error('Not implemented.');
  15061. }
  15062. if (this._value.type() instanceof torch.AwaitType) {
  15063. throw new python.Error('Not implemented.');
  15064. }
  15065. if (this._value.type() instanceof torch.ClassType) {
  15066. const classType = this._value.type();
  15067. if (classType.findMethod(field)) {
  15068. return new torch._C.MethodValue(this.getValue(), [field]);
  15069. }
  15070. if (classType.hasAttribute(field)) {
  15071. const g = m.graph();
  15072. const n = g.insertNode(g.createGetAttr(this._value, field));
  15073. return new torch._C.SimpleValue(n.output());
  15074. }
  15075. const prop = classType.getProperty(field);
  15076. if (prop) {
  15077. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15078. }
  15079. } else if (this._value.type() instanceof torch.InterfaceType) {
  15080. throw new python.Error('Not implemented.');
  15081. } else if (this._value.type() instanceof torch.EnumType) {
  15082. const g = m.graph();
  15083. if (field === 'name') {
  15084. const n = g.insertNode(g.createEnumName(this._value));
  15085. return new torch._C.SimpleValue(n.output());
  15086. }
  15087. if (field === 'value') {
  15088. const n = g.insertNode(g.createEnumValue(this._value));
  15089. return new torch._C.SimpleValue(n.output());
  15090. }
  15091. }
  15092. if (field === 'type') {
  15093. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15094. if (builtin) {
  15095. return builtin;
  15096. }
  15097. }
  15098. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15099. if (builtin) {
  15100. return builtin;
  15101. }
  15102. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15103. return torch._C.SpecialFormValue.create('prim::tolist');
  15104. }
  15105. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15106. return torch._C.SpecialFormValue.create('aten::index');
  15107. }
  15108. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15109. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15110. if (builtin) {
  15111. return builtin;
  15112. }
  15113. }
  15114. throw new python.Error('Object has no attribute or method.');
  15115. }
  15116. setAttr(loc, m, field, newValue) {
  15117. const type = this._value.type();
  15118. if (type instanceof torch.ClassType === false) {
  15119. throw new python.Error('Cannot set attribute on non-class type.');
  15120. }
  15121. const classType = type;
  15122. let expectedType = classType.findAttribute(field);
  15123. if (!expectedType) {
  15124. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15125. if (isInitializing) {
  15126. if (this.isRecursive(classType, newValue.type())) {
  15127. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15128. }
  15129. classType.addAttribute(field, newValue.type());
  15130. expectedType = newValue.type();
  15131. const insertPoint = m.graph().insertPoint();
  15132. const topLevelBlock = m.graph().block();
  15133. if (insertPoint.owningBlock() !== topLevelBlock) {
  15134. throw new python.Error('First assignment cannot be in a control-flow block.');
  15135. }
  15136. } else {
  15137. const prop = classType.getProperty(field);
  15138. if (prop && prop.setter) {
  15139. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15140. return;
  15141. }
  15142. if (prop && !prop.setter) {
  15143. throw new python.Error('Tried to set read-only attribute.');
  15144. }
  15145. throw new python.Error('Tried to set nonexistent attribute.');
  15146. }
  15147. }
  15148. torch._C.AT_ASSERT(expectedType);
  15149. const newType = newValue.type();
  15150. if (!newType.isSubtypeOf(expectedType)) {
  15151. throw new python.Error('Wrong type for attribute assignment.');
  15152. }
  15153. const g = m.graph();
  15154. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15155. }
  15156. getitem(loc, m, idx, type_hint) {
  15157. const val = this.getValue();
  15158. const val_type = val.type();
  15159. const g = m.graph();
  15160. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15161. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15162. } else if (val_type instanceof torch.DictType) {
  15163. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15164. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15165. 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));
  15166. } else if (val_type instanceof torch.ClassType) {
  15167. const class_type = val_type;
  15168. if (class_type.is_module() && type_hint) {
  15169. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15170. res.setType(type_hint);
  15171. return new torch._C.SimpleValue(res);
  15172. }
  15173. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15174. }
  15175. throw new python.Error('Object is not subscriptable.');
  15176. }
  15177. });
  15178. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15179. constructor(self, method_names) {
  15180. super();
  15181. this._self = self;
  15182. this._method_names = method_names;
  15183. }
  15184. call(loc, f, args, kwargs /*, n_binders */) {
  15185. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15186. const schemas = [];
  15187. for (const method_name of this._method_names) {
  15188. const type = this._self.type();
  15189. if (type instanceof torch.ClassType) {
  15190. const class_type = type;
  15191. const method = class_type.getMethod(method_name);
  15192. method.ensure_defined();
  15193. schemas.push(method.getSchema());
  15194. } else if (type instanceof torch.InterfaceType) {
  15195. const interface_type = type;
  15196. schemas.push(interface_type.getMethod(method_name));
  15197. } else {
  15198. throw new python.Error('Method constructed that is not a class or interface.');
  15199. }
  15200. }
  15201. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15202. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15203. output.node().setSourceRange(loc);
  15204. return new torch._C.SimpleValue(output);
  15205. }
  15206. });
  15207. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15208. constructor(type) {
  15209. super();
  15210. this._type = type;
  15211. }
  15212. attr(loc, m, field) {
  15213. const hook = this._type.findHook(field);
  15214. if (hook) {
  15215. return new torch._C.FunctionValue(hook);
  15216. }
  15217. if (field !== '__new__') {
  15218. throw new python.Error('Tried to lookup unknown attribute on class.');
  15219. }
  15220. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15221. }
  15222. });
  15223. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15224. constructor(type) {
  15225. super();
  15226. this._type = type;
  15227. }
  15228. call(loc, m, args, kwargs /*, n_binders */) {
  15229. const g = m.graph();
  15230. const schema = this._type.schema();
  15231. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15232. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15233. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15234. self.setType(this._type);
  15235. return new torch._C.SimpleValue(self);
  15236. }
  15237. });
  15238. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15239. constructor(enum_type) {
  15240. super();
  15241. this._enum_type = enum_type;
  15242. }
  15243. attr(loc, m, field) {
  15244. const names_values = this._enum_type.enumNamesValues();
  15245. const it = names_values.find((nv) => nv[0] === field);
  15246. if (it === null) {
  15247. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15248. }
  15249. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15250. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15251. }
  15252. });
  15253. this.registerType('torch._C.EnumHolder', class {
  15254. constructor(type, name, value) {
  15255. this._type = type;
  15256. this._name = name;
  15257. this._value = value;
  15258. }
  15259. name() {
  15260. return this._name;
  15261. }
  15262. type() {
  15263. return this._type;
  15264. }
  15265. });
  15266. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15267. constructor(...args) {
  15268. super();
  15269. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15270. this._callees = [args[0]];
  15271. } else {
  15272. throw new python.Error('Not implemented.');
  15273. }
  15274. }
  15275. call(loc, f, args, kwargs /*, n_binders */) {
  15276. const schemas = [];
  15277. for (const callee of this._callees) {
  15278. callee.ensure_defined();
  15279. schemas.push(callee.getSchema());
  15280. }
  15281. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15282. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15283. output.node().setSourceRange(loc);
  15284. return new torch._C.SimpleValue(output);
  15285. }
  15286. });
  15287. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15288. });
  15289. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15290. call(loc, m, args, kwargs /*, n_binders */) {
  15291. const g = m.graph();
  15292. if (kwargs.length > 0) {
  15293. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15294. }
  15295. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15296. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15297. return new torch._C.NoneValue();
  15298. }
  15299. });
  15300. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15301. constructor(form) {
  15302. super();
  15303. this._form = form;
  15304. }
  15305. form() {
  15306. return this._form;
  15307. }
  15308. static create(form) {
  15309. return new torch._C.SpecialFormValue(form);
  15310. }
  15311. });
  15312. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15313. return new torch._C.MagicMethod(name, base);
  15314. });
  15315. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15316. constructor(symbol, self) {
  15317. super();
  15318. this.symbol = symbol;
  15319. this.self = self;
  15320. }
  15321. call(loc, m, args, kwargs /*, n_binders */) {
  15322. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15323. }
  15324. static tryCreate(symbol, self) {
  15325. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15326. if (!self) {
  15327. return new torch._C.BuiltinFunction(symbol, null);
  15328. }
  15329. const index = op.schema().argumentIndexWithName('self');
  15330. if (index) {
  15331. const type_env = new Map();
  15332. const formal_type = op.schema().arguments()[index].type();
  15333. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15334. if (!matched.success()) {
  15335. continue;
  15336. }
  15337. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15338. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15339. continue;
  15340. }
  15341. return new torch._C.BuiltinFunction(symbol, self);
  15342. }
  15343. }
  15344. return null;
  15345. }
  15346. });
  15347. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15348. constructor(name, version) {
  15349. super();
  15350. this.name = name;
  15351. this.version = version || null;
  15352. }
  15353. attr(loc, m, field) {
  15354. if (field === 'autograd') {
  15355. return new torch._C.BuiltinModule('aten', this.version);
  15356. }
  15357. const sym = `${this.name}::${field}`;
  15358. return new torch._C.BuiltinFunction(sym, null);
  15359. }
  15360. });
  15361. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15362. constructor(version) {
  15363. super();
  15364. this._version = version;
  15365. }
  15366. attr(loc, m, field) {
  15367. return new torch._C.BuiltinModule(field, this._version);
  15368. }
  15369. });
  15370. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15371. constructor(constants) {
  15372. super();
  15373. this._constants = constants;
  15374. this.non_holding_object_cache = new Map();
  15375. }
  15376. attr(loc, m, field) {
  15377. const offset = parseInt(field.substring(1), 10);
  15378. if (!Number.isInteger(offset)) {
  15379. throw new python.Error(`Invalid constant identifier '${field}.`);
  15380. }
  15381. if (offset < 0 || offset >= this._constants.length) {
  15382. throw new python.Error('Invalid constant index.');
  15383. }
  15384. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15385. let value = null;
  15386. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15387. const obj = ivalue.toObject();
  15388. if (!this.non_holding_object_cache.has(obj)) {
  15389. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15390. }
  15391. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15392. } else {
  15393. value = m.graph().insertConstant(this._constants[offset], loc);
  15394. }
  15395. value.setType(torch._C.unshapedType(value.type()));
  15396. return new torch._C.SimpleValue(value);
  15397. }
  15398. });
  15399. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15400. constructor(type, method) {
  15401. super(method, null);
  15402. this._type = type;
  15403. }
  15404. call(loc, m, args, kwargs, n_binders) {
  15405. if (args.length === 1 && kwargs.length === 0) {
  15406. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15407. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15408. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15409. const v = args[0].value(m.graph());
  15410. if (v.type().isSubtypeOf(this._type)) {
  15411. return new torch._C.SimpleValue(v);
  15412. } 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)) {
  15413. const len = len_op.call(loc, m, [v], [], 1);
  15414. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15415. }
  15416. }
  15417. return super.call(loc, m, args, kwargs, n_binders);
  15418. }
  15419. });
  15420. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15421. constructor(desugared_name, base) {
  15422. super();
  15423. this._base_value = base;
  15424. this._desugared_name = desugared_name;
  15425. }
  15426. call(loc, m, args, kwargs, n_binders) {
  15427. if (args.length > 0) {
  15428. const self = args[0].value(m.graph());
  15429. if (self.type() instanceof torch.ClassType) {
  15430. return new torch._C.SimpleValue(self)
  15431. .attr(loc, m, this._desugared_name)
  15432. .call(loc, m, args.slice(1), kwargs, n_binders);
  15433. }
  15434. }
  15435. if (!this._base_value) {
  15436. throw new python.Error('Invalid magic method.');
  15437. }
  15438. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15439. }
  15440. });
  15441. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15442. constructor(loc, m, inputs, static_len) {
  15443. super();
  15444. static_len = static_len || null;
  15445. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15446. throw new python.Error('Invalid range inputs.');
  15447. }
  15448. const g = m.graph();
  15449. if (inputs.length === 1) {
  15450. [this._end] = inputs;
  15451. this._start = g.insertConstant(0, loc);
  15452. this._step = g.insertConstant(1, loc);
  15453. this._has_only_end = true;
  15454. } else {
  15455. [this._start, this._end] = inputs;
  15456. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15457. this._has_only_end = false;
  15458. }
  15459. this._static_len = static_len;
  15460. }
  15461. staticLen() {
  15462. return this._static_len;
  15463. }
  15464. iter() {
  15465. return this;
  15466. }
  15467. len(loc, m) {
  15468. if (this._static_len) {
  15469. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15470. }
  15471. if (this._has_only_end) {
  15472. return this._end;
  15473. }
  15474. const g = m.graph();
  15475. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15476. }
  15477. getitem(loc, m, idx /*, type_hint */) {
  15478. if (this._has_only_end) {
  15479. return new torch._C.SimpleValue(idx);
  15480. }
  15481. const g = m.graph();
  15482. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15483. }
  15484. });
  15485. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15486. });
  15487. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15488. constructor(name, si) {
  15489. super();
  15490. this._basename = name;
  15491. this._si = si;
  15492. }
  15493. attr(loc, m, name) {
  15494. const fullName = new torch._C.QualifiedName(this._basename, name);
  15495. const serializable_type = this._si.findNamedType(fullName);
  15496. if (serializable_type) {
  15497. if (serializable_type instanceof torch.ClassType) {
  15498. return new torch._C.ClassValue(serializable_type);
  15499. } else if (serializable_type instanceof torch.TupleType) {
  15500. return new torch._C.NamedTupleConstructor(serializable_type);
  15501. } else if (serializable_type instanceof torch.EnumType) {
  15502. return new torch._C.SugaredEnumClass(serializable_type);
  15503. }
  15504. }
  15505. const fn = this._si.findFunction(fullName);
  15506. if (fn) {
  15507. return new torch._C.FunctionValue(fn);
  15508. }
  15509. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15510. }
  15511. });
  15512. this.registerType('torch.package.PackageImporter', class {
  15513. constructor(reader) {
  15514. this.zip_reader = reader;
  15515. }
  15516. load_pickle(module, resource) {
  15517. const name = `${module.replace(/\./, '/')}/${resource}`;
  15518. const stream = this.zip_reader.get_record(name);
  15519. const loaded_reduces = new Map();
  15520. this.storage_context = new torch._C.DeserializationStorageContext();
  15521. const unpickler = new pickle.Unpickler(stream);
  15522. unpickler.persistent_load = (saved_id) => {
  15523. switch (saved_id[0]) {
  15524. case 'storage': {
  15525. const [, storage_type, key, , size] = saved_id;
  15526. if (!this.storage_context.has_storage(key)) {
  15527. const storage = new storage_type(size);
  15528. if (!storage._set_cdata) {
  15529. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15530. }
  15531. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15532. const buffer = stream.peek();
  15533. storage._set_cdata(buffer);
  15534. this.storage_context.add_storage(key, storage);
  15535. }
  15536. return this.storage_context.get_storage(key);
  15537. }
  15538. case 'reduce_package': {
  15539. if (saved_id.length === 2) {
  15540. const [, func, args] = saved_id;
  15541. return execution.invoke(func, args);
  15542. }
  15543. const [, reduce_id, func, args] = saved_id;
  15544. if (!loaded_reduces.has(reduce_id)) {
  15545. const value = execution.invoke(func, [this].concat(args));
  15546. loaded_reduces.set(reduce_id, value);
  15547. }
  15548. return loaded_reduces.get(reduce_id);
  15549. }
  15550. default: {
  15551. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15552. }
  15553. }
  15554. };
  15555. const obj = unpickler.load();
  15556. this.storage_context = null;
  15557. return obj;
  15558. }
  15559. import_module(name) {
  15560. return execution.import(name);
  15561. }
  15562. });
  15563. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15564. const cu = new torch.jit.CompilationUnit();
  15565. cu.execution = execution;
  15566. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15567. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15568. module.forward = cpp_module.forward; // remove
  15569. return module;
  15570. });
  15571. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15572. switch (arguments.length) {
  15573. case 4: {
  15574. const [device, extra_files] = args;
  15575. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15576. return deserializer.deserialize(device, extra_files);
  15577. }
  15578. case 5: {
  15579. const [storage_context, device, ts_id] = args;
  15580. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15581. return deserializer.deserialize(device, null);
  15582. }
  15583. default: {
  15584. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15585. }
  15586. }
  15587. });
  15588. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15589. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15590. });
  15591. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15592. if (value instanceof torch.Node) {
  15593. const n = value;
  15594. if (n.kind() === 'prim::CallFunction') {
  15595. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15596. const function_constant = n.input(0).node();
  15597. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15598. return torch._C.tryToGraphFunction(fun_type.function());
  15599. }
  15600. if (n.kind() === 'prim::CallMethod') {
  15601. const name = n.s('name');
  15602. const class_type = n.input(0).type();
  15603. if (class_type instanceof torch.ClassType) {
  15604. const fn = class_type.getMethod(name);
  15605. return torch._C.tryToGraphFunction(fn);
  15606. }
  15607. }
  15608. return null;
  15609. } else if (value instanceof torch._C.Function) {
  15610. const fn = value;
  15611. if (!fn.isGraphFunction()) {
  15612. return null;
  15613. }
  15614. return fn;
  15615. }
  15616. throw new python.Error('Not implemented.');
  15617. });
  15618. this.registerType('torch._C.ModuleInstanceInfo', class {
  15619. constructor(module_type, instance_name) {
  15620. this._module_type = module_type;
  15621. this._instance_name = instance_name;
  15622. }
  15623. });
  15624. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15625. torch._C.TORCH_CHECK(step !== 0);
  15626. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15627. if (start._ === Number.MAX_SAFE_INTEGER) {
  15628. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15629. }
  15630. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15631. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15632. }
  15633. if (start._ < 0) {
  15634. start._ += length;
  15635. if (start._ < 0) {
  15636. start._ = (step < 0) ? -1 : 0;
  15637. }
  15638. } else if (start._ >= length) {
  15639. start._ = (step < 0) ? length - 1 : length;
  15640. }
  15641. if (stop._ < 0) {
  15642. stop._ += length;
  15643. if (stop._ < 0) {
  15644. stop._ = (step < 0) ? -1 : 0;
  15645. }
  15646. } else if (stop._ >= length) {
  15647. stop._ = (step < 0) ? length - 1 : length;
  15648. }
  15649. if (step < 0) {
  15650. if (stop._ < start._) {
  15651. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15652. }
  15653. } else if (start._ < stop._) {
  15654. return Math.floor((stop._ - start._ - 1) / step + 1);
  15655. }
  15656. return 0;
  15657. });
  15658. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15659. if (v.node().kind() === 'prim::TupleConstruct') {
  15660. return v.node().inputs();
  15661. }
  15662. const g = v.owningGraph();
  15663. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15664. });
  15665. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15666. /*
  15667. const new_node_cs = new_node.callstack();
  15668. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15669. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15670. if (new_node_cs) {
  15671. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15672. } else {
  15673. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15674. }
  15675. }
  15676. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15677. for (const block of new_node.blocks()) {
  15678. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15679. }
  15680. */
  15681. });
  15682. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15683. if (arg === undefined || typeof arg === 'boolean') {
  15684. const inline_optimized_graph = arg === undefined ? true : arg;
  15685. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15686. return torch._C.inlineCallTo(to_replace, callee, graph);
  15687. }
  15688. if (arg instanceof torch.Graph === false) {
  15689. throw new python.Error('Invalid argument.');
  15690. }
  15691. const callee_graph = arg;
  15692. const guard = new torch._C.WithInsertPoint(to_replace);
  15693. const value_map = new Map();
  15694. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15695. const new_callstack_entries = new Map();
  15696. let module_instance_info = null;
  15697. if (to_replace.kind() === 'prim::CallMethod') {
  15698. const class_type_ptr = to_replace.input(0).type();
  15699. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15700. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15701. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15702. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15703. } else {
  15704. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15705. }
  15706. }
  15707. const updated_nodes = new Set();
  15708. for (const kv of value_map) {
  15709. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15710. if (is_graph_input === -1) {
  15711. continue;
  15712. }
  15713. const new_node = kv[1].node();
  15714. if (updated_nodes.has(new_node)) {
  15715. continue;
  15716. }
  15717. updated_nodes.add(new_node);
  15718. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15719. }
  15720. const old_outputs = to_replace.outputs();
  15721. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15722. for (let i = 0; i < old_outputs.length; i++) {
  15723. if (old_outputs[i].hasDebugName()) {
  15724. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15725. }
  15726. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15727. }
  15728. to_replace.destroy();
  15729. guard.dispose();
  15730. return new_outputs;
  15731. });
  15732. this.registerFunction('torch._C.inlineCalls', (block) => {
  15733. for (const cur of block.nodes()) {
  15734. switch (cur.kind()) {
  15735. case 'prim::CallFunction': {
  15736. const graphFunction = torch._C.tryToGraphFunction(cur);
  15737. if (graphFunction) {
  15738. const function_constant = cur.input(0).node();
  15739. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15740. cur.removeInput(0);
  15741. let g = null;
  15742. const fallback = function_constant.hasAttribute('fallback');
  15743. if (fallback && graphFunction.get_executor().isOptimized()) {
  15744. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15745. if (!exec_plans.empty()) {
  15746. g = exec_plans.begin().second.graph;
  15747. torch._C.Inline(g);
  15748. }
  15749. }
  15750. if (g === null) {
  15751. g = graphFunction.optimized_graph();
  15752. }
  15753. torch._C.inlineCallTo(cur, graphFunction, g);
  15754. }
  15755. break;
  15756. }
  15757. case 'prim::CallMethod': {
  15758. const graphFunction = torch._C.tryToGraphFunction(cur);
  15759. if (graphFunction) {
  15760. torch._C.inlineCallTo(cur, graphFunction);
  15761. }
  15762. break;
  15763. }
  15764. default: {
  15765. for (const b of cur.blocks()) {
  15766. torch._C.inlineCalls(b);
  15767. }
  15768. }
  15769. }
  15770. }
  15771. });
  15772. this.registerFunction('torch._C.Inline', (graph) => {
  15773. torch._C.inlineCalls(graph.block());
  15774. });
  15775. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15776. torch._C.Inline(graph);
  15777. });
  15778. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15779. });
  15780. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15781. const cu = new torch.jit.CompilationUnit();
  15782. cu.execution = execution;
  15783. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15784. return torch.jit._script.wrap_cpp_module(cpp_module);
  15785. });
  15786. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15787. const init_fn = (script_module) => {
  15788. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15789. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15790. }
  15791. };
  15792. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15793. });
  15794. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15795. has_storage(name) {
  15796. return this.has(name);
  15797. }
  15798. get_storage(name) {
  15799. return this.get(name);
  15800. }
  15801. add_storage(name, storage) {
  15802. return this.set(name, storage);
  15803. }
  15804. });
  15805. this.registerType('torch.ScriptFunction', class {
  15806. constructor(name, graph /*, function_creator */) {
  15807. this._name = name;
  15808. this._graph = graph;
  15809. }
  15810. });
  15811. this.registerType('torch.ScriptMethod', class {
  15812. constructor(owner, value) {
  15813. this._owner = owner;
  15814. this._function = value;
  15815. }
  15816. get name() {
  15817. return this._function.name();
  15818. }
  15819. get owner() {
  15820. return this._owner;
  15821. }
  15822. __call__(/* args, kwargs */) {
  15823. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  15824. }
  15825. get graph() {
  15826. return this._function.graph();
  15827. }
  15828. get schema() {
  15829. // return this.function().getSchema();
  15830. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  15831. }
  15832. get code() {
  15833. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  15834. }
  15835. get code_with_constants() {
  15836. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  15837. }
  15838. });
  15839. this.registerType('torch.ScriptObject', class {
  15840. constructor(type) {
  15841. this._typ = type;
  15842. this._ivalue = {};
  15843. }
  15844. static create(type) {
  15845. if (type.is_module()) {
  15846. return new torch.ScriptModule(type);
  15847. }
  15848. return new torch.ScriptObject(type);
  15849. }
  15850. type() {
  15851. return this._typ;
  15852. }
  15853. _type() {
  15854. return this._typ; // torch.ClassType
  15855. }
  15856. __setstate__(state) {
  15857. const [attrs, qualname] = state;
  15858. this._typ = torch._C.getCustomClass(qualname);
  15859. if (!this._typ) {
  15860. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  15861. }
  15862. for (let i = 0; i < this._typ.numAttributes(); i++) {
  15863. const name = this._typ.getAttributeName(i);
  15864. this.__setattr__(name, attrs[i]);
  15865. }
  15866. }
  15867. find_method(basename) {
  15868. for (const fn of this.type().methods()) {
  15869. if (fn.name() === basename) {
  15870. return new torch.ScriptMethod(this /* _value() */, fn);
  15871. }
  15872. }
  15873. return null;
  15874. }
  15875. _get_method(name) {
  15876. const method = this.find_method(name);
  15877. if (method) {
  15878. return method;
  15879. }
  15880. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  15881. return null;
  15882. }
  15883. _has_method(name) {
  15884. return this.find_method(name) ? true : false;
  15885. }
  15886. _method_names() {
  15887. return this.type().methods().map((fn) => fn.name());
  15888. }
  15889. __setattr__(name, value) {
  15890. // if (this._type.hasContant(name))
  15891. this._ivalue[name] = value;
  15892. }
  15893. __getattr__(name) {
  15894. return this._ivalue[name];
  15895. }
  15896. hasattr(name) {
  15897. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  15898. }
  15899. getattr(name) {
  15900. return this.__getattr__(name);
  15901. }
  15902. _properties() {
  15903. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  15904. }
  15905. is_weak_compilation_ref() {
  15906. return true; // not implemented
  15907. }
  15908. });
  15909. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  15910. constructor(...args) {
  15911. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  15912. const [class_name, cu, shouldMangle] = args;
  15913. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  15914. } else {
  15915. super(...args);
  15916. }
  15917. }
  15918. get qualified_name() {
  15919. return this.type().qualified_name();
  15920. }
  15921. get code_with_constants() {
  15922. const const_map = {};
  15923. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  15924. return [null, const_map];
  15925. }
  15926. get graph() {
  15927. if (!this._graph) {
  15928. const fn = this._typ.getMethod('forward');
  15929. this._graph = fn.graph();
  15930. }
  15931. return this._graph;
  15932. }
  15933. static create_module_object(class_name, cu, shouldMangle) {
  15934. shouldMangle = shouldMangle || false;
  15935. if (!class_name.prefix()) {
  15936. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  15937. }
  15938. if (shouldMangle && cu.get_class(class_name)) {
  15939. class_name = cu.mangle(class_name);
  15940. }
  15941. const cls = torch.ClassType.create(class_name, cu, true);
  15942. cu.register_type(cls);
  15943. return [cls, cu];
  15944. }
  15945. register_module(name, module) {
  15946. this.type().addOrCheckAttribute(name, module.type());
  15947. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  15948. }
  15949. register_buffer(name, v) {
  15950. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  15951. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  15952. }
  15953. register_parameter(name, v, is_buffer) {
  15954. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  15955. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  15956. }
  15957. register_attribute(name, t, v, is_param, is_buffer) {
  15958. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  15959. // _ivalue()->setAttr(name, v);
  15960. }
  15961. });
  15962. this.registerType('torch.ModuleDict', class {
  15963. constructor(mod) {
  15964. this._module = mod;
  15965. }
  15966. items() {
  15967. const result = new Map();
  15968. const type = this._module.type();
  15969. for (let i = 0; i < type.numAttributes(); i++) {
  15970. const k = type.getAttributeName(i);
  15971. const t = type.getAttribute(i);
  15972. if (t && t.is_module()) {
  15973. result.set(k, this._module.__getattr__(k));
  15974. }
  15975. }
  15976. return result;
  15977. }
  15978. });
  15979. this.registerType('torch.ParameterDict', class {
  15980. constructor(mod) {
  15981. this._module = mod;
  15982. }
  15983. items() {
  15984. const result = new Map();
  15985. const type = this._module.type();
  15986. for (let i = 0; i < type.numAttributes(); i++) {
  15987. if (type.is_parameter(i)) {
  15988. const k = type.getAttributeName(i);
  15989. const v = this._module.__getattr__(k);
  15990. if (v instanceof torch.Tensor) {
  15991. result.set(k, v);
  15992. }
  15993. }
  15994. }
  15995. return result;
  15996. }
  15997. });
  15998. this.registerType('torch.BufferDict', class {
  15999. constructor(mod) {
  16000. this._module = mod;
  16001. }
  16002. items() {
  16003. const result = new Map();
  16004. const type = this._module.type();
  16005. for (let i = 0; i < type.numAttributes(); i++) {
  16006. if (type.is_buffer(i)) {
  16007. const t = type.getAttribute(i);
  16008. if (t.isSubtypeOf(torch.TensorType.get())) {
  16009. const k = type.getAttributeName(i);
  16010. const v = this._module.__getattr__(k);
  16011. result.set(k, v);
  16012. }
  16013. }
  16014. }
  16015. return result;
  16016. }
  16017. });
  16018. this.registerType('torch._C.to_ir', class {
  16019. constructor(def, _resolver, self, method) {
  16020. this.method = method;
  16021. this.graph = method.graph();
  16022. this.resolver = _resolver;
  16023. this.integral_constants = new Map();
  16024. this.fp_constants = new Map();
  16025. this.complex_constants = new Map();
  16026. this.exit_blocks = new Set();
  16027. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16028. this._loop_status = 'NOT_IN_LOOP';
  16029. this.environment_stack = null;
  16030. this._def_stack = [];
  16031. this._temp_name_count = 0;
  16032. torch._C.AT_ASSERT(this.resolver);
  16033. this.pushFrame(this.graph.block(), true);
  16034. if (self && def && def.args.args.length === 0) {
  16035. throw new python.Error('Method must have a self argument.');
  16036. }
  16037. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16038. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16039. torch._C.ConvertToSSA(this.graph);
  16040. torch._C.CanonicalizeModifiedLoops(this.graph);
  16041. torch._C.NormalizeOps(this.graph.block());
  16042. torch._C.runCleanupPasses(this.graph);
  16043. }
  16044. pushFrame(b, starts_def) {
  16045. starts_def = starts_def || false;
  16046. if (starts_def) {
  16047. this._def_stack.push({});
  16048. }
  16049. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16050. }
  16051. popFrame(ends_def) {
  16052. const old_frame = this.environment_stack;
  16053. this.environment_stack = this.environment_stack.next;
  16054. if (ends_def) {
  16055. this._def_stack.pop();
  16056. }
  16057. return old_frame;
  16058. }
  16059. emitDef(def, self, block) {
  16060. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16061. if (schema.returns.length === 1) {
  16062. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16063. }
  16064. const args = this.emitFormalArguments(def, self, schema, block);
  16065. this.emitStatements(def.body);
  16066. this.handleMaybeNoReturn(def, block);
  16067. const returns = [this.emitOutput(def, schema, block)];
  16068. return new torch.FunctionSchema(def.name, '', args, returns);
  16069. }
  16070. emitFormalArguments(def, self, schema, block) {
  16071. const args = [];
  16072. const params = def.args.args;
  16073. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16074. if (schema.arguments.length !== expected_annotation_size) {
  16075. throw new python.Error('Invalid formal arguments.');
  16076. }
  16077. let it = 0;
  16078. if (self) {
  16079. const param = params[it];
  16080. const name = param.arg;
  16081. const new_input = block.addInput().setDebugName(name);
  16082. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16083. args.push(new torch.Argument(name, new_input.type()));
  16084. it++;
  16085. }
  16086. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16087. let arg_annotation_idx = 0;
  16088. for (; it < params.length; it++) {
  16089. const param = params[it];
  16090. const name = param.arg;
  16091. const new_input = block.addInput();
  16092. if (torch._C.meaningfulName(name)) {
  16093. new_input.setDebugName(name);
  16094. }
  16095. let arg = schema.arguments[arg_annotation_idx++];
  16096. if (shouldDeriveType) {
  16097. if (schema.arguments.length === 1) {
  16098. throw new python.Error('Invalid schema.');
  16099. }
  16100. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16101. arg = arg.cloneWithType(inferredStateType);
  16102. }
  16103. args.push(arg);
  16104. new_input.setType(arg.type);
  16105. this.environment_stack.setVar(param.range(), name, new_input);
  16106. }
  16107. return args;
  16108. }
  16109. emitOutput(range, schema, block) {
  16110. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16111. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16112. block.registerOutput(placeholder_return);
  16113. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16114. }
  16115. emitStatements(stmts) {
  16116. for (let i = 0; i < stmts.length; i++) {
  16117. const stmt = stmts[i];
  16118. if (stmt instanceof ast.If) {
  16119. this.emitIf(stmt);
  16120. } else if (stmt instanceof ast.While) {
  16121. this.emitWhile(stmt);
  16122. } else if (stmt instanceof ast.For) {
  16123. this.emitFor(stmt);
  16124. } else if (stmt instanceof ast.Assign) {
  16125. this.emitAssignment(stmt);
  16126. } else if (stmt instanceof ast.AnnAssign) {
  16127. this.emitAssignment(stmt);
  16128. } else if (stmt instanceof ast.Expr) {
  16129. this.emitSugaredExpr(stmt.value, 0);
  16130. } else if (stmt instanceof ast.Return) {
  16131. this.emitReturn(stmt);
  16132. } else if (stmt instanceof ast.Pass) {
  16133. // pass
  16134. } else if (stmt instanceof ast.With) {
  16135. this.emitWith(stmt);
  16136. } else {
  16137. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16138. }
  16139. if (this.exit_blocks.has(this.environment_stack.block())) {
  16140. return;
  16141. }
  16142. }
  16143. }
  16144. emitWith(stmt) {
  16145. const targets = stmt.items;
  16146. const entered = [];
  16147. for (const target of targets) {
  16148. const e = target.context_expr;
  16149. const rhs = this.emitExpr(e);
  16150. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16151. entered.push(rhs);
  16152. if (rhs.type() instanceof torch.ClassType === false) {
  16153. throw new python.Error('With item expression must return an object.');
  16154. }
  16155. const rhsClass = rhs.type();
  16156. const enterMethod = rhsClass.findMethod('__enter__');
  16157. const exitMethod = rhsClass.findMethod('__exit__');
  16158. if (!enterMethod || !exitMethod) {
  16159. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16160. }
  16161. const enterSchema = enterMethod.getSchema();
  16162. if (enterSchema.arguments.length !== 1) {
  16163. throw new python.Error('__enter__ must have only one argument and one return value.');
  16164. }
  16165. const exitSchema = exitMethod.getSchema();
  16166. if (exitSchema.arguments.length === 4) {
  16167. for (let i = 1; i < 4; i++) {
  16168. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16169. throw new python.Error('Argument of __exit__ must have Any type.');
  16170. }
  16171. }
  16172. } else {
  16173. throw new python.Error('__exit__ must have four arguments');
  16174. }
  16175. n.output(0).setType(enterSchema.returns[0].type);
  16176. if (target.optional_vars) {
  16177. throw new python.Error('Not implemented.');
  16178. // Var i = target.var().get();
  16179. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16180. }
  16181. }
  16182. this.emitStatements(stmt.body);
  16183. while (entered.length > 0) {
  16184. const input = entered.pop();
  16185. const n = this.graph.create('prim::Exit');
  16186. this.graph.insertNode(n);
  16187. n.addInput(input);
  16188. }
  16189. }
  16190. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16191. let max_trip_count_val = null;
  16192. if (iter_val === null) {
  16193. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16194. } else {
  16195. max_trip_count_val = iter_val.len(range, this.method);
  16196. }
  16197. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16198. const body_block = n.addBlock();
  16199. {
  16200. const condition_block = n.addBlock();
  16201. this.pushFrame(condition_block);
  16202. let out = null;
  16203. if (cond) {
  16204. const insert = new torch._C.WithInsertPoint(condition_block);
  16205. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16206. insert.dispose();
  16207. } else {
  16208. const insert = new torch._C.WithInsertPoint(n);
  16209. out = this.graph.insertConstant(true, range);
  16210. insert.dispose();
  16211. }
  16212. condition_block.registerOutput(out);
  16213. this.popFrame();
  16214. }
  16215. n.addInput(max_trip_count_val);
  16216. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16217. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16218. {
  16219. this.pushFrame(body_block);
  16220. const guard = new torch._C.WithInsertPoint(body_block);
  16221. if (iter_val !== null && targets) {
  16222. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16223. const sv = new torch._C.SimpleValue(cur_elem);
  16224. const target_exprs = targets;
  16225. this.validateAssignLhsExpr(target_exprs, range);
  16226. if (target_exprs.length > 1) {
  16227. throw new python.Error('Not implemented.');
  16228. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16229. // target_exprs = ListExpr.create(range, [tl]);
  16230. }
  16231. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16232. }
  16233. emit_body();
  16234. this.popFrame();
  16235. guard.dispose();
  16236. }
  16237. loop_guard.dispose();
  16238. }
  16239. emitFor(...args) {
  16240. if (args.length === 1 && args[0] instanceof ast.For) {
  16241. const [stmt] = args;
  16242. const emit_body = () => this.emitStatements(stmt.body);
  16243. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16244. } else if (args.length === 4) {
  16245. const [targets, itrs, loc, emit_body] = args;
  16246. if (itrs instanceof ast.Tuple) {
  16247. throw new python.Error('List of iterables is not supported currently.');
  16248. }
  16249. const sv = this.emitSugaredExpr(itrs, 1);
  16250. const iterable = sv.iter(loc, this.method);
  16251. if (iterable.shouldEmitUnrolled()) {
  16252. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16253. } else {
  16254. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16255. }
  16256. } else {
  16257. throw new python.Error('Not implemented.');
  16258. }
  16259. }
  16260. emitWhile(stmt) {
  16261. const cond = stmt.test;
  16262. const emit_body = () => this.emitStatements(stmt.body);
  16263. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16264. }
  16265. emitIsInstance(obj, classinfo) {
  16266. const lhs_val = this.emitExpr(obj);
  16267. const lhs_types = [];
  16268. const rhs_types = [];
  16269. const gather_rhs = (expr) => {
  16270. if (expr instanceof ast.Tuple) {
  16271. for (const e of expr.elts) {
  16272. gather_rhs(e);
  16273. }
  16274. return;
  16275. }
  16276. const type = this._typeParser.parseTypeFromExpr(expr);
  16277. rhs_types.push(type);
  16278. };
  16279. lhs_types.push(lhs_val.type());
  16280. gather_rhs(classinfo);
  16281. torch._C.standardizeVectorForUnion(lhs_types);
  16282. torch._C.standardizeVectorForUnion(rhs_types);
  16283. let refinement = new torch._C.RefinementSet([], []);
  16284. let unified_true = null;
  16285. let unified_false = null;
  16286. const isinstance_types = [];
  16287. const not_isinstance_types = [];
  16288. let true_refinements = [];
  16289. let false_refinements = [];
  16290. let all_lhs_subtype_some_rhs = true;
  16291. for (const lhs_type of lhs_types) {
  16292. if (lhs_type === torch.AnyType.get()) {
  16293. isinstance_types.push(...rhs_types);
  16294. not_isinstance_types.push(torch.AnyType.get());
  16295. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16296. all_lhs_subtype_some_rhs = false;
  16297. }
  16298. break;
  16299. }
  16300. const get_smaller_type = (t1, t2) => {
  16301. if (t1.isSubtypeOf(t2)) {
  16302. return t1;
  16303. } else if (t2.isSubtypeOf(t1)) {
  16304. return t2;
  16305. }
  16306. return null;
  16307. };
  16308. let found_refinement = null;
  16309. for (const rhs_type of rhs_types) {
  16310. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16311. if (!maybe_smaller_type) {
  16312. continue;
  16313. } else if (maybe_smaller_type === lhs_type) {
  16314. found_refinement = lhs_type;
  16315. } else if (maybe_smaller_type === rhs_type) {
  16316. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16317. }
  16318. }
  16319. if (found_refinement) {
  16320. if (found_refinement === lhs_type) {
  16321. all_lhs_subtype_some_rhs &= true;
  16322. }
  16323. isinstance_types.push(found_refinement);
  16324. } else {
  16325. not_isinstance_types.push(lhs_type);
  16326. all_lhs_subtype_some_rhs = false;
  16327. }
  16328. }
  16329. if (isinstance_types.length > 0) {
  16330. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16331. }
  16332. if (obj instanceof ast.Name && unified_true) {
  16333. const ident = obj.id;
  16334. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16335. }
  16336. if (not_isinstance_types.length > 0) {
  16337. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16338. }
  16339. if (obj instanceof ast.Name && unified_false) {
  16340. const ident = obj.id;
  16341. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16342. }
  16343. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16344. const is_statically_false = isinstance_types.length === 0;
  16345. if (all_lhs_subtype_some_rhs) {
  16346. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16347. }
  16348. if (is_statically_false) {
  16349. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16350. }
  16351. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16352. return new torch._C.CondValue(result, refinement, null);
  16353. }
  16354. emitIf(stmt) {
  16355. const cond_value = this.emitCondExpr(stmt.test);
  16356. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16357. }
  16358. emitCondExpr(expr) {
  16359. /*
  16360. switch (expr.kind()) {
  16361. case TK_AND:
  16362. case TK_OR: {
  16363. const binop = BinOp(expr);
  16364. return emitShortCircuitLogical(
  16365. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16366. }
  16367. case TK_NOT: {
  16368. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16369. Value* result = emitBuiltinCall(
  16370. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16371. std::optional<bool> static_if;
  16372. if (v.staticIf()) {
  16373. static_if = !*v.staticIf();
  16374. }
  16375. return CondValue(result, v.refinements().Not(), static_if);
  16376. } break;
  16377. case TK_IS:
  16378. case TK_ISNOT: {
  16379. // meta programming on AST for is/is not cases and emit branches base on
  16380. const cond_op = BinOp(expr);
  16381. Value* lhs_val = emitExpr(cond_op.lhs());
  16382. Value* rhs_val = emitExpr(cond_op.rhs());
  16383. const lhs_none = canBeNone(lhs_val);
  16384. const rhs_none = canBeNone(rhs_val);
  16385. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16386. // AA, -> statically IS always holds, IS_NOT never holds
  16387. // AN , NA-> statically IS_NOT always holds, IS never holds
  16388. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16389. bool its_is = expr.kind() == TK_IS;
  16390. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16391. return CondValue(*graph, expr.range(), its_is, {});
  16392. } else if (
  16393. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16394. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16395. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16396. return CondValue(*graph, expr.range(), !its_is, {});
  16397. } else {
  16398. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16399. Value* cond_value = emitBuiltinCall(
  16400. expr.get()->range(),
  16401. *method.graph(),
  16402. kind,
  16403. {lhs_val, rhs_val},
  16404. {});
  16405. const refinements = RefinementSet(findIsNoneRefinements(
  16406. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16407. return CondValue(cond_value, refinements, null);
  16408. }
  16409. } break;
  16410. */
  16411. if (expr instanceof ast.UnaryOp) {
  16412. throw new python.Error('Not implemented.');
  16413. }
  16414. if (expr instanceof ast.Call) {
  16415. const apply = expr;
  16416. const callee = expr.func;
  16417. if (callee instanceof ast.Name) {
  16418. if (callee.id === 'isinstance') {
  16419. this.checkApplyNumInputs(apply, 2);
  16420. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16421. }
  16422. if (callee.id === 'hasattr') {
  16423. this.checkApplyNumInputs(apply, 2);
  16424. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16425. }
  16426. const sv = this.emitSugaredExpr(callee, 1);
  16427. if (sv instanceof torch._C.SpecialFormValue) {
  16428. if (sv.form() === 'prim::isinstance') {
  16429. this.checkApplyNumInputs(apply, 2);
  16430. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16431. }
  16432. }
  16433. }
  16434. }
  16435. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16436. let static_if = null;
  16437. const kind = expr_out.node().kind();
  16438. if (kind === 'aten::is_scripting') {
  16439. static_if = true;
  16440. } else if (kind === 'aten::has_torch_function') {
  16441. static_if = false;
  16442. }
  16443. const maybe_ivalue = torch._C.toIValue(expr_out);
  16444. if (maybe_ivalue) {
  16445. static_if = maybe_ivalue.toBool();
  16446. }
  16447. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16448. }
  16449. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16450. if (cond_value.staticIf() !== null) {
  16451. if (cond_value.staticIf()) {
  16452. this.insertRefinements(loc, cond_value.refinements());
  16453. this.emitStatements(trueBranch);
  16454. } else {
  16455. this.insertRefinements(loc, cond_value.refinements().Not());
  16456. this.emitStatements(falseBranch);
  16457. }
  16458. return;
  16459. }
  16460. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16461. n.addInput(cond_value.value());
  16462. const true_block = n.addBlock();
  16463. const false_block = n.addBlock();
  16464. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16465. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16466. const true_exits = this.exit_blocks.has(true_block);
  16467. const false_exits = this.exit_blocks.has(false_block);
  16468. if (true_exits && false_exits) {
  16469. this.exit_blocks.add(n.owningBlock());
  16470. }
  16471. const mutated_variables = new Set();
  16472. for (const v of save_true.definedVariables()) {
  16473. const insert = new torch._C.WithInsertPoint(false_block);
  16474. if (save_false.findInAnyFrame(v) || false_exits) {
  16475. mutated_variables.add(v);
  16476. } else {
  16477. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16478. }
  16479. insert.dispose();
  16480. }
  16481. for (const v of save_false.definedVariables()) {
  16482. const insert = new torch._C.WithInsertPoint(true_block);
  16483. if (save_true.findInAnyFrame(v) || true_exits) {
  16484. mutated_variables.add(v);
  16485. } else {
  16486. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16487. }
  16488. insert.dispose();
  16489. }
  16490. for (const x of mutated_variables) {
  16491. let tv = null;
  16492. let fv = null;
  16493. {
  16494. const insert = new torch._C.WithInsertPoint(true_block);
  16495. if (!true_exits) {
  16496. tv = save_true.getVar(x, loc);
  16497. }
  16498. insert.dispose();
  16499. }
  16500. {
  16501. const insert = new torch._C.WithInsertPoint(false_block);
  16502. if (!false_exits) {
  16503. fv = save_false.getVar(x, loc);
  16504. }
  16505. insert.dispose();
  16506. }
  16507. if (true_exits && false_exits) {
  16508. continue;
  16509. } else if (true_exits) {
  16510. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16511. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16512. } else if (false_exits) {
  16513. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16514. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16515. }
  16516. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16517. let full_type = null;
  16518. if (maybe_sugared_x) {
  16519. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16520. if (maybe_simple) {
  16521. full_type = maybe_simple.type();
  16522. }
  16523. }
  16524. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16525. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16526. if (!unified) {
  16527. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16528. throw new python.Error('Type mismatch.');
  16529. } else {
  16530. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16531. continue;
  16532. }
  16533. }
  16534. this.environment_stack.setType(x, unified);
  16535. }
  16536. }
  16537. emitSingleIfBranch(b, branch, refinements) {
  16538. this.pushFrame(b);
  16539. const guard = new torch._C.WithInsertPoint(b);
  16540. this.insertRefinements(branch, refinements);
  16541. this.emitStatements(branch);
  16542. const frame = this.popFrame();
  16543. guard.dispose();
  16544. return frame;
  16545. }
  16546. create(kind, loc, n_outputs) {
  16547. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16548. }
  16549. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16550. is_dict_constructor = is_dict_constructor || false;
  16551. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16552. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16553. if (!is_dict_constructor && candidate_types.length === 0) {
  16554. throw new python.Error("No matching types found in Union type annotation.");
  16555. } else if (candidate_types.length === 1) {
  16556. [refined_type_hint_ptr._] = candidate_types;
  16557. } else {
  16558. all_candidates._ = candidate_types;
  16559. }
  16560. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16561. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16562. }
  16563. if (is_dict_constructor) {
  16564. return;
  16565. }
  16566. if (all_candidates._.length === 0) {
  16567. if (type_match(refined_type_hint_ptr._)) {
  16568. do_if_match();
  16569. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16570. do_if_anytype();
  16571. } else {
  16572. throw new python.Error('Invalid annotation type.');
  16573. }
  16574. }
  16575. }
  16576. emitToBool(loc, v) {
  16577. let out = null;
  16578. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16579. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16580. if (!out) {
  16581. throw new python.Error('Could not cast value to bool.');
  16582. }
  16583. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16584. throw new python.Error('Expected a bool expression for condition.');
  16585. }
  16586. return out;
  16587. }
  16588. emitUnaryOp(tree, magicMethod, opSymbol) {
  16589. const inputs = [tree.operand];
  16590. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16591. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16592. if (val.node().kind() !== opSymbol) {
  16593. return val;
  16594. }
  16595. const maybe_out_stack = this.runNodeIfInputsAreConstant(val.node());
  16596. if (!maybe_out_stack) {
  16597. return val;
  16598. }
  16599. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16600. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16601. }
  16602. emitAssignment(stmt) {
  16603. if (stmt instanceof ast.AnnAssign) {
  16604. return this.emitSingleAssignment(stmt);
  16605. }
  16606. if (stmt.targets.length === 1) {
  16607. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16608. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16609. for (const [key, value] of entries) {
  16610. assign[key] = value;
  16611. }
  16612. return this.emitSingleAssignment(assign);
  16613. }
  16614. if (stmt.targets.length <= 1) {
  16615. throw new python.Error('Invalid assignment.');
  16616. }
  16617. throw new python.Error('Not implemented.');
  16618. /*
  16619. const tmp_name = this.createTempName('$tmp_assign_');
  16620. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16621. const ident = new ast.Name(tmp_name);
  16622. for (const expr of lhs_list) {
  16623. const assign = new ast.Assign(targets, value, ctx);
  16624. this.emitSingleAssignment(Assign.create(stmt,
  16625. List<Expr>.create(expr.range(), [expr]),
  16626. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16627. Maybe<Expr>::create(stmt.range())));
  16628. }
  16629. */
  16630. }
  16631. emitSingleAssignment(stmt) {
  16632. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16633. const rhs = stmt.value;
  16634. const lhs = stmt.target;
  16635. if (lhs instanceof ast.Name) {
  16636. let type = null;
  16637. if (stmt.annotation) {
  16638. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16639. }
  16640. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16641. // BC HACK
  16642. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16643. } else if (lhs instanceof ast.Tuple) {
  16644. this.emitTupleAssign(lhs, rhs);
  16645. } else if (lhs instanceof ast.Attribute) {
  16646. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16647. } else {
  16648. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16649. }
  16650. }
  16651. emitSelectAssign(lhs, rhs, type, loc) {
  16652. if (!rhs) {
  16653. throw new python.Error('Expected RHS for assignment.');
  16654. }
  16655. let type_hint = null;
  16656. if (type) {
  16657. type_hint = this._typeParser.parseTypeFromExpr(type);
  16658. }
  16659. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16660. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16661. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16662. }
  16663. emitTupleAssign(...args) {
  16664. if (args.length === 2) {
  16665. const [tl, rhs] = args;
  16666. let n_binders = tl.elts.length;
  16667. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16668. if (starred_unpack) {
  16669. n_binders--;
  16670. }
  16671. const output = this.emitSugaredExpr(rhs, n_binders);
  16672. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16673. } else if (args.length === 5) {
  16674. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16675. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16676. if (outputs.length < n_binders) {
  16677. throw new python.Error('Not enough values to unpack.');
  16678. }
  16679. if (outputs.length > n_binders && !starred_unpack) {
  16680. throw new python.Error('Too many values to unpack.');
  16681. }
  16682. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16683. } else {
  16684. throw new python.Error('Not implemented.');
  16685. }
  16686. }
  16687. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16688. let i = 0;
  16689. for (const assignee of lhs_exprs) {
  16690. if (assignee instanceof ast.Subscript) {
  16691. throw new python.Error('Not implemented.');
  16692. /*
  16693. this.emitSubscriptAssign(
  16694. rhs_loc,
  16695. Subscript(assignee),
  16696. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16697. i++;
  16698. */
  16699. } else if (assignee instanceof ast.Name) {
  16700. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16701. i++;
  16702. } else if (assignee instanceof ast.Starred) {
  16703. throw new python.Error('Not implemented.');
  16704. /*
  16705. const var = Starred(assignee).expr();
  16706. if (var.kind() != TK_VAR) {
  16707. throw(
  16708. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16709. }
  16710. size_t n_matched = outputs.size() - n_binders;
  16711. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16712. const values = fmap(
  16713. outputs_ref.slice(i, n_matched),
  16714. [&](const std::shared_ptr<SugaredValue>& v) {
  16715. return v.asValue(assignee.range(), method);
  16716. });
  16717. const tup = graph.insertNode(graph.createTuple(values)).output();
  16718. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16719. i += n_matched;
  16720. */
  16721. } else if (assignee instanceof ast.Tuple) {
  16722. throw new python.Error('Not implemented.');
  16723. /*
  16724. // recursively emit tuple assignments on tuple literal input
  16725. TupleLiteral sub_tl = TupleLiteral(assignee);
  16726. size_t sub_n_binders = sub_tl.inputs().length;
  16727. bool sub_starred_unpack =
  16728. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16729. if (sub_starred_unpack)
  16730. sub_n_binders--;
  16731. emitTupleAssign(
  16732. sub_tl,
  16733. outputs.at(i),
  16734. rhs_loc,
  16735. sub_n_binders,
  16736. sub_starred_unpack);
  16737. i++;
  16738. */
  16739. } else if (assignee instanceof ast.Attribute) {
  16740. throw new python.Error('Not implemented.');
  16741. /*
  16742. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16743. i++;
  16744. */
  16745. } else {
  16746. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16747. }
  16748. }
  16749. }
  16750. emitReturn(stmt) {
  16751. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16752. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16753. if (declared_return_type) {
  16754. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16755. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16756. }
  16757. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16758. throw new python.Error(`Invalid return type.`);
  16759. }
  16760. } else {
  16761. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16762. if (!declared_return_type) {
  16763. declared_return_type = actual_return.type();
  16764. }
  16765. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16766. if (!merged_return_type) {
  16767. throw new python.Error(`Invalid return type.`);
  16768. }
  16769. declared_return_type = merged_return_type;
  16770. }
  16771. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16772. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16773. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16774. }
  16775. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16776. this.exit_blocks.add(this.environment_stack.block());
  16777. }
  16778. getNamedValues(trees, maybe_unpack) {
  16779. const values = [];
  16780. for (const tree of trees) {
  16781. if (maybe_unpack && tree instanceof ast.Starred) {
  16782. throw new python.Error('Starred argument not supported.');
  16783. } else {
  16784. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16785. }
  16786. }
  16787. return values;
  16788. }
  16789. getValues(trees, maybe_unpack) {
  16790. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16791. }
  16792. emitExpr(tree, type_hint) {
  16793. type_hint = type_hint || null;
  16794. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16795. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16796. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16797. }
  16798. return out_val;
  16799. }
  16800. emitSugaredExpr(tree, n_binders, type_hint) {
  16801. if (tree instanceof ast.Name) { // TK_VAR
  16802. return this.environment_stack.getSugaredVar(tree.id);
  16803. } else if (tree instanceof ast.Attribute) {
  16804. const sv = this.emitSugaredExpr(tree.value, 1);
  16805. return sv.attr(tree.range(), this.method, tree.attr);
  16806. } else if (tree instanceof ast.Call) { // TK_APPLY
  16807. return this.emitApplyExpr(tree, n_binders, type_hint);
  16808. } if (tree instanceof ast.Subscript) {
  16809. return this.emitSubscript(tree, type_hint);
  16810. }
  16811. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  16812. }
  16813. emitApplyExpr(apply, n_binders, type_hint) {
  16814. type_hint = type_hint || null;
  16815. const sv = this.emitSugaredExpr(apply.func, 1);
  16816. const loc = apply.func.range();
  16817. if (sv instanceof torch._C.SpecialFormValue) {
  16818. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  16819. }
  16820. const args = this.getNamedValues(apply.args, true);
  16821. const kwargs = this.emitAttributes(apply.keywords);
  16822. return sv.call(loc, this.method, args, kwargs, n_binders);
  16823. }
  16824. emitAttributes(attributes) {
  16825. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  16826. }
  16827. emitApplySpecialForm(form, apply, sv, type_hint) {
  16828. switch (form) {
  16829. case 'prim::fork': {
  16830. throw new python.Error('Not implemented.');
  16831. }
  16832. case 'prim::awaitable': {
  16833. throw new python.Error('Not implemented.');
  16834. }
  16835. case 'prim::annotate': {
  16836. this.checkApplyNumInputs(apply, 2);
  16837. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16838. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  16839. if (!expr.type().isSubtypeOf(type)) {
  16840. throw new python.Error('Invalid expression type.');
  16841. }
  16842. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  16843. const none = this.graph.createNone();
  16844. none.output().setType(type);
  16845. this.graph.insertNode(none);
  16846. expr = none.output();
  16847. }
  16848. return new torch._C.SimpleValue(expr);
  16849. }
  16850. case 'prim::unchecked_cast': {
  16851. this.checkApplyNumInputs(apply, 2);
  16852. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16853. let v = this.emitExpr(apply.args[1]);
  16854. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  16855. v = this.graph.insertUncheckedCast(v, type);
  16856. }
  16857. return new torch._C.SimpleValue(v);
  16858. }
  16859. case 'prim::GetAttr': {
  16860. this.checkApplyNumInputsRange(apply, 2, 3);
  16861. const obj = this.emitSugaredExpr(apply.args[0], 1);
  16862. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  16863. throw new python.Error('Invalid argument.');
  16864. }
  16865. const name = apply.args[1].value;
  16866. if (apply.args.length === 2) {
  16867. return obj.attr(apply, this.method, name);
  16868. } else if (obj.hasAttr(apply, this.method, name)) {
  16869. return obj.attr(apply, this.method, name);
  16870. }
  16871. return this.emitSugaredExpr(apply.inputs()[2], 1);
  16872. }
  16873. case 'prim::Uninitialized': {
  16874. this.checkApplyNumInputs(apply, 1);
  16875. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16876. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  16877. return new torch._C.SimpleValue(out.output());
  16878. }
  16879. case 'prim::TupleConstruct': {
  16880. throw new python.Error('Not implemented.');
  16881. }
  16882. case 'prim::isinstance': {
  16883. this.checkApplyNumInputs(apply, 2);
  16884. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  16885. return new torch._C.SimpleValue(result.value());
  16886. }
  16887. case 'prim::tolist': {
  16888. const value = apply.func.value;
  16889. const operand = this.emitSugaredExpr(value, 1);
  16890. if (!type_hint) {
  16891. throw new python.Error('Expected type hint for result of tolist().');
  16892. }
  16893. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  16894. }
  16895. case 'prim::HasAttr': {
  16896. throw new python.Error('Not implemented.');
  16897. }
  16898. case 'prim::CreateObject': {
  16899. if (apply.args.length !== 1) {
  16900. throw python.Error('Only one argument to __new__ allowed.');
  16901. }
  16902. const arg = this.emitSugaredExpr(apply.args[0], 1);
  16903. if (arg instanceof torch._C.ClassValue === false) {
  16904. throw python.Error('Expected class value as argument to __new__.');
  16905. }
  16906. const class_arg = arg;
  16907. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  16908. createNode.setSourceRange(apply.range());
  16909. return new torch._C.SimpleValue(createNode.output());
  16910. }
  16911. case 'prim::range': {
  16912. const input_vals = this.getValues(apply.args, true);
  16913. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  16914. }
  16915. case 'prim::enumerate': {
  16916. throw new python.Error('Not implemented.');
  16917. }
  16918. case 'prim::zip': {
  16919. throw new python.Error('Not implemented.');
  16920. }
  16921. case 'prim::list': {
  16922. throw new python.Error('Not implemented.');
  16923. }
  16924. case 'prim::dict': {
  16925. throw new python.Error('Not implemented.');
  16926. }
  16927. case 'aten::index': {
  16928. throw new python.Error('Not implemented.');
  16929. }
  16930. default: {
  16931. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  16932. }
  16933. }
  16934. }
  16935. emitSimpleExpr(tree, type_hint) {
  16936. if (tree instanceof ast.Constant) {
  16937. if (tree.value === true) {
  16938. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  16939. } else if (tree.value === false) {
  16940. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  16941. } else if (tree.value === null) {
  16942. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  16943. } else if (typeof tree.value === 'string') {
  16944. return this.emitStringLiteral(tree);
  16945. }
  16946. return this.emitConst(tree);
  16947. } else if (tree instanceof ast.List) {
  16948. return this.emitListLiteral(tree, type_hint);
  16949. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  16950. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  16951. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  16952. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  16953. } else if (tree instanceof ast.BinOp) {
  16954. return this.emitBinaryOp(tree);
  16955. } else if (tree instanceof ast.Dict) {
  16956. return this.emitDictLiteral(tree, type_hint);
  16957. } else if (tree instanceof ast.Tuple) {
  16958. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  16959. return this.graph.insertNode(this.graph.createTuple(values)).output();
  16960. }
  16961. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  16962. }
  16963. getNodeKind(kind /*, ninputs */) {
  16964. if (kind instanceof ast.Add) {
  16965. return 'aten::add';
  16966. } else if (kind instanceof ast.Sub) {
  16967. return 'aten::sub';
  16968. } else if (kind instanceof ast.Mult) {
  16969. return 'aten::mul';
  16970. }
  16971. /*
  16972. case TK_UNARY_MINUS: return 'aten::neg';
  16973. case TK_POW: return 'aten::pow';
  16974. case '@': return 'aten::matmul';
  16975. case TK_STARRED: return 'prim::Starred';
  16976. case '/': return 'aten::div';
  16977. case '%': return 'aten::remainder';
  16978. case TK_NE: return 'aten::ne';
  16979. case TK_EQ: return 'aten::eq';
  16980. case '<': return 'aten::lt';
  16981. case '>': return 'aten::gt';
  16982. case TK_LE: return 'aten::le';
  16983. case TK_GE: return 'aten::ge';
  16984. case TK_AND: return 'aten::__and__';
  16985. case TK_OR: return 'aten::__or__';
  16986. case TK_IS: return 'aten::__is__';
  16987. case TK_ISNOT: return 'aten::__isnot__';
  16988. case TK_NOT: return 'aten::__not__';
  16989. case TK_FLOOR_DIV: return 'aten::floordiv';
  16990. case TK_LSHIFT: return 'aten::__lshift__';
  16991. case TK_RSHIFT: return 'aten::__rshift__';
  16992. case '&': return 'aten::__and__';
  16993. case '|': return 'aten::__or__';
  16994. case '^': return 'aten::__xor__';
  16995. case TK_IN: return 'aten::__contains__';
  16996. */
  16997. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  16998. }
  16999. getOperatorOverload(kind /*, ninputs */) {
  17000. if (kind instanceof ast.Add) {
  17001. return '__add__';
  17002. } else if (kind instanceof ast.Sub) {
  17003. return '__sub__';
  17004. } else if (kind instanceof ast.Mult) {
  17005. return '__mul__';
  17006. }
  17007. /*
  17008. case TK_UNARY_MINUS: return "__neg__";
  17009. case '~': return "__invert__";
  17010. case TK_POW: return "__pow__";
  17011. case '/': return "__truediv__";
  17012. case '%': return "__mod__";
  17013. case TK_NE: return "__ne__";
  17014. case TK_EQ: return "__eq__";
  17015. case '<': return "__lt__";
  17016. case '>': return "__gt__";
  17017. case TK_LE: return "__le__";
  17018. case TK_GE: return "__ge__";
  17019. case '&': return "__and__";
  17020. case '|': return "__or__";
  17021. case '^': return "__xor__";
  17022. case TK_IN: return "__contains__";
  17023. case TK_LSHIFT: return "__lshift__";
  17024. case TK_RSHIFT: return "__rshift__";
  17025. */
  17026. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17027. }
  17028. emitBinaryOp(tree) {
  17029. const inputs = [tree.left, tree.right];
  17030. const kind = this.getNodeKind(tree.op, inputs.length);
  17031. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17032. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17033. if (tree.op instanceof ast.In) {
  17034. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17035. throw new python.Error('Not implemented.');
  17036. }
  17037. if (named_values[0].type() instanceof torch.TupleType &&
  17038. named_values[1].type() instanceof torch.TupleType &&
  17039. kind === 'aten::add') {
  17040. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17041. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17042. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17043. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17044. }
  17045. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17046. }
  17047. emitDictLiteral(dl, type_hint) {
  17048. const key_trees = dl.keys;
  17049. const value_trees = dl.values;
  17050. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17051. const keys = [];
  17052. const values = [];
  17053. let rhs_value_type = null;
  17054. for (let i = 0; i < key_trees.length; i++) {
  17055. keys.push(this.emitExpr(key_trees[i]));
  17056. values.push(this.emitExpr(value_trees[i]));
  17057. if (i === 0) {
  17058. rhs_value_type = values[i].type();
  17059. } else {
  17060. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17061. throw new python.Error('Dict keys must contain only a single type.');
  17062. }
  17063. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17064. }
  17065. }
  17066. const refined_type_hint = { _: type_hint };
  17067. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17068. const all_candidates = { _: [] };
  17069. const default_refined_type_hint_setter = () => {
  17070. if (keys.length === 0) {
  17071. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17072. } else {
  17073. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17074. if (rhs_value_type instanceof torch.UnionType) {
  17075. throw new python.Error('Dict values consist of heterogeneous types.');
  17076. }
  17077. }
  17078. };
  17079. if (type_hint) {
  17080. const type_match = (t) => t instanceof torch.DictType;
  17081. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17082. if (all_candidates._.length > 0 && values.length === 0) {
  17083. throw new python.Error('Cannot assign an empty dict.');
  17084. }
  17085. } else {
  17086. default_refined_type_hint_setter();
  17087. }
  17088. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17089. if (values.length > 0) {
  17090. if (all_candidates._.length > 0) {
  17091. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17092. }
  17093. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17094. throw new python.Error('Type annotation does not match key type.');
  17095. }
  17096. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17097. throw new python.Error('Type annotation does not match value type.');
  17098. }
  17099. }
  17100. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17101. if (annotated_union_type) {
  17102. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17103. n.output().setType(annotated_union_type);
  17104. result = n;
  17105. }
  17106. return result.output();
  17107. }
  17108. emitStringLiteral(c) {
  17109. return torch._C.insertConstant(this.graph, c.value, c.range());
  17110. }
  17111. emitConst(c) {
  17112. if (c.type === 'int') {
  17113. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17114. } else if (c.type === 'complex') {
  17115. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17116. } else if (c.type === 'float') {
  17117. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17118. }
  17119. throw new python.Error(`Unsupported constant type.`);
  17120. }
  17121. emitListLiteral(ll, type_hint) {
  17122. type_hint = type_hint || null;
  17123. const values = this.getValues(ll.elts, true);
  17124. if (values.length === 0 && type_hint === null) {
  17125. throw new python.Error('Not implemented.');
  17126. }
  17127. let inferred_elem_type = torch.TensorType.get();
  17128. const refined_type_hint = { _: type_hint };
  17129. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17130. const all_candidates = { _: [] };
  17131. if (refined_type_hint._) {
  17132. const do_if_type_match = () => {
  17133. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17134. };
  17135. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17136. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17137. if (all_candidates._.length > 0 && values.len === 0) {
  17138. throw new python.Error('Cannot assign an empty list.');
  17139. }
  17140. }
  17141. if (values.length !== 0) {
  17142. const types = values.map((v) => v.type());
  17143. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17144. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17145. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17146. throw new python.Error('Not implemented.');
  17147. }
  17148. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17149. throw new python.Error('Not implemented.');
  17150. }
  17151. if (all_candidates._.length !== 0) {
  17152. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17153. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17154. }
  17155. if (!refined_type_hint._) {
  17156. inferred_elem_type = unified_elem_type;
  17157. }
  17158. }
  17159. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17160. if (annotated_union_type) {
  17161. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17162. n.output().setType(annotated_union_type);
  17163. result = n;
  17164. }
  17165. return result.output();
  17166. }
  17167. insertRefinements(loc, ref) {
  17168. for (const r of ref.activeRefinements()) {
  17169. const v = this.environment_stack.getVar(r.identifier(), loc);
  17170. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17171. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17172. }
  17173. }
  17174. shouldDeriveSetStateType(def, schema) {
  17175. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17176. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17177. if (!shouldInfer) {
  17178. return false;
  17179. }
  17180. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17181. throw new python.Error(`Invalid '__setstate' method.`);
  17182. }
  17183. return true;
  17184. }
  17185. checkApplyNumInputs(apply, expected_inputs) {
  17186. if (apply.args.length !== expected_inputs) {
  17187. throw new python.Error('Invalid number of arguments.');
  17188. }
  17189. if (apply.keywords.length > 0) {
  17190. throw new python.Error('Invalid number of keyword arguments.');
  17191. }
  17192. }
  17193. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17194. const position_arg_size = apply.args.length;
  17195. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17196. throw new python.Error('Invalid number of arguments.');
  17197. }
  17198. if (apply.keywords.length > 0) {
  17199. throw new python.Error('Invalid number of keyword arguments.');
  17200. }
  17201. }
  17202. validateAssignLhsExpr(lhs /*, r */) {
  17203. let num_normal_assign = 0;
  17204. let num_starred = 0;
  17205. for (const assignee of lhs) {
  17206. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17207. num_normal_assign++;
  17208. } else if (assignee instanceof ast.Starred) {
  17209. num_starred++;
  17210. } else {
  17211. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17212. }
  17213. }
  17214. if (num_starred > 1) {
  17215. throw new python.Error('Only one starred expression is allowed.');
  17216. }
  17217. if (num_starred > 0 && num_normal_assign === 0) {
  17218. throw new python.Error('Invalid starred expression.');
  17219. }
  17220. return num_starred;
  17221. }
  17222. createTempName(prefix) {
  17223. return `${prefix}${this._temp_name_count++}`;
  17224. }
  17225. handleMaybeNoReturn(def, block) {
  17226. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17227. if (this.exit_blocks.size === 0) {
  17228. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17229. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17230. }
  17231. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17232. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17233. b.dispose();
  17234. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17235. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17236. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17237. }
  17238. }
  17239. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17240. let adj_index = input_index;
  17241. const tuple_len = tuple_type.elements().length;
  17242. if (input_index < 0) {
  17243. adj_index = tuple_len + input_index;
  17244. }
  17245. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17246. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17247. }
  17248. return adj_index;
  17249. }
  17250. emitTupleIndex(loc, tuple_val, idx_val) {
  17251. const tuple_typ = tuple_val.type();
  17252. const elems = tuple_typ.elements();
  17253. let output_type = null;
  17254. if (idx_val.type() !== torch.IntType.get()) {
  17255. throw new python.Error('Tuple index must be an integer.');
  17256. }
  17257. const idx = torch._C.toIValue(idx_val);
  17258. if (idx) {
  17259. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17260. output_type = elems[adj_index];
  17261. } else {
  17262. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17263. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17264. }
  17265. [output_type] = elems;
  17266. }
  17267. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17268. }
  17269. getSliceInd(idx_val, loc) {
  17270. const ivalue = torch._C.toIValue(idx_val);
  17271. if (ivalue && ivalue.isInt()) {
  17272. return ivalue.toInt();
  17273. }
  17274. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17275. }
  17276. emitTupleSlice(loc, tuple_val, tuple_args) {
  17277. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17278. const tuple_len = tuple_type.elements().length;
  17279. const [beg_val, end_val, step] = tuple_args;
  17280. let step_size = 1;
  17281. if (step) {
  17282. const val = torch._C.toIValue(step.value(this.graph));
  17283. torch._C.TORCH_CHECK(val.isInt());
  17284. step_size = val.toInt();
  17285. }
  17286. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17287. if (beg_val) {
  17288. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17289. }
  17290. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17291. if (end_val) {
  17292. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17293. }
  17294. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17295. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17296. }
  17297. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17298. const args = [];
  17299. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17300. if (dim) {
  17301. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17302. args.emplace_back(new torch._C.NamedValue(dim));
  17303. } else {
  17304. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17305. }
  17306. if (sliceable.type() instanceof torch.TupleType) {
  17307. const tuple_args = [];
  17308. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17309. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17310. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17311. return this.emitTupleSlice(loc, args[0], tuple_args);
  17312. }
  17313. if (!step) {
  17314. step = this.graph.insertConstant(1, loc);
  17315. }
  17316. args.push(new torch._C.NamedValue(loc, 'start', start));
  17317. args.push(new torch._C.NamedValue(loc, 'end', end));
  17318. args.push(new torch._C.NamedValue(loc, 'step', step));
  17319. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17320. }
  17321. emitSlice(loc, input, dim, slice) {
  17322. let start = null;
  17323. let end = null;
  17324. let step = null;
  17325. if (slice.lower) {
  17326. start = this.emitExpr(slice.lower);
  17327. }
  17328. if (slice.upper) {
  17329. end = this.emitExpr(slice.upper);
  17330. }
  17331. if (slice.step) {
  17332. step = this.emitExpr(slice.step);
  17333. }
  17334. return this.emitSliceOp(loc, input, dim, start, end, step);
  17335. }
  17336. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17337. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17338. const slice_exp = subscript_exprs;
  17339. let maybe_dim = null;
  17340. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17341. maybe_dim = this.graph.insertConstant(0, loc);
  17342. }
  17343. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17344. }
  17345. emitSubscript(subscript, type_hint) {
  17346. type_hint = type_hint === undefined ? null : type_hint;
  17347. const sv = this.emitSugaredExpr(subscript.value, 1);
  17348. const subscript_exprs = subscript.slice;
  17349. const range = subscript.range();
  17350. const val_range = subscript.value;
  17351. if (subscript_exprs instanceof ast.Tuple) {
  17352. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17353. }
  17354. if (subscript_exprs instanceof ast.Slice) {
  17355. if (sv.kind() === 'module') {
  17356. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17357. const [slice] = subscript_exprs;
  17358. const tuple_args = [];
  17359. if (slice.start().present()) {
  17360. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17361. tuple_args.push(begin);
  17362. } else {
  17363. tuple_args.push(null);
  17364. }
  17365. if (slice.end().present()) {
  17366. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17367. tuple_args.push(end);
  17368. } else {
  17369. tuple_args.push(null);
  17370. }
  17371. if (slice.step().present()) {
  17372. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17373. tuple_args.push(step);
  17374. } else {
  17375. tuple_args.push(null);
  17376. }
  17377. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17378. return new torch._C.SimpleValue(tupleSliceValue);
  17379. }
  17380. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17381. }
  17382. const sliceable = sv.asValue(val_range, this.method);
  17383. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17384. if (subscript_sv instanceof torch._C.SliceValue) {
  17385. const slice_value = subscript_sv;
  17386. let dim = null;
  17387. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17388. dim = this.method.graph().insertConstant(0, val_range);
  17389. }
  17390. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17391. return new torch._C.SimpleValue(sliced);
  17392. }
  17393. const idx = subscript_sv.asValue(val_range, this.method);
  17394. if (sliceable.type() instanceof torch.TupleType) {
  17395. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17396. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17397. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17398. }
  17399. return sv.getitem(range, this.method, idx, type_hint);
  17400. }
  17401. });
  17402. this.registerType('torch.jit.CompilationUnit', class {
  17403. constructor() {
  17404. this._functions = new Map();
  17405. this._classes = new Map();
  17406. }
  17407. register_type(namedType) {
  17408. this._classes.set(namedType.annotation_str, namedType);
  17409. }
  17410. register_function(fn) {
  17411. const name = fn.qualname().qualifiedName();
  17412. torch._C.TORCH_CHECK(!this._functions.has(name));
  17413. this._functions.set(name, fn);
  17414. return fn;
  17415. }
  17416. define(...args) {
  17417. if (Array.isArray(args[1])) {
  17418. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17419. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17420. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17421. const functions = [];
  17422. const function_table = new Map();
  17423. const record_function = (fn) => {
  17424. function_table.set(fn.name(), fn);
  17425. functions.push(fn);
  17426. this.register_function(fn);
  17427. };
  17428. for (let i = 0; i < properties.length; i++) {
  17429. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17430. const getter_fn = property_fns.getGetter();
  17431. const setter_fn = property_fns.getSetter();
  17432. record_function(getter_fn);
  17433. if (setter_fn) {
  17434. record_function(setter_fn);
  17435. }
  17436. }
  17437. for (let i = 0; i < definitions.length; i++) {
  17438. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17439. record_function(fn);
  17440. }
  17441. for (const [name, fn] of function_table) {
  17442. if (name === '__init__') {
  17443. fn.ensure_defined();
  17444. }
  17445. }
  17446. for (const fn of functions) {
  17447. fn.ensure_defined();
  17448. }
  17449. return functions;
  17450. } else if (args[1] instanceof ast.FunctionDef) {
  17451. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17452. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17453. const creator = (method) => {
  17454. return new torch._C.to_ir(def, _resolver, self, method);
  17455. };
  17456. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17457. if (shouldMangle && this.find_function(name)) {
  17458. name = this.mangle(name);
  17459. }
  17460. const graph = new torch.Graph();
  17461. graph.set_op_version(operator_set_version);
  17462. const fn = new torch._C.GraphFunction(name, graph, creator);
  17463. fn.__ast__ = def; // remove
  17464. if (self) {
  17465. if (type === 'hook') {
  17466. self.getClassType().addForwardHook(fn);
  17467. } else if (type === 'prehook') {
  17468. self.getClassType().addPreHook(fn);
  17469. } else {
  17470. self.getClassType().addMethod(fn);
  17471. }
  17472. }
  17473. return fn;
  17474. }
  17475. throw new python.Error('Invalid arguments.');
  17476. }
  17477. get_type(name) {
  17478. return this._classes.get(name.qualifiedName());
  17479. }
  17480. get_class(name) {
  17481. return this.get_type(name);
  17482. }
  17483. find_function(name) {
  17484. const key = name.qualifiedName();
  17485. return this._functions.get(key);
  17486. }
  17487. });
  17488. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17489. const ctrl = new torch._C.ControlFlowLoadStores();
  17490. ctrl.run(graph);
  17491. const exit_vars = new torch._C.LoopContinuations();
  17492. exit_vars.run(graph);
  17493. torch._C.InlineLoopCondition(graph);
  17494. const erase_loads_stores = new torch._C.EraseLoadStores();
  17495. erase_loads_stores.run(graph);
  17496. torch._C.TransformExits(graph);
  17497. });
  17498. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17499. /*
  17500. LoopView loop(n);
  17501. if (loop.loopType() != LoopView::ModifiedLoop) {
  17502. return;
  17503. }
  17504. const g = n.owningGraph();
  17505. WithInsertPoint node_insert(n);
  17506. const zero = g.insertConstant(0);
  17507. const one = g.insertConstant(1);
  17508. const max_trip_count = loop.maxTripCount();
  17509. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17510. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17511. const inp_condition = toIValue(loop.inputCond());
  17512. if (inp_condition == null || inp_condition.toBool() == false) {
  17513. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17514. }
  17515. loop.replaceInputCondition(condition);
  17516. n.addOutput().setType(IntType::get());
  17517. WithInsertPoint loop_insert(loop.bodyBlock());
  17518. n.addInput(zero);
  17519. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17520. // unset unique name for jitter, its replacement does not have a name
  17521. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17522. const inc_iter = g.insert(aten::add, {new_iter, one});
  17523. loop.bodyBlock().registerOutput(inc_iter);
  17524. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17525. const loop_continue = loop.nextCond();
  17526. const new_condition =
  17527. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17528. loop.bodyBlock().eraseOutput(0);
  17529. loop.bodyBlock().insertOutput(0, new_condition);
  17530. */
  17531. });
  17532. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17533. for (const n of block.nodes()) {
  17534. for (const b of n.blocks()) {
  17535. torch._C.canonicalizeModifiedLoops(b);
  17536. }
  17537. if (n.kind() === 'prim::Loop') {
  17538. torch._C.canonicalizeModifiedLoop(n);
  17539. }
  17540. }
  17541. });
  17542. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17543. torch._C.canonicalizeModifiedLoops(graph.block());
  17544. });
  17545. this.registerType('torch._C.MiniEnvironment', class {
  17546. constructor(b, next) {
  17547. this.next = next || null;
  17548. this.table = new Map();
  17549. }
  17550. setVar(name, value) {
  17551. this.table.set(name, value);
  17552. }
  17553. definedVariables() {
  17554. const result = Array.from(this.table.keys());
  17555. return result.sort();
  17556. }
  17557. findInThisFrame(name) {
  17558. if (this.table.has(name)) {
  17559. return this.table.get(name);
  17560. }
  17561. return null;
  17562. }
  17563. findInAnyFrame(name) {
  17564. /* eslint-disable consistent-this */
  17565. const self = this;
  17566. /* eslint-enable consistent-this */
  17567. for (let runner = self; runner; runner = runner.next) {
  17568. const r = runner.findInThisFrame(name);
  17569. if (r) {
  17570. return r;
  17571. }
  17572. }
  17573. return null;
  17574. }
  17575. });
  17576. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17577. });
  17578. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17579. });
  17580. this.registerType('torch._C.ControlFlowLoadStores', class {
  17581. constructor() {
  17582. this.environment_stack = null;
  17583. }
  17584. pushFrame(b) {
  17585. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17586. }
  17587. popFrame() {
  17588. const old_frame = this.environment_stack;
  17589. this.environment_stack = this.environment_stack.next;
  17590. return old_frame;
  17591. }
  17592. addBlockInput(b, type, name) {
  17593. const g = b.owningGraph();
  17594. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17595. }
  17596. addBlockOutput(exit_block, type, name) {
  17597. const insert = new torch._C.WithInsertPoint(exit_block);
  17598. const g = exit_block.owningGraph();
  17599. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17600. exit_block.registerOutput(block_exit);
  17601. insert.dispose();
  17602. }
  17603. addNodeOutput(n, type, name) {
  17604. const out = n.addOutput().setType(type);
  17605. if (torch._C.meaningfulName(name)) {
  17606. out.setDebugName(name);
  17607. }
  17608. const g = n.owningGraph();
  17609. g.createStore(name, out).insertAfter(n);
  17610. }
  17611. addNodeInput(n, type, name) {
  17612. const g = n.owningGraph();
  17613. const inp = g.createLoad(name, type).insertBefore(n).output();
  17614. n.addInput(inp);
  17615. }
  17616. addIfLoadStores(n) {
  17617. const [true_block, false_block] = n.blocks();
  17618. const true_vars = this.addControlFlowLoadStores(true_block);
  17619. const false_vars = this.addControlFlowLoadStores(false_block);
  17620. const mutated_variables = new Set();
  17621. for (const v of true_vars.definedVariables()) {
  17622. if (false_vars.findInAnyFrame(v)) {
  17623. mutated_variables.add(v);
  17624. }
  17625. }
  17626. for (const v of false_vars.definedVariables()) {
  17627. if (true_vars.findInAnyFrame(v)) {
  17628. mutated_variables.add(v);
  17629. }
  17630. }
  17631. for (const x of mutated_variables) {
  17632. const true_type = true_vars.findInAnyFrame(x);
  17633. const false_type = false_vars.findInAnyFrame(x);
  17634. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17635. this.addBlockOutput(true_block, true_type, x);
  17636. this.addBlockOutput(false_block, false_type, x);
  17637. this.addNodeOutput(n, unified, x);
  17638. }
  17639. }
  17640. addLoopLoadStores(n) {
  17641. const [body_block] = n.blocks();
  17642. const loop_vars = this.addControlFlowLoadStores(body_block);
  17643. for (const name of loop_vars.definedVariables()) {
  17644. const parent_type = this.environment_stack.findInAnyFrame(name);
  17645. if (!parent_type) {
  17646. continue;
  17647. }
  17648. const block_type = loop_vars.findInThisFrame(name);
  17649. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17650. this.addNodeInput(n, parent_type, name);
  17651. this.addBlockInput(body_block, unified_type, name);
  17652. this.addBlockOutput(body_block, block_type, name);
  17653. this.addNodeOutput(n, unified_type, name);
  17654. }
  17655. }
  17656. addControlFlowLoadStores(block) {
  17657. this.pushFrame(block);
  17658. for (const n of block.nodes()) {
  17659. switch (n.kind()) {
  17660. case 'prim::If': {
  17661. this.addIfLoadStores(n);
  17662. break;
  17663. }
  17664. case 'prim::Loop': {
  17665. this.addLoopLoadStores(n);
  17666. break;
  17667. }
  17668. case 'prim::Closure': {
  17669. for (const b of n.blocks()) {
  17670. this.addControlFlowLoadStores(b);
  17671. }
  17672. break;
  17673. }
  17674. case 'prim::Store': {
  17675. this.environment_stack.setVar(n.s('name'), n.input().type());
  17676. break;
  17677. }
  17678. case 'prim::ComprehensionScope': {
  17679. this.addControlFlowLoadStores(n.blocks().at(0));
  17680. break;
  17681. }
  17682. default: {
  17683. break;
  17684. }
  17685. }
  17686. }
  17687. return this.popFrame();
  17688. }
  17689. run(graph) {
  17690. this.addControlFlowLoadStores(graph.block());
  17691. }
  17692. });
  17693. this.registerType('torch._C.LoopContinuations', class {
  17694. constructor() {
  17695. this._graph = null;
  17696. this._false_val = null;
  17697. this._curr_loop = null;
  17698. }
  17699. assignExitContinuations(block) {
  17700. for (const n of block.nodes()) {
  17701. switch (n.kind()) {
  17702. case 'prim::If': {
  17703. this.assignExitContinuations(n.blocks().at(0));
  17704. this.assignExitContinuations(n.blocks().at(1));
  17705. break;
  17706. }
  17707. case 'prim::Closure': {
  17708. const closure_block = new torch._C.LoopContinuations();
  17709. closure_block.run(n.blocks().at(0));
  17710. break;
  17711. }
  17712. case 'prim::Loop': {
  17713. const prev_loop = this._curr_loop;
  17714. this._curr_loop = n;
  17715. this.assignExitContinuations(n.blocks().at(0));
  17716. this._curr_loop = prev_loop;
  17717. break;
  17718. }
  17719. case 'prim::ContinueStmt': {
  17720. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17721. const header_block = loop_continuation.addBlock();
  17722. const [, pre_header] = this._curr_loop.blocks();
  17723. header_block.cloneFrom(pre_header, (v) => v);
  17724. this.InlineBlockBeforeNode(n, header_block);
  17725. loop_continuation.addInput(header_block.outputs()[0]);
  17726. loop_continuation.eraseBlock(0);
  17727. this.addLoopCarriedOutputs(loop_continuation);
  17728. n.destroy();
  17729. break;
  17730. }
  17731. case 'prim::BreakStmt': {
  17732. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17733. loop_exit.addInput(this._false_val);
  17734. this.addLoopCarriedOutputs(loop_exit);
  17735. n.destroy();
  17736. break;
  17737. }
  17738. default: {
  17739. break;
  17740. }
  17741. }
  17742. }
  17743. }
  17744. run(...args) {
  17745. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17746. const [graph] = args;
  17747. this.run(graph.block());
  17748. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17749. const [b] = args;
  17750. {
  17751. this._graph = b.owningGraph();
  17752. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17753. this._false_val = this._graph.insertConstant(false);
  17754. guard.dispose();
  17755. }
  17756. this.assignExitContinuations(b);
  17757. } else {
  17758. throw new python.Error('Not implemented.');
  17759. }
  17760. }
  17761. });
  17762. this.registerType('torch._C.LoopView', class {
  17763. constructor(node) {
  17764. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17765. this._node = node;
  17766. }
  17767. bodyBlock() {
  17768. return this._node.blocks().at(0);
  17769. }
  17770. nextCond() {
  17771. return this.bodyBlock().outputs()[0];
  17772. }
  17773. carriedOutputs() {
  17774. return this._node.outputs();
  17775. }
  17776. bodyCarriedInputs() {
  17777. return this.bodyBlock().inputs().slice(1);
  17778. }
  17779. bodyCarriedOutputs() {
  17780. return this.bodyBlock().outputs().slice(1);
  17781. }
  17782. });
  17783. this.registerType('torch._C.WithLoopStatus', class {
  17784. constructor(to_ir, new_status) {
  17785. this._to_ir = to_ir;
  17786. this._prev = this._to_ir._loop_status;
  17787. this._to_ir._loop_status = new_status;
  17788. }
  17789. dispose() {
  17790. this._to_ir._loop_status = this._prev;
  17791. }
  17792. });
  17793. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17794. for (const block_node of block.nodes()) {
  17795. block_node.moveBefore(before_node);
  17796. }
  17797. });
  17798. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  17799. if (args.length === 1 && args[0] instanceof torch.Block) {
  17800. const [block] = args;
  17801. for (const n of block.nodes()) {
  17802. for (const b of n.blocks()) {
  17803. torch._C.inlineLoopCondition(b);
  17804. }
  17805. if (n.kind() === 'prim::Loop') {
  17806. torch._C.inlineLoopCondition(n);
  17807. }
  17808. }
  17809. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  17810. const [n] = args;
  17811. const [body_block, pre_header] = n.blocks();
  17812. const temp_block = n.addBlock();
  17813. temp_block.cloneFrom(pre_header, (v) => v);
  17814. torch._C.InlineBlockBeforeNode(n, temp_block);
  17815. n.insertInput(1, temp_block.outputs()[0]);
  17816. n.eraseBlock(2);
  17817. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  17818. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  17819. n.eraseBlock(1);
  17820. } else {
  17821. throw new python.Error('Not implemented.');
  17822. }
  17823. });
  17824. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  17825. torch._C.inlineLoopCondition(graph.block());
  17826. });
  17827. this.registerType('torch._C.EraseLoadStores', class {
  17828. pushFrame(b) {
  17829. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  17830. }
  17831. popFrame() {
  17832. const old_frame = this.environment_stack;
  17833. this.environment_stack = this.environment_stack.next;
  17834. return old_frame;
  17835. }
  17836. eraseBlockLoadStores(block) {
  17837. this.pushFrame(block);
  17838. for (const n of block.nodes()) {
  17839. switch (n.kind()) {
  17840. case 'prim::Store': {
  17841. this.environment_stack.setVar(n.s('name'), n.input());
  17842. n.destroy();
  17843. break;
  17844. }
  17845. case 'prim::Load': {
  17846. const name = n.s('name');
  17847. const value = this.environment_stack.findInAnyFrame(name);
  17848. torch._C.TORCH_INTERNAL_ASSERT(value);
  17849. n.output().replaceAllUsesWith(value);
  17850. n.destroy();
  17851. break;
  17852. }
  17853. case 'prim::ComprehensionScope': {
  17854. const [body] = n.blocks();
  17855. this.eraseBlockLoadStores(body);
  17856. for (const body_node of body.nodes()) {
  17857. body_node.moveBefore(n);
  17858. }
  17859. n.destroy();
  17860. break;
  17861. }
  17862. default: {
  17863. for (const b of n.blocks()) {
  17864. this.eraseBlockLoadStores(b);
  17865. }
  17866. break;
  17867. }
  17868. }
  17869. }
  17870. this.popFrame();
  17871. }
  17872. run(graph) {
  17873. this.eraseBlockLoadStores(graph.block());
  17874. }
  17875. });
  17876. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  17877. });
  17878. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  17879. });
  17880. this.registerType('torch._C.ExitPair', class {
  17881. constructor(exit_v, exit_val_ref) {
  17882. const exit_vals = [];
  17883. for (const v of exit_val_ref) {
  17884. exit_vals.push(v);
  17885. }
  17886. if (exit_v.type() !== torch.BoolType.get()) {
  17887. throw new python.Error('Invalid exit value type.');
  17888. }
  17889. this.first = exit_v;
  17890. this.second = exit_vals;
  17891. }
  17892. hasExited() {
  17893. return this.first;
  17894. }
  17895. exitValues() {
  17896. return this.second;
  17897. }
  17898. });
  17899. this.registerType('torch._C.ExitTransformer', class {
  17900. constructor(graph) {
  17901. this._graph = graph;
  17902. this._target_block = null;
  17903. this._unit_values = new Map();
  17904. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  17905. this._true_val = this._graph.insertConstant(true);
  17906. this._false_val = this._graph.insertConstant(false);
  17907. this._throws_val = this.getUnitValue(torch.BoolType.get());
  17908. guard.dispose();
  17909. }
  17910. getUnitValue(type) {
  17911. const maybe_val = this._unit_values.get(type);
  17912. if (maybe_val) {
  17913. return maybe_val;
  17914. }
  17915. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  17916. this._unit_values.set(type, unit);
  17917. return unit;
  17918. }
  17919. transformReturnStmts() {
  17920. this._current_exit_kind = 'prim::ReturnStmt';
  17921. this.transformExits(this._graph.block());
  17922. }
  17923. transformLoopContinuations() {
  17924. this._current_exit_kind = 'prim::LoopContinuation';
  17925. this.transformExits(this._graph.block());
  17926. }
  17927. destroyNodeAfterExit(n) {
  17928. for (const output of n.outputs()) {
  17929. if (output.uses().length > 0) {
  17930. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  17931. }
  17932. }
  17933. n.destroy();
  17934. }
  17935. deleteAfterExitNodes(block, iter) {
  17936. const nodes = block.nodes();
  17937. if (iter === nodes.end()) {
  17938. return;
  17939. }
  17940. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  17941. for (const it of Array.from(nodes).reverse()) {
  17942. if (it === iter) {
  17943. break;
  17944. }
  17945. if (it !== block.return_node()) {
  17946. this.destroyNodeAfterExit(it);
  17947. }
  17948. }
  17949. this.destroyNodeAfterExit(iter);
  17950. insert.dispose();
  17951. }
  17952. updateTargetBlock(block) {
  17953. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  17954. this._target_block = block;
  17955. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  17956. this._target_block = block;
  17957. }
  17958. }
  17959. transformLoop(node) {
  17960. const loop = new torch._C.LoopView(node);
  17961. const body = loop.bodyBlock();
  17962. const exit_pair = this.transformExits(body);
  17963. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  17964. return this.constructWontExitPair();
  17965. }
  17966. const insert = new torch._C.WithInsertPoint(body);
  17967. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  17968. new_if.addInput(exit_pair.hasExited());
  17969. new_if.addBlock().registerOutput(this._false_val);
  17970. new_if.addBlock().registerOutput(loop.nextCond());
  17971. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  17972. loop.bodyBlock().eraseOutput(0);
  17973. loop.bodyBlock().insertOutput(0, new_condition);
  17974. node.addInput(this._false_val);
  17975. body.addInput().setType(torch.BoolType.get());
  17976. body.registerOutput(exit_pair.hasExited());
  17977. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  17978. for (const exit_value of exit_pair.exitValues()) {
  17979. const typ = exit_value.type();
  17980. node.addInput(this.getUnitValue(typ));
  17981. node.addOutput().setType(typ);
  17982. body.addInput().setType(typ);
  17983. body.registerOutput(exit_value);
  17984. }
  17985. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  17986. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  17987. insert.dispose();
  17988. return result;
  17989. }
  17990. calcIfExitStatus(then_status, else_status) {
  17991. if (then_status === 'THROWS') {
  17992. return else_status;
  17993. } else if (else_status === 'THROWS') {
  17994. return then_status;
  17995. }
  17996. if (then_status === 'WONT' && else_status === 'WONT') {
  17997. return 'WONT';
  17998. }
  17999. if (then_status === 'WILL' && else_status === 'WILL') {
  18000. return 'WILL';
  18001. }
  18002. return 'MIGHT';
  18003. }
  18004. transformIf(node) {
  18005. const [then_block, else_block] = node.blocks();
  18006. let then_pair = this.transformExits(then_block);
  18007. let else_pair = this.transformExits(else_block);
  18008. const then_status = this.getExitStatus(then_pair);
  18009. const else_status = this.getExitStatus(else_pair);
  18010. const if_status = this.calcIfExitStatus(then_status, else_status);
  18011. if (if_status === 'THROWS') {
  18012. return this.constructThrowsExitPair();
  18013. }
  18014. if (if_status === 'WONT') {
  18015. return this.constructWontExitPair();
  18016. }
  18017. if (then_status === 'WONT' || then_status === 'THROWS') {
  18018. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18019. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18020. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18021. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18022. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18023. }
  18024. let has_exited = null;
  18025. if (if_status === 'WILL') {
  18026. has_exited = this._true_val;
  18027. } else {
  18028. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18029. has_exited = node.outputs().at(node.outputs().length - 1);
  18030. }
  18031. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18032. const num_exit_vals = then_pair.exitValues().size();
  18033. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18034. return new torch._C.ExitPair(has_exited, exit_vals);
  18035. }
  18036. transformExits(block) {
  18037. const prev_target_block = this._target_block;
  18038. this.updateTargetBlock(block);
  18039. let exit_pair = this.constructWontExitPair();
  18040. for (const node of block.nodes()) {
  18041. const it = node.next;
  18042. switch (node.kind()) {
  18043. case 'prim::RaiseException': {
  18044. exit_pair = this.constructThrowsExitPair();
  18045. break;
  18046. }
  18047. case 'prim::ReturnStmt':
  18048. case 'prim::LoopContinuation': {
  18049. if (node.kind() === this._current_exit_kind) {
  18050. exit_pair = this.constructWillExitPair(node.inputs());
  18051. node.destroy();
  18052. }
  18053. break;
  18054. }
  18055. case 'prim::If': {
  18056. exit_pair = this.transformIf(node);
  18057. break;
  18058. }
  18059. case 'prim::With': {
  18060. exit_pair = this.transformWith(node);
  18061. break;
  18062. }
  18063. case 'prim::Closure': {
  18064. this.transformExits(node.blocks().at(0));
  18065. break;
  18066. }
  18067. case 'prim::Loop': {
  18068. exit_pair = this.transformLoop(node);
  18069. break;
  18070. }
  18071. default: {
  18072. break;
  18073. }
  18074. }
  18075. const status = this.getExitStatus(exit_pair);
  18076. if (status === 'WILL' || status === 'THROWS') {
  18077. this.deleteAfterExitNodes(block, it);
  18078. break;
  18079. }
  18080. if (status === 'MIGHT') {
  18081. throw new python.Error('Not implemented.');
  18082. // const nodes = block.nodes();
  18083. // if (node === nodes[nodes.length - 1]) {
  18084. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18085. // }
  18086. // break;
  18087. }
  18088. }
  18089. if (this._target_block === block) {
  18090. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18091. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18092. new_if.addBlock();
  18093. new_if.addBlock();
  18094. new_if.addInput(exit_pair.hasExited());
  18095. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18096. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18097. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18098. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18099. }
  18100. exit_pair = this.constructWontExitPair();
  18101. }
  18102. this._target_block = prev_target_block;
  18103. return exit_pair;
  18104. }
  18105. constructThrowsExitPair() {
  18106. return new torch._C.ExitPair(this._throws_val, []);
  18107. }
  18108. constructWontExitPair() {
  18109. return new torch._C.ExitPair(this._false_val, []);
  18110. }
  18111. constructWillExitPair(exit_val_ref) {
  18112. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18113. }
  18114. getExitStatus(exit_pair) {
  18115. const exit_v = exit_pair.hasExited();
  18116. if (exit_v === this._true_val) {
  18117. return 'WILL';
  18118. } else if (exit_v === this._false_val) {
  18119. return 'WONT';
  18120. } else if (exit_v === this._throws_val) {
  18121. return 'THROWS';
  18122. }
  18123. return 'MIGHT';
  18124. }
  18125. static owningNodeKind(block) {
  18126. if (block.owningNode()) {
  18127. return block.owningNode().kind();
  18128. }
  18129. return null;
  18130. }
  18131. static isGraphOrClosureBlock(block) {
  18132. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18133. }
  18134. static removeOutputs(b) {
  18135. while (b.outputs().length > 0) {
  18136. b.eraseOutput(0);
  18137. }
  18138. }
  18139. static registerBlockOutputs(b, outs) {
  18140. for (const out of outs) {
  18141. b.registerOutput(out);
  18142. }
  18143. }
  18144. static replaceBlockOutputs(b, outs) {
  18145. torch._C.ExitTransformer.removeOutputs(b);
  18146. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18147. }
  18148. });
  18149. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18150. });
  18151. this.registerFunction('torch._C.TransformExits', (graph) => {
  18152. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18153. const e_loop = new torch._C.ExitTransformer(graph);
  18154. e_loop.transformLoopContinuations();
  18155. const e_ret = new torch._C.ExitTransformer(graph);
  18156. e_ret.transformReturnStmts();
  18157. torch._C.inlineConsecutiveIfs(graph.block());
  18158. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18159. });
  18160. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18161. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18162. const args = iter.inputs();
  18163. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18164. newSub.replaceInput(0, args[1]);
  18165. newSub.replaceInput(1, args[0]);
  18166. iter.destroyCurrent();
  18167. return true;
  18168. }
  18169. return false;
  18170. });
  18171. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18172. });
  18173. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18174. const args = iter.inputs();
  18175. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18176. if (iter.kind() === 'aten::__is__') {
  18177. iter.replaceWithNewSymbol('aten::eq');
  18178. iter.destroyCurrent();
  18179. return true;
  18180. }
  18181. if (iter.kind() === 'aten::__isnot__') {
  18182. iter.replaceWithNewSymbol('aten::ne');
  18183. iter.destroyCurrent();
  18184. return true;
  18185. }
  18186. }
  18187. return false;
  18188. });
  18189. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18190. for (const it of block.nodes()) {
  18191. for (const sub of it.blocks()) {
  18192. torch._C.NormalizeOps(sub);
  18193. }
  18194. if (torch._C.normalizeRSub(it)) {
  18195. continue;
  18196. }
  18197. if (torch._C.normalizeOpAliases(it)) {
  18198. continue;
  18199. }
  18200. if (torch._C.normalizeIsBool(it)) {
  18201. continue;
  18202. }
  18203. }
  18204. });
  18205. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18206. return false;
  18207. });
  18208. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18209. /*
  18210. torch._C.liftClosures(to_clean);
  18211. torch._C.inlineForkedClosures(to_clean);
  18212. */
  18213. if (torch._C.getInlineEverythingMode()) {
  18214. torch._C.Inline(to_clean);
  18215. }
  18216. /*
  18217. torch._C.eraseListLiterals(to_clean);
  18218. */
  18219. torch._C.LowerSimpleTuples(to_clean);
  18220. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18221. torch._C.ConstantPooling(to_clean);
  18222. /*
  18223. torch._C.CanonicalizeOutputs(to_clean);
  18224. torch._C.AnnotateWarns(to_clean);
  18225. */
  18226. });
  18227. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18228. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18229. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18230. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18231. constructor(cpp_module) {
  18232. super();
  18233. this._initializing = true;
  18234. this._c = cpp_module;
  18235. }
  18236. static _construct(cpp_module, init_fn) {
  18237. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18238. init_fn(script_module);
  18239. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18240. return script_module;
  18241. }
  18242. static _finalize_scriptmodule(script_module) {
  18243. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18244. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18245. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18246. script_module._initializing = false;
  18247. }
  18248. get graph() {
  18249. // return this._c._get_method('forward').graph;
  18250. return this._c.graph;
  18251. }
  18252. get code_with_constants() {
  18253. // return this.forward.code_with_constants;
  18254. return this._c.code_with_constants;
  18255. }
  18256. __setattr__(name, value) {
  18257. if (this._initializing) {
  18258. super.__setattr__(name, value);
  18259. } else if (this._modules.has(name)) {
  18260. this._modules.set(name, value);
  18261. } else if (this._c.hasattr(name)) {
  18262. this._c.setattr(name, value);
  18263. } else {
  18264. //
  18265. }
  18266. }
  18267. __getattr__(name) {
  18268. if (this._initializing) {
  18269. return super.__getattr__(name);
  18270. }
  18271. if (this._modules.has(name)) {
  18272. return this._modules.get(name);
  18273. }
  18274. if (this._c.hasattr(name)) {
  18275. return this._c.getattr(name);
  18276. }
  18277. if (this._c._has_method(name)) {
  18278. //
  18279. }
  18280. return super.__getattr__(name);
  18281. }
  18282. });
  18283. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18284. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18285. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18286. torch.CompilationUnit = torch.jit.CompilationUnit;
  18287. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18288. torch._C.ScriptModule = torch.ScriptModule;
  18289. torch._C.ClassType = torch.ClassType;
  18290. this.registerType('torch._C.FlatBuffersLoader', class {
  18291. constructor(cu) {
  18292. this._cu = cu;
  18293. const torch = cu.execution.__import__('torch');
  18294. this._torch = torch;
  18295. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18296. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18297. this._ivalue_parsers = new Map();
  18298. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18299. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18300. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18301. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18302. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18303. }
  18304. parseModule(module) {
  18305. this._module = module;
  18306. this._all_functions = new Map();
  18307. this._all_ivalues = new Array(module.ivalues.length);
  18308. this._all_types = new Array(module.object_types.length);
  18309. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18310. for (let i = 0; i < mobile_ivalue_size; i++) {
  18311. this.parseAndPopulate(i, module.ivalues[i]);
  18312. }
  18313. const m = this._all_ivalues[module.state_obj];
  18314. for (const [name, value] of this._all_functions) {
  18315. const class_index = module.ivalues[name].val.class_type;
  18316. const class_type = this._all_types[class_index];
  18317. if (value) {
  18318. class_type.addMethod(value);
  18319. }
  18320. }
  18321. m._min_operator_version = module.operator_version;
  18322. m._bytecode_version = module.bytecode_version;
  18323. return m;
  18324. }
  18325. parseAndPopulate(i, ivalue) {
  18326. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18327. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18328. } else {
  18329. this._all_ivalues[i] = this.parseIValue(ivalue);
  18330. }
  18331. }
  18332. parseFunction(/* val */) {
  18333. return null;
  18334. }
  18335. parseIValue(ivalue) {
  18336. if (ivalue.val) {
  18337. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18338. return callback(ivalue);
  18339. }
  18340. return null;
  18341. }
  18342. parseTensor(ivalue) {
  18343. return this.parseTensorFromMetadata(ivalue.val);
  18344. }
  18345. parseTensorFromMetadata(metadata) {
  18346. if (metadata.quantized_schema) {
  18347. throw new torch.Error('Quantized schema not implemented.');
  18348. }
  18349. const index = metadata.storage_location_index;
  18350. const data = this._module.storage_data[index].data;
  18351. const dtype = this._dtypes.get(metadata.scalar_type);
  18352. const size = data.length / dtype.itemsize();
  18353. const storage = new torch.storage.TypedStorage(size, dtype);
  18354. storage._set_cdata(data);
  18355. const tensor = new torch.Tensor();
  18356. const shape = Array.from(metadata.sizes);
  18357. const stride = Array.from(metadata.strides);
  18358. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18359. return tensor;
  18360. }
  18361. parseObject(ivalue) {
  18362. const object = ivalue.val;
  18363. const obj_type = this._module.object_types[object.type_index];
  18364. const cls = this.getOrCreateClassTypeForObject(object);
  18365. switch (obj_type.type) {
  18366. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18367. const torch = this._torch;
  18368. const obj = torch.ScriptObject.create(cls);
  18369. for (let i = 0; i < object.attrs.length; i++) {
  18370. const attr_name = obj_type.attr_names[i];
  18371. const val = this._all_ivalues[object.attrs[i]];
  18372. obj.__setattr__(attr_name, val);
  18373. }
  18374. return obj;
  18375. }
  18376. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18377. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18378. default: {
  18379. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18380. }
  18381. }
  18382. }
  18383. getOrCreateClassTypeForObject(object) {
  18384. let cls = this._all_types[object.type_index];
  18385. const obj_type = this._module.object_types[object.type_index];
  18386. if (!cls) {
  18387. const name = obj_type.type_name;
  18388. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18389. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18390. if (!cls) {
  18391. const torch = this._torch;
  18392. cls = torch.ClassType.create(name, this._cu, true);
  18393. this._cu.register_type(cls);
  18394. }
  18395. } else {
  18396. // cls = c10::parseType(qn_str).cast<ClassType>();
  18397. }
  18398. this._all_types[object.type_index] = cls;
  18399. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18400. for (let i = 0; i < object.attrs.length; i++) {
  18401. // const val = this._all_ivalues[object.attrs[i]];
  18402. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18403. }
  18404. }
  18405. }
  18406. return cls;
  18407. }
  18408. });
  18409. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18410. constructor(export_module, flat_args_adapter) {
  18411. super();
  18412. const export_graph = copy.deepcopy(export_module.graph);
  18413. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18414. this.graph = torch.fx.Graph();
  18415. this.graph.owning_module = this;
  18416. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18417. this.flat_args_adapter = flat_args_adapter;
  18418. this.adapted = false;
  18419. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18420. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18421. }
  18422. });
  18423. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18424. constructor(input_specs, output_specs) {
  18425. this.input_specs = input_specs;
  18426. this.output_specs = output_specs;
  18427. }
  18428. get user_inputs() {
  18429. const user_inputs = [];
  18430. for (const s of this.input_specs) {
  18431. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18432. continue;
  18433. }
  18434. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18435. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18436. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18437. user_inputs.push(s.arg.name);
  18438. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18439. user_inputs.push(s.arg.value);
  18440. } else {
  18441. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18442. }
  18443. }
  18444. return user_inputs;
  18445. }
  18446. get user_outputs() {
  18447. const user_outputs = [];
  18448. for (const s of this.output_specs) {
  18449. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18450. continue;
  18451. }
  18452. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18453. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18454. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18455. user_outputs.push(s.arg.name);
  18456. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18457. user_outputs.push(s.arg.value);
  18458. } else {
  18459. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18460. }
  18461. }
  18462. return user_outputs;
  18463. }
  18464. get inputs_to_parameters() {
  18465. return new Map(this.input_specs
  18466. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18467. .map((s) => [s.arg.name, s.target]));
  18468. }
  18469. get inputs_to_buffers() {
  18470. return new Map(this.input_specs
  18471. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18472. .map((s) => [s.arg.name, s.target]));
  18473. }
  18474. get inputs_to_lifted_tensor_constants() {
  18475. return new Map(this.input_specs
  18476. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18477. .map((s) => [s.arg.name, s.target]));
  18478. }
  18479. });
  18480. torch.export.graph_signature.InputKind = {
  18481. USER_INPUT: 0,
  18482. PARAMETER: 1,
  18483. BUFFER: 2,
  18484. CONSTANT_TENSOR: 3,
  18485. CUSTOM_OBJ: 4,
  18486. TOKEN: 5
  18487. };
  18488. this.registerType('torch.export.graph_signature.InputSpec', class {
  18489. constructor(kind, arg, target, persistent) {
  18490. this.kind = kind;
  18491. this.arg = arg;
  18492. this.target = target;
  18493. this.persistent = persistent || null;
  18494. }
  18495. });
  18496. torch.export.graph_signature.OutputKind = {
  18497. USER_OUTPUT: 0,
  18498. LOSS_OUTPUT: 1,
  18499. BUFFER_MUTATION: 2,
  18500. GRADIENT_TO_PARAMETER: 3,
  18501. GRADIENT_TO_USER_INPUT: 4,
  18502. USER_INPUT_MUTATION: 5,
  18503. TOKEN: 6
  18504. };
  18505. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18506. constructor(kind, arg, target) {
  18507. this.kind = kind;
  18508. this.arg = arg;
  18509. this.target = target;
  18510. }
  18511. });
  18512. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18513. constructor(name, value) {
  18514. this.name = name;
  18515. this.value = value; // Union[int, float, bool, str, None]
  18516. }
  18517. });
  18518. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18519. constructor(name) {
  18520. this.name = name;
  18521. }
  18522. });
  18523. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18524. constructor(name) {
  18525. this.name = name;
  18526. }
  18527. });
  18528. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18529. constructor(name, class_fqn, fake_val) {
  18530. this.name = name;
  18531. this.class_fqn = class_fqn;
  18532. this.fake_val = fake_val;
  18533. }
  18534. });
  18535. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18536. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18537. // graph._codegen = torch.fx.graph.CodeGen()
  18538. this._graph_module = this._create_graph_module_for_export(root, graph);
  18539. if (root instanceof torch.fx.GraphModule) {
  18540. // this._graph_module.meta.update(root.meta);
  18541. }
  18542. this._graph_signature = graph_signature;
  18543. this._state_dict = state_dict;
  18544. this._range_constraints = range_constraints;
  18545. this._module_call_graph = module_call_graph;
  18546. this._example_inputs = example_inputs;
  18547. this._constants = tensor_constants || constants || {};
  18548. }
  18549. _create_graph_module_for_export(root, graph) {
  18550. let gm = null;
  18551. try {
  18552. gm = new torch.fx.GraphModule(root, graph);
  18553. } catch {
  18554. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18555. gm._graph = graph;
  18556. }
  18557. return gm;
  18558. }
  18559. get graph_module() {
  18560. return this._graph_module;
  18561. }
  18562. get graph() {
  18563. return this._graph_module.graph;
  18564. }
  18565. get graph_signature() {
  18566. return this._graph_signature;
  18567. }
  18568. get state_dict() {
  18569. return this._state_dict;
  18570. }
  18571. get constants() {
  18572. return this._constants;
  18573. }
  18574. });
  18575. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18576. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18577. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18578. return new torch.fx.graph_module.GraphModule(root, graph);
  18579. });
  18580. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18581. module = torch.export._remove_effect_tokens(module);
  18582. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18583. });
  18584. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18585. return new torch.fx.graph_module.GraphModule(root, graph);
  18586. });
  18587. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18588. constructor(exported_program, state_dict, constants, example_inputs) {
  18589. this.exported_program = exported_program;
  18590. this.state_dict = state_dict;
  18591. this.constants = constants;
  18592. this.example_inputs = example_inputs;
  18593. }
  18594. });
  18595. torch._export.serde.serialize._SYM_OPS = new Set([
  18596. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18597. operator.neg, operator.pos, operator.and_, operator.or_,
  18598. math.trunc, torch.sym_not,
  18599. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18600. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18601. operator.truediv, operator.and_
  18602. ]);
  18603. this.registerType('torch._export.serde.union._Union', class {
  18604. constructor(obj) {
  18605. if (obj.$type) {
  18606. this.type = obj.$type;
  18607. this[obj.$type] = obj.$value;
  18608. delete obj.$type;
  18609. delete obj.$value;
  18610. } else if (obj.type) {
  18611. this.type = obj.type;
  18612. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18613. this[obj.type] = Object.fromEntries(entries);
  18614. } else {
  18615. let entries = Object.entries(obj);
  18616. if (entries.length > 1) {
  18617. entries = entries.filter(([, value]) => value !== null);
  18618. }
  18619. if (entries.length !== 1) {
  18620. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18621. }
  18622. const [entry] = entries;
  18623. const [type, value] = entry;
  18624. this.type = type;
  18625. this[type] = value;
  18626. }
  18627. }
  18628. get value() {
  18629. return this[this.type];
  18630. }
  18631. });
  18632. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18633. constructor(obj) {
  18634. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18635. this.name = obj.name;
  18636. }
  18637. });
  18638. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18639. constructor(obj) {
  18640. super(obj);
  18641. switch (this.type) {
  18642. case 'as_int':
  18643. case 'as_ints':
  18644. case 'as_float':
  18645. case 'as_floats':
  18646. case 'as_bool':
  18647. case 'as_bools':
  18648. case 'as_string':
  18649. case 'as_strings':
  18650. case 'as_scalar_type':
  18651. case 'as_device':
  18652. case 'as_memory_format':
  18653. case 'as_layout':
  18654. break;
  18655. case 'as_none':
  18656. this.as_none = null;
  18657. break;
  18658. case 'as_tensor':
  18659. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18660. break;
  18661. case 'as_tensors':
  18662. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18663. break;
  18664. case 'as_graph':
  18665. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18666. break;
  18667. case 'as_sym_int':
  18668. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18669. break;
  18670. case 'as_sym_ints':
  18671. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18672. break;
  18673. case 'as_sym_bool':
  18674. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18675. break;
  18676. case 'as_sym_bools':
  18677. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18678. break;
  18679. case 'as_sym_float':
  18680. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18681. break;
  18682. case 'as_sym_floats':
  18683. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18684. break;
  18685. case 'as_optional_tensors':
  18686. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18687. break;
  18688. case 'as_custom_obj':
  18689. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18690. break;
  18691. // case 'as_graph': GraphArgument
  18692. default:
  18693. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18694. }
  18695. }
  18696. });
  18697. this.registerType('torch._export.serde.schema.Node', class {
  18698. constructor(obj) {
  18699. this.target = obj.target;
  18700. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18701. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18702. this.metadata = new Map(Object.entries(obj.metadata));
  18703. }
  18704. });
  18705. torch._export.serde.schema.ScalarType = {
  18706. UNKNOWN: 0,
  18707. BYTE: 1,
  18708. CHAR: 2,
  18709. SHORT: 3,
  18710. INT: 4,
  18711. LONG: 5,
  18712. HALF: 6,
  18713. FLOAT: 7,
  18714. DOUBLE: 8,
  18715. COMPLEXHALF: 9,
  18716. COMPLEXFLOAT: 10,
  18717. COMPLEXDOUBLE: 11,
  18718. BOOL: 12,
  18719. BFLOAT16: 13,
  18720. UINT16: 28,
  18721. FLOAT8E4M3FN: 29,
  18722. FLOAT8E5M2: 30,
  18723. FLOAT8E4M3FNUZ: 31,
  18724. FLOAT8E5M2FNUZ: 32,
  18725. };
  18726. torch._export.serde.schema.Layout = {
  18727. Unknown: 0,
  18728. SparseCoo: 1,
  18729. SparseCsr: 2,
  18730. SparseCsc: 3,
  18731. SparseBsr: 4,
  18732. SparseBsc: 5,
  18733. _mkldnn: 6,
  18734. Strided: 7
  18735. };
  18736. torch._export.serde.schema.MemoryFormat = {
  18737. Unknown: 0,
  18738. ContiguousFormat: 1,
  18739. ChannelsLast: 2,
  18740. ChannelsLast3d: 3,
  18741. PreserveFormat: 4,
  18742. };
  18743. this.registerType('torch._export.serde.schema.Device', class {
  18744. constructor(obj) {
  18745. Object.assign(this, { ...obj });
  18746. }
  18747. });
  18748. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18749. constructor(obj) {
  18750. obj = obj.meta || obj;
  18751. this.dtype = obj.dtype;
  18752. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18753. this.requires_grad = obj.requires_grad;
  18754. this.device = obj.device;
  18755. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18756. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18757. this.layout = obj.layout;
  18758. }
  18759. });
  18760. this.registerType('torch._export.serde.schema.Graph', class {
  18761. constructor(obj) {
  18762. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18763. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18764. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18765. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18766. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18767. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18768. this.is_single_tensor_return = obj.is_single_tensor_return;
  18769. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18770. if (obj.contants) {
  18771. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18772. // graph_signature -> input_specs -> tensor_constant
  18773. }
  18774. }
  18775. });
  18776. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18777. constructor(obj) {
  18778. Object.assign(this, { ...obj });
  18779. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18780. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18781. }
  18782. });
  18783. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18784. constructor(obj) {
  18785. Object.assign(this, { ...obj });
  18786. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18787. }
  18788. });
  18789. this.registerType('torch._export.serde.schema.GraphModule', class {
  18790. constructor(obj) {
  18791. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18792. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18793. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18794. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18795. }
  18796. });
  18797. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  18798. constructor(obj) {
  18799. Object.assign(this, { ...obj });
  18800. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  18801. }
  18802. });
  18803. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  18804. this.registerType('torch._export.serde.schema.SymExpr', class {
  18805. constructor(obj) {
  18806. this.expr_str = obj.expr_str;
  18807. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  18808. }
  18809. });
  18810. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  18811. constructor(obj) {
  18812. super(obj);
  18813. if (this.type === 'as_int') {
  18814. // continue
  18815. } else if (this.type === 'as_expr') {
  18816. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18817. } else {
  18818. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  18819. }
  18820. }
  18821. });
  18822. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  18823. constructor(obj) {
  18824. super(obj);
  18825. if (this.type === 'as_bool') {
  18826. // continue
  18827. } else if (this.type === 'as_expr') {
  18828. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18829. } else {
  18830. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  18831. }
  18832. }
  18833. });
  18834. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  18835. constructor(obj) {
  18836. super(obj);
  18837. Object.assign(this, { ...obj });
  18838. }
  18839. });
  18840. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  18841. constructor(obj) {
  18842. super(obj);
  18843. Object.assign(this, { ...obj });
  18844. }
  18845. });
  18846. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  18847. constructor(obj) {
  18848. super(obj);
  18849. Object.assign(this, { ...obj });
  18850. }
  18851. });
  18852. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  18853. constructor(obj) {
  18854. Object.assign(this, { ...obj });
  18855. }
  18856. });
  18857. this.registerType('torch._export.serde.schema.GraphSignature', class {
  18858. constructor(obj) {
  18859. this.input_specs = [];
  18860. if (Array.isArray(obj.input_specs)) {
  18861. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  18862. }
  18863. if (Array.isArray(obj.user_inputs)) {
  18864. for (const user_input of obj.user_inputs) {
  18865. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  18866. }
  18867. }
  18868. if (obj.inputs_to_parameters) {
  18869. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  18870. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  18871. }
  18872. }
  18873. this.output_specs = [];
  18874. if (Array.isArray(obj.output_specs)) {
  18875. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  18876. }
  18877. }
  18878. });
  18879. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  18880. constructor(obj) {
  18881. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18882. }
  18883. });
  18884. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  18885. constructor(obj) {
  18886. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18887. this.parameter_name = obj.parameter_name;
  18888. }
  18889. });
  18890. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  18891. constructor(obj) {
  18892. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18893. this.buffer_name = obj.buffer_name;
  18894. }
  18895. });
  18896. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  18897. constructor(obj) {
  18898. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18899. this.tensor_constant_name = obj.tensor_constant_name;
  18900. }
  18901. });
  18902. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  18903. constructor(obj) {
  18904. this.name = obj.name;
  18905. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  18906. }
  18907. });
  18908. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  18909. constructor(obj) {
  18910. super(obj);
  18911. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  18912. // continue
  18913. } else if (this.type === 'as_none') {
  18914. this.as_none = null;
  18915. } else {
  18916. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  18917. }
  18918. }
  18919. });
  18920. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  18921. constructor(obj) {
  18922. super(obj);
  18923. if (this.type === 'user_input') {
  18924. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  18925. } else if (this.type === 'parameter') {
  18926. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  18927. } else if (this.type === 'buffer') {
  18928. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  18929. } else if (this.type === 'tensor_constant') {
  18930. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  18931. } else if (this.type === 'constant_input') {
  18932. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  18933. } else {
  18934. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  18935. }
  18936. /*
  18937. custom_obj: InputToCustomObjSpec
  18938. token: InputTokenSpec
  18939. */
  18940. }
  18941. });
  18942. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  18943. constructor(obj) {
  18944. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18945. }
  18946. });
  18947. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  18948. constructor(obj) {
  18949. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18950. this.buffer_name = obj.buffer_name;
  18951. }
  18952. });
  18953. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  18954. constructor(obj) {
  18955. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18956. this.parameter_name = obj.parameter_name;
  18957. }
  18958. });
  18959. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  18960. constructor(obj) {
  18961. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18962. this.user_input_name = obj.user_input_name;
  18963. }
  18964. });
  18965. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  18966. constructor(obj) {
  18967. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18968. this.user_input_name = obj.user_input_name;
  18969. }
  18970. });
  18971. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  18972. constructor(obj) {
  18973. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  18974. }
  18975. });
  18976. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  18977. constructor(obj) {
  18978. super(obj);
  18979. if (this.type === 'user_output') {
  18980. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  18981. } else if (this.type === 'loss_output') {
  18982. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  18983. } else if (this.type === 'buffer_mutation') {
  18984. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  18985. } else if (this.type === 'gradient_to_parameter') {
  18986. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  18987. } else if (this.type === 'gradient_to_user_input') {
  18988. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  18989. } else if (this.type === 'user_input_mutation') {
  18990. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  18991. } else if (this.type === 'token') {
  18992. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  18993. }
  18994. }
  18995. });
  18996. this.registerType('torch._export.serde.schema.TensorArgument', class {
  18997. constructor(obj) {
  18998. this.name = obj.name;
  18999. }
  19000. });
  19001. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19002. constructor(obj) {
  19003. this.name = obj.name;
  19004. }
  19005. });
  19006. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19007. constructor(obj) {
  19008. this.name = obj.name;
  19009. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19010. }
  19011. });
  19012. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19013. constructor(obj) {
  19014. super(obj);
  19015. if (this.type === 'as_tensor') {
  19016. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19017. } else if (this.type === 'as_none') {
  19018. this.as_none = null;
  19019. } else {
  19020. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19021. }
  19022. }
  19023. });
  19024. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19025. const legacy_file = `data/weights/${model_name}.pt`;
  19026. if (f.has(legacy_file)) {
  19027. return f.get(legacy_file);
  19028. }
  19029. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19030. if (!f.has(weights_config_file)) {
  19031. return null;
  19032. }
  19033. const weights_config = f.get(weights_config_file);
  19034. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19035. const state_dict = new builtins.dict();
  19036. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19037. if (payload_meta.use_pickle) {
  19038. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19039. const weight_tensor = torch.load(weight_bytes);
  19040. state_dict.set(weight_fqn, weight_tensor);
  19041. } else {
  19042. const tensor_meta = payload_meta.tensor_meta;
  19043. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19044. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19045. const strides = tensor_meta.strides.map((s) => s.as_int);
  19046. const storage_offset = tensor_meta.storage_offset.as_int;
  19047. const weight_tensor = new torch.Tensor();
  19048. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19049. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19050. if (payload_meta.is_param) {
  19051. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19052. } else {
  19053. state_dict.set(weight_fqn, weight_tensor);
  19054. }
  19055. }
  19056. }
  19057. return state_dict;
  19058. });
  19059. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19060. const legacy_file = `data/constants/${model_name}.pt`;
  19061. if (f.has(legacy_file)) {
  19062. const entries = f.get(legacy_file);
  19063. return new builtins.dict(entries);
  19064. }
  19065. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19066. if (!f.has(constants_config_file)) {
  19067. return null;
  19068. }
  19069. const constants_config = f.get(constants_config_file);
  19070. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19071. const constants = new builtins.dict();
  19072. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19073. const path_name = payload_meta.path_name;
  19074. if (path_name.startsWith('tensor_')) {
  19075. if (payload_meta.use_pickle) {
  19076. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19077. const constant_tensor = torch.load(constant_bytes);
  19078. constants.set(constant_fqn, constant_tensor);
  19079. } else {
  19080. const tensor_meta = payload_meta.tensor_meta;
  19081. const tensor = constant_file_map.get(payload_meta.path_name);
  19082. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19083. const strides = tensor_meta.strides.map((s) => s.as_int);
  19084. const storage_offset = tensor_meta.storage_offset.as_int;
  19085. const constant_tensor = new torch.Tensor();
  19086. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19087. constants.set(constant_fqn, constant_tensor);
  19088. }
  19089. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19090. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19091. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19092. constants.set(constant_fqn, custom_obj);
  19093. }
  19094. }
  19095. return constants;
  19096. });
  19097. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19098. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19099. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19100. }
  19101. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19102. });
  19103. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19104. const file_map = new builtins.dict();
  19105. for (const payload_meta of Object.values(config.config)) {
  19106. if (payload_meta.use_pickle) {
  19107. continue;
  19108. }
  19109. if (file_map.has(payload_meta.path_name)) {
  19110. continue;
  19111. }
  19112. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19113. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19114. file_map.set(payload_meta.path_name, tensor);
  19115. }
  19116. return file_map;
  19117. });
  19118. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19119. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19120. const itemsize = dtype.itemsize();
  19121. const num_elements = tensor_bytes.length / itemsize;
  19122. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19123. storage._set_cdata(tensor_bytes);
  19124. const tensor = new torch.Tensor();
  19125. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19126. tensor.requires_grad = tensor_meta.requires_grad || false;
  19127. return tensor;
  19128. });
  19129. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19130. const exported_programs = new Map();
  19131. for (const name of f.keys()) {
  19132. const match = name.match(/^models\/([^/]+)\.json$/);
  19133. if (match) {
  19134. const [, model_name] = match;
  19135. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19136. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19137. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19138. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19139. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19140. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19141. exported_programs.set(model_name, exported_program);
  19142. }
  19143. }
  19144. return { exported_programs };
  19145. });
  19146. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19147. if (data === null) {
  19148. return data;
  19149. }
  19150. if (cls) {
  19151. return new cls(data);
  19152. }
  19153. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19154. });
  19155. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19156. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19157. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19158. });
  19159. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19160. constructor(expected_opset_version) {
  19161. this.expected_opset_version = expected_opset_version;
  19162. }
  19163. deserialize(exported_program, state_dict, constants, example_inputs) {
  19164. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19165. /*
  19166. symbol_name_to_range = {
  19167. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19168. for k, v in exported_program.range_constraints.items()
  19169. }
  19170. */
  19171. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19172. const res = deserializer.deserialize(
  19173. exported_program.graph_module,
  19174. state_dict,
  19175. constants,
  19176. example_inputs,
  19177. symbol_name_to_range);
  19178. const range_constraints = null;
  19179. /*
  19180. range_constraints = self.deserialize_range_constraints(
  19181. symbol_name_to_range, res.names_to_symbols,
  19182. )
  19183. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19184. self._validate_model_opset_version(model_opset_version)
  19185. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19186. */
  19187. return new torch.export.exported_program.ExportedProgram(
  19188. res.graph_module, res.graph_module.graph, res.signature,
  19189. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19190. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19191. res.constants);
  19192. // return upgrader.upgrade(exported_program)
  19193. }
  19194. });
  19195. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19196. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19197. return serialized;
  19198. }
  19199. if (serialized === null || serialized.length === 0) {
  19200. return new builtins.dict();
  19201. }
  19202. const artifact = torch.load(serialized);
  19203. return artifact;
  19204. });
  19205. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19206. constructor() {
  19207. this.serialized_name_to_node = new builtins.dict();
  19208. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19209. this.graph = new torch.fx.Graph();
  19210. this.module = new torch.nn.Module();
  19211. }
  19212. save_graph_module() {
  19213. const Context = class {
  19214. constructor(self) {
  19215. this.self = self;
  19216. }
  19217. __enter__() {
  19218. this.saved = [
  19219. this.self.graph,
  19220. this.self.module,
  19221. this.self.serialized_name_to_node,
  19222. this.self.serialized_name_to_meta,
  19223. this.self.unbacked_symbols,
  19224. ];
  19225. this.self.graph = new torch.fx.graph.Graph();
  19226. this.self.module = new torch.nn.modules.module.Module();
  19227. this.self.serialized_name_to_node = new builtins.dict();
  19228. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19229. this.self.unbacked_symbols = new Set();
  19230. }
  19231. __exit__(/* exc_type, exc_value, traceback */) {
  19232. const self = this.self;
  19233. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19234. }
  19235. };
  19236. return new Context(this);
  19237. }
  19238. deserialize_graph_output(output) {
  19239. if (output.type === 'as_tensor') {
  19240. return this.serialized_name_to_node.get(output.as_tensor.name);
  19241. } else if (output.type === 'as_sym_int') {
  19242. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19243. } else if (output.type === 'as_sym_bool') {
  19244. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19245. } else if (output.type === 'as_int') {
  19246. return this.serialized_name_to_node.get(output.as_int.as_name);
  19247. } else if (output.type === 'as_none') {
  19248. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19249. }
  19250. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19251. }
  19252. deserialize_graph(serialized_graph) {
  19253. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19254. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19255. this.serialized_name_to_meta.set(name, meta_val);
  19256. }
  19257. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19258. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19259. }
  19260. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19261. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19262. }
  19263. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19264. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19265. }
  19266. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19267. const input = serialized_graph.inputs[i];
  19268. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19269. const node_name = input.value.name;
  19270. const placeholder_node = this.graph.placeholder(node_name);
  19271. placeholder_node.name = node_name;
  19272. this.sync_fx_node(node_name, placeholder_node);
  19273. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19274. const node_name = this.signature.input_specs[i].arg.name;
  19275. const placeholder_node = this.graph.placeholder(node_name);
  19276. placeholder_node.meta.set('val', this.deserialize_input(input));
  19277. } else {
  19278. throw new python.Error(`Invalid input ${input.type}.`);
  19279. }
  19280. }
  19281. for (const serialized_node of serialized_graph.nodes) {
  19282. const target = this.deserialize_operator(serialized_node.target);
  19283. this.deserialize_node(serialized_node, target);
  19284. }
  19285. let outputs = [];
  19286. for (const output of serialized_graph.outputs) {
  19287. outputs.push(this.deserialize_graph_output(output));
  19288. }
  19289. if (serialized_graph.is_single_tensor_return) {
  19290. [outputs] = outputs;
  19291. } else {
  19292. outputs = new builtins.tuple(outputs);
  19293. }
  19294. const output_node = this.graph.output(outputs);
  19295. if (serialized_graph.is_single_tensor_return) {
  19296. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19297. } else {
  19298. /* output_node.meta['val'] = tuple(
  19299. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19300. for arg in output_node.args[0]
  19301. ) */
  19302. }
  19303. return self.graph;
  19304. }
  19305. deserialize_operator(serialized_target) {
  19306. let module = null;
  19307. let serialized_target_names = null;
  19308. if (serialized_target.startsWith('_operator')) {
  19309. module = operator;
  19310. serialized_target_names = serialized_target.split('.').slice(1);
  19311. } else if (serialized_target.startsWith('torch')) {
  19312. module = torch;
  19313. serialized_target_names = serialized_target.split('.').slice(1);
  19314. } else if (serialized_target.startsWith('#')) {
  19315. return self.deserialize_extension_operator(serialized_target);
  19316. } else {
  19317. return serialized_target;
  19318. }
  19319. let target = module;
  19320. for (const name of serialized_target_names) {
  19321. target = builtins.getattr(target, name);
  19322. if (!target) {
  19323. return serialized_target;
  19324. }
  19325. }
  19326. return target;
  19327. }
  19328. deserialize_node(serialized_node, target) {
  19329. let fx_node = null;
  19330. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19331. const name = serialized_node.outputs[0].value.as_name;
  19332. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19333. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19334. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19335. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19336. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19337. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19338. for (const x of [...args, ...kwargs.values()]) {
  19339. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19340. x.meta.update(metadata);
  19341. }
  19342. }
  19343. const name = serialized_node.outputs.length === 1 &&
  19344. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19345. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19346. serialized_node.outputs[0].as_tensor.name : null;
  19347. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19348. this.deserialize_outputs(serialized_node, fx_node);
  19349. fx_node.meta.update(metadata);
  19350. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19351. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19352. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19353. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19354. this.deserialize_outputs(serialized_node, fx_node);
  19355. } else if (typeof target === 'string') {
  19356. // Handle unresolved operators
  19357. execution.emit('resolve', target);
  19358. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19359. throw new python.Error(`Unsupported node target type '${target}'.`);
  19360. }
  19361. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19362. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19363. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19364. this.deserialize_outputs(serialized_node, fx_node);
  19365. } else {
  19366. throw new python.Error(`Unsupported node target type '${target}'.`);
  19367. }
  19368. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19369. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19370. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19371. }
  19372. }
  19373. deserialize_input_spec(i) {
  19374. if (i.type === 'user_input') {
  19375. return new torch.export.graph_signature.InputSpec(
  19376. torch.export.graph_signature.InputKind.USER_INPUT,
  19377. this.deserialize_argument_spec(i.user_input.arg),
  19378. null);
  19379. } else if (i.type === 'parameter') {
  19380. return new torch.export.graph_signature.InputSpec(
  19381. torch.export.graph_signature.InputKind.PARAMETER,
  19382. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19383. i.parameter.parameter_name,
  19384. );
  19385. } else if (i.type === 'buffer') {
  19386. return new torch.export.graph_signature.InputSpec(
  19387. torch.export.graph_signature.InputKind.BUFFER,
  19388. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19389. i.buffer.buffer_name,
  19390. i.buffer.persistent,
  19391. );
  19392. } else if (i.type === 'tensor_constant') {
  19393. return new torch.export.graph_signature.InputSpec(
  19394. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19395. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19396. i.tensor_constant.tensor_constant_name);
  19397. } else if (i.type === 'custom_obj') {
  19398. return new torch.export.graph_signature.InputSpec(
  19399. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19400. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19401. i.custom_obj.custom_obj_name);
  19402. } else if (i.type === 'token') {
  19403. return new torch.export.graph_signature.InputSpec(
  19404. torch.export.graph_signature.InputKind.TOKEN,
  19405. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19406. null);
  19407. } else if (i.type === 'constant_input') {
  19408. return new torch.export.graph_signature.InputSpec(
  19409. torch.export.graph_signature.InputKind.USER_INPUT,
  19410. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19411. null);
  19412. }
  19413. throw new python.Error(`Unknown input spec ${i}`);
  19414. }
  19415. deserialize_constant_input(inp) {
  19416. if (inp.type === 'as_int') {
  19417. return inp.as_int;
  19418. } else if (inp.type === 'as_float') {
  19419. return inp.as_float;
  19420. } else if (inp.type === 'as_string') {
  19421. return inp.as_string;
  19422. } else if (inp.type === 'as_bool') {
  19423. return inp.as_bool;
  19424. } else if (inp.type === 'as_none') {
  19425. return null;
  19426. }
  19427. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19428. }
  19429. deserialize_output_spec(o) {
  19430. if (o.type === 'user_output') {
  19431. return new torch.export.graph_signature.OutputSpec(
  19432. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19433. this.deserialize_argument_spec(o.user_output.arg),
  19434. null);
  19435. } else if (o.type === 'loss_output') {
  19436. return new torch.export.graph_signature.OutputSpec(
  19437. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19438. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19439. null);
  19440. } else if (o.type === 'buffer_mutation') {
  19441. return new torch.export.graph_signature.OutputSpec(
  19442. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19443. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19444. o.buffer_mutation.buffer_name);
  19445. } else if (o.type === 'gradient_to_parameter') {
  19446. return new torch.export.graph_signature.OutputSpec(
  19447. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19448. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19449. o.gradient_to_parameter.parameter_name);
  19450. } else if (o.type === 'gradient_to_user_input') {
  19451. return new torch.export.graph_signature.OutputSpec(
  19452. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19453. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19454. o.gradient_to_user_input.user_input_name);
  19455. } else if (o.type === 'user_input_mutation') {
  19456. return new torch.export.graph_signature.OutputSpec(
  19457. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19458. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19459. o.user_input_mutation.user_input_name);
  19460. } else if (o.type === 'token') {
  19461. return new torch.export.graph_signature.OutputSpec(
  19462. torch.export.graph_signature.OutputKind.TOKEN,
  19463. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19464. null);
  19465. }
  19466. throw new python.Error(`Unknown output spec ${o}.`);
  19467. }
  19468. deserialize_signature(sig) {
  19469. return new torch.export.graph_signature.ExportGraphSignature(
  19470. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19471. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19472. }
  19473. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19474. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19475. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19476. this.sympy_functions = new Map([
  19477. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19478. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19479. ['Where', torch.utils._sympy.functions.Where],
  19480. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19481. ['Mod', torch.utils._sympy.functions.Mod],
  19482. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19483. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19484. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19485. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19486. ['LShift', torch.utils._sympy.functions.LShift],
  19487. ['RShift', torch.utils._sympy.functions.RShift],
  19488. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19489. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19490. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19491. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19492. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19493. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19494. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19495. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19496. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19497. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19498. ['Identity', torch.utils._sympy.functions.Identity],
  19499. ]);
  19500. this.symbol_name_to_symbol = new Map();
  19501. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19502. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19503. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19504. /*
  19505. if symbol_name_to_range:
  19506. for k, vr in symbol_name_to_range.items():
  19507. lower = int(vr.lower)
  19508. if vr.upper >= 2: # max is >= 2, not sym bool range
  19509. lower = max(2, lower)
  19510. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19511. */
  19512. this.example_inputs = null;
  19513. if (example_inputs) {
  19514. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19515. }
  19516. this.deserialize_graph(serialized_graph_module.graph);
  19517. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19518. return {
  19519. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19520. signature: this.signature,
  19521. module_call_graph,
  19522. names_to_symbols: this.symbol_name_to_symbol,
  19523. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19524. constants: this.constants,
  19525. example_inputs: this.example_inputs,
  19526. };
  19527. }
  19528. sync_fx_node(name, fx_node) {
  19529. if (this.serialized_name_to_node.has(name)) {
  19530. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19531. }
  19532. this.serialized_name_to_node.set(name, fx_node);
  19533. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19534. }
  19535. deserialize_sym_op_inputs(inputs) {
  19536. return inputs.map((input) => this.deserialize_input(input.arg));
  19537. }
  19538. deserialize_inputs(target, serialized_node) {
  19539. const schema_args = this._get_schema_from_target(target).arguments;
  19540. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19541. const args = new builtins.list();
  19542. const kwargs = new builtins.dict();
  19543. for (const schema_arg of schema_args) {
  19544. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19545. if (is_positional) {
  19546. args.push(actual_args.get(schema_arg.name));
  19547. } else if (actual_args.has(schema_arg.name)) {
  19548. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19549. }
  19550. }
  19551. return [args, kwargs];
  19552. }
  19553. deserialize_hoo_inputs(inputs) {
  19554. const args = [];
  19555. const kwargs = new builtins.dict();
  19556. for (const input_ of inputs) {
  19557. if (input_.name === '') {
  19558. args.push(this.deserialize_input(input_.arg));
  19559. } else {
  19560. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19561. }
  19562. }
  19563. return [new builtins.tuple(args), kwargs];
  19564. }
  19565. deserialize_input(inp) {
  19566. const value = inp.value;
  19567. const typ_ = inp.type;
  19568. if (typ_ === 'as_none') {
  19569. return null;
  19570. } else if (typ_ === 'as_tensor') {
  19571. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19572. } else if (typ_ === 'as_scalar_type') {
  19573. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19574. } else if (typ_ === 'as_memory_format') {
  19575. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19576. } else if (typ_ === 'as_layout') {
  19577. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19578. } else if (typ_ === 'as_graph') {
  19579. const context = this.save_graph_module();
  19580. context.__enter__();
  19581. this.deserialize_graph(value.graph);
  19582. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19583. context.__exit__(null, null, null);
  19584. this.module.register_module(value.name, submodule);
  19585. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19586. } else if (typ_ === 'as_device') {
  19587. return this.deserialize_device(inp.as_device);
  19588. } else if (typ_ === 'as_int') {
  19589. return inp.as_int;
  19590. } else if (typ_ === 'as_float') {
  19591. return inp.as_float;
  19592. } else if (typ_ === 'as_bool') {
  19593. return inp.as_bool;
  19594. } else if (typ_ === 'as_string') {
  19595. return inp.as_string;
  19596. } else if (typ_ === 'as_sym_int') {
  19597. return this.deserialize_sym_argument(inp.as_sym_int);
  19598. } else if (typ_ === 'as_sym_float') {
  19599. return this.deserialize_sym_argument(inp.as_sym_float);
  19600. } else if (typ_ === 'as_sym_bool') {
  19601. return this.deserialize_sym_argument(inp.as_sym_bool);
  19602. } else if (Array.isArray(value)) {
  19603. if (value.length === 0) {
  19604. return [];
  19605. } else if (typ_ === 'as_tensors') {
  19606. const result = [];
  19607. for (const arg of value) {
  19608. result.push(this.serialized_name_to_node.get(arg.name));
  19609. }
  19610. return result;
  19611. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19612. return Array.from(value);
  19613. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19614. return value.map((arg) => this.deserialize_sym_argument(arg));
  19615. } else if (typ_ === 'as_optional_tensors') {
  19616. const deserialize_optional_tensor_args = (a) => {
  19617. if (a.type === 'as_none') {
  19618. return null;
  19619. } else if (a.type === 'as_tensor') {
  19620. return this.serialized_name_to_node.get(a.value.name);
  19621. }
  19622. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19623. };
  19624. return value.map((item) => deserialize_optional_tensor_args(item));
  19625. }
  19626. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19627. } else if (typ_ === 'as_custom_obj') {
  19628. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19629. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19630. }
  19631. return this.constants[inp.as_custom_obj.name];
  19632. } else if (typ_ === 'as_operator') {
  19633. return this.deserialize_operator(inp.as_operator);
  19634. }
  19635. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19636. }
  19637. deserialize_sym_argument(sym_arg) {
  19638. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19639. if (sym_arg.type === 'as_int') {
  19640. return sym_arg.as_int;
  19641. } else if (sym_arg.type === 'as_name') {
  19642. return this.serialized_name_to_node.get(sym_arg.as_name);
  19643. }
  19644. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19645. if (sym_arg.type === 'as_float') {
  19646. return sym_arg.as_float;
  19647. } else if (sym_arg.type === 'as_name') {
  19648. return this.serialized_name_to_node.get(sym_arg.as_name);
  19649. }
  19650. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19651. if (sym_arg.type === 'as_bool') {
  19652. return sym_arg.as_bool;
  19653. } else if (sym_arg.type === 'as_name') {
  19654. return this.serialized_name_to_node.get(sym_arg.as_name);
  19655. }
  19656. }
  19657. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19658. }
  19659. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19660. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19661. }
  19662. deserialize_outputs(serialized_node, fx_node) {
  19663. if (serialized_node.outputs.length === 0) {
  19664. return;
  19665. }
  19666. if (serialized_node.outputs.length === 1 &&
  19667. serialized_node.outputs[0].type === 'as_tensor') {
  19668. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19669. return;
  19670. } else if (serialized_node.outputs.length === 1 &&
  19671. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19672. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19673. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19674. return;
  19675. }
  19676. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19677. }
  19678. deserialize_multiple_outputs(serialized_node, fx_node) {
  19679. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19680. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19681. let name = '';
  19682. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19683. name = arg.name;
  19684. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19685. name = arg.as_name;
  19686. } else {
  19687. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19688. }
  19689. const individual_output = this.graph.create_node(
  19690. 'call_function',
  19691. operator.getitem,
  19692. new builtins.tuple([fx_node, idx]),
  19693. null,
  19694. name,
  19695. );
  19696. this.sync_fx_node(name, individual_output);
  19697. meta_val.push(this.serialized_name_to_meta.get(name));
  19698. individual_output.meta.update(deserialized_metadata);
  19699. };
  19700. const generate_getitems = (meta_val, fx_node, args) => {
  19701. for (let idx = 0; idx < args.length; idx++) {
  19702. let arg = args[idx];
  19703. if (arg instanceof torch._export.serde.schema.Argument) {
  19704. arg = arg.value;
  19705. }
  19706. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19707. generate_getitem(meta_val, fx_node, arg, idx);
  19708. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19709. const list_output = this.graph.create_node(
  19710. 'call_function',
  19711. operator.getitem,
  19712. (fx_node, idx),
  19713. );
  19714. meta_val.push([]);
  19715. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  19716. list_output.meta.update(deserialized_metadata);
  19717. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  19718. } else {
  19719. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19720. }
  19721. }
  19722. };
  19723. const meta_val = [];
  19724. if (serialized_node.outputs.length === 1) {
  19725. // assert isinstance(serialized_node.outputs[0].value, list)
  19726. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19727. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19728. } else {
  19729. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19730. }
  19731. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19732. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19733. }
  19734. deserialize_metadata(metadata) {
  19735. const ret = new builtins.dict();
  19736. const stack_trace = metadata.get('stack_trace');
  19737. if (stack_trace) {
  19738. ret.set('stack_trace', stack_trace);
  19739. }
  19740. const deserialize_meta_func = (serialized_target) => {
  19741. let module = null;
  19742. let serialized_target_names = [];
  19743. if (serialized_target.startsWith('torch.nn')) {
  19744. module = torch.nn;
  19745. serialized_target_names = serialized_target.split('.').slice(1);
  19746. } else if (serialized_target.startsWith('torch')) {
  19747. module = torch;
  19748. serialized_target_names = serialized_target.split('.').slice(1);
  19749. } else {
  19750. return this.deserialize_operator(serialized_target);
  19751. }
  19752. let target = module;
  19753. for (const name of serialized_target_names) {
  19754. if (!builtins.hasattr(target, name)) {
  19755. return serialized_target;
  19756. }
  19757. target = builtins.getattr(target, name);
  19758. }
  19759. return target;
  19760. };
  19761. const nn_module_stack_str = metadata.get('nn_module_stack');
  19762. if (nn_module_stack_str) {
  19763. const import_nn_module_stack = (key, path, ty) => {
  19764. return [key, [path, ty]];
  19765. };
  19766. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19767. ret.set('nn_module_stack', nn_module_stack);
  19768. }
  19769. const source_fn_st_str = metadata.get('source_fn_stack');
  19770. if (source_fn_st_str) {
  19771. const source_fn_st = [];
  19772. for (const source_fn_str of source_fn_st_str.split(';')) {
  19773. const [name, target_str] = source_fn_str.split(',');
  19774. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19775. }
  19776. ret.set('source_fn_stack', source_fn_st);
  19777. }
  19778. const torch_fn = metadata.get('torch_fn');
  19779. if (torch_fn) {
  19780. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19781. }
  19782. const custom_str = metadata.get('custom');
  19783. if (custom_str) {
  19784. ret.set('custom', JSON.parse(custom_str));
  19785. }
  19786. return ret;
  19787. }
  19788. deserialize_argument_spec(x) {
  19789. if (x.type === 'as_tensor') {
  19790. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19791. } else if (x.type === 'as_sym_int') {
  19792. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19793. } else if (x.type === 'as_custom_obj') {
  19794. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19795. }
  19796. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19797. }
  19798. deserialize_tensor_meta(tensor_meta) {
  19799. try {
  19800. this.fake_tensor_mode.__enter__();
  19801. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  19802. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  19803. const device = this.deserialize_device(tensor_meta.device);
  19804. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19805. return torch.empty_strided(sizes, strides, dtype, null, device);
  19806. } finally {
  19807. this.fake_tensor_mode.__exit__(null, null, null);
  19808. }
  19809. }
  19810. deserialize_script_obj_meta(script_obj_meta) {
  19811. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  19812. }
  19813. _parse_sym_expr(expr_str, hint) {
  19814. const _process_sym_expr = (sym, hint) => {
  19815. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  19816. return sym;
  19817. }
  19818. expr_str = sym.__str__();
  19819. for (const arg of sym.args) {
  19820. this._parse_sym_expr(arg);
  19821. }
  19822. if (this.symbol_name_to_symbol.has(expr_str)) {
  19823. sym = this.symbol_name_to_symbol.get(expr_str);
  19824. } else {
  19825. this.symbol_name_to_symbol.set(expr_str, sym);
  19826. 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])) {
  19827. this.unbacked_symbols.add(sym);
  19828. }
  19829. }
  19830. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  19831. this.shape_env.add_var_to_val(sym, hint);
  19832. }
  19833. const vr = this.symbol_name_to_range.get(expr_str);
  19834. if (vr) {
  19835. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  19836. }
  19837. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  19838. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  19839. }
  19840. return sym;
  19841. };
  19842. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  19843. const expr = sympy.core.sympify.sympify(expr_str, locals);
  19844. return _process_sym_expr(expr, hint);
  19845. }
  19846. deserialize_sym_int(s) {
  19847. const val = s.value;
  19848. let hint = null;
  19849. if (s.type === 'as_expr') {
  19850. if (val.hint === null) {
  19851. hint = null;
  19852. } else {
  19853. // assert val.hint.type == "as_int"
  19854. hint = val.hint.value;
  19855. }
  19856. const sym = this._parse_sym_expr(val.expr_str, hint);
  19857. return this.shape_env.create_symintnode(sym, hint);
  19858. } else if (s.type === 'as_int') {
  19859. // assert type(val) is int
  19860. return val;
  19861. }
  19862. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  19863. }
  19864. deserialize_sym_bool(s) {
  19865. const val = s.value;
  19866. let hint = null;
  19867. if (s.type === 'as_expr') {
  19868. if (val.hint === null) {
  19869. hint = null;
  19870. } else {
  19871. // assert val.hint.type == "as_bool"
  19872. hint = val.hint.value;
  19873. }
  19874. const sym = this._parse_sym_expr(val.expr_str, hint);
  19875. return this.shape_env.create_symboolnode(sym, hint);
  19876. } else if (s.type === 'as_bool') {
  19877. // assert type(val) is bool
  19878. return val;
  19879. }
  19880. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  19881. }
  19882. deserialize_device(d) {
  19883. if (d.index === null) {
  19884. return new torch.device(d.type);
  19885. }
  19886. return new torch.device(d.type, d.index);
  19887. }
  19888. _get_schema_from_target(target) {
  19889. if (target instanceof torch._ops.OpOverload) {
  19890. return target._schema;
  19891. }
  19892. throw new python.Error(`Unsupported schema '${target.name}'.`);
  19893. }
  19894. _is_single_tensor_return(target) {
  19895. const schema = this._get_schema_from_target(target);
  19896. const returns = schema.returns;
  19897. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  19898. }
  19899. });
  19900. this.registerType('torch._export.verifier.Verifier', class {});
  19901. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  19902. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  19903. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  19904. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  19905. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  19906. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  19907. constructor(mod, dynamo_ctx) {
  19908. builtins.object.__setattr__(self, '_orig_mod', mod);
  19909. // this._super_module_initialized = false;
  19910. super();
  19911. // this._super_module_initialized = true;
  19912. this._orig_mod = mod;
  19913. this.dynamo_ctx = dynamo_ctx;
  19914. // this._initialize();
  19915. this.training = this._orig_mod.training;
  19916. }
  19917. });
  19918. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  19919. this.registerType('torch._dynamo.hooks.Hooks', class {});
  19920. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  19921. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  19922. this.registerType('torch._TorchCompileInductorWrapper', class {});
  19923. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  19924. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  19925. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  19926. const module = new types.ModuleType(name);
  19927. execution.register('sys').modules.set(name, module);
  19928. const context = new python.Execution.Context(module, null);
  19929. execution.exec(meta.get('module_src'), context);
  19930. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  19931. const state = meta.get('state');
  19932. if (state) {
  19933. if (obj.__setstate__) {
  19934. obj.__setstate__(state);
  19935. } else {
  19936. for (const [key, value] of state) {
  19937. obj[key] = value;
  19938. }
  19939. }
  19940. }
  19941. return obj;
  19942. });
  19943. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  19944. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  19945. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  19946. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  19947. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  19948. this.registerType('torch.device', class {
  19949. constructor(type, index) {
  19950. this.type = type;
  19951. this.index = index ? index : null;
  19952. }
  19953. __str__() {
  19954. return this.index === null ? this.type : `${this.type}:${this.index}`;
  19955. }
  19956. toString() {
  19957. const index = this.index === null ? '' : `, index=${this.index}`;
  19958. return `device(type='${this.type}'${index})`;
  19959. }
  19960. });
  19961. this.registerType('torch.memory_format', class {
  19962. constructor(name) {
  19963. this.name = name;
  19964. }
  19965. __str__() {
  19966. return `torch.${this.name}`;
  19967. }
  19968. toString() {
  19969. return this.__str__();
  19970. }
  19971. });
  19972. this.registerType('torch.dtype', class {
  19973. constructor(scalar_type, name, itemsize) {
  19974. this._scalar_type = scalar_type;
  19975. this._name = name;
  19976. this._itemsize = itemsize;
  19977. }
  19978. scalar_type() {
  19979. return this._scalar_type;
  19980. }
  19981. itemsize() {
  19982. return this._itemsize;
  19983. }
  19984. __reduce__() {
  19985. return this._name;
  19986. }
  19987. __str__() {
  19988. return `torch.${this._name}`;
  19989. }
  19990. toString() {
  19991. return this.__str__();
  19992. }
  19993. });
  19994. this.registerType('torch.layout', class {
  19995. constructor(name) {
  19996. this._name = name;
  19997. }
  19998. __str__() {
  19999. return `torch.${this._name}`;
  20000. }
  20001. toString() {
  20002. return this.__str__();
  20003. }
  20004. });
  20005. this.registerType('torch.qscheme', class {
  20006. constructor(name) {
  20007. this._name = name;
  20008. }
  20009. __str__() {
  20010. return this._name;
  20011. }
  20012. toString() {
  20013. return this.__str__();
  20014. }
  20015. });
  20016. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20017. __setstate__(state) {
  20018. [this.hooks_dict_ref, this.id] = state;
  20019. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20020. }
  20021. });
  20022. this.registerType('torch.storage._StorageBase', class {
  20023. constructor(size, dtype) {
  20024. this._size = size;
  20025. this._dtype = dtype;
  20026. this._device = null;
  20027. }
  20028. get device() {
  20029. return this._device;
  20030. }
  20031. get dtype() {
  20032. return this._dtype;
  20033. }
  20034. element_size() {
  20035. return this._dtype.element_size;
  20036. }
  20037. size() {
  20038. return this._size;
  20039. }
  20040. get data() {
  20041. return this._cdata;
  20042. }
  20043. _set_cdata(data) {
  20044. const length = this.size() * this.dtype.itemsize();
  20045. if (length !== data.length) {
  20046. throw new python.Error('Typed storage data size mismatch.');
  20047. }
  20048. this._cdata = data;
  20049. }
  20050. _set_from_file(unpickler) {
  20051. const buffer = unpickler.read(8);
  20052. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20053. if (size !== this.size()) {
  20054. throw new python.Error('Typed storage size mismatch.');
  20055. }
  20056. const itemsize = this.dtype.itemsize();
  20057. const data = unpickler.stream(itemsize * size);
  20058. this._set_cdata(data);
  20059. }
  20060. static _new_with_file(unpickler) {
  20061. const buffer = unpickler.read(8);
  20062. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20063. const storage = new this(size);
  20064. const itemsize = storage.dtype.itemsize();
  20065. const data = unpickler.stream(itemsize * size);
  20066. storage._set_cdata(data);
  20067. return storage;
  20068. }
  20069. });
  20070. this.registerType('torch.storage.UntypedStorage', class {
  20071. constructor(size) {
  20072. this._size = size;
  20073. }
  20074. _set_cdata(data) {
  20075. if (this._size !== data.length) {
  20076. throw new python.Error('Untyped storage data size mismatch.');
  20077. }
  20078. this._cdata = data;
  20079. }
  20080. });
  20081. this.registerType('torch.storage.TypedStorage', class {
  20082. constructor(...args) {
  20083. if (args.length === 0) {
  20084. this._size = 0;
  20085. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20086. [this._size] = args;
  20087. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20088. if (args[3] instanceof torch.device) {
  20089. [this._size, this.dtype, , this._device] = args;
  20090. } else {
  20091. [this._size, this.dtype] = args;
  20092. }
  20093. } else {
  20094. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20095. }
  20096. }
  20097. get device() {
  20098. return this._device;
  20099. }
  20100. get dtype() {
  20101. return this._dtype;
  20102. }
  20103. set dtype(value) {
  20104. this._dtype = value;
  20105. }
  20106. element_size() {
  20107. return this._dtype.element_size;
  20108. }
  20109. size() {
  20110. return this._size;
  20111. }
  20112. get data() {
  20113. return this._cdata;
  20114. }
  20115. _set_cdata(data) {
  20116. const length = this.size() * this.dtype.itemsize();
  20117. if (length !== data.length) {
  20118. throw new python.Error('Storage data size mismatch.');
  20119. }
  20120. this._cdata = data;
  20121. }
  20122. _set_from_file(unpickler) {
  20123. const buffer = unpickler.read(8);
  20124. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20125. if (size !== this.size()) {
  20126. throw new python.Error('Storage size mismatch.');
  20127. }
  20128. const itemsize = this.dtype.itemsize();
  20129. const data = unpickler.stream(itemsize * size);
  20130. this._set_cdata(data);
  20131. }
  20132. static _new_with_file(unpickler) {
  20133. const buffer = unpickler.read(8);
  20134. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20135. const storage = new this(size);
  20136. const itemsize = storage.dtype.itemsize();
  20137. const data = unpickler.stream(itemsize * size);
  20138. storage._set_cdata(data);
  20139. return storage;
  20140. }
  20141. });
  20142. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20143. });
  20144. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20145. constructor(...args) {
  20146. // eslint-disable-next-line no-constructor-return
  20147. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20148. }
  20149. });
  20150. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20151. constructor(...args) {
  20152. // eslint-disable-next-line no-constructor-return
  20153. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20154. }
  20155. });
  20156. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20157. constructor(...args) {
  20158. // eslint-disable-next-line no-constructor-return
  20159. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20160. }
  20161. });
  20162. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20163. constructor(...args) {
  20164. // eslint-disable-next-line no-constructor-return
  20165. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20166. }
  20167. });
  20168. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20169. constructor(...args) {
  20170. // eslint-disable-next-line no-constructor-return
  20171. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20172. }
  20173. });
  20174. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20175. constructor(...args) {
  20176. // eslint-disable-next-line no-constructor-return
  20177. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20178. }
  20179. });
  20180. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20181. constructor(...args) {
  20182. // eslint-disable-next-line no-constructor-return
  20183. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20184. }
  20185. });
  20186. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20187. constructor(...args) {
  20188. // eslint-disable-next-line no-constructor-return
  20189. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20190. }
  20191. });
  20192. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20193. constructor(...args) {
  20194. // eslint-disable-next-line no-constructor-return
  20195. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20196. }
  20197. });
  20198. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20199. constructor(...args) {
  20200. // eslint-disable-next-line no-constructor-return
  20201. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20202. }
  20203. });
  20204. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20205. constructor(...args) {
  20206. // eslint-disable-next-line no-constructor-return
  20207. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20208. }
  20209. });
  20210. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20211. constructor(...args) {
  20212. // eslint-disable-next-line no-constructor-return
  20213. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20214. }
  20215. });
  20216. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20217. constructor(...args) {
  20218. // eslint-disable-next-line no-constructor-return
  20219. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20220. }
  20221. });
  20222. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20223. constructor(...args) {
  20224. // eslint-disable-next-line no-constructor-return
  20225. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20226. }
  20227. });
  20228. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20229. constructor(...args) {
  20230. // eslint-disable-next-line no-constructor-return
  20231. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20232. }
  20233. });
  20234. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20235. constructor(...args) {
  20236. // eslint-disable-next-line no-constructor-return
  20237. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20238. }
  20239. });
  20240. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20241. constructor(...args) {
  20242. // eslint-disable-next-line no-constructor-return
  20243. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20244. }
  20245. });
  20246. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20247. constructor(...args) {
  20248. // eslint-disable-next-line no-constructor-return
  20249. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20250. }
  20251. });
  20252. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20253. constructor(...args) {
  20254. // eslint-disable-next-line
  20255. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20256. }
  20257. });
  20258. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20259. constructor(...args) {
  20260. // eslint-disable-next-line no-constructor-return
  20261. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20262. }
  20263. });
  20264. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20265. constructor(...args) {
  20266. // eslint-disable-next-line no-constructor-return
  20267. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20268. }
  20269. });
  20270. this.registerType('torch.Size', class extends Array {
  20271. constructor(size) {
  20272. super(size.length);
  20273. for (let i = 0; i < size.length; i++) {
  20274. this[i] = size[i];
  20275. }
  20276. }
  20277. __len__() {
  20278. return this.length;
  20279. }
  20280. });
  20281. this.registerType('torch._C.TensorMeta', class {
  20282. });
  20283. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20284. });
  20285. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20286. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20287. super();
  20288. if (storage) {
  20289. this._storage = storage;
  20290. }
  20291. if (shape !== null && shape !== undefined) {
  20292. this._shape = shape;
  20293. }
  20294. if (dtype) {
  20295. this._dtype = dtype;
  20296. }
  20297. this._layout = layout || torch.strided;
  20298. if (device) {
  20299. this._device = device;
  20300. }
  20301. if (requires_grad !== undefined) {
  20302. this.requires_grad = requires_grad;
  20303. }
  20304. }
  20305. get device() {
  20306. if (this._device !== undefined) {
  20307. return this._device;
  20308. }
  20309. return this.storage().device;
  20310. }
  20311. get dtype() {
  20312. if (this._dtype !== undefined) {
  20313. return this._dtype;
  20314. }
  20315. if (this._layout === torch.sparse_coo) {
  20316. return this._values.dtype;
  20317. }
  20318. return this.storage().dtype;
  20319. }
  20320. get shape() {
  20321. return this._shape;
  20322. }
  20323. get layout() {
  20324. return this._layout;
  20325. }
  20326. get values() {
  20327. if (this._layout === torch.sparse_coo) {
  20328. return this._values;
  20329. }
  20330. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20331. }
  20332. get indices() {
  20333. if (this._layout === torch.sparse_coo) {
  20334. return this._indices;
  20335. }
  20336. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20337. }
  20338. get is_quantized() {
  20339. return this.__quantized__ === true;
  20340. }
  20341. get is_nested() {
  20342. return this.__nested__ === true;
  20343. }
  20344. get is_sparse() {
  20345. return this.layout !== torch.strided;
  20346. }
  20347. size() {
  20348. return this._shape;
  20349. }
  20350. storage() {
  20351. return this._storage;
  20352. }
  20353. storage_offset() {
  20354. return this._storage_offset;
  20355. }
  20356. stride() {
  20357. return this._stride;
  20358. }
  20359. resize_(shape) {
  20360. this._shape = shape;
  20361. }
  20362. __len__() {
  20363. return this._shape[0];
  20364. }
  20365. __setstate__(state) {
  20366. switch (state.length) {
  20367. case 3:
  20368. break;
  20369. case 4:
  20370. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20371. break;
  20372. case 5:
  20373. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20374. break;
  20375. default:
  20376. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20377. }
  20378. }
  20379. set_(source, storage_offset, size, stride) {
  20380. this._storage = source;
  20381. this._storage_offset = storage_offset;
  20382. this._shape = size;
  20383. this._stride = stride;
  20384. }
  20385. __bool__() {
  20386. return true;
  20387. }
  20388. __int__() {
  20389. const storage = this.storage();
  20390. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20391. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20392. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20393. return view.getBigInt64(0, true);
  20394. }
  20395. return NaN;
  20396. }
  20397. __float__() {
  20398. const storage = this.storage();
  20399. if (storage && storage.dtype.__reduce__() === 'float32') {
  20400. if (storage.size() !== undefined && storage.data.length === 4) {
  20401. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20402. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20403. return view.getFloat32(0, true);
  20404. }
  20405. }
  20406. return NaN;
  20407. }
  20408. __str__() {
  20409. return 'tensor(...)';
  20410. }
  20411. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20412. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20413. t.__setstate__([null, storage_offset, size, stride]);
  20414. return t;
  20415. }
  20416. });
  20417. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20418. constructor(data, requires_grad) {
  20419. super();
  20420. this.data = data || new torch.Tensor([]);
  20421. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20422. }
  20423. });
  20424. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20425. });
  20426. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20427. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20428. super();
  20429. this.allow_fallback_kernels = allow_fallback_kernels;
  20430. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20431. this.shape_env = shape_env;
  20432. this.enter_stack = [];
  20433. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20434. }
  20435. __enter__() {
  20436. const prev_only_lift_cpu_tensors = null;
  20437. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20438. if (this === maybe_prev_fake_mode) {
  20439. torch._C._set_dispatch_mode(this);
  20440. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20441. } else {
  20442. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20443. return super.__enter__();
  20444. }
  20445. return this;
  20446. }
  20447. __exit__(exc_type, exc_value, traceback) {
  20448. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20449. if (live) {
  20450. super.__exit__(exc_type, exc_value, traceback);
  20451. if (maybe_prev_fake_mode !== null) {
  20452. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20453. }
  20454. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20455. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20456. }
  20457. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20458. }
  20459. }
  20460. });
  20461. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20462. constructor(requires_grad /*, device, dtype */) {
  20463. super(undefined, requires_grad);
  20464. }
  20465. });
  20466. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20467. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20468. constructor(...args) {
  20469. // eslint-disable-next-line no-constructor-return
  20470. return new torch.Tensor(...args);
  20471. }
  20472. });
  20473. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20474. constructor(...args) {
  20475. // eslint-disable-next-line no-constructor-return
  20476. return new torch.Tensor(...args);
  20477. }
  20478. });
  20479. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20480. constructor(...args) {
  20481. // eslint-disable-next-line no-constructor-return
  20482. return new torch.Tensor(...args);
  20483. }
  20484. });
  20485. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20486. constructor(...args) {
  20487. // eslint-disable-next-line no-constructor-return
  20488. return new torch.Tensor(...args);
  20489. }
  20490. });
  20491. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20492. constructor(...args) {
  20493. // eslint-disable-next-line no-constructor-return
  20494. return new torch.Tensor(...args);
  20495. }
  20496. });
  20497. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20498. constructor(...args) {
  20499. // eslint-disable-next-line no-constructor-return
  20500. return new torch.Tensor(...args);
  20501. }
  20502. });
  20503. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20504. constructor(...args) {
  20505. // eslint-disable-next-line no-constructor-return
  20506. return new torch.Tensor(...args);
  20507. }
  20508. });
  20509. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20510. constructor(...args) {
  20511. // eslint-disable-next-line no-constructor-return
  20512. return new torch.Tensor(...args);
  20513. }
  20514. });
  20515. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20516. constructor(...args) {
  20517. // eslint-disable-next-line no-constructor-return
  20518. return new torch.Tensor(...args);
  20519. }
  20520. });
  20521. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20522. constructor(...args) {
  20523. // eslint-disable-next-line no-constructor-return
  20524. return new torch.Tensor(...args);
  20525. }
  20526. });
  20527. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20528. constructor(...args) {
  20529. // eslint-disable-next-line no-constructor-return
  20530. return new torch.Tensor(...args);
  20531. }
  20532. });
  20533. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20534. constructor(...args) {
  20535. // eslint-disable-next-line no-constructor-return
  20536. return new torch.Tensor(...args);
  20537. }
  20538. });
  20539. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20540. constructor(...args) {
  20541. // eslint-disable-next-line no-constructor-return
  20542. return new torch.Tensor(...args);
  20543. }
  20544. });
  20545. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20546. constructor(...args) {
  20547. // eslint-disable-next-line no-constructor-return
  20548. return new torch.Tensor(...args);
  20549. }
  20550. });
  20551. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20552. constructor(...args) {
  20553. // eslint-disable-next-line no-constructor-return
  20554. return new torch.Tensor(...args);
  20555. }
  20556. });
  20557. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20558. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20559. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20560. constructor(...args) {
  20561. // eslint-disable-next-line no-constructor-return
  20562. return new torch.Tensor(...args);
  20563. }
  20564. });
  20565. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20566. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20567. constructor(...args) {
  20568. // eslint-disable-next-line no-constructor-return
  20569. return new torch.Tensor(...args);
  20570. }
  20571. });
  20572. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20573. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20574. constructor(...args) {
  20575. // eslint-disable-next-line no-constructor-return
  20576. return new torch.Tensor(...args);
  20577. }
  20578. });
  20579. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20580. this.registerType('torchao.dtypes.utils.Layout', class {});
  20581. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20582. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20583. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20584. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20585. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20586. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20587. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20588. this.registerType('torch.SymBool', class {
  20589. constructor(node) {
  20590. this.node = node;
  20591. }
  20592. });
  20593. this.registerType('torch.SymInt', class {
  20594. constructor(node) {
  20595. this.node = node;
  20596. }
  20597. toString() {
  20598. return this.node.__str__();
  20599. }
  20600. });
  20601. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20602. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20603. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20604. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20605. /* eslint-disable no-multi-assign */
  20606. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20607. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20608. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20609. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20610. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20611. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20612. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20613. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20614. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20615. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20616. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20617. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20618. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20619. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20620. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20621. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20622. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20623. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20624. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20625. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20626. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20627. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20628. torch.bits8 = new torch.dtype(21, 'bits8');
  20629. torch.bits16 = new torch.dtype(22, 'bits16');
  20630. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20631. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20632. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20633. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20634. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  20635. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  20636. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  20637. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20638. ['uint8', 'BYTE'],
  20639. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20640. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20641. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20642. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20643. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20644. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20645. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20646. torch.channels_last = new torch.memory_format('channels_last');
  20647. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20648. torch.preserve_format = new torch.memory_format('preserve_format');
  20649. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20650. ['contiguous_format', 'ContiguousFormat'],
  20651. ['channels_last', 'ChannelsLast'],
  20652. ['channels_last_3d', 'ChannelsLast3d'],
  20653. ['preserve_format', 'PreserveFormat']
  20654. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20655. /* eslint-enable no-multi-assign */
  20656. torch.strided = new torch.layout('strided');
  20657. torch.sparse_coo = new torch.layout('sparse_coo');
  20658. torch.sparse_csr = new torch.layout('sparse_csr');
  20659. torch.sparse_csc = new torch.layout('sparse_csc');
  20660. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20661. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20662. torch._mkldnn = new torch.layout('_mkldnn');
  20663. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20664. ['sparse_coo', 'SparseCoo'],
  20665. ['sparse_csr', 'SparseCsr'],
  20666. ['sparse_csc', 'SparseCsc'],
  20667. ['sparse_bsr', 'SparseBsr'],
  20668. ['sparse_bsc', 'SparseBsc'],
  20669. ['_mkldnn', '_mkldnn'],
  20670. ['strided', 'Strided'],
  20671. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20672. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20673. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20674. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20675. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20676. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20677. torch.inf = this.register('math').inf;
  20678. this.registerFunction('fastcore.basics._using_attr');
  20679. this.registerFunction('fastcore.imports.noop');
  20680. this.registerType('fastcore.basics.fastuple', class {});
  20681. this.registerType('fastcore.basics.GetAttr', class {});
  20682. this.registerType('fastcore.dispatch._TypeDict', class {});
  20683. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20684. this.registerType('fastcore.foundation.L', class {});
  20685. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20686. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20687. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20688. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20689. this.registerType('fastai.basic_train.Learner', class {});
  20690. this.registerType('fastai.basic_train.Recorder', class {});
  20691. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20692. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20693. return self.invoke(cls, [tensor]);
  20694. });
  20695. this.registerFunction('fastai.torch_core.trainable_params');
  20696. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20697. const tensor = self.invoke(type, [func(...args)]);
  20698. Object.assign(tensor, dict);
  20699. return tensor;
  20700. });
  20701. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20702. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20703. constructor(x) {
  20704. super();
  20705. Object.assign(this, x);
  20706. }
  20707. });
  20708. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20709. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20710. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20711. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20712. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20713. this.registerFunction('fastai.torch_core.uniform');
  20714. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20715. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20716. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20717. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20718. this.registerFunction('fastai.callback.hook._hook_inner');
  20719. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20720. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20721. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20722. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20723. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20724. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20725. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20726. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20727. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20728. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20729. this.registerType('fastai.data.core.Datasets', class {});
  20730. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20731. this.registerType('fastai.data.core.FilteredBase', class {});
  20732. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20733. this.registerType('fastai.data.core.TfmdLists', class {});
  20734. this.registerType('fastai.data.load._FakeLoader', class {});
  20735. this.registerFunction('fastai.data.load._wif');
  20736. this.registerType('fastai.data.transforms.Categorize', class {});
  20737. this.registerType('fastai.data.transforms.Category', class {});
  20738. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20739. this.registerType('fastai.data.transforms.ColReader', class {});
  20740. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20741. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20742. this.registerType('fastai.data.transforms.Normalize', class {});
  20743. this.registerType('fastai.data.transforms.parent_label', class {});
  20744. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20745. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20746. this.registerType('fastai.data.transforms.ToTensor', class {});
  20747. this.registerType('fastai.data_block.CategoryList', class {});
  20748. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20749. this.registerType('fastai.imports.noop', class {});
  20750. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20751. this.registerType('fastai.layers.ConvLayer', class {});
  20752. this.registerType('fastai.layers.Embedding', class {});
  20753. this.registerType('fastai.layers.Flatten', class {});
  20754. this.registerType('fastai.layers.FlattenedLoss', class {});
  20755. this.registerType('fastai.layers.LinBnDrop', class {});
  20756. this.registerType('fastai.layers.MergeLayer', class {});
  20757. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20758. this.registerType('fastai.layers.ResBlock', class {});
  20759. this.registerType('fastai.layers.SelfAttention', class {});
  20760. this.registerType('fastai.layers.SigmoidRange', class {});
  20761. this.registerType('fastai.layers.TimeDistributed', class {});
  20762. this.registerType('fastai.layers.ToTensorBase', class {});
  20763. this.registerType('fastai.learner._ConstantFunc', class {});
  20764. this.registerType('fastai.learner.Metric', class {});
  20765. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20766. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20767. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20768. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20769. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20770. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20771. this.registerType('fastai.learner.Recorder', class {});
  20772. this.registerType('fastai.losses.BaseLoss', class {});
  20773. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20774. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20775. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20776. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20777. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20778. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20779. this.registerType('fastai.metrics.Dice', class {});
  20780. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20781. this.registerFunction('fastai.metrics._rmse');
  20782. this.registerFunction('fastai.metrics.accuracy');
  20783. this.registerFunction('fastai.metrics.accuracy_multi');
  20784. this.registerFunction('fastai.metrics.foreground_acc');
  20785. this.registerFunction('fastai.metrics.mse');
  20786. this.registerFunction('fastai.metrics.error_rate');
  20787. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  20788. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  20789. this.registerFunction('fastai.optimizer.Adam');
  20790. this.registerFunction('fastai.optimizer.adam_step');
  20791. this.registerFunction('fastai.optimizer.average_grad');
  20792. this.registerFunction('fastai.optimizer.average_sqr_grad');
  20793. this.registerFunction('fastai.optimizer.RAdam');
  20794. this.registerFunction('fastai.optimizer.step_stat');
  20795. this.registerFunction('fastai.optimizer.weight_decay');
  20796. this.registerType('fastai.tabular.core.Categorify', class {});
  20797. this.registerType('fastai.tabular.core.FillMissing', class {});
  20798. this.registerType('fastai.tabular.core.FillStrategy', class {});
  20799. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  20800. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  20801. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  20802. this.registerType('fastai.tabular.core.Tabular', class {});
  20803. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  20804. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  20805. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  20806. this.registerType('fastai.tabular.model.TabularModel', class {});
  20807. this.registerFunction('fastai.vision.augment.aug_transforms');
  20808. this.registerFunction('fastai.vision.augment.dihedral_mat');
  20809. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  20810. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  20811. this.registerType('fastai.vision.augment._WarpCoord', class {});
  20812. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  20813. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  20814. this.registerType('fastai.vision.augment.Brightness', class {});
  20815. this.registerType('fastai.vision.augment.flip_mat', class {});
  20816. this.registerType('fastai.vision.augment.Flip', class {});
  20817. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  20818. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  20819. this.registerType('fastai.vision.augment.Resize', class {});
  20820. this.registerType('fastai.vision.augment.rotate_mat', class {});
  20821. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  20822. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  20823. this.registerType('fastai.vision.augment.zoom_mat', class {});
  20824. this.registerType('fastai.vision.core.PILImage', class {});
  20825. this.registerType('fastai.vision.core.PILMask', class {});
  20826. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  20827. this.registerType('fastai.vision.data.ImageList', class {});
  20828. this.registerType('fastai.vision.data.ImageItemList', class {});
  20829. this.registerType('fastai.vision.image.Image', class {});
  20830. this.registerType('fastai.vision.image.RandTransform', class {});
  20831. this.registerType('fastai.vision.image.TfmCrop', class {});
  20832. this.registerFunction('fastai.vision.learner._resnet_split');
  20833. this.registerFunction('fastai.vision.learner.default_split');
  20834. this.registerFunction('fastai.vision.learner.default_split');
  20835. this.registerType('fastai.vision.learner.TimmBody', class {});
  20836. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  20837. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  20838. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  20839. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  20840. this.registerFunction('fastai.vision.transform._crop_pad');
  20841. }
  20842. exec(code , context) {
  20843. const ast = this.ast;
  20844. const program = ast.parse(code, '', null, null);
  20845. if (!program) {
  20846. throw new python.Error("Module '?' parse error.");
  20847. }
  20848. this.block(program.body, context);
  20849. }
  20850. debug(/* file */) {
  20851. }
  20852. source(file) {
  20853. if (this._sources.has(file)) {
  20854. return this._sources.get(file);
  20855. }
  20856. return null;
  20857. }
  20858. read(file) {
  20859. const buffer = this.source(file);
  20860. if (buffer) {
  20861. const debug = this.debug(file);
  20862. return this.parse(file, buffer, debug);
  20863. }
  20864. return null;
  20865. }
  20866. parse(filename, buffer, debug) {
  20867. const ast = this.ast;
  20868. const source = this._utf8Decoder.decode(buffer);
  20869. const program = ast.parse(source, filename, null, debug);
  20870. if (!program) {
  20871. throw new python.Error(`Module '${filename}' parse error.`);
  20872. }
  20873. return program;
  20874. }
  20875. import(name, current, level) {
  20876. if (level) {
  20877. let bits = current.split('.');
  20878. if (bits.length < level) {
  20879. throw new python.Error('Invalid relative import beyond top-level package.');
  20880. }
  20881. bits = bits.slice(0, bits.length - level);
  20882. const base = bits.join('.');
  20883. name = name ? [base, name].join('.') : base;
  20884. }
  20885. const index = name.lastIndexOf('.');
  20886. let parent = null;
  20887. let child = null;
  20888. if (index > 0) {
  20889. parent = name.substring(0, index);
  20890. child = name.substring(index + 1);
  20891. this.import(parent);
  20892. }
  20893. if (!this._modules.has(name)) {
  20894. const module = this._registry.get(name) || new this.builtins.module(name);
  20895. module.__package__ = name;
  20896. this._modules.set(name, module);
  20897. const path = name.split('.').join('/');
  20898. module.__path__ = [path];
  20899. const file = `${path}.py`;
  20900. const program = this.read(file);
  20901. if (program) {
  20902. module.__file__ = file;
  20903. for (const [name, value] of Object.entries(this.builtins)) {
  20904. switch (name) {
  20905. case '__class__':
  20906. case '__package__':
  20907. case '__module__':
  20908. case '__name__':
  20909. case '__path__':
  20910. case '__file__':
  20911. break;
  20912. default:
  20913. module[name] = value;
  20914. break;
  20915. }
  20916. }
  20917. const context = new python.Execution.Context(module, null);
  20918. if (name !== 'builtins') {
  20919. context.set('__builtins__', this._modules.get('builtins'));
  20920. }
  20921. this.block(program.body, context);
  20922. }
  20923. if (parent) {
  20924. const parent_module = this._modules.get(parent);
  20925. parent_module[child] = module;
  20926. }
  20927. }
  20928. return this._modules.get(name);
  20929. }
  20930. __import__(name, globals, locals, fromlist, level) {
  20931. let module = null;
  20932. level = level || 0;
  20933. if (level === 0) {
  20934. module = this.import(name);
  20935. } else {
  20936. globals = globals || {};
  20937. let current = globals.__package__;
  20938. if (!current) {
  20939. const spec = globals.__spec__;
  20940. if (spec) {
  20941. current = spec.parent;
  20942. } else {
  20943. const name = globals.__name__;
  20944. const bits = name.split('.');
  20945. bits.pop();
  20946. current = bits.join('.');
  20947. }
  20948. }
  20949. module = this.import(name, current, level);
  20950. }
  20951. if (!fromlist) {
  20952. if (level === 0) {
  20953. return this.import(name.split('.')[0]);
  20954. } else if (name) {
  20955. throw new python.Error(`Unsupported relative import '${name}'.`);
  20956. // cut_off = len(name) - len(name.partition('.')[0])
  20957. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  20958. }
  20959. } else if (module.__path__) {
  20960. const handle_fromlist = (module, fromlist, recursive) => {
  20961. for (const name of fromlist) {
  20962. if (name === '*') {
  20963. if (!recursive && module.__all__) {
  20964. handle_fromlist(module, module.__all__, true);
  20965. }
  20966. } else if (!module[name]) {
  20967. this.import(`${module.__name__}.${name}`);
  20968. }
  20969. }
  20970. return module;
  20971. };
  20972. handle_fromlist(module, fromlist);
  20973. }
  20974. return module;
  20975. }
  20976. module(name) {
  20977. return this._modules.get(name);
  20978. }
  20979. resolve(name) {
  20980. const index = name.lastIndexOf('.');
  20981. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  20982. const moduleName = index === -1 ? '' : name.substring(0, index);
  20983. const module = this.import(moduleName);
  20984. let type = module ? module[memberName] : null;
  20985. if (!type) {
  20986. if (!this._unresolved.has(name)) {
  20987. const moduleName = name.split('.').shift();
  20988. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  20989. this.emit('resolve', name);
  20990. }
  20991. const type = this._createType(name, class {});
  20992. this._unresolved.set(name, type);
  20993. }
  20994. type = this._unresolved.get(name);
  20995. }
  20996. return type;
  20997. }
  20998. invoke(target, args) {
  20999. const builtins = this.builtins;
  21000. if (typeof target === 'string') {
  21001. target = this.resolve(target);
  21002. }
  21003. if (target) {
  21004. if (target.__class__ === builtins.type) {
  21005. if (target.prototype && target.prototype.__class__ === target) {
  21006. return Reflect.construct(target, args);
  21007. }
  21008. const obj = Object.create(target);
  21009. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21010. obj.__init__(...args);
  21011. }
  21012. return obj;
  21013. } else if (target.__class__ === builtins.function) {
  21014. if (target.__call__) {
  21015. return target.__call__(args);
  21016. }
  21017. return target(...args);
  21018. }
  21019. }
  21020. throw new python.Error('Unsupported invoke target.');
  21021. }
  21022. call(target, name, args, keywords, context) {
  21023. const builtins = this.builtins;
  21024. const callTarget = this.target(target, context);
  21025. const callArguments = args.map((arg) => this.expression(arg, context));
  21026. if (!callTarget || (name !== null && !callTarget[name])) {
  21027. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21028. name = null;
  21029. callArguments.shift();
  21030. } else {
  21031. const targetName = `${this.identifier(target)}.${name}`;
  21032. throw new python.Error(`Unknown function '${targetName}'.`);
  21033. }
  21034. }
  21035. const func = name ? callTarget[name] : callTarget;
  21036. if (func.__class__ === builtins.type) {
  21037. if (func.prototype && func.prototype.__class__ === func) {
  21038. return Reflect.construct(func, callArguments);
  21039. }
  21040. const obj = Object.create(func);
  21041. obj.__class__ = func;
  21042. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21043. obj.__init__(...args);
  21044. }
  21045. return obj;
  21046. }
  21047. if (func.__class__ === builtins.function) {
  21048. if (func.__call__) {
  21049. return func.__call__(callArguments);
  21050. }
  21051. }
  21052. if (func.__class__ === builtins.method) {
  21053. if (func.__call__) {
  21054. return func.__call__([callTarget].concat(callArguments));
  21055. }
  21056. }
  21057. if (typeof func === 'function') {
  21058. return func.apply(callTarget, callArguments);
  21059. }
  21060. throw new python.Error('Unsupported call expression.');
  21061. }
  21062. apply(method, args, context) {
  21063. const locals = Array.prototype.slice.call(args);
  21064. context = new python.Execution.Context(context.globals, {});
  21065. args = method.args.posonlyargs.concat(method.args.args);
  21066. const default_pos = args.length - method.args.defaults.length;
  21067. for (let i = 0; i < method.args.args.length; i++) {
  21068. const arg = method.args.args[i];
  21069. let value = null;
  21070. if (locals.length > 0) {
  21071. value = locals.shift();
  21072. } else if (i >= default_pos) {
  21073. value = this.expression(method.args.defaults[i - default_pos], context);
  21074. } else {
  21075. throw new python.Error('Missing required positional argument.');
  21076. }
  21077. context.set(arg.arg, value);
  21078. }
  21079. return this.block(method.body, context);
  21080. }
  21081. block(statements, context) {
  21082. statements = Array.prototype.slice.call(statements);
  21083. while (statements.length > 0) {
  21084. const stmt = statements.shift();
  21085. const value = this.statement(stmt, context);
  21086. if (value !== undefined) {
  21087. return value;
  21088. }
  21089. }
  21090. return undefined;
  21091. }
  21092. statement(stmt, context) {
  21093. const ast = this.ast;
  21094. const builtins = this.builtins;
  21095. if (stmt instanceof ast.Pass) {
  21096. // pass
  21097. } else if (stmt instanceof ast.Constant) {
  21098. // pass
  21099. } else if (stmt instanceof ast.Return) {
  21100. return this.expression(stmt.value, context);
  21101. } else if (stmt instanceof ast.FunctionDef) {
  21102. const module = context.get('__name__');
  21103. /* eslint-disable consistent-this */
  21104. const self = this;
  21105. /* eslint-enable consistent-this */
  21106. const parent = context.get('__class__');
  21107. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21108. const func = {
  21109. __class__: type,
  21110. __globals__: context,
  21111. __module__: module,
  21112. __name__: stmt.name,
  21113. __code__: stmt,
  21114. __call__(args) {
  21115. return self.apply(this.__code__, args, this.__globals__);
  21116. }
  21117. };
  21118. context.set(stmt.name, func);
  21119. } else if (stmt instanceof ast.ClassDef) {
  21120. const bases = stmt.bases.map((base) => this.base(base, context));
  21121. if (bases.length > 1) {
  21122. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21123. }
  21124. const base = bases.length === 1 ? bases[0] : null;
  21125. const name = `${context.get('__name__')}.${stmt.name}`;
  21126. const value = this._createType(name, base ? class extends base {} : class {});
  21127. value.__bases__ = bases;
  21128. context.set(stmt.name, value);
  21129. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21130. } else if (stmt instanceof ast.AnnAssign) {
  21131. const target = this.identifier(stmt.target, context);
  21132. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21133. } else if (stmt instanceof ast.Assign) {
  21134. this.expression(stmt, context);
  21135. } else if (stmt instanceof ast.If) {
  21136. const test = this.expression(stmt.test, context);
  21137. if (test === true || test) {
  21138. const value = this.block(stmt.body, context);
  21139. if (value !== undefined) {
  21140. return value;
  21141. }
  21142. } else if (test === false) {
  21143. if (stmt.orelse) {
  21144. const value = this.block(stmt.orelse, context);
  21145. if (value !== undefined) {
  21146. return value;
  21147. }
  21148. }
  21149. } else {
  21150. throw new python.Error('Unsupported condition.');
  21151. }
  21152. } else if (stmt instanceof ast.For) {
  21153. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21154. const range = this.expression(stmt.iter, context);
  21155. const variable = stmt.target;
  21156. for (const current of range) {
  21157. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21158. const value = this.block(stmt.body.statements, context);
  21159. if (value !== undefined) {
  21160. return value;
  21161. }
  21162. }
  21163. } else {
  21164. throw new python.Error("Unsupported 'for' statement.");
  21165. }
  21166. } else if (stmt instanceof ast.While) {
  21167. const test = this.expression(stmt.test, context);
  21168. if (test) {
  21169. const value = this.block(stmt.body.statements, context);
  21170. if (value !== undefined) {
  21171. return value;
  21172. }
  21173. }
  21174. } else if (stmt instanceof ast.With) {
  21175. const items = [];
  21176. for (const item of stmt.items) {
  21177. items.push(this.expression(item.context_expr, context));
  21178. }
  21179. for (const item of items) {
  21180. if (item.__enter__ && item.__enter__.__call__) {
  21181. item.__enter__.__call__([item]);
  21182. }
  21183. }
  21184. const value = this.block(stmt.body, context);
  21185. for (const item of items) {
  21186. if (item.__exit__ && item.__exit__.__call__) {
  21187. item.__exit__.__call__([item]);
  21188. }
  21189. }
  21190. if (value !== undefined) {
  21191. return value;
  21192. }
  21193. } else if (stmt instanceof ast.Expr) {
  21194. this.expression(stmt.value, context);
  21195. } else if (stmt instanceof ast.Import) {
  21196. for (const alias of stmt.names) {
  21197. let module = this.__import__(alias.name, context);
  21198. if (alias.asname) {
  21199. const bits = alias.name.split('.').reverse();
  21200. bits.pop();
  21201. while (bits.length > 0) {
  21202. module = module[bits.pop()];
  21203. }
  21204. context.set(alias.asname, module);
  21205. } else {
  21206. context.set(alias.name.split('.')[0], module);
  21207. }
  21208. }
  21209. } else if (stmt instanceof ast.ImportFrom) {
  21210. const fromlist = stmt.names.map((name) => name.name);
  21211. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21212. for (const entry of stmt.names) {
  21213. const name = entry.name;
  21214. const asname = entry.asname ? entry.asname : null;
  21215. if (!module[name]) {
  21216. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21217. }
  21218. context.set(asname ? asname : name, module[name]);
  21219. }
  21220. } else {
  21221. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21222. }
  21223. return undefined;
  21224. }
  21225. expression(expr, context) {
  21226. const ast = this.ast;
  21227. const builtins = this.builtins;
  21228. const typing = this.typing;
  21229. const self = context.get('self');
  21230. switch (expr.__class__.__name__) {
  21231. case 'Assign': {
  21232. const [target] = expr.targets;
  21233. if (target instanceof ast.Name) {
  21234. const value = this.expression(expr.value, context);
  21235. context.set(target.id, value);
  21236. return undefined;
  21237. } else if (target instanceof ast.Subscript) {
  21238. if (target.value instanceof ast.Name &&
  21239. target.slice instanceof ast.List &&
  21240. target.slice.elts.length === 1) {
  21241. const index = this.expression(target.slice.elts[0], context);
  21242. const id = target.value.id;
  21243. if (id === '__annotations__') {
  21244. context.set(id, context.get(id) || {});
  21245. }
  21246. const obj = context.get(id);
  21247. const value = this.expression(expr.value, context);
  21248. if (obj instanceof Map) {
  21249. obj.set(index, value);
  21250. } else {
  21251. obj[index] = value;
  21252. }
  21253. return undefined;
  21254. }
  21255. } else if (target instanceof ast.Attribute) {
  21256. const obj = this.expression(target.value, context);
  21257. const value = this.expression(expr.value, context);
  21258. obj[target.attr] = value;
  21259. return undefined;
  21260. } else if (target instanceof ast.Tuple) {
  21261. context.target.push(target.elts);
  21262. const value = this.expression(expr.value, context);
  21263. context.target.pop();
  21264. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21265. if (target.elts.length < value.length) {
  21266. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21267. }
  21268. if (target.elts.length > value.length) {
  21269. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21270. }
  21271. for (let i = 0; i < value.length; i++) {
  21272. context.set(target.elts[i].id, value[i]);
  21273. }
  21274. return undefined;
  21275. }
  21276. }
  21277. break;
  21278. }
  21279. case 'List': {
  21280. return expr.elts.map((expr) => this.expression(expr, context));
  21281. }
  21282. case 'Constant': {
  21283. return expr.value;
  21284. }
  21285. case 'Subscript': {
  21286. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21287. const id = expr.value.id;
  21288. if (context.get(id)) {
  21289. const index = this.expression(expr.slice, context);
  21290. const target = context.get(id);
  21291. if (target instanceof Map) {
  21292. return target.get(index);
  21293. }
  21294. return target[index < 0 ? target.length + index : index];
  21295. }
  21296. }
  21297. const value = this.expression(expr.value, context);
  21298. if (value && expr.slice instanceof ast.List &&
  21299. (value.__class__ === typing._TupleType ||
  21300. value.__class__ === typing._SpecialGenericAlias ||
  21301. value.__class__ === typing._SpecialForm)) {
  21302. const type = { ...value };
  21303. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21304. return type;
  21305. }
  21306. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21307. const index = this.expression(expr.slice.elts[0], context);
  21308. if (value instanceof Map) {
  21309. return value.get(index);
  21310. }
  21311. return value[index < 0 ? value.length + index : index];
  21312. }
  21313. break;
  21314. }
  21315. case 'Attribute': {
  21316. const value = this.target(expr.value, context);
  21317. return value[expr.attr];
  21318. }
  21319. case 'Call': {
  21320. const func = expr.func;
  21321. if (func instanceof ast.Attribute) {
  21322. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21323. }
  21324. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21325. }
  21326. case 'Name': {
  21327. const id = expr.id;
  21328. if (id === 'self') {
  21329. return self;
  21330. }
  21331. const type = (value) => {
  21332. return value &&
  21333. (value.__class__ === builtins.type ||
  21334. value.__class__ === typing._TupleType ||
  21335. value.__class__ === typing._SpecialGenericAlias ||
  21336. value.__class__ === typing._SpecialForm);
  21337. };
  21338. const builtin = builtins[id];
  21339. if (type(builtin)) {
  21340. return builtin;
  21341. }
  21342. const value = context.get(id);
  21343. if (value === undefined) {
  21344. const value = typing[id];
  21345. if (type(value)) {
  21346. return value;
  21347. }
  21348. }
  21349. return value;
  21350. }
  21351. case 'Tuple': {
  21352. return expr.elts.map((expr) => this.expression(expr, context));
  21353. }
  21354. case 'Dict': {
  21355. const dict = {};
  21356. for (let i = 0; i < expr.keys.length; i++) {
  21357. const key = this.expression(expr.keys[i], context);
  21358. const value = this.expression(expr.values[i], context);
  21359. dict[key] = value;
  21360. }
  21361. return dict;
  21362. }
  21363. case 'UnaryOp': {
  21364. if (expr.op instanceof ast.USub) {
  21365. return -this.expression(expr.operand, context);
  21366. }
  21367. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21368. }
  21369. case 'binary': {
  21370. switch (expr.op) {
  21371. case '==': {
  21372. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21373. }
  21374. default: {
  21375. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21376. }
  21377. }
  21378. }
  21379. default: {
  21380. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21381. }
  21382. }
  21383. return undefined;
  21384. }
  21385. base(expr, context) {
  21386. return this.expression(expr, context);
  21387. }
  21388. identifier(expr) {
  21389. const ast = this.ast;
  21390. if (expr instanceof ast.Name) {
  21391. return expr.id;
  21392. }
  21393. if (expr instanceof ast.Attribute) {
  21394. return `${this.identifier(expr.value)}.${expr.attr}`;
  21395. }
  21396. return null;
  21397. }
  21398. target(expr, context) {
  21399. const ast = this.ast;
  21400. let current = expr;
  21401. let path = [];
  21402. for (;;) {
  21403. if (current instanceof ast.Attribute) {
  21404. path.push(current.attr);
  21405. current = current.value;
  21406. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21407. path.push(current.id);
  21408. break;
  21409. } else {
  21410. path = null;
  21411. break;
  21412. }
  21413. }
  21414. if (path) {
  21415. let target = null;
  21416. for (let i = path.length - 1; i >= 0; i--) {
  21417. const name = path[i];
  21418. if (target) {
  21419. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21420. } else {
  21421. target = context.get(name);
  21422. }
  21423. if (!target) {
  21424. break;
  21425. }
  21426. }
  21427. if (!target) {
  21428. path.reverse();
  21429. const name = path.join('.');
  21430. const file = `${path.join('/')}.py`;
  21431. if (this._sources.has(file)) {
  21432. target = this.import(name);
  21433. } else {
  21434. target = this.resolve(name);
  21435. }
  21436. }
  21437. return target;
  21438. }
  21439. return this.expression(expr, context);
  21440. }
  21441. add(name, source) {
  21442. this._sources.set(name, source);
  21443. }
  21444. on(event, listener) {
  21445. const value = this._events.get(event) || [];
  21446. value.push(listener);
  21447. this._events.set(event, value);
  21448. }
  21449. emit(event, ...args) {
  21450. if (this._events.has(event)) {
  21451. for (const callback of this._events.get(event)) {
  21452. callback(this, ...args);
  21453. }
  21454. }
  21455. }
  21456. register(name, value) {
  21457. if (!this._registry.has(name)) {
  21458. value = value || new (this._registry.get('builtins').module)(name);
  21459. this._registry.set(name, value);
  21460. let current = name;
  21461. for (;;) {
  21462. const index = current.lastIndexOf('.');
  21463. if (index === -1) {
  21464. break;
  21465. }
  21466. const child = current.substring(index + 1);
  21467. current = current.substring(0, index);
  21468. if (!value.__module__) {
  21469. value.__module__ = current;
  21470. }
  21471. const parent = this.register(current);
  21472. parent[child] = value;
  21473. value = parent;
  21474. }
  21475. }
  21476. return this._registry.get(name);
  21477. }
  21478. registerFunction(name, value) {
  21479. const builtins = this.builtins;
  21480. const index = name.lastIndexOf('.');
  21481. if (!value) {
  21482. value = () => {
  21483. throw new python.Error(`'${name}' is not implemented.`);
  21484. };
  21485. }
  21486. value.__class__ = builtins.function;
  21487. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21488. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21489. const module = this.register(value.__module__);
  21490. if (module[name]) {
  21491. throw new python.Error(`Function '${name}' is already registered.`);
  21492. }
  21493. module[value.__name__] = value;
  21494. return value;
  21495. }
  21496. registerOperator(name, value) {
  21497. this._operators.set(name, value);
  21498. }
  21499. _createType(name, value) {
  21500. const builtins = this.builtins;
  21501. const index = name.lastIndexOf('.');
  21502. value.__class__ = builtins.type;
  21503. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21504. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21505. value.prototype.__class__ = value;
  21506. return value;
  21507. }
  21508. registerType(name, value) {
  21509. value = this._createType(name, value);
  21510. const parts = name.split('.');
  21511. const memberName = parts.pop();
  21512. const moduleName = parts.join('.');
  21513. const module = this.register(moduleName);
  21514. if (module[memberName]) {
  21515. throw new python.Error(`Class '${memberName}' is already registered.`);
  21516. }
  21517. module[memberName] = value;
  21518. return value;
  21519. }
  21520. };
  21521. python.Execution.Context = class {
  21522. constructor(globals, locals) {
  21523. this.globals = globals;
  21524. this.locals = locals;
  21525. }
  21526. set(name, value) {
  21527. if (this.locals) {
  21528. this.locals[name] = value;
  21529. } else {
  21530. this.globals[name] = value;
  21531. }
  21532. }
  21533. get(name) {
  21534. if (this.locals && name in this.locals) {
  21535. return this.locals[name];
  21536. }
  21537. if (name in this.globals) {
  21538. return this.globals[name];
  21539. }
  21540. return undefined;
  21541. }
  21542. get target() {
  21543. this._target = this._target || [];
  21544. return this._target;
  21545. }
  21546. };
  21547. python.BinaryReader = class {
  21548. constructor(buffer) {
  21549. this._buffer = buffer;
  21550. this._length = buffer.length;
  21551. this._position = 0;
  21552. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21553. this._utf8Decoder = new TextDecoder('utf-8');
  21554. this._asciiDecoder = new TextDecoder('ascii');
  21555. }
  21556. get position() {
  21557. return this._position;
  21558. }
  21559. get length() {
  21560. return this._length;
  21561. }
  21562. seek(position) {
  21563. this._position = position >= 0 ? position : this._length + position;
  21564. if (this._position > this._buffer.length) {
  21565. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21566. }
  21567. }
  21568. skip(offset) {
  21569. this._position += offset;
  21570. if (this._position > this._buffer.length) {
  21571. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21572. }
  21573. }
  21574. stream(length) {
  21575. const buffer = this.read(length);
  21576. return new python.BinaryReader(buffer);
  21577. }
  21578. peek(length) {
  21579. const position = this._position;
  21580. length = length === undefined ? this._length - this._position : length;
  21581. this.skip(length);
  21582. const end = this._position;
  21583. this.skip(-length);
  21584. if (position === 0 && length === this._length) {
  21585. return this._buffer;
  21586. }
  21587. return this._buffer.subarray(position, end);
  21588. }
  21589. read(length) {
  21590. const position = this._position;
  21591. length = length === undefined ? this._length - this._position : length;
  21592. this.skip(length);
  21593. if (position === 0 && length === this._length) {
  21594. return this._buffer;
  21595. }
  21596. return this._buffer.subarray(position, this._position);
  21597. }
  21598. byte() {
  21599. const position = this._position;
  21600. this.skip(1);
  21601. return this._view.getUint8(position);
  21602. }
  21603. uint16() {
  21604. const position = this._position;
  21605. this.skip(2);
  21606. return this._view.getUint16(position, true);
  21607. }
  21608. int32() {
  21609. const position = this._position;
  21610. this.skip(4);
  21611. return this._view.getInt32(position, true);
  21612. }
  21613. uint32() {
  21614. const position = this._position;
  21615. this.skip(4);
  21616. return this._view.getUint32(position, true);
  21617. }
  21618. int64() {
  21619. const position = this._position;
  21620. this.skip(8);
  21621. return this._view.getBigInt64(position, true);
  21622. }
  21623. float64() {
  21624. const position = this._position;
  21625. this.skip(8);
  21626. return this._view.getFloat64(position, false);
  21627. }
  21628. string(size, encoding) {
  21629. const data = this.read(size);
  21630. return (encoding === 'utf-8') ?
  21631. this._utf8Decoder.decode(data) :
  21632. this._asciiDecoder.decode(data);
  21633. }
  21634. line() {
  21635. const index = this._buffer.indexOf(0x0A, this._position);
  21636. if (index === -1) {
  21637. throw new python.Error('Could not find end of line.');
  21638. }
  21639. const size = index - this._position;
  21640. const text = this.string(size, 'ascii');
  21641. this.skip(1);
  21642. return text;
  21643. }
  21644. };
  21645. python.StreamReader = class {
  21646. constructor(stream) {
  21647. this._stream = stream;
  21648. this._length = stream.length;
  21649. this._position = 0;
  21650. this._utf8Decoder = new TextDecoder('utf-8');
  21651. this._asciiDecoder = new TextDecoder('ascii');
  21652. }
  21653. get position() {
  21654. return this._position;
  21655. }
  21656. get length() {
  21657. return this._length;
  21658. }
  21659. seek(position) {
  21660. this._stream.seek(position);
  21661. this._position = this._stream.position;
  21662. }
  21663. skip(offset) {
  21664. this._position += offset;
  21665. if (this._position > this._length) {
  21666. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21667. }
  21668. }
  21669. stream(length) {
  21670. this._stream.seek(this._position);
  21671. this.skip(length);
  21672. return this._stream.stream(length);
  21673. }
  21674. peek(length) {
  21675. this._stream.seek(this._position);
  21676. return this._stream.peek(length);
  21677. }
  21678. read(length) {
  21679. this._stream.seek(this._position);
  21680. this.skip(length);
  21681. return this._stream.read(length);
  21682. }
  21683. byte() {
  21684. const position = this._fill(1);
  21685. return this._view.getUint8(position);
  21686. }
  21687. uint16() {
  21688. const position = this._fill(2);
  21689. return this._view.getUint16(position, true);
  21690. }
  21691. int32() {
  21692. const position = this._fill(4);
  21693. return this._view.getInt32(position, true);
  21694. }
  21695. uint32() {
  21696. const position = this._fill(4);
  21697. return this._view.getUint32(position, true);
  21698. }
  21699. int64() {
  21700. const position = this._fill(8);
  21701. return this._view.getBigInt64(position, true);
  21702. }
  21703. float64() {
  21704. const position = this._fill(8);
  21705. return this._view.getFloat64(position, false);
  21706. }
  21707. string(size, encoding) {
  21708. const data = this.read(size);
  21709. return (encoding === 'utf-8') ?
  21710. this._utf8Decoder.decode(data) :
  21711. this._asciiDecoder.decode(data);
  21712. }
  21713. line() {
  21714. let position = this._fill(0);
  21715. let index = this._buffer.indexOf(0x0A, position);
  21716. if (index === -1) {
  21717. const size = Math.min(0x20000000, this._stream.length - this._position);
  21718. this._fill(size);
  21719. this.skip(-size);
  21720. position = this._fill(0);
  21721. index = this._buffer.indexOf(0x0A, position);
  21722. if (index === -1) {
  21723. throw new python.Error('Could not find end of line.');
  21724. }
  21725. }
  21726. const size = index - position;
  21727. const text = this.string(size, 'ascii');
  21728. this.skip(1);
  21729. return text;
  21730. }
  21731. _fill(length) {
  21732. if (this._position + length > this._length) {
  21733. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21734. }
  21735. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21736. this._offset = this._position;
  21737. this._stream.seek(this._offset);
  21738. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21739. this._buffer = this._stream.read(size);
  21740. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21741. }
  21742. const position = this._position;
  21743. this._position += length;
  21744. return position - this._offset;
  21745. }
  21746. };
  21747. python.Error = class extends Error {
  21748. constructor(message) {
  21749. super(message);
  21750. this.name = 'Python Error';
  21751. }
  21752. };
  21753. export const Execution = python.Execution;