python.js 987 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Execution = class {
  4. constructor(sources) {
  5. const self = this;
  6. const execution = self;
  7. this._sources = sources || new Map();
  8. this._events = new Map();
  9. this._utf8Decoder = new TextDecoder('utf-8');
  10. this._unresolved = new Map();
  11. const dict = class extends Map {
  12. constructor(items) {
  13. super();
  14. if (items) {
  15. if (items instanceof Map) {
  16. items = Array.from(items);
  17. } else if (!Array.isArray(items)) {
  18. items = Object.entries(items);
  19. }
  20. for (const [name, value] of items) {
  21. this.__setitem__(name, value);
  22. }
  23. }
  24. }
  25. __contains__(key) {
  26. return this.has(key);
  27. }
  28. __setitem__(key, value) {
  29. this.set(key, value);
  30. }
  31. __getitem__(key) {
  32. return this.get(key);
  33. }
  34. __delitem__(key) {
  35. this.delete(key);
  36. }
  37. get(key, defaultValue) {
  38. return super.get(key) || defaultValue;
  39. }
  40. setdefault(key, defaultValue) {
  41. if (this.has(key)) {
  42. return this.get(key);
  43. }
  44. const value = defaultValue || null;
  45. this.set(key, value);
  46. return value;
  47. }
  48. pop(key) {
  49. if (this.__contains__(key)) {
  50. const v = this.__getitem__(key);
  51. this.__delitem__(key);
  52. return v;
  53. }
  54. return null;
  55. }
  56. items() {
  57. return Array.from(this);
  58. }
  59. update(other) {
  60. for (const [key, value] of other) {
  61. this.set(key, value);
  62. }
  63. }
  64. };
  65. this._modules = new dict();
  66. this._registry = new Map();
  67. const module = class {
  68. constructor(name) {
  69. this.__name__ = name;
  70. }
  71. };
  72. const builtins = this.register('builtins', new module('builtins'));
  73. this.builtins = builtins;
  74. this._registry.set('__builtin__', builtins);
  75. this.registerType('builtins.type', class {
  76. constructor(...args) {
  77. if (args.length === 1) {
  78. const [obj] = args;
  79. if (obj === null) {
  80. /* eslint-disable no-constructor-return */
  81. return builtins.NoneType;
  82. /* eslint-enable no-constructor-return */
  83. }
  84. if (obj && obj.__class__) {
  85. /* eslint-disable no-constructor-return */
  86. return obj.__class__;
  87. /* eslint-enable no-constructor-return */
  88. }
  89. throw new python.Error(`Unknown type '${obj}'`);
  90. }
  91. if (args.length === 3) {
  92. const [name, bases, body] = args;
  93. const cls = bases.length > 0 ? class extends bases[0] {} : class {};
  94. execution.registerType(name, cls);
  95. for (const [key, value] of body) {
  96. cls[key] = value;
  97. }
  98. /* eslint-disable no-constructor-return */
  99. return cls;
  100. /* eslint-enable no-constructor-return */
  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. 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. this.register('torch.storage');
  167. this.register('torch.nn.parameter');
  168. this.register('torch.ops');
  169. this.register('torch._ops');
  170. this.register('torch.ops.torchvision');
  171. this.register('torch.ops.torchaudio');
  172. this.register('torch.ops._caffe2');
  173. this.register('torchvision');
  174. this.register('__torch__');
  175. const sys = this.register('sys');
  176. sys.modules = this._modules;
  177. this.register('xgboost');
  178. this.registerType('ast.AST', class {});
  179. this.registerType('ast.mod', class extends ast.AST {});
  180. this.registerType('ast.expr', class extends ast.AST {});
  181. this.registerType('ast.unaryop', class extends ast.AST {});
  182. this.registerType('ast.binop', class extends ast.AST {});
  183. this.registerType('ast.operator', class extends ast.AST {});
  184. this.registerType('ast.boolop', class extends ast.AST {});
  185. this.registerType('ast.cmpop', class extends ast.AST {});
  186. this.registerType('ast.stmt', class extends ast.AST {});
  187. this.registerType('ast.excepthandler', class extends ast.AST {});
  188. this.registerType('ast.keyword', class extends ast.AST {
  189. constructor(arg, value) {
  190. super();
  191. this.arg = arg;
  192. this.value = value;
  193. }
  194. });
  195. this.registerType('ast.alias', class extends ast.AST {
  196. constructor(name, asname) {
  197. super();
  198. this.name = name;
  199. this.asname = asname;
  200. }
  201. });
  202. this.registerType('ast.Name', class extends ast.expr {
  203. constructor(id, ctx) {
  204. super();
  205. this.id = id;
  206. if (ctx) {
  207. this.ctx = ctx;
  208. }
  209. }
  210. });
  211. this.registerType('ast.Constant', class extends ast.expr {
  212. constructor(value, type) {
  213. super();
  214. this.value = value;
  215. this.type = type || null;
  216. }
  217. });
  218. this.registerType('ast.Ellipsis', class extends ast.Constant {
  219. constructor() {
  220. super(builtins.ellipsis);
  221. }
  222. });
  223. this.registerType('ast.Starred', class extends ast.expr {
  224. constructor(value, ctx) {
  225. super();
  226. this.value = value;
  227. if (ctx) {
  228. this.ctx = ctx;
  229. }
  230. }
  231. });
  232. this.registerType('ast.List', class extends ast.expr {
  233. constructor(elts, ctx) {
  234. super();
  235. this.elts = elts;
  236. if (ctx) {
  237. this.ctx = ctx;
  238. }
  239. }
  240. });
  241. this.registerType('ast.Set', class extends ast.expr {
  242. constructor(elts) {
  243. super();
  244. this.elts = elts;
  245. }
  246. });
  247. this.registerType('ast.Tuple', class extends ast.expr {
  248. constructor(elts, ctx) {
  249. super();
  250. this.elts = elts;
  251. if (ctx) {
  252. this.ctx = ctx;
  253. }
  254. }
  255. });
  256. this.registerType('ast.Dict', class extends ast.expr {
  257. constructor(keys, values) {
  258. super();
  259. this.keys = keys;
  260. this.values = values;
  261. }
  262. });
  263. this.registerType('ast.ListComp', class extends ast.expr {
  264. constructor(elt, generators) {
  265. super();
  266. this.elt = elt;
  267. this.generators = generators;
  268. }
  269. });
  270. this.registerType('ast.SetComp', class extends ast.expr {
  271. constructor(elt, generators) {
  272. super();
  273. this.elt = elt;
  274. this.generators = generators;
  275. }
  276. });
  277. this.registerType('ast.GeneratorExp', class extends ast.expr {
  278. constructor(elt, generators) {
  279. super();
  280. this.elt = elt;
  281. this.generators = generators;
  282. }
  283. });
  284. this.registerType('ast.DictComp', class extends ast.expr {
  285. constructor(key, value, generators) {
  286. super();
  287. this.key = key;
  288. this.value = value;
  289. this.generators = generators;
  290. }
  291. });
  292. this.registerType('ast.comprehension', class extends ast.AST {
  293. constructor(target, iter, ifs, is_async) {
  294. super();
  295. this.target = target;
  296. this.iter = iter;
  297. this.ifs = ifs;
  298. this.is_async = is_async;
  299. }
  300. });
  301. this.registerType('ast.Subscript', class extends ast.expr {
  302. constructor(value, slice, ctx) {
  303. super();
  304. this.value = value;
  305. this.slice = slice;
  306. if (ctx) {
  307. this.ctx = ctx;
  308. }
  309. }
  310. });
  311. this.registerType('ast.Slice', class extends ast.expr {
  312. constructor(lower, upper, step) {
  313. super();
  314. this.lower = lower;
  315. this.upper = upper;
  316. this.step = step;
  317. }
  318. });
  319. this.registerType('ast.UnaryOp', class extends ast.expr {
  320. constructor(op, operand) {
  321. super();
  322. this.op = op;
  323. this.operand = operand;
  324. }
  325. });
  326. this.registerType('ast.UAdd', class extends ast.unaryop {});
  327. this.registerType('ast.USub', class extends ast.unaryop {});
  328. this.registerType('ast.Not', class extends ast.unaryop {});
  329. this.registerType('ast.Invert', class extends ast.unaryop {});
  330. this.registerType('ast.BinOp', class extends ast.expr {
  331. constructor(left, op, right) {
  332. super();
  333. this.left = left;
  334. this.op = op;
  335. this.right = right;
  336. }
  337. });
  338. this.registerType('ast.Add', class extends ast.operator {});
  339. this.registerType('ast.Sub', class extends ast.operator {});
  340. this.registerType('ast.Mult', class extends ast.operator {});
  341. this.registerType('ast.Div', class extends ast.operator {});
  342. this.registerType('ast.FloorDiv', class extends ast.operator {});
  343. this.registerType('ast.Mod', class extends ast.operator {});
  344. this.registerType('ast.Pow', class extends ast.operator {});
  345. this.registerType('ast.LShift', class extends ast.operator {});
  346. this.registerType('ast.RShift', class extends ast.operator {});
  347. this.registerType('ast.BitOr', class extends ast.operator {});
  348. this.registerType('ast.BitXor', class extends ast.operator {});
  349. this.registerType('ast.BitAnd', class extends ast.operator {});
  350. this.registerType('ast.MatMult', class extends ast.operator {});
  351. this.registerType('ast.BoolOp', class extends ast.expr {
  352. constructor(op, values) {
  353. super();
  354. this.op = op;
  355. this.values = values;
  356. }
  357. });
  358. this.registerType('ast.And', class extends ast.boolop {});
  359. this.registerType('ast.Or', class extends ast.boolop {});
  360. this.registerType('ast.Compare', class extends ast.expr {
  361. constructor(left, ops, comparators) {
  362. super();
  363. this.left = left;
  364. this.ops = ops;
  365. this.comparators = comparators;
  366. }
  367. });
  368. this.registerType('ast.Eq', class extends ast.cmpop {});
  369. this.registerType('ast.NotEq', class extends ast.cmpop {});
  370. this.registerType('ast.Lt', class extends ast.cmpop {});
  371. this.registerType('ast.LtE', class extends ast.cmpop {});
  372. this.registerType('ast.Gt', class extends ast.cmpop {});
  373. this.registerType('ast.GtE', class extends ast.cmpop {});
  374. this.registerType('ast.Is', class extends ast.cmpop {});
  375. this.registerType('ast.IsNot', class extends ast.cmpop {});
  376. this.registerType('ast.In', class extends ast.cmpop {});
  377. this.registerType('ast.NotIn', class extends ast.cmpop {});
  378. this.registerType('ast.Call', class extends ast.expr {
  379. constructor(func, args, keywords) {
  380. super();
  381. this.func = func;
  382. this.args = args;
  383. this.keywords = keywords || [];
  384. }
  385. });
  386. this.registerType('ast.Attribute', class extends ast.expr {
  387. constructor(value, attr, ctx) {
  388. super();
  389. this.value = value;
  390. this.attr = attr;
  391. if (ctx) {
  392. this.ctx = ctx;
  393. }
  394. }
  395. });
  396. this.registerType('ast.Lambda', class extends ast.expr {
  397. constructor(args, body) {
  398. super();
  399. this.args = args;
  400. this.body = body;
  401. }
  402. });
  403. this.registerType('ast.IfExp', class extends ast.expr {
  404. constructor(test, body, orelse) {
  405. super();
  406. this.test = test;
  407. this.body = body;
  408. this.orelse = orelse;
  409. }
  410. });
  411. this.registerType('ast.NamedExpr', class extends ast.expr {
  412. constructor(target, value) {
  413. super();
  414. this.target = target;
  415. this.value = value;
  416. }
  417. });
  418. this.registerType('ast.Yield', class extends ast.expr {
  419. constructor(value) {
  420. super();
  421. this.value = value;
  422. }
  423. });
  424. this.registerType('ast.YieldFrom', class extends ast.expr {
  425. constructor(value) {
  426. super();
  427. this.value = value;
  428. }
  429. });
  430. this.registerType('ast.Expr', class extends ast.stmt {
  431. constructor(value) {
  432. super();
  433. this.value = value;
  434. }
  435. });
  436. this.registerType('ast.Assign', class extends ast.stmt {
  437. constructor(targets, value, ctx) {
  438. super();
  439. this.targets = targets;
  440. this.value = value;
  441. if (ctx) {
  442. this.ctx = ctx;
  443. }
  444. }
  445. });
  446. this.registerType('ast.AnnAssign', class extends ast.stmt {
  447. constructor(target, annotation, value, simple) {
  448. super();
  449. this.target = target;
  450. this.annotation = annotation;
  451. this.value = value;
  452. this.simple = simple;
  453. }
  454. });
  455. this.registerType('ast.AugAssign', class extends ast.stmt {
  456. constructor(target, op, value) {
  457. super();
  458. this.target = target;
  459. this.op = op;
  460. this.value = value;
  461. }
  462. });
  463. this.registerType('ast.If', class extends ast.stmt {
  464. constructor(test, body, orelse) {
  465. super();
  466. this.test = test;
  467. this.body = body;
  468. this.orelse = orelse;
  469. }
  470. });
  471. this.registerType('ast.For', class extends ast.stmt {
  472. constructor(target, iter, body, orelse /*, type_comment */) {
  473. super();
  474. this.target = target;
  475. this.iter = iter;
  476. this.body = body;
  477. this.orelse = orelse;
  478. }
  479. });
  480. this.registerType('ast.While', class extends ast.stmt {
  481. constructor(test, body, orelse /*, type_comment */) {
  482. super();
  483. this.test = test;
  484. this.body = body;
  485. this.orelse = orelse;
  486. }
  487. });
  488. this.registerType('ast.Del', class extends ast.stmt {
  489. constructor(targets) {
  490. super();
  491. this.targets = targets;
  492. }
  493. });
  494. this.registerType('ast.Return', class extends ast.stmt {
  495. constructor(value) {
  496. super();
  497. this.value = value;
  498. }
  499. });
  500. this.registerType('ast.Try', class extends ast.stmt {
  501. constructor(body, handlers, orelse, finalbody) {
  502. super();
  503. this.body = body;
  504. this.handlers = handlers;
  505. this.orelse = orelse;
  506. this.finalbody = finalbody;
  507. }
  508. });
  509. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  510. constructor(type, name, body) {
  511. super();
  512. this.type_ = type;
  513. this.name = name;
  514. this.body = body;
  515. }
  516. });
  517. this.registerType('ast.ClassDef', class extends ast.stmt {
  518. constructor(name, bases, keywords, body, decorator_list, type_params) {
  519. super();
  520. this.name = name;
  521. this.bases = bases;
  522. this.keywords = keywords;
  523. this.body = body;
  524. this.decorator_list = decorator_list;
  525. this.type_params = type_params;
  526. }
  527. });
  528. this.registerType('ast.FunctionDef', class extends ast.stmt {
  529. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  530. super();
  531. this.name = name;
  532. this.args = args;
  533. this.body = body;
  534. this.decorator_list = decorator_list;
  535. this.returns = returns;
  536. this.type_comment = type_comment;
  537. this.type_params = type_params;
  538. }
  539. });
  540. this.registerType('ast.arguments', class extends ast.AST {
  541. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  542. super();
  543. this.posonlyargs = posonlyargs;
  544. this.args = args;
  545. this.vararg = vararg;
  546. this.kwonlyargs = kwonlyargs;
  547. this.kw_defaults = kw_defaults;
  548. this.kwarg = kwarg;
  549. this.defaults = defaults;
  550. }
  551. });
  552. this.registerType('ast.arg', class extends ast.AST {
  553. constructor(arg, annotation, type_comment) {
  554. super();
  555. this.arg = arg;
  556. this.annotation = annotation;
  557. this.type_comment = type_comment;
  558. }
  559. });
  560. this.registerType('ast.Import', class extends ast.stmt {
  561. constructor(names) {
  562. super();
  563. this.names = names;
  564. }
  565. });
  566. this.registerType('ast.ImportFrom', class extends ast.stmt {
  567. constructor(module, names, level) {
  568. super();
  569. this.module = module;
  570. this.names = names;
  571. this.level = level;
  572. }
  573. });
  574. this.registerType('ast.Assert', class extends ast.stmt {
  575. constructor(test, msg) {
  576. super();
  577. this.test = test;
  578. this.msg = msg;
  579. }
  580. });
  581. this.registerType('ast.Raise', class extends ast.stmt {
  582. constructor(exc, cause) {
  583. super();
  584. this.exc = exc;
  585. this.cause = cause;
  586. }
  587. });
  588. this.registerType('ast.With', class extends ast.stmt {
  589. constructor(items, body, type_comment) {
  590. super();
  591. this.items = items;
  592. this.body = body;
  593. this.type_comment = type_comment;
  594. }
  595. });
  596. this.registerType('ast.withitem', class extends ast.AST {
  597. constructor(context_expr, optional_vars) {
  598. super();
  599. this.context_expr = context_expr;
  600. this.optional_vars = optional_vars;
  601. }
  602. });
  603. this.registerType('ast.Global', class extends ast.stmt {
  604. constructor(names) {
  605. super();
  606. this.names = names;
  607. }
  608. });
  609. this.registerType('ast.Nonlocal', class extends ast.stmt {
  610. constructor(names) {
  611. super();
  612. this.names = names;
  613. }
  614. });
  615. this.registerType('ast.Continue', class extends ast.stmt {});
  616. this.registerType('ast.Break', class extends ast.stmt {});
  617. this.registerType('ast.Pass', class extends ast.stmt {});
  618. this.registerType('ast.Await', class extends ast.stmt {
  619. constructor(value) {
  620. super();
  621. this.value = value;
  622. }
  623. });
  624. this.registerType('ast.Module', class extends ast.mod {
  625. constructor(body, type_ignores) {
  626. super();
  627. this.body = body;
  628. this.type_ignores = type_ignores;
  629. }
  630. });
  631. this.registerFunction('ast.parse', (source, filename, debug) => {
  632. const parser = new ast._Parser(source, filename, debug);
  633. return parser.parse();
  634. });
  635. this.registerType('ast._Parser', class {
  636. constructor(text, file, debug) {
  637. this._tokenizer = new ast._Tokenizer(text, file);
  638. this._debug = debug;
  639. ast._Parser._precedence = ast._Parser._precedence || {
  640. 'or': 2, 'and': 3, 'not' : 4,
  641. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  642. '|': 6, '^' : 7, '&' : 8,
  643. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  644. // '+': 12, '-': 12,
  645. '~': 13, '**': 14
  646. };
  647. }
  648. parse() {
  649. const position = this._position();
  650. const body = [];
  651. while (!this._tokenizer.match('eof')) {
  652. const statement = this._parseStatement();
  653. if (statement) {
  654. body.push(statement);
  655. continue;
  656. }
  657. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type === 'eof') {
  658. continue;
  659. }
  660. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type === 'eof') {
  661. continue;
  662. }
  663. throw new python.Error(`Unsupported statement ${this._location()}`);
  664. }
  665. const node = new ast.Module(body);
  666. this._mark(node, position);
  667. return node;
  668. }
  669. _parseSuite() {
  670. const body = [];
  671. let statement = null;
  672. if (this._tokenizer.eat('\n')) {
  673. if (this._tokenizer.eat('indent')) {
  674. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  675. if (this._tokenizer.eat(';')) {
  676. continue;
  677. }
  678. statement = this._parseStatement();
  679. if (statement) {
  680. body.push(statement);
  681. continue;
  682. }
  683. if (this._tokenizer.eat('\n')) {
  684. continue;
  685. }
  686. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  687. continue;
  688. }
  689. throw new python.Error(`Empty statement ${this._location()}`);
  690. }
  691. }
  692. } else if (!this._tokenizer.eat('eof')) {
  693. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  694. if (this._tokenizer.eat(';')) {
  695. continue;
  696. }
  697. statement = this._parseStatement();
  698. if (statement) {
  699. body.push(statement);
  700. continue;
  701. }
  702. throw new python.Error(`Empty statement ${this._location()}`);
  703. }
  704. this._tokenizer.eat('\n');
  705. }
  706. return body;
  707. }
  708. _parseStatement() {
  709. let node = null;
  710. let position = this._position();
  711. if (this._eat('id', 'break')) {
  712. const node = new ast.Break();
  713. return this._mark(node, position);
  714. }
  715. if (this._eat('id', 'continue')) {
  716. const node = new ast.Continue();
  717. return this._mark(node, position);
  718. }
  719. if (this._eat('id', 'return')) {
  720. const value = this._parseExpression(-1, [], true);
  721. const node = new ast.Return(value);
  722. return this._mark(node, position);
  723. }
  724. if (this._eat('id', 'raise')) {
  725. let exc = this._parseExpression(-1, ['from']);
  726. let cause = null;
  727. if (this._tokenizer.eat('id', 'from')) {
  728. cause = this._parseExpression();
  729. } else if (this._tokenizer.eat(',')) {
  730. exc = [exc];
  731. exc.push(this._parseExpression());
  732. if (this._tokenizer.eat(',')) {
  733. exc.push(this._parseExpression());
  734. }
  735. }
  736. node = new ast.Raise(exc, cause);
  737. return this._mark(node, position);
  738. }
  739. if (this._eat('id', 'assert')) {
  740. const test = this._parseExpression(-1, [',']);
  741. let msg = null;
  742. if (this._tokenizer.eat(',')) {
  743. msg = this._parseExpression();
  744. }
  745. node = new ast.Assert(test, msg);
  746. return this._mark(node, position);
  747. }
  748. if (this._eat('id', 'global')) {
  749. const names = [];
  750. do {
  751. const name = this._parseName(true);
  752. names.push(name.id);
  753. }
  754. while (this._tokenizer.eat(','));
  755. const node = new ast.Global(names);
  756. return this._mark(node, position);
  757. }
  758. if (this._eat('id', 'nonlocal')) {
  759. const names = [];
  760. do {
  761. const name = this._parseName(true);
  762. names.push(name.id);
  763. }
  764. while (this._tokenizer.eat(','));
  765. const node = new ast.Nonlocal(names);
  766. return this._mark(node, position);
  767. }
  768. if (this._eat('id', 'import')) {
  769. const names = [];
  770. do {
  771. const name = this._parseDottedName();
  772. let asname = null;
  773. if (this._tokenizer.eat('id', 'as')) {
  774. asname = this._parseName(true).id;
  775. }
  776. const node = new ast.alias(name, asname);
  777. names.push(node);
  778. }
  779. while (this._tokenizer.eat(','));
  780. const node = new ast.Import(names);
  781. return this._mark(node, position);
  782. }
  783. if (this._eat('id', 'from')) {
  784. let level = 0;
  785. const dots = this._tokenizer.peek();
  786. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  787. this._eat(dots.type);
  788. level = Array.from(dots.type).length;
  789. }
  790. const module = this._parseDottedName();
  791. this._tokenizer.expect('id', 'import');
  792. const names = [];
  793. const close = this._tokenizer.eat('(');
  794. do {
  795. const name = this._parseName(true).id;
  796. let asname = null;
  797. if (this._tokenizer.eat('id', 'as')) {
  798. asname = this._parseName(true).id;
  799. }
  800. const node = new ast.alias(name, asname);
  801. names.push(node);
  802. }
  803. while (this._tokenizer.eat(','));
  804. if (close) {
  805. this._tokenizer.expect(')');
  806. }
  807. const node = new ast.ImportFrom(module, names, level);
  808. return this._mark(node, position);
  809. }
  810. const decorator_list = this._decorator();
  811. position = this._position();
  812. if (this._eat('id', 'class')) {
  813. const name = this._parseName(true);
  814. const bases = [];
  815. if (this._tokenizer.eat('(')) {
  816. while (!this._tokenizer.eat(')')) {
  817. if (this._tokenizer.eat('\n')) {
  818. continue;
  819. }
  820. const expression = this._parseExpression(-1, [], false);
  821. if (expression === null) {
  822. throw new python.Error(`Expected expression ${this._location()}`);
  823. }
  824. bases.push(expression);
  825. if (!this._tokenizer.eat(',')) {
  826. this._tokenizer.eat('\n');
  827. this._tokenizer.expect(')');
  828. break;
  829. }
  830. }
  831. }
  832. this._tokenizer.expect(':');
  833. const body = this._parseSuite();
  834. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  835. return this._mark(node, position);
  836. }
  837. const async = this._eat('id', 'async') !== null;
  838. if (async &&
  839. !this._tokenizer.match('id', 'def') &&
  840. !this._tokenizer.match('id', 'with') &&
  841. !this._tokenizer.match('id', 'for')) {
  842. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  843. }
  844. if (this._eat('id', 'def')) {
  845. const name = this._parseName(true);
  846. this._tokenizer.expect('(');
  847. const args = this._parseArguments(')');
  848. let returns = null;
  849. if (this._tokenizer.eat('->')) {
  850. returns = this._parseType();
  851. }
  852. this._tokenizer.expect(':');
  853. const body = this._parseSuite();
  854. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  855. if (async) {
  856. node.async = async;
  857. }
  858. return this._mark(node, position);
  859. }
  860. if (decorator_list && decorator_list.length > 0) {
  861. throw new python.Error('Unexpected decorator.');
  862. }
  863. if (this._eat('id', 'del')) {
  864. const targets = this._parseExpression(-1, [], true);
  865. node = new ast.Del(targets);
  866. return this._mark(node, position);
  867. }
  868. if (this._eat('id', 'if')) {
  869. const test = this._parseExpression();
  870. this._tokenizer.expect(':');
  871. const body = this._parseSuite();
  872. const node = new ast.If(test, body);
  873. let current = node;
  874. this._tokenizer.eat('\n');
  875. while (this._tokenizer.eat('id', 'elif')) {
  876. const test = this._parseExpression();
  877. this._tokenizer.expect(':');
  878. const body = this._parseSuite();
  879. current.orelse = new ast.If(test, body);
  880. current = current.orelse;
  881. this._tokenizer.eat('\n');
  882. }
  883. if (this._tokenizer.eat('id', 'else')) {
  884. this._tokenizer.expect(':');
  885. current.orelse = this._parseSuite();
  886. }
  887. return this._mark(node, position);
  888. }
  889. if (this._eat('id', 'while')) {
  890. const test = this._parseExpression();
  891. this._tokenizer.expect(':');
  892. const body = this._parseSuite();
  893. let orelse = null;
  894. if (this._tokenizer.eat('id', 'else')) {
  895. this._tokenizer.expect(':');
  896. orelse = this._parseSuite();
  897. }
  898. const node = new ast.While(test, body, orelse);
  899. return this._mark(node, position);
  900. }
  901. if (this._eat('id', 'pass')) {
  902. const node = new ast.Pass();
  903. return this._mark(node, position);
  904. }
  905. if (this._eat('id', 'for')) {
  906. let target = this._parseExpression(-1, ['in']);
  907. while (this._tokenizer.eat(',')) {
  908. if (target instanceof ast.Tuple === false) {
  909. target = new ast.Tuple([target]);
  910. }
  911. if (this._tokenizer.match('id', 'in')) {
  912. target.elts.push({});
  913. break;
  914. }
  915. target.elts.push(this._parseExpression(-1, ['in']));
  916. }
  917. this._tokenizer.expect('id', 'in');
  918. let iter = this._parseExpression();
  919. while (this._tokenizer.eat(',')) {
  920. if (iter.type !== 'tuple') {
  921. iter = new ast.Tuple([iter]);
  922. }
  923. if (this._tokenizer.match(':')) {
  924. iter.elts.push({});
  925. break;
  926. }
  927. iter.elts.push(this._parseExpression(-1, ['in']));
  928. }
  929. this._tokenizer.expect(':');
  930. const body = this._parseSuite();
  931. let orelse = null;
  932. if (this._tokenizer.eat('id', 'else')) {
  933. this._tokenizer.expect(':');
  934. orelse = this._parseSuite();
  935. }
  936. const node = new ast.For(target, iter, body, orelse);
  937. return this._mark(node, position);
  938. }
  939. if (this._eat('id', 'with')) {
  940. const items = [];
  941. do {
  942. const context_expr = this._parseExpression();
  943. let optional_vars = null;
  944. if (this._tokenizer.eat('id', 'as')) {
  945. optional_vars = this._parseExpression();
  946. }
  947. const node = new ast.withitem(context_expr, optional_vars);
  948. items.push(node);
  949. }
  950. while (this._tokenizer.eat(','));
  951. this._tokenizer.expect(':');
  952. const body = this._parseSuite();
  953. const node = new ast.With(items, body, null);
  954. if (async) {
  955. node.async = async;
  956. }
  957. return this._mark(node, position);
  958. }
  959. if (this._eat('id', 'try')) {
  960. this._tokenizer.expect(':');
  961. const body = this._parseSuite();
  962. const handlers = [];
  963. let orelse = null;
  964. let finalbody = null;
  965. while (this._tokenizer.match('id', 'except')) {
  966. this._tokenizer.expect('id', 'except');
  967. const type = this._parseExpression();
  968. const name = this._tokenizer.eat('id', 'as') ? this._parseExpression() : null;
  969. this._tokenizer.expect(':');
  970. const body = this._parseSuite();
  971. const except = new ast.ExceptHandler(type, name, body);
  972. handlers.push(except);
  973. }
  974. if (this._tokenizer.match('id', 'else')) {
  975. this._tokenizer.expect('id', 'else');
  976. this._tokenizer.expect(':');
  977. orelse = this._parseSuite();
  978. }
  979. if (this._tokenizer.match('id', 'finally')) {
  980. this._tokenizer.expect('id', 'finally');
  981. this._tokenizer.expect(':');
  982. finalbody = this._parseSuite();
  983. }
  984. const node = new ast.Try(body, handlers, orelse, finalbody);
  985. return this._mark(node, position);
  986. }
  987. const expr = this._parseExpression(-1, [], true);
  988. if (expr) {
  989. if (expr instanceof ast.Name && this._tokenizer.eat(':')) {
  990. const position = this._position();
  991. const annotation = this._parseExpression(-1, ['=']);
  992. let value = null;
  993. if (this._tokenizer.eat('=')) {
  994. value = this._parseExpression();
  995. }
  996. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  997. return this._mark(node, position);
  998. }
  999. if (expr instanceof ast.stmt) {
  1000. return expr;
  1001. }
  1002. switch (expr.__class__.__name__) {
  1003. case 'AnnAssign':
  1004. case 'Assert':
  1005. case 'Assign':
  1006. case 'Attribute':
  1007. case 'AugAssign':
  1008. case 'Await':
  1009. case 'BinOp':
  1010. case 'Call':
  1011. case 'Compare':
  1012. case 'Constant':
  1013. case 'Ellipsis':
  1014. case 'For':
  1015. case 'If':
  1016. case 'Lambda':
  1017. case 'List':
  1018. case 'Name':
  1019. case 'NamedExpr':
  1020. case 'Raise':
  1021. case 'Subscript':
  1022. case 'Tuple':
  1023. case 'Yield':
  1024. // return expr;
  1025. return new ast.Expr(expr);
  1026. default:
  1027. throw new python.Error(`Unhandled expression ${this._location()}`);
  1028. }
  1029. }
  1030. return null;
  1031. }
  1032. _parseExpression(minPrecedence, terminal, tuple) {
  1033. minPrecedence = minPrecedence || -1;
  1034. const terminalSet = new Set(terminal);
  1035. const stack = [];
  1036. for (;;) {
  1037. let position = this._position();
  1038. let node = null;
  1039. const token = this._tokenizer.peek();
  1040. if (stack.length === 1 && terminalSet.has(token.value)) {
  1041. break;
  1042. }
  1043. const precedence = ast._Parser._precedence[token.value];
  1044. if (precedence) {
  1045. if (precedence >= minPrecedence) {
  1046. this._tokenizer.read();
  1047. if (token.value === 'not' && this._tokenizer.eat('id', 'in')) {
  1048. token.value = 'not in';
  1049. } else if (token.value === 'is' && this._tokenizer.eat('id', 'not')) {
  1050. token.value = 'is not';
  1051. }
  1052. if (stack.length > 0) {
  1053. let op = null;
  1054. switch (token.value) {
  1055. case '+': op = new ast.Add(); break;
  1056. case '-': op = new ast.Sub(); break;
  1057. case '*': op = new ast.Mult(); break;
  1058. case '/': op = new ast.Div(); break;
  1059. case '//': op = new ast.FloorDiv(); break;
  1060. case '**': op = new ast.Pow(); break;
  1061. case '@': op = new ast.MatMult(); break;
  1062. case '&': op = new ast.BitAnd(); break;
  1063. case '^': op = new ast.BitXor(); break;
  1064. case '|': op = new ast.BitOr(); break;
  1065. case '%': op = new ast.Mod(); break;
  1066. case '>>': op = new ast.RShift(); break;
  1067. case '<<': op = new ast.LShift(); break;
  1068. default: break;
  1069. }
  1070. if (op) {
  1071. const left = stack.pop();
  1072. const right = this._parseExpression(precedence, terminal, tuple === true ? true : false);
  1073. node = new ast.BinOp(left, op, right);
  1074. } else {
  1075. switch (token.value) {
  1076. case '==': op = new ast.Eq(); break;
  1077. case '!=': op = new ast.NotEq(); break;
  1078. case '>=': op = new ast.GtE(); break;
  1079. case '<=': op = new ast.LtE(); break;
  1080. case '<': op = new ast.Lt(); break;
  1081. case '>': op = new ast.Gt(); break;
  1082. case 'is': op = new ast.Is(); break;
  1083. case 'is not': op = new ast.IsNot(); break;
  1084. case 'in': op = new ast.In(); break;
  1085. case 'not in': op = new ast.NotIn(); break;
  1086. default: break;
  1087. }
  1088. const left = stack.pop();
  1089. const comparator = this._parseExpression(precedence, ['for', 'if'], tuple === true ? true : false);
  1090. node = new ast.Compare(left, [op], [comparator]);
  1091. }
  1092. } else if (token.value === '*') {
  1093. const value = this._parseExpression(precedence, terminal, tuple === true ? true : false);
  1094. node = new ast.Starred(value);
  1095. } else if (token.value === '**') {
  1096. const value = this._parseExpression(precedence, terminal, tuple === true ? true : false);
  1097. node = new ast.keyword(null, value);
  1098. } else {
  1099. let op = null;
  1100. switch (token.value) {
  1101. case '-': op = new ast.USub(); break;
  1102. case '+': op = new ast.UAdd(); break;
  1103. case '~': op = new ast.Invert(); break;
  1104. case 'not': op = new ast.Not(); break;
  1105. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1106. }
  1107. const operand = this._parseExpression(precedence, terminal, tuple === true ? true : false);
  1108. node = new ast.UnaryOp(op, operand);
  1109. node = this._mark(node, position);
  1110. }
  1111. stack.push(node);
  1112. continue;
  1113. }
  1114. }
  1115. if (this._tokenizer.eat(':=')) {
  1116. const target = stack.pop();
  1117. const value = this._parseExpression(-1, terminal, tuple === false ? false : true);
  1118. const node = new ast.NamedExpr(target, value);
  1119. this._mark(node, position);
  1120. stack.push(node);
  1121. continue;
  1122. }
  1123. if (this._tokenizer.eat('=')) {
  1124. const position = this._position();
  1125. const targets = stack.pop();
  1126. const value = this._parseExpression(-1, terminal, tuple === false ? false : true);
  1127. const node = new ast.Assign([targets], value);
  1128. this._mark(node, position);
  1129. stack.push(node);
  1130. continue;
  1131. }
  1132. let op = null;
  1133. switch (token.type) {
  1134. case '+=': op = new ast.Add(); break;
  1135. case '-=': op = new ast.Sub(); break;
  1136. case '**=': op = new ast.Pow(); break;
  1137. case '*=': op = new ast.Mult(); break;
  1138. case '//=': op = new ast.FloorDiv(); break;
  1139. case '/=': op = new ast.Div(); break;
  1140. case '&=': op = new ast.BitAnd(); break;
  1141. case '%=': op = new ast.Mod(); break;
  1142. case '^=': op = new ast.BitXor(); break;
  1143. case '<<=': op = new ast.LShift(); break;
  1144. case '>>=': op = new ast.RShift(); break;
  1145. case '|=': op = new ast.BitOr(); break;
  1146. case '@=': op = new ast.MatMul(); break;
  1147. default: break;
  1148. }
  1149. if (op) {
  1150. this._tokenizer.expect(token.type);
  1151. const target = stack.pop();
  1152. const value = this._parseExpression(-1, terminal, true);
  1153. const node = new ast.AugAssign(target, op, value);
  1154. stack.push(node);
  1155. continue;
  1156. }
  1157. position = this._position();
  1158. if (this._eat('id', 'if')) {
  1159. const body = stack.pop();
  1160. const test = this._parseExpression();
  1161. this._tokenizer.expect('id', 'else');
  1162. const orelse = this._parseExpression();
  1163. const node = new ast.IfExp(test, body, orelse);
  1164. this._mark(node, position);
  1165. stack.push(node);
  1166. continue;
  1167. }
  1168. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1169. const position = this._position();
  1170. const elt = stack.pop();
  1171. const generators = this._parseGenerators();
  1172. let node = null;
  1173. if (elt instanceof ast.Dict) {
  1174. if (elt.keys.length !== 1 || elt.values.length !== 1) {
  1175. throw new python.Error(`Invalid dict comprehension ${this._location()}`);
  1176. }
  1177. node = new ast.DictComp(elt.keys[0], elt.values[0], generators);
  1178. } else if (elt instanceof ast.Set) {
  1179. if (elt.elts.length !== 1) {
  1180. throw new python.Error(`Invalid set comprehension ${this._location()}`);
  1181. }
  1182. node = new ast.SetComp(elt.elts[0], generators);
  1183. } else {
  1184. node = new ast.GeneratorExp(elt, generators);
  1185. }
  1186. this._mark(node, position);
  1187. stack.push(node);
  1188. continue;
  1189. }
  1190. if (this._eat('id', 'lambda')) {
  1191. const args = this._parseArguments(':');
  1192. const body = this._parseExpression(-1, terminal, false);
  1193. const node = new ast.Lambda(args, body);
  1194. this._mark(node, position);
  1195. stack.push(node);
  1196. continue;
  1197. }
  1198. if (this._eat('id', 'yield')) {
  1199. if (this._tokenizer.eat('id', 'from')) {
  1200. const value = this._parseExpression(-1, [], true);
  1201. node = new ast.YieldFrom(value);
  1202. stack.push(node);
  1203. } else {
  1204. const value = [];
  1205. do {
  1206. value.push(this._parseExpression(-1, [], false));
  1207. }
  1208. while (this._tokenizer.eat(','));
  1209. node = new ast.Yield(value);
  1210. stack.push(node);
  1211. }
  1212. continue;
  1213. }
  1214. if (this._eat('id', 'await')) {
  1215. const value = this._parseExpression(minPrecedence, terminal, tuple);
  1216. const node = new ast.Await(value);
  1217. this._mark(node, position);
  1218. stack.push(node);
  1219. continue;
  1220. }
  1221. if (this._eat('.')) {
  1222. const value = stack.pop();
  1223. const attr = this._parseName().id;
  1224. const node = new ast.Attribute(value, attr);
  1225. this._mark(node, position);
  1226. stack.push(node);
  1227. continue;
  1228. }
  1229. if (this._tokenizer.peek().type === '(') {
  1230. const position = this._position();
  1231. const args = [];
  1232. const keywords = [];
  1233. this._tokenizer.expect('(');
  1234. let tuple = false;
  1235. while (!this._tokenizer.eat(')')) {
  1236. if (this._tokenizer.eat('\n')) {
  1237. continue;
  1238. }
  1239. const position = this._position();
  1240. const expr = this._parseExpression(-1, [], false);
  1241. if (expr === null) {
  1242. throw new python.Error(`Expected expression ${this._location()}`);
  1243. }
  1244. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1245. const [target] = expr.targets;
  1246. if (target instanceof ast.Name === false) {
  1247. throw new python.Error(`Expected name ${this._location()}`);
  1248. }
  1249. const node = new ast.keyword(target.id, expr.value);
  1250. this._mark(node, position);
  1251. keywords.push(node);
  1252. } else {
  1253. args.push(expr);
  1254. }
  1255. if (this._tokenizer.eat(',')) {
  1256. tuple = true;
  1257. } else {
  1258. this._tokenizer.eat('\n');
  1259. this._tokenizer.expect(')');
  1260. break;
  1261. }
  1262. }
  1263. if (stack.length === 0 && keywords.length === 0) {
  1264. node = args.length === 1 && !tuple ? args[0] : new ast.Tuple(args);
  1265. this._mark(node, position);
  1266. } else {
  1267. const func = stack.pop();
  1268. node = new ast.Call(func, args, keywords);
  1269. let start = func;
  1270. while (start instanceof ast.Attribute) {
  1271. start = start.value;
  1272. }
  1273. position.lineno = start.lineno;
  1274. position.col_offset = start.col_offset;
  1275. this._mark(node, position);
  1276. }
  1277. stack.push(node);
  1278. continue;
  1279. }
  1280. if (this._tokenizer.peek().type === '[') {
  1281. if (stack.length === 0) {
  1282. stack.push(this._parseList());
  1283. } else {
  1284. const value = stack.pop();
  1285. const position = this._position();
  1286. const slice = this._parseSlice();
  1287. node = new ast.Subscript(value, slice);
  1288. this._mark(node, position);
  1289. stack.push(node);
  1290. }
  1291. continue;
  1292. }
  1293. if (this._tokenizer.peek().type === '{') {
  1294. const elts = [];
  1295. const keys = [];
  1296. const values = [];
  1297. this._tokenizer.expect('{');
  1298. let dict = true;
  1299. while (!this._tokenizer.eat('}')) {
  1300. const item = this._parseExpression(-1, [], false);
  1301. if (item === null) {
  1302. throw new python.Error(`Expected expression ${this._location()}`);
  1303. }
  1304. if (!this._tokenizer.eat(':')) {
  1305. dict = false;
  1306. }
  1307. if (dict) {
  1308. const value = this._parseExpression(-1, ['for'], false);
  1309. if (value === null) {
  1310. throw new python.Error(`Expected expression ${this._location()}`);
  1311. }
  1312. if (this._eat('id', 'for')) {
  1313. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1314. throw new python.Error(`Invalid list expression ${this._location()}`);
  1315. }
  1316. const target = this._parseExpression(-1, ['in'], true);
  1317. this._tokenizer.expect('id', 'in');
  1318. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1319. const ifs = [];
  1320. while (this._tokenizer.eat('id', 'if')) {
  1321. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1322. }
  1323. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1324. const generators = [comprehension];
  1325. this._tokenizer.expect('}');
  1326. return new ast.DictComp(item, value, generators);
  1327. }
  1328. keys.push(item);
  1329. values.push(value);
  1330. } else {
  1331. elts.push(item);
  1332. }
  1333. this._tokenizer.eat(',');
  1334. this._tokenizer.eat('\n');
  1335. if (this._tokenizer.eat('}')) {
  1336. break;
  1337. }
  1338. }
  1339. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1340. throw new python.Error(`Invalid set expression ${this._location()}`);
  1341. }
  1342. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1343. stack.push(node);
  1344. continue;
  1345. }
  1346. const literal = this._parseLiteral();
  1347. if (literal) {
  1348. if (stack.length > 0 &&
  1349. (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') &&
  1350. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  1351. const op = literal.value < 0 ? new ast.Sub() : new ast.Add();
  1352. const left = stack.pop();
  1353. const right = new ast.Constant(Math.abs(literal.value));
  1354. node = new ast.BinOp(left, op, right);
  1355. stack.push(node);
  1356. } else if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1357. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1358. } else {
  1359. let value = literal.value;
  1360. if (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') {
  1361. switch (value) {
  1362. case 'inf': value = Infinity; break;
  1363. case '-inf': value = -Infinity; break;
  1364. default: value = Number(value); break;
  1365. }
  1366. } else if (literal.type === 'str') {
  1367. value = literal.value.substring(1, literal.value.length - 1);
  1368. } else {
  1369. throw new python.Error(`Invalid literal ${this._location()}`);
  1370. }
  1371. const node = new ast.Constant(value, literal.type);
  1372. this._mark(node, position);
  1373. stack.push(node);
  1374. }
  1375. continue;
  1376. }
  1377. if (this._eat('id', 'False')) {
  1378. const node = new ast.Constant(false, 'bool');
  1379. this._mark(node, position);
  1380. stack.push(node);
  1381. continue;
  1382. }
  1383. if (this._eat('id', 'True')) {
  1384. const node = new ast.Constant(true, 'bool');
  1385. this._mark(node, position);
  1386. stack.push(node);
  1387. continue;
  1388. }
  1389. if (this._eat('id', 'None')) {
  1390. const node = new ast.Constant(null);
  1391. this._mark(node, position);
  1392. stack.push(node);
  1393. continue;
  1394. }
  1395. if (this._tokenizer.peek().keyword) {
  1396. break;
  1397. }
  1398. if (this._eat('...')) {
  1399. const node = new ast.Ellipsis();
  1400. this._mark(node, position);
  1401. stack.push(node);
  1402. continue;
  1403. }
  1404. const name = this._parseName();
  1405. if (name) {
  1406. stack.push(name);
  1407. continue;
  1408. }
  1409. if (tuple === true && stack.length === 1 && this._tokenizer.eat(',')) {
  1410. if (stack[0] instanceof ast.Tuple) {
  1411. [node] = stack;
  1412. } else {
  1413. const position = this._position();
  1414. const elts = [stack.pop()];
  1415. node = new ast.Tuple(elts);
  1416. this._mark(node, position);
  1417. stack.push(node);
  1418. }
  1419. // for, bar, = <expr>
  1420. if (this._tokenizer.peek().type === '=') {
  1421. continue;
  1422. }
  1423. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1424. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1425. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1426. if (expression) {
  1427. node.elts.push(expression);
  1428. continue;
  1429. }
  1430. }
  1431. break;
  1432. }
  1433. break;
  1434. }
  1435. if (stack.length === 1) {
  1436. return stack.pop();
  1437. }
  1438. if (stack.length !== 0) {
  1439. throw new python.Error(`Unexpected expression ${this._location()}`);
  1440. }
  1441. return null;
  1442. }
  1443. _decorator() {
  1444. const list = [];
  1445. while (this._tokenizer.eat('@')) {
  1446. const value = this._parseExpression();
  1447. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1448. throw new python.Error(`Invalid decorator ${this._location()}`);
  1449. }
  1450. this._tokenizer.eat('\n');
  1451. list.push(value);
  1452. }
  1453. return list;
  1454. }
  1455. _parseGenerators() {
  1456. const generators = [];
  1457. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1458. const is_async = this._eat('id', 'async') ? 1 : 0;
  1459. this._tokenizer.expect('id', 'for');
  1460. const target = this._parseExpression(-1, ['in'], true);
  1461. this._tokenizer.expect('id', 'in');
  1462. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1463. const ifs = [];
  1464. while (this._tokenizer.eat('id', 'if')) {
  1465. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1466. }
  1467. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1468. generators.push(comprehension);
  1469. }
  1470. return generators;
  1471. }
  1472. _parseList() {
  1473. const elts = [];
  1474. this._tokenizer.expect('[');
  1475. if (!this._tokenizer.match(']')) {
  1476. const position = this._position();
  1477. const expr = this._parseExpression(-1, ['for']);
  1478. if (this._tokenizer.match('id', 'for')) {
  1479. const generators = this._parseGenerators();
  1480. this._tokenizer.expect(']');
  1481. const node = new ast.ListComp(expr, generators);
  1482. this._mark(node, position);
  1483. return node;
  1484. }
  1485. if (expr === null) {
  1486. throw new python.Error(`Expected expression ${this._location()}`);
  1487. }
  1488. elts.push(expr);
  1489. while (this._tokenizer.eat(',')) {
  1490. if (this._tokenizer.match(']')) {
  1491. break;
  1492. }
  1493. const expr = this._parseExpression(-1, ['for']);
  1494. if (!expr) {
  1495. throw new python.Error(`Expected expression ${this._location()}`);
  1496. }
  1497. elts.push(expr);
  1498. }
  1499. }
  1500. this._tokenizer.expect(']');
  1501. return new ast.List(elts);
  1502. }
  1503. _parseSlice() {
  1504. const elts = [];
  1505. let slice = [null, null, null];
  1506. let index = 0;
  1507. let valid = false;
  1508. this._tokenizer.expect('[');
  1509. while (true) {
  1510. if (this._tokenizer.eat(':')) {
  1511. index++;
  1512. valid = true;
  1513. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1514. if (!valid || index > 2) {
  1515. throw new python.Error(`Invalid slice at ${this._location()}`);
  1516. }
  1517. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1518. slice = [null, null, null];
  1519. index = 0;
  1520. if (this._tokenizer.eat(']')) {
  1521. break;
  1522. }
  1523. this._tokenizer.expect(',');
  1524. } else {
  1525. const expression = this._parseExpression();
  1526. if (expression === null) {
  1527. throw new python.Error(`Expected expression ${this._location()}`);
  1528. }
  1529. slice[index] = expression;
  1530. valid = true;
  1531. }
  1532. }
  1533. if (elts.length > 1) {
  1534. return new ast.Tuple(elts);
  1535. }
  1536. return elts[0];
  1537. }
  1538. _parseName(required) {
  1539. const token = this._tokenizer.peek();
  1540. if (token.type === 'id' && !token.keyword) {
  1541. const position = this._position();
  1542. this._tokenizer.read();
  1543. const node = new ast.Name(token.value);
  1544. return this._mark(node, position);
  1545. }
  1546. if (required) {
  1547. throw new python.Error(`Invalid syntax ${this._location()}`);
  1548. }
  1549. return null;
  1550. }
  1551. _parseDottedName() {
  1552. const list = [];
  1553. do {
  1554. const name = this._parseName(true);
  1555. list.push(name.id);
  1556. }
  1557. while (this._tokenizer.eat('.'));
  1558. return list.join('.');
  1559. }
  1560. _parseLiteral() {
  1561. const token = this._tokenizer.peek();
  1562. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1563. this._tokenizer.read();
  1564. return token;
  1565. }
  1566. return null;
  1567. }
  1568. _parseTypeArguments() {
  1569. const list = [];
  1570. this._tokenizer.expect('[');
  1571. while (!this._tokenizer.eat(']')) {
  1572. const type = this._parseType();
  1573. if (type === null) {
  1574. throw new python.Error(`Expected type ${this._location()}`);
  1575. }
  1576. list.push(type);
  1577. if (!this._tokenizer.eat(',')) {
  1578. this._tokenizer.expect(']');
  1579. break;
  1580. }
  1581. }
  1582. return list;
  1583. }
  1584. _parseType() {
  1585. const target = this._parseExpression(-1, ['[', '=']);
  1586. if (target) {
  1587. if (this._tokenizer.peek().value === '[') {
  1588. const list = this._parseList();
  1589. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1590. return new ast.Subscript(target, slice);
  1591. }
  1592. return target;
  1593. }
  1594. return null;
  1595. }
  1596. _parseArguments(terminal) {
  1597. let posonlyargs = [];
  1598. let args = [];
  1599. let vararg = null;
  1600. const kwonlyargs = [];
  1601. const kw_defaults = [];
  1602. let kwarg = null;
  1603. const defaults = [];
  1604. let is_slash = false;
  1605. let is_vararg = false; // '*'
  1606. let is_kwarg = false; // '**'
  1607. const read = (required) => {
  1608. const name = this._parseName(required);
  1609. if (name) {
  1610. const annotation = terminal !== ':' && this._tokenizer.eat(':') ? this._parseType() : null;
  1611. return new ast.arg(name.id, annotation, null);
  1612. }
  1613. return null;
  1614. };
  1615. while (!this._tokenizer.eat(terminal)) {
  1616. this._tokenizer.eat('\n');
  1617. if (this._tokenizer.eat('/')) {
  1618. if (is_slash || is_vararg || is_kwarg) {
  1619. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1620. }
  1621. is_slash = true;
  1622. } else if (this._tokenizer.eat('*')) {
  1623. if (is_vararg) {
  1624. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1625. }
  1626. is_vararg = true;
  1627. const arg = read(false);
  1628. vararg = arg ? arg : vararg;
  1629. } else if (this._tokenizer.eat('**')) {
  1630. if (is_kwarg) {
  1631. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1632. }
  1633. is_kwarg = true;
  1634. kwarg = read(true);
  1635. } else {
  1636. const arg = read(false);
  1637. if (!arg) {
  1638. this._tokenizer.expect(terminal);
  1639. break;
  1640. }
  1641. const default_value = this._tokenizer.eat('=') ? this._parseExpression() : null;
  1642. if (!is_vararg && !is_kwarg) {
  1643. if (is_slash) {
  1644. args.push(arg);
  1645. } else {
  1646. posonlyargs.push(arg);
  1647. }
  1648. if (default_value !== null) {
  1649. defaults.push(default_value);
  1650. }
  1651. } else if (is_vararg && !is_kwarg) {
  1652. kwonlyargs.push(arg);
  1653. kw_defaults.push(default_value);
  1654. } else {
  1655. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1656. }
  1657. }
  1658. this._tokenizer.eat('\n');
  1659. if (!this._tokenizer.eat(',')) {
  1660. this._tokenizer.expect(terminal);
  1661. break;
  1662. }
  1663. }
  1664. if (!is_slash) {
  1665. args = posonlyargs.concat(args);
  1666. posonlyargs = [];
  1667. }
  1668. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1669. }
  1670. _eat(type, value) {
  1671. if (this._tokenizer.match(type, value)) {
  1672. const position = this._position();
  1673. this._tokenizer.expect(type, value);
  1674. return position;
  1675. }
  1676. return null;
  1677. }
  1678. _mark(node, position) {
  1679. node.filename = position.filename;
  1680. node.lineno = position.lineno;
  1681. node.col_offset = position.col_offset;
  1682. node.end_lineno = this._tokenizer.lineno;
  1683. node.end_col_offset = this._tokenizer.col_offset;
  1684. return node;
  1685. }
  1686. _position() {
  1687. return {
  1688. filename: this._tokenizer.filename,
  1689. lineno: this._tokenizer.lineno,
  1690. col_offset: this._tokenizer.col_offset
  1691. };
  1692. }
  1693. _location() {
  1694. return this._tokenizer.location();
  1695. }
  1696. });
  1697. this.registerType('ast._Tokenizer', class {
  1698. constructor(text, file) {
  1699. this._text = text;
  1700. this.filename = file;
  1701. this.linepos = 0;
  1702. this.lineno = 1;
  1703. this._position = 0;
  1704. this._token = { type: '', value: '' };
  1705. this._brackets = 0;
  1706. this._indentation = [];
  1707. this._outdent = 0;
  1708. if (!ast._Tokenizer._whitespace) {
  1709. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1710. 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';
  1711. 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';
  1712. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1713. /* eslint-disable no-misleading-character-class */
  1714. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1715. /* eslint-enable no-misleading-character-class */
  1716. }
  1717. }
  1718. peek() {
  1719. if (!this._cache) {
  1720. this._tokenize();
  1721. this._cache = true;
  1722. }
  1723. return this._token;
  1724. }
  1725. read() {
  1726. if (!this._cache) {
  1727. this._tokenize();
  1728. }
  1729. const next = this._position + this._token.value.length;
  1730. while (this._position < next) {
  1731. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1732. this._position = this._newLine(this._position);
  1733. this.linepos = this._position;
  1734. this.lineno++;
  1735. } else {
  1736. this._position++;
  1737. }
  1738. }
  1739. this._cache = false;
  1740. return this._token;
  1741. }
  1742. match(type, value) {
  1743. const token = this.peek();
  1744. if (token.type === type && (!value || token.value === value)) {
  1745. return true;
  1746. }
  1747. return false;
  1748. }
  1749. eat(type, value) {
  1750. const token = this.peek();
  1751. if (token.type === type && (!value || token.value === value)) {
  1752. this.read();
  1753. return true;
  1754. }
  1755. return false;
  1756. }
  1757. expect(type, value) {
  1758. const token = this.peek();
  1759. if (token.type !== type) {
  1760. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1761. }
  1762. if (value && token.value !== value) {
  1763. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1764. }
  1765. this.read();
  1766. }
  1767. location() {
  1768. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1769. }
  1770. get col_offset() {
  1771. return this._position - this.linepos + 1;
  1772. }
  1773. static _isSpace(c) {
  1774. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1775. return true;
  1776. }
  1777. if (c.charCodeAt(0) >= 0x1680) {
  1778. return ast._Tokenizer._whitespace.test(c);
  1779. }
  1780. return false;
  1781. }
  1782. static _isNewline(c) {
  1783. switch (c) {
  1784. case '\n':
  1785. case '\r':
  1786. case '\u2028': // 8232
  1787. case '\u2029': // 8233
  1788. return true;
  1789. default:
  1790. return false;
  1791. }
  1792. }
  1793. static _isIdentifierStartChar(c) {
  1794. if (c < 'A') {
  1795. return c === '$';
  1796. }
  1797. if (c <= 'Z') {
  1798. return true;
  1799. }
  1800. if (c < 'a') {
  1801. return c === '_';
  1802. }
  1803. if (c <= 'z') {
  1804. return true;
  1805. }
  1806. const code = c.charCodeAt(0);
  1807. if (code >= 0xAA) {
  1808. return ast._Tokenizer._identifierStart.test(c);
  1809. }
  1810. return false;
  1811. }
  1812. static _isIdentifierChar(c) {
  1813. if (c < '0') {
  1814. return c === '$';
  1815. }
  1816. if (c <= '9') {
  1817. return true;
  1818. }
  1819. if (c < 'A') {
  1820. return false;
  1821. }
  1822. if (c <= 'Z') {
  1823. return true;
  1824. }
  1825. if (c < 'a') {
  1826. return c === '_';
  1827. }
  1828. if (c <= 'z') {
  1829. return true;
  1830. }
  1831. const code = c.charCodeAt(0);
  1832. if (code >= 0xAA) {
  1833. return ast._Tokenizer._identifierChar.test(c);
  1834. }
  1835. return false;
  1836. }
  1837. _get(position) {
  1838. return position >= this._text.length ? '\0' : this._text[position];
  1839. }
  1840. _skipLine() {
  1841. while (this._position < this._text.length) {
  1842. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1843. break;
  1844. }
  1845. this._position++;
  1846. }
  1847. }
  1848. _skipWhitespace() {
  1849. while (this._position < this._text.length) {
  1850. const c = this._text[this._position];
  1851. if (c === '#') {
  1852. this._skipLine();
  1853. } else if (ast._Tokenizer._isSpace(c)) {
  1854. this._position++;
  1855. } else if (c === '\\') {
  1856. // Explicit Line Continuation
  1857. this._position++;
  1858. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1859. this._position = this._newLine(this._position);
  1860. this.linepos = this._position;
  1861. this.lineno += 1;
  1862. } else {
  1863. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1864. }
  1865. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1866. // Implicit Line Continuation
  1867. this._position = this._newLine(this._position);
  1868. this.linepos = this._position;
  1869. this.lineno += 1;
  1870. } else {
  1871. break;
  1872. }
  1873. }
  1874. }
  1875. _newLine(position) {
  1876. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1877. return position + 2;
  1878. }
  1879. return position + 1;
  1880. }
  1881. _tokenize() {
  1882. if (this._token.type !== '\n') {
  1883. this._skipWhitespace();
  1884. }
  1885. if (this._token.type === 'dedent') {
  1886. this._indentation.pop();
  1887. this._outdent--;
  1888. if (this._outdent > 0) {
  1889. this._token = { type: 'dedent', value: '' };
  1890. return;
  1891. }
  1892. }
  1893. if (this._token.type === '\n') {
  1894. let indent = '';
  1895. let i = this._position;
  1896. while (i < this._text.length) {
  1897. const c = this._text[i];
  1898. if (ast._Tokenizer._isSpace(c)) {
  1899. indent += c;
  1900. i++;
  1901. } else if (ast._Tokenizer._isNewline(c)) {
  1902. indent = '';
  1903. i = this._newLine(i);
  1904. this._position = i;
  1905. this.linepos = i;
  1906. this.lineno += 1;
  1907. } else if (c === '#') {
  1908. indent = '';
  1909. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1910. i++;
  1911. }
  1912. continue;
  1913. } else {
  1914. break;
  1915. }
  1916. }
  1917. let type = null;
  1918. if (indent.length > 0) {
  1919. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1920. if (indent.length > current.length) {
  1921. type = 'indent';
  1922. this._indentation.push(indent);
  1923. } else if (indent.length > 0 && indent.length < current.length) {
  1924. type = 'dedent';
  1925. this._outdent = 0;
  1926. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1927. this._outdent++;
  1928. }
  1929. } else {
  1930. this._position += indent.length;
  1931. }
  1932. } else if (i >= this._text.length) {
  1933. this._token = { type: 'eof', value: '' };
  1934. return;
  1935. } else if (this._indentation.length > 0) {
  1936. type = 'dedent';
  1937. this._outdent = this._indentation.length;
  1938. }
  1939. if (type === 'indent' || type === 'dedent') {
  1940. this._token = { type, value: indent };
  1941. return;
  1942. }
  1943. }
  1944. if (this._position >= this._text.length) {
  1945. this._token = { type: 'eof', value: '' };
  1946. return;
  1947. }
  1948. const c = this._get(this._position);
  1949. const string = this._string();
  1950. if (string) {
  1951. this._token = string;
  1952. return;
  1953. }
  1954. switch (c) {
  1955. case '(':
  1956. case '[':
  1957. case '{':
  1958. this._brackets++;
  1959. this._token = { type: c, value: c };
  1960. return;
  1961. case ')':
  1962. case ']':
  1963. case '}':
  1964. if (this._brackets === 0) {
  1965. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  1966. }
  1967. this._brackets--;
  1968. this._token = { type: c, value: c };
  1969. return;
  1970. case ',':
  1971. case ';':
  1972. case '?':
  1973. this._token = { type: c, value: c };
  1974. return;
  1975. default: {
  1976. const number = this._number();
  1977. if (number) {
  1978. this._token = number;
  1979. return;
  1980. }
  1981. if (c === '.') {
  1982. let end = this._position + 1;
  1983. while (this._get(end) === '.') {
  1984. end++;
  1985. }
  1986. const text = this._text.substring(this._position, end);
  1987. this._token = { type: text, value: text };
  1988. return;
  1989. }
  1990. const identifier = this._identifier();
  1991. if (identifier) {
  1992. this._token = identifier;
  1993. return;
  1994. }
  1995. const operator = this._operator();
  1996. if (operator) {
  1997. this._token = operator;
  1998. return;
  1999. }
  2000. break;
  2001. }
  2002. }
  2003. if (c === '.') {
  2004. this._token = { type: c, value: c };
  2005. return;
  2006. }
  2007. if (c === '\\') {
  2008. this._token = { type: '\\', value: c };
  2009. return;
  2010. }
  2011. if (ast._Tokenizer._isNewline(c)) {
  2012. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2013. return;
  2014. }
  2015. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2016. }
  2017. _number() {
  2018. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2019. const binary = (c) => c === '0' || c === '1' || c === '_';
  2020. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2021. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2022. let c = this._get(this._position);
  2023. const sign = (c === '-' || c === '+') ? 1 : 0;
  2024. let i = this._position + sign;
  2025. c = this._get(i);
  2026. if (c === '0') {
  2027. let radix = 0;
  2028. const n = this._get(i + 1);
  2029. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2030. i += 2;
  2031. while (hex(this._get(i))) {
  2032. i += 1;
  2033. }
  2034. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2035. i += 1;
  2036. }
  2037. radix = 16;
  2038. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2039. i += 2;
  2040. while (binary(this._get(i))) {
  2041. i++;
  2042. }
  2043. radix = 2;
  2044. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2045. i += 2;
  2046. while (octal(this._get(i))) {
  2047. i++;
  2048. }
  2049. radix = 8;
  2050. } else if (n >= '0' && n <= '7') {
  2051. i++;
  2052. while (octal(this._get(i))) {
  2053. i += 1;
  2054. }
  2055. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2056. i += 1;
  2057. }
  2058. radix = 8;
  2059. }
  2060. if (radix > 0 && this._get(i) !== '.') {
  2061. const radixText = this._text.substring(this._position, i);
  2062. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2063. if (!isNaN(parseInt(radixParseText, radix))) {
  2064. return { type: 'int', value: radixText };
  2065. }
  2066. }
  2067. }
  2068. i = this._position + sign;
  2069. let isDecimal = false;
  2070. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2071. while (decimal(this._get(i))) {
  2072. i++;
  2073. }
  2074. c = this._get(i).toLowerCase();
  2075. isDecimal = c !== '.' && c !== 'e';
  2076. }
  2077. if (this._get(i) === '0') {
  2078. i++;
  2079. c = this._get(i).toLowerCase();
  2080. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2081. }
  2082. if (isDecimal) {
  2083. if (this._get(i) === 'j' || this._get(i) === 'J' || this._get(i) === 'l' || this._get(i) === 'L') {
  2084. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2085. }
  2086. const intText = this._text.substring(this._position, i);
  2087. if (!isNaN(parseInt(intText, 10))) {
  2088. return { type: 'int', value: intText };
  2089. }
  2090. }
  2091. i = this._position + sign;
  2092. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2093. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2094. while (decimal(this._get(i))) {
  2095. i++;
  2096. }
  2097. if (this._get(i) === '.') {
  2098. i++;
  2099. }
  2100. while (decimal(this._get(i))) {
  2101. i++;
  2102. }
  2103. if (i > (this._position + sign)) {
  2104. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2105. i++;
  2106. if (this._get(i) === '-' || this._get(i) === '+') {
  2107. i++;
  2108. }
  2109. if (decimal(this._get(i))) {
  2110. while (decimal(this._get(i))) {
  2111. i++;
  2112. }
  2113. } else {
  2114. i = this._position;
  2115. }
  2116. } else {
  2117. while (decimal(this._get(i))) {
  2118. i++;
  2119. }
  2120. }
  2121. }
  2122. if (i > (this._position + sign)) {
  2123. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2124. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2125. }
  2126. const floatText = this._text.substring(this._position, i);
  2127. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2128. if (!isNaN(parseFloat(floatParseText))) {
  2129. return { type: 'float', value: floatText };
  2130. }
  2131. }
  2132. }
  2133. return null;
  2134. }
  2135. _identifier() {
  2136. let i = this._position;
  2137. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2138. i++;
  2139. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2140. i++;
  2141. }
  2142. }
  2143. if (i > this._position) {
  2144. const text = this._text.substring(this._position, i);
  2145. let keyword = false;
  2146. switch (text) {
  2147. case 'and':
  2148. case 'as':
  2149. case 'else':
  2150. case 'For':
  2151. case 'If':
  2152. case 'Import':
  2153. case 'in':
  2154. case 'is':
  2155. case 'not':
  2156. case 'or':
  2157. keyword = true;
  2158. break;
  2159. default:
  2160. break;
  2161. }
  2162. return { type: 'id', value: text, keyword };
  2163. }
  2164. return null;
  2165. }
  2166. _operator() {
  2167. let length = 0;
  2168. const c0 = this._get(this._position);
  2169. const c1 = this._get(this._position + 1);
  2170. const c2 = this._get(this._position + 2);
  2171. switch (c0) {
  2172. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2173. length = c1 === '=' ? 2 : 1;
  2174. break;
  2175. case '-':
  2176. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2177. break;
  2178. case '*':
  2179. switch (c1) {
  2180. case '*': length = c2 === '=' ? 3 : 2; break;
  2181. case '=': length = 2; break;
  2182. default: length = 1; break;
  2183. }
  2184. break;
  2185. case '/':
  2186. switch (c1) {
  2187. case '/': length = c2 === '=' ? 3 : 2; break;
  2188. case '=': length = 2; break;
  2189. default: length = 1; break;
  2190. }
  2191. break;
  2192. case '<':
  2193. switch (c1) {
  2194. case '>': length = 2; break;
  2195. case '<': length = c2 === '=' ? 3 : 2; break;
  2196. case '=': length = 2; break;
  2197. default: length = 1; break;
  2198. }
  2199. break;
  2200. case '>':
  2201. switch (c1) {
  2202. case '>': length = c2 === '=' ? 3 : 2; break;
  2203. case '=': length = 2; break;
  2204. default: length = 1; break;
  2205. }
  2206. break;
  2207. case '@':
  2208. length = c1 === '=' ? 2 : 1;
  2209. break;
  2210. case ':':
  2211. length = c1 === '=' ? 2 : 1;
  2212. break;
  2213. default:
  2214. return null;
  2215. }
  2216. const text = this._text.substring(this._position, this._position + length);
  2217. return { type: text, value: text };
  2218. }
  2219. _string() {
  2220. let i = this._position;
  2221. let prefix = -1;
  2222. if (this._get(i) === "'" || this._get(i) === '"') {
  2223. prefix = '';
  2224. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2225. const c = this._get(i);
  2226. const cc = c.toLowerCase();
  2227. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2228. prefix = c;
  2229. }
  2230. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2231. const c = this._text.substr(this._position, 2);
  2232. const cc = c.toLowerCase();
  2233. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2234. prefix = c;
  2235. }
  2236. }
  2237. if (prefix.length >= 0) {
  2238. i += prefix.length;
  2239. let quote = '';
  2240. let count = 0;
  2241. const q0 = this._get(i);
  2242. const q1 = this._get(i + 1);
  2243. const q2 = this._get(i + 2);
  2244. switch (q0) {
  2245. case "'":
  2246. quote = q0;
  2247. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2248. break;
  2249. case '"':
  2250. quote = q0;
  2251. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2252. break;
  2253. default:
  2254. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2255. }
  2256. i += count;
  2257. if (count === 1) {
  2258. while (i < this._text.length) {
  2259. if (this._text[i] === quote) {
  2260. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2261. } else if (this._text[i] === '\\' &&
  2262. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2263. i += 2;
  2264. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2265. break;
  2266. } else {
  2267. i++;
  2268. }
  2269. }
  2270. } else if (count === 3) {
  2271. while (i < this._text.length) {
  2272. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2273. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2274. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2275. i += 2;
  2276. continue;
  2277. }
  2278. i++;
  2279. }
  2280. }
  2281. }
  2282. i = this._position;
  2283. if (this._get(i) === '`') {
  2284. i++;
  2285. while (i < this._text.length) {
  2286. if (this._text[i] === '`') {
  2287. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2288. }
  2289. i++;
  2290. }
  2291. }
  2292. return null;
  2293. }
  2294. });
  2295. this.registerType('builtins.dict', dict);
  2296. this.registerType('builtins.ellipsis', class {});
  2297. this.registerType('builtins.cell', class {});
  2298. this.registerType('builtins.list', class extends Array {});
  2299. this.registerType('builtins.number', class {});
  2300. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2301. return execution.__import__(name, globals, locals, fromlist, level);
  2302. });
  2303. this.registerType('builtins.bool', class extends Boolean {
  2304. constructor(value) {
  2305. if (value && value.__bool__) {
  2306. value = value.__bool__();
  2307. } else if (value && value.__len__) {
  2308. value = value.__len__() > 0;
  2309. } else {
  2310. value = value ? true : false;
  2311. }
  2312. super(value);
  2313. }
  2314. });
  2315. this.registerType('builtins.int', class extends Number {
  2316. constructor(value) {
  2317. if (value && value.__int__) {
  2318. value = value.__int__();
  2319. } else if (!Number.isInteger(value)) {
  2320. value = NaN;
  2321. }
  2322. super(value);
  2323. }
  2324. });
  2325. this.registerType('builtins.float', class extends Number {
  2326. constructor(value) {
  2327. if (value && value.__float__) {
  2328. value = value.__float__();
  2329. } else if (Number(value) !== value) {
  2330. value = NaN;
  2331. }
  2332. super(value);
  2333. }
  2334. });
  2335. this.registerType('builtins.long', class extends Number {
  2336. constructor(value) {
  2337. if (value && value.__int__) {
  2338. value = value.__int__();
  2339. } else if (!Number.isInteger(value)) {
  2340. value = NaN;
  2341. }
  2342. super(value);
  2343. }
  2344. });
  2345. this.registerType('builtins.str', class extends String {
  2346. constructor(value) {
  2347. if (value && value.__str__) {
  2348. value = value.__str__();
  2349. } else if (typeof value !== 'string') {
  2350. value = JSON.stringify(value);
  2351. }
  2352. super(value);
  2353. }
  2354. });
  2355. this.registerType('builtins.complex', class {
  2356. constructor(real, imaginary) {
  2357. this.real = real;
  2358. this.imag = imaginary;
  2359. }
  2360. });
  2361. this.registerType('builtins.NoneType', class {});
  2362. this.registerType('builtins.object', class {
  2363. static __new__(cls, ...args) {
  2364. return execution.invoke(cls, args);
  2365. }
  2366. static __setattr__(obj, name, value) {
  2367. builtins.setattr(obj, name, value);
  2368. }
  2369. });
  2370. this.registerType('builtins.tuple', class extends Array {
  2371. constructor(items) {
  2372. super(items ? items.length : 0);
  2373. if (items) {
  2374. for (let i = 0; i < items.length; i++) {
  2375. this[i] = items[i];
  2376. }
  2377. }
  2378. }
  2379. });
  2380. this.registerType('builtins.staticmethod', class {});
  2381. this.registerType('builtins.Warning', class {});
  2382. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2383. this.registerType('builtins.BaseException', class {});
  2384. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2385. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2386. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2387. this.registerFunction('builtins.print', () => {});
  2388. this.registerFunction('builtins.unicode');
  2389. builtins.Ellipsis = new builtins.ellipsis();
  2390. this.registerType('typing._Final', class {});
  2391. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2392. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2393. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2394. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2395. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2396. this.registerType('typing._CallableType', class {});
  2397. this.registerFunction('typing.cast');
  2398. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2399. typing.Callable = Reflect.construct(typing._CallableType, []);
  2400. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2401. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2402. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2403. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2404. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2405. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2406. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2407. this.registerType('enum.Enum', class {});
  2408. this.registerFunction('operator.add');
  2409. this.registerFunction('operator.eq');
  2410. this.registerFunction('operator.ge');
  2411. this.registerFunction('operator.getitem');
  2412. this.registerFunction('operator.gt');
  2413. this.registerFunction('operator.mul');
  2414. this.registerFunction('operator.mod');
  2415. this.registerFunction('operator.le');
  2416. this.registerFunction('operator.lt');
  2417. this.registerFunction('operator.ne');
  2418. this.registerFunction('operator.floordiv');
  2419. this.registerFunction('operator.sub');
  2420. this.registerFunction('sys.path.append', () => {});
  2421. this.registerFunction('sys.path.insert', () => {});
  2422. this.registerType('argparse.Namespace', class {
  2423. constructor(args) {
  2424. this.args = args;
  2425. }
  2426. });
  2427. this.registerType('catboost._catboost._CatBoost', class {
  2428. _deserialize_model(/* serialized_model_str */) {
  2429. }
  2430. });
  2431. this.registerType('catboost.core._CatBoostBase', class {
  2432. constructor() {
  2433. this._object = new catboost._catboost._CatBoost();
  2434. }
  2435. __setstate__(state) {
  2436. for (const [key, value] of state) {
  2437. if (key === '__model') {
  2438. this._load_from_string(value);
  2439. continue;
  2440. }
  2441. this[key] = value;
  2442. }
  2443. }
  2444. _load_from_string(dump_model_str) {
  2445. this._deserialize_model(dump_model_str);
  2446. }
  2447. _deserialize_model(dump_model_str) {
  2448. this._object._deserialize_model(dump_model_str);
  2449. }
  2450. });
  2451. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2452. load_model(/* blob */) {
  2453. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2454. // this._load_from_string(blob);
  2455. }
  2456. });
  2457. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2458. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2459. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2460. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2461. catboost.CatBoost = catboost.core.CatBoost;
  2462. this.registerType('collections.deque', class extends Array {
  2463. constructor(iterable) {
  2464. super();
  2465. if (Array.isArray(iterable)) {
  2466. for (const value of iterable) {
  2467. this.push(value);
  2468. }
  2469. }
  2470. }
  2471. });
  2472. this.registerType('collections.OrderedDict', class extends dict {});
  2473. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2474. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2475. this.registerType('cuml.internals.array.CumlArray', class {});
  2476. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2477. this.registerType('cuml.raft.common.handle.Handle', class {
  2478. __setstate__(state) {
  2479. this._handle = state;
  2480. }
  2481. });
  2482. this.registerType('cuml.svm.svr.SVR', class {});
  2483. this.registerType('datetime.date', class {});
  2484. this.registerType('datetime.datetime', class extends datetime.date {});
  2485. this.registerType('datetime.timedelta', class {});
  2486. this.registerType('datetime.tzinfo', class {});
  2487. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2488. this.registerType('dnnlib.tflib.network.Network', class {});
  2489. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2490. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2491. constructor(dict) {
  2492. Object.assign(this, dict);
  2493. }
  2494. });
  2495. this.registerType('haiku._src.data_structures.frozendict', class {
  2496. constructor(obj) {
  2497. Object.assign(this, obj);
  2498. }
  2499. });
  2500. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2501. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2502. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2503. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2504. this.registerType('io.BytesIO', class {
  2505. constructor(buf, mode) {
  2506. this.mode = mode || 'r';
  2507. this._buf = this.mode === 'w' ? null : buf;
  2508. this._point = 0;
  2509. }
  2510. seek(offset) {
  2511. if (this._buf.seek) {
  2512. this._buf.seek(offset);
  2513. }
  2514. this._point = offset;
  2515. }
  2516. read(size, stream) {
  2517. if (this._buf.stream && stream) {
  2518. return this._buf.stream(size);
  2519. }
  2520. if (this._buf.peek) {
  2521. return this._buf.read(size);
  2522. }
  2523. if (this._buf instanceof Uint8Array) {
  2524. const start = this._point;
  2525. this._point = size === undefined ? this._buf.length : start + size;
  2526. return this._buf.subarray(start, this._point);
  2527. }
  2528. throw new python.Error('Unsupported buffer type.');
  2529. }
  2530. write(data) {
  2531. const src = this._buf || new Uint8Array();
  2532. this._point = src.length + data.length;
  2533. this._buf = new Uint8Array(this._point);
  2534. this._buf.set(src, 0);
  2535. this._buf.set(data, src.length);
  2536. }
  2537. getbuffer() {
  2538. return new builtins.memoryview(this._buf);
  2539. }
  2540. });
  2541. this.registerType('io.StringIO', class {
  2542. constructor() {
  2543. this._buf = [];
  2544. }
  2545. write(text) {
  2546. this._buf.push(text);
  2547. }
  2548. toString() {
  2549. return this._buf.join('');
  2550. }
  2551. });
  2552. this.registerType('numpy.dtype', class {
  2553. constructor(obj, align, copy) {
  2554. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2555. this.byteorder = obj.substring(0, 1);
  2556. obj = obj.substring(1);
  2557. } else {
  2558. this.byteorder = '=';
  2559. }
  2560. switch (obj) {
  2561. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2562. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2563. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2564. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2565. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2566. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2567. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2568. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2569. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2570. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2571. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2572. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2573. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2574. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2575. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2576. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2577. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2578. default:
  2579. if (obj.startsWith('V')) {
  2580. this.itemsize = parseInt(obj.substring(1), 10);
  2581. this.kind = 'V';
  2582. } else if (obj.startsWith('O')) {
  2583. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2584. this.kind = 'O';
  2585. } else if (obj.startsWith('S')) {
  2586. this.itemsize = parseInt(obj.substring(1), 10);
  2587. this.kind = 'S';
  2588. } else if (obj.startsWith('U')) { // Unicode string
  2589. this.kind = 'U';
  2590. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2591. } else if (obj.startsWith('T')) {
  2592. this.kind = 'T';
  2593. this.itemsize = parseInt(obj.substring(1), 10);
  2594. } else {
  2595. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2596. }
  2597. break;
  2598. }
  2599. if (align) {
  2600. this.align = align;
  2601. }
  2602. if (copy) {
  2603. this.copy = copy;
  2604. }
  2605. }
  2606. get str() {
  2607. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2608. }
  2609. get name() {
  2610. switch (this.kind) {
  2611. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2612. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2613. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2614. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2615. case 'M': return 'datetime64';
  2616. case 'b': return 'bool';
  2617. default: return this.__name__;
  2618. }
  2619. }
  2620. __setstate__(state) {
  2621. switch (state.length) {
  2622. case 8:
  2623. [
  2624. this.version, this.byteorder, this.subarray, this.names,
  2625. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2626. ] = state;
  2627. break;
  2628. case 9:
  2629. [
  2630. this.version, this.byteorder, this.subarray, this.names,
  2631. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2632. this.metadata
  2633. ] = state;
  2634. break;
  2635. default:
  2636. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2637. }
  2638. }
  2639. get __name__() {
  2640. switch (this.kind) {
  2641. case 'b':
  2642. switch (this.itemsize) {
  2643. case 1: return 'boolean';
  2644. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2645. }
  2646. case 'i':
  2647. switch (this.itemsize) {
  2648. case 1: return 'int8';
  2649. case 2: return 'int16';
  2650. case 4: return 'int32';
  2651. case 8: return 'int64';
  2652. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2653. }
  2654. case 'u':
  2655. switch (this.itemsize) {
  2656. case 1: return 'uint8';
  2657. case 2: return 'uint16';
  2658. case 4: return 'uint32';
  2659. case 8: return 'uint64';
  2660. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2661. }
  2662. case 'f':
  2663. switch (this.itemsize) {
  2664. case 1: return 'float8e5m2';
  2665. case 2: return 'float16';
  2666. case 4: return 'float32';
  2667. case 8: return 'float64';
  2668. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2669. }
  2670. case 'c':
  2671. switch (this.itemsize) {
  2672. case 8: return 'complex64';
  2673. case 16: return 'complex128';
  2674. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2675. }
  2676. case 'S':
  2677. case 'T':
  2678. return 'string';
  2679. case 'U':
  2680. return 'string';
  2681. case 'M':
  2682. return 'datetime';
  2683. case 'O':
  2684. return 'object';
  2685. case 'V':
  2686. return 'void';
  2687. default:
  2688. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2689. }
  2690. }
  2691. });
  2692. this.registerType('numpy.generic', class {});
  2693. this.registerType('numpy.inexact', class {});
  2694. this.registerType('numpy.bool_', class extends numpy.generic {});
  2695. this.registerType('numpy.number', class extends numpy.generic {});
  2696. this.registerType('numpy.integer', class extends numpy.number {});
  2697. this.registerType('numpy.floating', class extends numpy.inexact {});
  2698. this.registerType('numpy.float16', class extends numpy.floating {});
  2699. this.registerType('numpy.float32', class extends numpy.floating {});
  2700. this.registerType('numpy.float64', class extends numpy.floating {});
  2701. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2702. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2703. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2704. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2705. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2706. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2707. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2708. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2709. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2710. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2711. this.registerType('numpy.datetime64', class extends numpy.generic {});
  2712. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2713. constructor() {
  2714. super('|T16');
  2715. }
  2716. });
  2717. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2718. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2719. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2720. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2721. this.registerType('gensim.models.fasttext.FastText', class {});
  2722. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2723. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2724. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2725. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2726. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2727. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2728. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2729. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2730. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2731. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2732. this.registerFunction('gensim.models.phrases.original_scorer');
  2733. this.registerType('gensim.models.phrases.Phraser', class {});
  2734. this.registerType('gensim.models.phrases.Phrases', class {});
  2735. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2736. this.registerType('gensim.models.word2vec.Vocab', class {});
  2737. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2738. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2739. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2740. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2741. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2742. throw new builtins.AttributeError('This method should be called on a class object.');
  2743. });
  2744. this.registerFunction('gensim.utils.identity');
  2745. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2746. constructor(obj) {
  2747. Object.assign(this, obj);
  2748. }
  2749. });
  2750. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2751. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2752. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2753. __read__(unpickler) {
  2754. if (this.dtype.__name__ === 'object') {
  2755. return unpickler.load();
  2756. }
  2757. if (this.numpy_array_alignment_bytes) {
  2758. const [size] = unpickler.read(1);
  2759. unpickler.read(size);
  2760. }
  2761. if (this.order === 'F') {
  2762. throw new python.Error('Fortran order not implemented.');
  2763. }
  2764. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2765. this.data = unpickler.read(size);
  2766. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2767. }
  2768. });
  2769. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2770. __setstate__(state) {
  2771. this.subclass = state.get('subclass');
  2772. this.filename = state.get('state');
  2773. this.allow_mmap = state.get('allow_mmap');
  2774. }
  2775. __read__(/* unpickler */) {
  2776. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2777. }
  2778. });
  2779. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2780. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2781. this.registerType('keras.engine.sequential.Sequential', class {});
  2782. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2783. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2784. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2785. this.registerType('lasagne.layers.input.InputLayer', class {});
  2786. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2787. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2788. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2789. this.registerType('lightgbm.basic.Booster', class {
  2790. constructor() {
  2791. this.average_output = false;
  2792. this.models = [];
  2793. this.loaded_parameter = '';
  2794. }
  2795. __setstate__(state) {
  2796. const model_str = state.get('_handle', state.get('handle', null));
  2797. if (model_str) {
  2798. this.LoadModelFromString(model_str);
  2799. return;
  2800. }
  2801. for (const [key, value] of state) {
  2802. this[key] = value;
  2803. }
  2804. }
  2805. LoadModelFromString(model_str) {
  2806. const lines = model_str.split('\n');
  2807. const signature = lines.shift() || '?';
  2808. if (signature.trim() !== 'tree') {
  2809. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2810. }
  2811. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2812. const key_vals = new Map();
  2813. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2814. const cur_line = lines.shift().trim();
  2815. if (cur_line.length > 0) {
  2816. const strs = cur_line.split('=');
  2817. if (strs.length === 1) {
  2818. key_vals.set(strs[0], '');
  2819. } else if (strs.length === 2) {
  2820. key_vals.set(strs[0], strs[1]);
  2821. } else if (strs.length > 2) {
  2822. if (strs[0] === "feature_names") {
  2823. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2824. } else if (strs[0] === 'monotone_constraints') {
  2825. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2826. } else {
  2827. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2828. }
  2829. }
  2830. }
  2831. }
  2832. const atoi = (key, value) => {
  2833. if (key_vals.has(key)) {
  2834. return parseInt(key_vals.get(key), 10);
  2835. }
  2836. if (value !== undefined) {
  2837. return value;
  2838. }
  2839. throw new python.Error(`Model file does not specify ${key}.`);
  2840. };
  2841. const list = (key, size) => {
  2842. if (key_vals.has(key)) {
  2843. const value = key_vals.get(key).split(' ');
  2844. if (value.length !== size) {
  2845. throw new python.Error(`Wrong size of ${key}.`);
  2846. }
  2847. return value;
  2848. }
  2849. throw new python.Error(`Model file does not contain ${key}.`);
  2850. };
  2851. this.version = key_vals.get('version') || '';
  2852. this.num_class = atoi('num_class');
  2853. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2854. this.label_index = atoi('label_index');
  2855. this.max_feature_idx = atoi('max_feature_idx');
  2856. if (key_vals.has('average_output')) {
  2857. this.average_output = true;
  2858. }
  2859. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2860. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2861. if (key_vals.has('monotone_constraints')) {
  2862. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2863. }
  2864. if (key_vals.has('objective')) {
  2865. this.objective = key_vals.get('objective');
  2866. }
  2867. let tree = null;
  2868. while (lines.length > 0) {
  2869. const text = lines.shift();
  2870. const line = text.trim();
  2871. if (line.length === 0) {
  2872. continue;
  2873. }
  2874. if (line.startsWith('Tree=')) {
  2875. tree = { index: parseInt(line.split('=').pop(), 10) };
  2876. this.models.push(tree);
  2877. continue;
  2878. }
  2879. if (line === 'end of trees') {
  2880. break;
  2881. }
  2882. const param = line.split('=');
  2883. if (param.length !== 2) {
  2884. throw new python.Error(`Invalid property '${line}'.`);
  2885. }
  2886. const name = param[0].trim();
  2887. const value = param[1].trim();
  2888. tree[name] = value;
  2889. }
  2890. const ss = [];
  2891. let is_inparameter = false;
  2892. while (lines.length > 0) {
  2893. const text = lines.shift();
  2894. const line = text.trim();
  2895. if (line === 'parameters:') {
  2896. is_inparameter = true;
  2897. continue;
  2898. } else if (line === 'end of parameters') {
  2899. break;
  2900. } else if (is_inparameter) {
  2901. ss.push(line);
  2902. }
  2903. }
  2904. if (ss.length > 0) {
  2905. this.loaded_parameter = ss.join('\n');
  2906. }
  2907. }
  2908. });
  2909. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2910. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  2911. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  2912. this.registerFunction('megengine.functional.nn.relu', () => {});
  2913. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  2914. this.registerFunction('megengine.functional.tensor.arange', () => {});
  2915. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  2916. this.registerFunction('megengine.functional.tensor.concat', () => {});
  2917. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  2918. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  2919. this.registerFunction('megengine.functional.tensor.full', () => {});
  2920. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  2921. this.registerFunction('megengine.functional.tensor.split', () => {});
  2922. this.registerFunction('megengine.functional.tensor.stack', () => {});
  2923. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  2924. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  2925. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  2926. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  2927. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  2928. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  2929. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  2930. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  2931. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  2932. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  2933. this.registerType('megengine.distributed.group.Group', class {});
  2934. this.registerType('megengine.module.activation.ReLU', class {});
  2935. this.registerType('megengine.module.activation.Softmax', class {});
  2936. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  2937. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  2938. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  2939. this.registerType('megengine.module.conv.Conv2d', class {});
  2940. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  2941. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  2942. this.registerType('megengine.module.dropout.Dropout', class {});
  2943. this.registerType('megengine.module.identity.Identity', class {});
  2944. this.registerType('megengine.module.linear.Linear', class {});
  2945. this.registerType('megengine.module.module.Module', class {});
  2946. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  2947. this.registerType('megengine.module.normalization.GroupNorm', class {});
  2948. this.registerType('megengine.module.normalization.LayerNorm', class {});
  2949. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  2950. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  2951. this.registerType('megengine.module.qat.concat.Concat', class {});
  2952. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  2953. this.registerType('megengine.module.sequential.Sequential', class {});
  2954. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  2955. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  2956. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  2957. this.registerType('megengine.quantization.utils.QParams', class {});
  2958. this.registerType('megengine.quantization.utils.QuantMode', class {});
  2959. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  2960. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  2961. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  2962. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  2963. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  2964. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  2965. this.registerType('megengine.traced_module.expr.Apply', class {});
  2966. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  2967. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  2968. this.registerType('megengine.traced_module.expr.Constant', class {});
  2969. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  2970. this.registerType('megengine.traced_module.expr.Input', class {});
  2971. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  2972. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  2973. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  2974. this.registerType('megengine.traced_module.node.TensorNode', class {});
  2975. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  2976. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  2977. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  2978. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  2979. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  2980. this.registerType('megengine.tensor.Parameter', class {
  2981. constructor(data, dtype, device) {
  2982. this.data = data;
  2983. this.dtype = dtype;
  2984. this.device = device;
  2985. }
  2986. });
  2987. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  2988. toString() {
  2989. let content = '';
  2990. for (const child of this.children_defs) {
  2991. content += `${child},`;
  2992. }
  2993. if (typeof this.type === "string") {
  2994. return `${this.type.split(".").slice(-1)}(${content})`;
  2995. }
  2996. return `${this.type.__name__}(${content})`;
  2997. }
  2998. });
  2999. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3000. toString() {
  3001. let content = '';
  3002. if (this.const_val === null) {
  3003. content += '[';
  3004. } else {
  3005. content += this.const_val;
  3006. }
  3007. for (const t of Object.values(this.type)) {
  3008. content += t.__name__;
  3009. }
  3010. content += ']';
  3011. return content;
  3012. }
  3013. });
  3014. this.registerType('megengine.tensor.Tensor', class {
  3015. constructor(data, dtype, device) {
  3016. this.data = data;
  3017. this.dtype = dtype;
  3018. this.device = device;
  3019. }
  3020. });
  3021. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3022. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3023. this.name = name;
  3024. this.cname = cname;
  3025. this.np_dtype = np_dtype;
  3026. this.qmin = qmin;
  3027. this.qmax = qmax;
  3028. this.is_signed = is_signed;
  3029. }
  3030. });
  3031. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3032. this.registerType('nolearn.lasagne.base.Layers', class {});
  3033. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3034. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3035. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3036. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3037. this.registerType('numpy.ndarray', class {
  3038. constructor(shape, dtype, buffer, offset, strides, order) {
  3039. this.shape = shape;
  3040. this.dtype = dtype;
  3041. this.data = buffer === undefined ? null : buffer;
  3042. this.offset = offset === undefined ? 0 : offset;
  3043. this._strides = strides === undefined ? null : strides;
  3044. this.order = order === undefined ? null : order;
  3045. this.flags = {};
  3046. this._read();
  3047. }
  3048. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3049. return new cls(shape, dtype, buffer, offset, strides, order);
  3050. }
  3051. __setstate__(state) {
  3052. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3053. this._read();
  3054. }
  3055. flatten() {
  3056. const size = this.shape.reduce((a, b) => a * b, 1);
  3057. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3058. value.flags = this.flags;
  3059. return value;
  3060. }
  3061. reshape(shape, order) {
  3062. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3063. }
  3064. tobytes() {
  3065. return this.data;
  3066. }
  3067. tolist() {
  3068. if (this.shape.length < 0 || this.shape.length > 1) {
  3069. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3070. }
  3071. const size = this.shape.reduce((a, b) => a * b, 1);
  3072. const list = new Array(size);
  3073. switch (this.dtype.kind) {
  3074. case 'U': {
  3075. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3076. const itemsize = this.dtype.itemsize >> 2;
  3077. let offset = 0;
  3078. for (let i = 0; i < size; i++) {
  3079. const buffer = data.subarray(offset, offset + itemsize);
  3080. const index = buffer.indexOf(0);
  3081. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3082. offset += itemsize;
  3083. }
  3084. return list;
  3085. }
  3086. case 'S': {
  3087. const data = this.data;
  3088. const itemsize = this.dtype.itemsize;
  3089. const decoder = new TextDecoder('utf-8');
  3090. let offset = 0;
  3091. for (let i = 0; i < size; i++) {
  3092. const buffer = data.subarray(offset, offset + itemsize);
  3093. const index = buffer.indexOf(0);
  3094. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3095. offset += itemsize;
  3096. }
  3097. return list;
  3098. }
  3099. case 'V': {
  3100. const data = this.data;
  3101. const itemsize = this.dtype.itemsize;
  3102. let offset = 0;
  3103. for (let i = 0; i < size; i++) {
  3104. list[i] = data.slice(offset, offset + itemsize);
  3105. offset += itemsize;
  3106. }
  3107. return list;
  3108. }
  3109. case 'T': {
  3110. return this.data;
  3111. }
  3112. case 'O': {
  3113. return this.data;
  3114. }
  3115. default: {
  3116. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3117. }
  3118. }
  3119. }
  3120. get itemsize() {
  3121. return this.dtype.itemsize;
  3122. }
  3123. get size() {
  3124. return (this.shape || []).reduce((a, b) => a * b, 1);
  3125. }
  3126. get strides() {
  3127. if (!this._strides) {
  3128. const shape = this.shape;
  3129. const strides = new Array(shape.length);
  3130. let stride = this.itemsize;
  3131. for (let i = shape.length - 1; i >= 0; i--) {
  3132. strides[i] = stride;
  3133. stride *= shape[i];
  3134. }
  3135. return strides;
  3136. }
  3137. return this._strides;
  3138. }
  3139. _read() {
  3140. if (this.data) {
  3141. const length = this.dtype.itemsize * this.size;
  3142. if (typeof this.data === 'string') {
  3143. this.data = this._unescape(this.data, length);
  3144. if (this.data.length !== length) {
  3145. throw new python.Error('Invalid string array data size.');
  3146. }
  3147. } else if (this.data.length !== length) {
  3148. // throw new python.Error('Invalid array data size.');
  3149. }
  3150. }
  3151. }
  3152. _unescape(token, size) {
  3153. const length = token.length;
  3154. const a = new Uint8Array(length);
  3155. if (size && size === length) {
  3156. for (let p = 0; p < size; p++) {
  3157. a[p] = token.charCodeAt(p);
  3158. }
  3159. return a;
  3160. }
  3161. let i = 0;
  3162. let o = 0;
  3163. while (i < length) {
  3164. let c = token.charCodeAt(i++);
  3165. if (c !== 0x5C || i >= length) {
  3166. a[o++] = c;
  3167. } else {
  3168. c = token.charCodeAt(i++);
  3169. switch (c) {
  3170. case 0x27: a[o++] = 0x27; break; // '
  3171. case 0x5C: a[o++] = 0x5C; break; // \\
  3172. case 0x22: a[o++] = 0x22; break; // "
  3173. case 0x72: a[o++] = 0x0D; break; // \r
  3174. case 0x6E: a[o++] = 0x0A; break; // \n
  3175. case 0x74: a[o++] = 0x09; break; // \t
  3176. case 0x62: a[o++] = 0x08; break; // \b
  3177. case 0x58: // x
  3178. case 0x78: { // X
  3179. const xsi = i - 1;
  3180. const xso = o;
  3181. for (let xi = 0; xi < 2; xi++) {
  3182. if (i >= length) {
  3183. i = xsi;
  3184. o = xso;
  3185. a[o] = 0x5c;
  3186. break;
  3187. }
  3188. let c = token.charCodeAt(i++);
  3189. if (c >= 65 && c <= 70) {
  3190. c -= 55;
  3191. } else if (c >= 97 && c <= 102) {
  3192. c -= 87;
  3193. } else if (c >= 48 && c <= 57) {
  3194. c -= 48;
  3195. } else {
  3196. c = -1;
  3197. }
  3198. if (c === -1) {
  3199. i = xsi;
  3200. o = xso;
  3201. a[o] = 0x5c;
  3202. break;
  3203. }
  3204. a[o] = a[o] << 4 | c;
  3205. }
  3206. o++;
  3207. break;
  3208. }
  3209. default:
  3210. if (c < 48 || c > 57) { // 0-9
  3211. a[o++] = 0x5c;
  3212. a[o++] = c;
  3213. } else {
  3214. i--;
  3215. const osi = i;
  3216. const oso = o;
  3217. for (let oi = 0; oi < 3; oi++) {
  3218. if (i >= length) {
  3219. i = osi;
  3220. o = oso;
  3221. a[o] = 0x5c;
  3222. break;
  3223. }
  3224. const od = token.charCodeAt(i++);
  3225. if (od < 48 || od > 57) {
  3226. i = osi;
  3227. o = oso;
  3228. a[o] = 0x5c;
  3229. break;
  3230. }
  3231. a[o] = a[o] << 3 | od - 48;
  3232. }
  3233. o++;
  3234. }
  3235. break;
  3236. }
  3237. }
  3238. }
  3239. return a.slice(0, o);
  3240. }
  3241. });
  3242. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3243. static __new__(/* subtype, data, dtype, copy */) {
  3244. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3245. }
  3246. });
  3247. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3248. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3249. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3250. super(data.shape, data.dtype, data.data);
  3251. }
  3252. });
  3253. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  3254. });
  3255. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3256. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {});
  3257. this.registerType('pandas.core.arrays.integer.IntegerArray', class {});
  3258. this.registerType('pandas.core.generic.Flags', class {});
  3259. this.registerType('pandas.core.generic.NDFrame', class {
  3260. constructor(data) {
  3261. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3262. this._metadata = [];
  3263. builtins.object.__setattr__(self, "_mgr", data);
  3264. builtins.object.__setattr__(self, "_attrs", {});
  3265. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3266. }
  3267. __setstate__(state) {
  3268. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3269. this._mgr = state;
  3270. } else if (state instanceof builtins.dict) {
  3271. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3272. state.__setitem__('_mgr', state.pop('_data'));
  3273. }
  3274. const typ = state.get('_typ');
  3275. if (typ) {
  3276. let attrs = state.get('_attrs', new builtins.dict());
  3277. if (!attrs) {
  3278. attrs = new builtins.dict();
  3279. }
  3280. builtins.object.__setattr__(this, '_attrs', attrs);
  3281. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3282. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3283. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3284. for (const k of meta) {
  3285. if (state.__contains__(k) && k !== '_flags') {
  3286. const v = state.__getitem__(k);
  3287. builtins.object.__setattr__(this, k, v);
  3288. }
  3289. }
  3290. for (const [k, v] of state) {
  3291. if (!meta.has(k)) {
  3292. builtins.object.__setattr__(this, k, v);
  3293. }
  3294. }
  3295. } else {
  3296. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3297. }
  3298. } else if (state.size === 2) {
  3299. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3300. }
  3301. }
  3302. });
  3303. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3304. });
  3305. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3306. return new cls(d);
  3307. });
  3308. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3309. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3310. this.registerType('pandas.core.indexes.base.Index', class {});
  3311. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3312. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3313. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3314. this.registerType('pandas.core.index.Int64Index', class {});
  3315. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3316. });
  3317. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3318. });
  3319. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3320. return pandas.core.internals.blocks.NumpyBlock;
  3321. });
  3322. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3323. return values;
  3324. });
  3325. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3326. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3327. return new klass(values, ndim, placement, refs);
  3328. });
  3329. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3330. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3331. this.registerType('pandas.core.series.Series', class {});
  3332. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked');
  3333. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3334. values = execution.invoke('pandas.core.internals.blocks.maybe_coerce_values', [values]);
  3335. // if not isinstance(placement, BlockPlacement):
  3336. // placement = BlockPlacement(placement)
  3337. return execution.invoke('pandas.core.internals.blocks.new_block', [values, placement, ndim]);
  3338. });
  3339. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3340. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3341. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3342. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3343. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3344. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3345. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3346. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3347. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3348. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3349. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3350. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3351. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3352. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3353. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3354. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3355. this.registerType('pathlib.Path', class {});
  3356. this.registerType('pathlib.PosixPath', class {});
  3357. this.registerType('pathlib.WindowsPath', class {});
  3358. this.registerType('shap._serializable.Serializable', class {});
  3359. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3360. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3361. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3362. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3363. this.registerType('sklearn._loss.link.BaseLink', class {});
  3364. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3365. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3366. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3367. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3368. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3369. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3370. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3371. this.registerType('sklearn._loss.link.Interval', class {});
  3372. this.registerType('sklearn._loss.link.LogitLink', class {});
  3373. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3374. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3375. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3376. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3377. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3378. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3379. this.registerType('sklearn.base.BaseEstimator', class {});
  3380. this.registerType('sklearn.base.TransformerMixin', class {});
  3381. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3382. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3383. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3384. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3385. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3386. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3387. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3388. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3389. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3390. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3391. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3392. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3393. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3394. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3395. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3396. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3397. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3398. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3399. this.registerType('sklearn.decomposition.PCA', class {});
  3400. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3401. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3402. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3403. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3404. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3405. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3406. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3407. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3408. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3409. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3410. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3411. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3412. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3413. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3414. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3415. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3416. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3417. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3418. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3419. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3420. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3421. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3422. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3423. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3424. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3425. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3426. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3427. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3428. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3429. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3430. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3431. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3432. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3433. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3434. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3435. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3436. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3437. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3438. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3439. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3440. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3441. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3442. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3443. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3444. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3445. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3446. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3447. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3448. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3449. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3450. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3451. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3452. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3453. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3454. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3455. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3456. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3457. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3458. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3459. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3460. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3461. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3462. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3463. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3464. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3465. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3466. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3467. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3468. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3469. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3470. this.registerType('sklearn.impute.SimpleImputer', class {});
  3471. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3472. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3473. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3474. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3475. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3476. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3477. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3478. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3479. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3480. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3481. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3482. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3483. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3484. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3485. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3486. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3487. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3488. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3489. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3490. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3491. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3492. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3493. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3494. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3495. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3496. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3497. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3498. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3499. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3500. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3501. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3502. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3503. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3504. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3505. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3506. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3507. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3508. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3509. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3510. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3511. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3512. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3513. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3514. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3515. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3516. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3517. this.registerType('sklearn.model_selection._split.KFold', class {});
  3518. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3519. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3520. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3521. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3522. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3523. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3524. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3525. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3526. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3527. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3528. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3529. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3530. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3531. return obj.__new__(obj);
  3532. });
  3533. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3534. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3535. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3536. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3537. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3538. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3539. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3540. return obj.__new__(obj);
  3541. });
  3542. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3543. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3544. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3545. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3546. return obj.__new__(obj);
  3547. });
  3548. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3549. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3550. return obj.__new__(obj);
  3551. });
  3552. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3553. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3554. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3555. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3556. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3557. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3558. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3559. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3560. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3561. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3562. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3563. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3564. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3565. this.registerType('sklearn.pipeline.Pipeline', class {});
  3566. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3567. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3568. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3569. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3570. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3571. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3572. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3573. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3574. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3575. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3576. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3577. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3578. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3579. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3580. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3581. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3582. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3583. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3584. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3585. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3586. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3587. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3588. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3589. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3590. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3591. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3592. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3593. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3594. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3595. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3596. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3597. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3598. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3599. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3600. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3601. this.registerType('sklearn.svm._classes.SVC', class {});
  3602. this.registerType('sklearn.svm._classes.SVR', class {});
  3603. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3604. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3605. this.registerType('sklearn.svm.classes.SVC', class {});
  3606. this.registerType('sklearn.svm.classes.SVR', class {});
  3607. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3608. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3609. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3610. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3611. this.registerType('sklearn.tree._tree.Tree', class {
  3612. constructor(n_features, n_classes, n_outputs) {
  3613. this.n_features = n_features;
  3614. this.n_classes = n_classes;
  3615. this.n_outputs = n_outputs;
  3616. }
  3617. __setstate__(state) {
  3618. this.max_depth = state.get('max_depth');
  3619. this.node_count = state.get('node_count');
  3620. this.nodes = state.get('nodes');
  3621. this.values = state.get('values');
  3622. }
  3623. });
  3624. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3625. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3626. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3627. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3628. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3629. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3630. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3631. this.registerType('pickle.Unpickler', class {
  3632. constructor(data) {
  3633. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3634. this.persistent_load = () => {
  3635. throw new python.Error('Unsupported persistent id.');
  3636. };
  3637. }
  3638. load() {
  3639. const reader = this._reader;
  3640. const marker = [];
  3641. let stack = [];
  3642. const memo = {};
  3643. let size = 0;
  3644. while (reader.position < reader.length) {
  3645. const opcode = reader.byte();
  3646. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3647. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3648. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3649. switch (opcode) {
  3650. case 128: { // PROTO
  3651. const version = reader.byte();
  3652. if (version > 5) {
  3653. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3654. }
  3655. break;
  3656. }
  3657. case 99: { // GLOBAL 'c'
  3658. const module = reader.line();
  3659. const name = reader.line();
  3660. stack.push(this.find_class(module, name));
  3661. break;
  3662. }
  3663. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3664. const name = stack.pop();
  3665. const module = stack.pop();
  3666. stack.push(this.find_class(module, name));
  3667. break;
  3668. }
  3669. case 111: { // OBJ 'o'
  3670. const args = stack;
  3671. const cls = args.pop();
  3672. stack = marker.pop();
  3673. const obj = this._instantiate(cls, args);
  3674. stack.push(obj);
  3675. break;
  3676. }
  3677. case 112 : { // PUT 'p'
  3678. const index = parseInt(reader.line(), 10);
  3679. memo[index] = stack[stack.length - 1];
  3680. size++;
  3681. break;
  3682. }
  3683. case 103: { // GET 'g'
  3684. const index = parseInt(reader.line(), 10);
  3685. stack.push(memo[index]);
  3686. break;
  3687. }
  3688. case 48: // POP '0'
  3689. stack.pop();
  3690. break;
  3691. case 49: // POP_MARK '1'
  3692. stack = marker.pop();
  3693. break;
  3694. case 50: // DUP '2'
  3695. stack.push(stack[stack.length - 1]);
  3696. break;
  3697. case 80: // PERSID 'P'
  3698. stack.push(this.persistent_load(reader.line()));
  3699. break;
  3700. case 81: // BINPERSID 'Q'
  3701. stack.push(this.persistent_load(stack.pop()));
  3702. break;
  3703. case 82: { // REDUCE 'R'
  3704. const args = stack.pop();
  3705. const func = stack.pop();
  3706. stack.push(this._reduce(func, args));
  3707. break;
  3708. }
  3709. case 129: { // NEWOBJ
  3710. const args = stack.pop();
  3711. const cls = stack.pop();
  3712. const obj = this._newobj(cls, args);
  3713. stack.push(obj);
  3714. break;
  3715. }
  3716. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3717. const kwargs = stack.pop();
  3718. const args = stack.pop();
  3719. const cls = stack.pop();
  3720. if (Object.entries(kwargs).length > 0) {
  3721. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3722. }
  3723. const obj = this._newobj(cls, args);
  3724. stack.push(obj);
  3725. break;
  3726. }
  3727. case 104: // BINGET 'h'
  3728. stack.push(memo[reader.byte()]);
  3729. break;
  3730. case 105: { // INST 'i'
  3731. const module = reader.line();
  3732. const name = reader.line();
  3733. const args = stack;
  3734. const cls = `${module}.${name}`;
  3735. stack = marker.pop();
  3736. // cls = this.find_class(module, name)
  3737. const obj = this._instantiate(cls, args);
  3738. stack.push(obj);
  3739. break;
  3740. }
  3741. case 106: // LONG_BINGET 'j'
  3742. stack.push(memo[reader.uint32()]);
  3743. break;
  3744. case 113: // BINPUT 'q'
  3745. memo[reader.byte()] = stack[stack.length - 1];
  3746. size++;
  3747. break;
  3748. case 114: // LONG_BINPUT 'r'
  3749. memo[reader.uint32()] = stack[stack.length - 1];
  3750. size++;
  3751. break;
  3752. case 74: // BININT 'J'
  3753. stack.push(reader.int32());
  3754. break;
  3755. case 75: // BININT1 'K'
  3756. stack.push(reader.byte());
  3757. break;
  3758. case 76: // LONG 'L'
  3759. stack.push(parseInt(reader.line(), 10));
  3760. break;
  3761. case 77: // BININT2 'M'
  3762. stack.push(reader.uint16());
  3763. break;
  3764. case 66: // BINBYTES 'B' (Protocol 3)
  3765. stack.push(reader.read(reader.int32()));
  3766. break;
  3767. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3768. stack.push(reader.read(reader.byte()));
  3769. break;
  3770. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3771. stack.push(reader.read(reader.int64().toNumber()));
  3772. break;
  3773. case 70: // FLOAT 'F'
  3774. stack.push(parseFloat(reader.line()));
  3775. break;
  3776. case 71: // BINFLOAT 'G'
  3777. stack.push(reader.float64());
  3778. break;
  3779. case 73: { // INT 'I'
  3780. const value = reader.line();
  3781. if (value === '01') {
  3782. stack.push(true);
  3783. } else if (value === '00') {
  3784. stack.push(false);
  3785. } else {
  3786. stack.push(parseInt(value, 10));
  3787. }
  3788. break;
  3789. }
  3790. case 93: // EMPTY_LIST ']'
  3791. stack.push(new builtins.list());
  3792. break;
  3793. case 41: // EMPTY_TUPLE ')'
  3794. stack.push([]);
  3795. break;
  3796. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3797. stack.push([]);
  3798. break;
  3799. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3800. const items = stack;
  3801. stack = marker.pop();
  3802. const obj = stack[stack.length - 1];
  3803. for (let i = 0; i < items.length; i++) {
  3804. obj.push(items[i]);
  3805. }
  3806. break;
  3807. }
  3808. case 145: { // FROZENSET '\x91' (Protocol 4)
  3809. const items = stack;
  3810. stack = marker.pop();
  3811. stack.push(items);
  3812. break;
  3813. }
  3814. case 100: { // DICT 'd'
  3815. const items = stack;
  3816. stack = marker.pop();
  3817. const dict = new builtins.dict();
  3818. for (let i = 0; i < items.length; i += 2) {
  3819. dict.__setitem__(items[i], items[i + 1]);
  3820. }
  3821. stack.push(dict);
  3822. break;
  3823. }
  3824. case 108: { // LIST 'l'
  3825. const items = stack;
  3826. stack = marker.pop();
  3827. stack.push(items);
  3828. break;
  3829. }
  3830. case 116: { // TUPLE 't'
  3831. const items = stack;
  3832. stack = marker.pop();
  3833. stack.push(items);
  3834. break;
  3835. }
  3836. case 133: { // TUPLE1 // '\x85'
  3837. stack.push([stack.pop()]);
  3838. break;
  3839. }
  3840. case 134: { // TUPLE2 '\x86'
  3841. const b = stack.pop();
  3842. const a = stack.pop();
  3843. stack.push([a, b]);
  3844. break;
  3845. }
  3846. case 135: { // TUPLE3 '\x87'
  3847. const c = stack.pop();
  3848. const b = stack.pop();
  3849. const a = stack.pop();
  3850. stack.push([a, b, c]);
  3851. break;
  3852. }
  3853. case 115: { // SETITEM 's'
  3854. const value = stack.pop();
  3855. const key = stack.pop();
  3856. const obj = stack[stack.length - 1];
  3857. if (obj.__setitem__) {
  3858. obj.__setitem__(key, value);
  3859. } else {
  3860. obj[key] = value;
  3861. }
  3862. break;
  3863. }
  3864. case 117: { // SETITEMS 'u'
  3865. const items = stack;
  3866. stack = marker.pop();
  3867. const obj = stack[stack.length - 1];
  3868. if (obj.__setitem__) {
  3869. for (let i = 0; i < items.length; i += 2) {
  3870. obj.__setitem__(items[i], items[i + 1]);
  3871. }
  3872. } else {
  3873. for (let i = 0; i < items.length; i += 2) {
  3874. obj[items[i]] = items[i + 1];
  3875. }
  3876. }
  3877. break;
  3878. }
  3879. case 125: // EMPTY_DICT '}'
  3880. stack.push(new builtins.dict());
  3881. break;
  3882. case 97: { // APPEND 'a'
  3883. const append = stack.pop();
  3884. stack[stack.length - 1].push(append);
  3885. break;
  3886. }
  3887. case 101: { // APPENDS 'e'
  3888. const appends = stack;
  3889. stack = marker.pop();
  3890. const list = stack[stack.length - 1];
  3891. list.push(...appends);
  3892. break;
  3893. }
  3894. case 83: { // STRING 'S'
  3895. const str = reader.line();
  3896. stack.push(str.substr(1, str.length - 2));
  3897. break;
  3898. }
  3899. case 84: // BINSTRING 'T'
  3900. stack.push(reader.string(reader.uint32()));
  3901. break;
  3902. case 85 : // SHORT_BINSTRING 'U'
  3903. stack.push(reader.string(reader.byte()));
  3904. break;
  3905. case 86: // UNICODE 'V'
  3906. stack.push(reader.line());
  3907. break;
  3908. case 88: // BINUNICODE 'X
  3909. stack.push(reader.string(reader.uint32(), 'utf-8'));
  3910. break;
  3911. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  3912. stack.push(reader.string(reader.byte(), 'utf-8'));
  3913. break;
  3914. case 98: { // BUILD 'b'
  3915. const state = stack.pop();
  3916. let obj = stack.pop();
  3917. if (obj.__setstate__) {
  3918. if (obj.__setstate__.__call__) {
  3919. obj.__setstate__.__call__([obj, state]);
  3920. } else {
  3921. obj.__setstate__(state);
  3922. }
  3923. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  3924. obj.__state__ = state;
  3925. } else if (obj instanceof Map && state instanceof Map) {
  3926. for (const [key, value] of state) {
  3927. obj.set(key, value);
  3928. }
  3929. } else if (obj instanceof Map) {
  3930. for (const key in state) {
  3931. obj.set(key, state[key]);
  3932. }
  3933. } else if (state instanceof Map) {
  3934. for (const [key, value] of state) {
  3935. obj[key] = value;
  3936. }
  3937. } else {
  3938. Object.assign(obj, state);
  3939. }
  3940. if (obj.__read__) {
  3941. obj = obj.__read__(this);
  3942. }
  3943. stack.push(obj);
  3944. break;
  3945. }
  3946. case 40: // MARK '('
  3947. marker.push(stack);
  3948. stack = [];
  3949. break;
  3950. case 136: // NEWTRUE '\x88'
  3951. stack.push(true);
  3952. break;
  3953. case 137: // NEWFALSE '\x89'
  3954. stack.push(false);
  3955. break;
  3956. case 138: { // LONG1 '\x8a'
  3957. const data = reader.read(reader.byte());
  3958. let number = 0;
  3959. switch (data.length) {
  3960. case 0: number = 0; break;
  3961. /* eslint-disable prefer-destructuring */
  3962. case 1: number = data[0]; break;
  3963. /* eslint-enable prefer-destructuring */
  3964. case 2: number = data[1] << 8 | data[0]; break;
  3965. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  3966. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  3967. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  3968. default: number = Array.prototype.slice.call(data, 0); break;
  3969. }
  3970. stack.push(number);
  3971. break;
  3972. }
  3973. case 139: // LONG4 '\x8b'
  3974. // decode LONG4
  3975. stack.push(reader.read(reader.uint32()));
  3976. break;
  3977. case 148: // MEMOIZE '\x94' (Protocol 4)
  3978. memo[size++] = stack[stack.length - 1];
  3979. break;
  3980. case 149: // FRAME '\x95' (Protocol 4)
  3981. reader.read(8);
  3982. break;
  3983. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  3984. stack.push(reader.read(reader.int64().toNumber()));
  3985. break;
  3986. }
  3987. case 78: // NONE 'N'
  3988. stack.push(null);
  3989. break;
  3990. case 46: // STOP '.'
  3991. return stack.pop();
  3992. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  3993. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  3994. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  3995. default:
  3996. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  3997. }
  3998. }
  3999. throw new python.Error('Unexpected end of file.');
  4000. }
  4001. find_class(module, name) {
  4002. execution.__import__(module);
  4003. return execution.resolve(`${module}.${name}`);
  4004. }
  4005. _instantiate(cls, args) {
  4006. return execution.invoke(cls, args);
  4007. }
  4008. _newobj(cls, args) {
  4009. // cls.__new__(cls, args)
  4010. return execution.invoke(cls, args);
  4011. }
  4012. _reduce(func, args) {
  4013. return execution.invoke(func, args);
  4014. }
  4015. read(size) {
  4016. return this._reader.read(size);
  4017. }
  4018. stream(size) {
  4019. return this._reader.stream(size);
  4020. }
  4021. });
  4022. this.registerType('random.Random', class {});
  4023. this.registerType('re.Pattern', class {
  4024. constructor(pattern, flags) {
  4025. this.pattern = pattern;
  4026. this.flags = flags;
  4027. }
  4028. });
  4029. this.registerType('spacy._ml.PrecomputableAffine', class {
  4030. __setstate__(state) {
  4031. Object.assign(this, new pickle.Unpickler(state).load());
  4032. }
  4033. });
  4034. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4035. __setstate__(state) {
  4036. Object.assign(this, new pickle.Unpickler(state).load());
  4037. }
  4038. });
  4039. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4040. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4041. this.registerType('theano.compile.function_module.Function', class {});
  4042. this.registerType('theano.compile.function_module.Supervisor', class {});
  4043. this.registerType('theano.compile.io.In', class {});
  4044. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4045. this.registerType('theano.compile.mode.Mode', class {});
  4046. this.registerType('theano.compile.ops.OutputGuard', class {});
  4047. this.registerType('theano.compile.ops.Shape', class {});
  4048. this.registerType('theano.compile.ops.Shape_i', class {});
  4049. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4050. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4051. this.registerType('theano.gof.graph.Apply', class {});
  4052. this.registerType('theano.gof.link.Container', class {});
  4053. this.registerType('theano.gof.opt._metadict', class {});
  4054. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4055. this.registerType('theano.gof.opt.MergeFeature', class {});
  4056. this.registerType('theano.gof.optdb.Query', class {});
  4057. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4058. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4059. this.registerType('theano.gof.utils.scratchpad', class {});
  4060. this.registerType('theano.misc.ordered_set.Link', class {});
  4061. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4062. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4063. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4064. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4065. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4066. this.registerType('theano.scalar.basic.Abs', class {});
  4067. this.registerType('theano.scalar.basic.Add', class {});
  4068. this.registerType('theano.scalar.basic.Cast', class {});
  4069. this.registerType('theano.scalar.basic.Composite', class {});
  4070. this.registerType('theano.scalar.basic.EQ', class {});
  4071. this.registerType('theano.scalar.basic.GE', class {});
  4072. this.registerType('theano.scalar.basic.Identity', class {});
  4073. this.registerType('theano.scalar.basic.IntDiv', class {});
  4074. this.registerType('theano.scalar.basic.Inv', class {});
  4075. this.registerType('theano.scalar.basic.LE', class {});
  4076. this.registerType('theano.scalar.basic.LT', class {});
  4077. this.registerType('theano.scalar.basic.Mul', class {});
  4078. this.registerType('theano.scalar.basic.Neg', class {});
  4079. this.registerType('theano.scalar.basic.Pow', class {});
  4080. this.registerType('theano.scalar.basic.Scalar', class {});
  4081. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4082. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4083. this.registerType('theano.scalar.basic.Second', class {});
  4084. this.registerType('theano.scalar.basic.Sgn', class {});
  4085. this.registerType('theano.scalar.basic.specific_out', class {});
  4086. this.registerType('theano.scalar.basic.Sub', class {});
  4087. this.registerType('theano.scalar.basic.Switch', class {});
  4088. this.registerType('theano.scalar.basic.Tanh', class {});
  4089. this.registerType('theano.scalar.basic.transfer_type', class {});
  4090. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4091. this.registerType('theano.tensor.basic.Alloc', class {});
  4092. this.registerType('theano.tensor.basic.Dot', class {});
  4093. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4094. this.registerType('theano.tensor.basic.Reshape', class {});
  4095. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4096. this.registerType('theano.tensor.blas.Dot22', class {});
  4097. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4098. this.registerType('theano.tensor.blas.Gemm', class {});
  4099. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4100. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4101. this.registerType('theano.tensor.elemwise.Sum', class {});
  4102. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4103. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4104. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4105. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4106. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4107. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4108. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4109. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4110. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4111. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4112. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4113. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4114. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4115. this.registerType('theano.tensor.opt.MakeVector', class {});
  4116. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4117. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4118. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4119. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4120. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4121. this.registerType('theano.tensor.type.TensorType', class {});
  4122. this.registerType('theano.tensor.var.TensorConstant', class {});
  4123. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4124. this.registerType('theano.tensor.var.TensorVariable', class {});
  4125. this.registerType('thinc.describe.Biases', class {});
  4126. this.registerType('thinc.describe.Dimension', class {});
  4127. this.registerType('thinc.describe.Gradient', class {});
  4128. this.registerType('thinc.describe.Weights', class {});
  4129. this.registerType('thinc.describe.Synapses', class {});
  4130. this.registerType('thinc.neural._classes.affine.Affine', class {
  4131. __setstate__(state) {
  4132. Object.assign(this, new pickle.Unpickler(state).load());
  4133. }
  4134. });
  4135. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4136. __setstate__(state) {
  4137. Object.assign(this, new pickle.Unpickler(state).load());
  4138. }
  4139. });
  4140. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4141. __setstate__(state) {
  4142. Object.assign(this, new pickle.Unpickler(state).load());
  4143. }
  4144. });
  4145. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4146. __setstate__(state) {
  4147. Object.assign(this, new pickle.Unpickler(state).load());
  4148. }
  4149. });
  4150. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4151. __setstate__(state) {
  4152. Object.assign(this, new pickle.Unpickler(state).load());
  4153. }
  4154. });
  4155. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4156. __setstate__(state) {
  4157. Object.assign(this, new pickle.Unpickler(state).load());
  4158. }
  4159. });
  4160. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4161. __setstate__(state) {
  4162. Object.assign(this, new pickle.Unpickler(state).load());
  4163. }
  4164. });
  4165. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4166. __setstate__(state) {
  4167. Object.assign(this, new pickle.Unpickler(state).load());
  4168. }
  4169. });
  4170. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4171. __setstate__(state) {
  4172. Object.assign(this, new pickle.Unpickler(state).load());
  4173. }
  4174. });
  4175. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4176. __setstate__(state) {
  4177. Object.assign(this, new pickle.Unpickler(state).load());
  4178. }
  4179. });
  4180. this.registerType('thinc.neural.mem.Memory', class {
  4181. });
  4182. this.registerType('thinc.neural.ops.NumpyOps', class {
  4183. });
  4184. this.registerType('__main__.BYOLState', class {
  4185. constructor(dict) {
  4186. Object.assign(this, dict);
  4187. }
  4188. });
  4189. const types = this.register('types');
  4190. this.registerType('types.GenericAlias', class {});
  4191. this.registerType('types.SimpleNamespace', class {});
  4192. this.registerFunction('types.resolve_bases', (bases) => {
  4193. return bases;
  4194. });
  4195. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4196. if (kwds) {
  4197. kwds = new builtins.dict(kwds);
  4198. } else {
  4199. kwds = new builtins.dict();
  4200. }
  4201. let meta = null;
  4202. if (kwds.__contains__('metaclass')) {
  4203. meta = kwds.pop('metaclass');
  4204. } else if (bases && bases.length > 0) {
  4205. meta = builtins.type(bases[0]);
  4206. } else {
  4207. meta = builtins.type;
  4208. }
  4209. if (meta instanceof builtins.type) {
  4210. meta = types._calculate_meta(meta, bases);
  4211. }
  4212. let ns = null;
  4213. if (builtins.hasattr(meta, '__prepare__')) {
  4214. // ns = meta.__prepare__(name, bases, **kwds)
  4215. } else {
  4216. ns = new builtins.dict();
  4217. }
  4218. return [meta, ns, kwds];
  4219. });
  4220. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4221. const winner = meta;
  4222. return winner;
  4223. });
  4224. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4225. const resolved_bases = types.resolve_bases(bases);
  4226. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4227. if (exec_body) {
  4228. exec_body(ns);
  4229. }
  4230. return new meta(name, resolved_bases, ns);
  4231. });
  4232. types.ObjectType = builtins.object;
  4233. types.ModuleType = builtins.module;
  4234. types.MethodType = builtins.method;
  4235. types.FunctionType = builtins.function;
  4236. types.TypeType = builtins.type;
  4237. types.CodeType = builtins.code;
  4238. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4239. this.registerType('xgboost.core.Booster', class {});
  4240. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4241. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4242. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4243. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4244. return execution.invoke('builtins.bytearray', [obj, encoding]);
  4245. });
  4246. this.registerType('builtins.bytearray', class extends Uint8Array {
  4247. constructor(source, encoding /*, errors */) {
  4248. source = builtins.bytes.__encode__(source, encoding);
  4249. super(Number.isInteger(source) ? source : source.length);
  4250. if (Array.isArray(source)) {
  4251. for (let i = 0; i < source.length; i++) {
  4252. this[i] = source;
  4253. }
  4254. } else if (source instanceof Uint8Array) {
  4255. this.set(source, 0);
  4256. } else if (typeof source === 'string') {
  4257. for (let i = 0; i < source.length; i++) {
  4258. this[i] = source.charCodeAt(i);
  4259. }
  4260. }
  4261. }
  4262. static __encode__(source, encoding) {
  4263. if (source === undefined) {
  4264. return 0;
  4265. }
  4266. if (Number.isInteger(source)) {
  4267. return source;
  4268. }
  4269. if (Array.isArray(source) || source instanceof Uint8Array) {
  4270. return source;
  4271. }
  4272. if (typeof source === 'string') {
  4273. switch (encoding) {
  4274. case 'latin1':
  4275. case 'latin-1':
  4276. return source;
  4277. case 'utf8':
  4278. case 'utf-8':
  4279. return new TextEncoder('utf-8').encode(source);
  4280. case undefined:
  4281. throw new python.Error('Unsupported string argument without an encoding.');
  4282. default:
  4283. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4284. }
  4285. }
  4286. throw new python.Error('Unsupported source.');
  4287. }
  4288. });
  4289. this.registerType('builtins.bytes', class extends Uint8Array {
  4290. constructor(source, encoding /*, errors */) {
  4291. source = builtins.bytes.__encode__(source, encoding);
  4292. super(Number.isInteger(source) ? source : source.length);
  4293. if (Array.isArray(source)) {
  4294. for (let i = 0; i < source.length; i++) {
  4295. this[i] = source;
  4296. }
  4297. } else if (source instanceof Uint8Array) {
  4298. this.set(source, 0);
  4299. } else if (typeof source === 'string') {
  4300. for (let i = 0; i < source.length; i++) {
  4301. this[i] = source.charCodeAt(i);
  4302. }
  4303. }
  4304. }
  4305. static __encode__(source, encoding) {
  4306. if (source === undefined) {
  4307. return 0;
  4308. }
  4309. if (Number.isInteger(source)) {
  4310. return source;
  4311. }
  4312. if (Array.isArray(source) || source instanceof Uint8Array) {
  4313. return source;
  4314. }
  4315. if (typeof source === 'string') {
  4316. switch (encoding) {
  4317. case 'latin1':
  4318. case 'latin-1':
  4319. return source;
  4320. case 'utf8':
  4321. case 'utf-8':
  4322. return new TextEncoder('utf-8').encode(source);
  4323. case undefined:
  4324. throw new python.Error('Unsupported string argument without an encoding.');
  4325. default:
  4326. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4327. }
  4328. }
  4329. throw new python.Error('Unsupported source.');
  4330. }
  4331. });
  4332. this.registerType('builtins.memoryview', class {
  4333. constructor(buf) {
  4334. this._buf = buf;
  4335. }
  4336. get nbytes() {
  4337. return this._buf.length;
  4338. }
  4339. });
  4340. this.registerType('builtins.frozenset', class extends Set {
  4341. constructor(iterable) {
  4342. super();
  4343. if (iterable) {
  4344. for (const item of iterable) {
  4345. this.add(item);
  4346. }
  4347. }
  4348. }
  4349. });
  4350. this.registerFunction('builtins.exec');
  4351. this.registerFunction('builtins.issubclass', (obj, type) => {
  4352. const name = `${type.__module__}.${type.__name__}`;
  4353. if (obj.__module__ && obj.__name__) {
  4354. if (name === `${obj.__module__}.${obj.__name__}`) {
  4355. return true;
  4356. }
  4357. }
  4358. if (obj.__bases__) {
  4359. for (const base of obj.__bases__) {
  4360. if (builtins.issubclass(base, type)) {
  4361. return true;
  4362. }
  4363. }
  4364. }
  4365. return false;
  4366. });
  4367. this.registerFunction('builtins.isinstance', (obj, type) => {
  4368. return obj.__class__ ? builtins.issubclass(obj.__class__, type) : false;
  4369. });
  4370. this.registerFunction('builtins.hasattr', (obj, name) => {
  4371. if (obj instanceof Map && obj.__contains__) {
  4372. return obj.__contains__(name);
  4373. }
  4374. return Object.prototype.hasOwnProperty.call(obj, name);
  4375. });
  4376. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4377. if (obj && obj.__getattr__) {
  4378. return obj.__getattr__(name);
  4379. }
  4380. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4381. return obj[name];
  4382. }
  4383. return defaultValue;
  4384. });
  4385. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4386. obj[name] = value;
  4387. });
  4388. this.registerType('builtins.set', class extends Set {
  4389. __contains__(item) {
  4390. return this.has(item);
  4391. }
  4392. update(iterable) {
  4393. for (const item of iterable) {
  4394. this.add(item);
  4395. }
  4396. }
  4397. });
  4398. this.registerType('builtins.slice', class {
  4399. constructor(start, stop, step) {
  4400. this.start = start;
  4401. this.stop = stop;
  4402. this.step = step;
  4403. }
  4404. });
  4405. this.registerFunction('builtins.hash');
  4406. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4407. return name;
  4408. });
  4409. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4410. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4411. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4412. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4413. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4414. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4415. cell.cell_contents = value;
  4416. }
  4417. return cell;
  4418. });
  4419. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4420. // globals["__builtins__"] = __builtins__
  4421. return new types.FunctionType(code, globals, name, argdefs, closure);
  4422. });
  4423. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4424. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4425. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4426. if (class_tracker_id) {
  4427. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4428. }
  4429. return class_def;
  4430. });
  4431. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4432. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4433. const kwds = { 'metaclass': type_constructor };
  4434. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4435. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4436. });
  4437. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4438. return new builtins.cell();
  4439. });
  4440. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4441. [state] = state;
  4442. let registry = null;
  4443. for (const [attrname, attr] of state.items()) {
  4444. if (attrname === '_abc_impl') {
  4445. registry = attr;
  4446. } else {
  4447. builtins.setattr(obj, attrname, attr);
  4448. }
  4449. }
  4450. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4451. obj.__firstlineno__ = state.get('__firstlineno__');
  4452. }
  4453. if (registry) {
  4454. for (const subclass of registry) {
  4455. obj.register(subclass);
  4456. }
  4457. }
  4458. return obj;
  4459. });
  4460. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4461. const [, slotstate] = state;
  4462. [state] = state;
  4463. // obj.__dict__.update(state)
  4464. /* const obj_globals = */ slotstate.pop('__globals__');
  4465. const obj_closure = slotstate.pop('__closure__');
  4466. slotstate.pop('_cloudpickle_submodules');
  4467. if (obj.__globals__) {
  4468. // obj.__globals__.update(obj_globals);
  4469. // obj.__globals__.__builtins__ = __builtins__;
  4470. }
  4471. if (obj_closure) {
  4472. // let value = null;
  4473. for (let i = 0; i < obj_closure.length; i++) {
  4474. // const cell = obj_closure[i];
  4475. try {
  4476. // value = cell.cell_contents;
  4477. } catch {
  4478. // cell is empty
  4479. }
  4480. // obj.__closure__[i].cell_contents = value;
  4481. }
  4482. }
  4483. for (const [k, v] of slotstate.items()) {
  4484. builtins.setattr(obj, k, v);
  4485. }
  4486. });
  4487. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4488. execution.__import__(name);
  4489. return sys.modules.get(name);
  4490. });
  4491. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4492. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4493. const ray = this.register('ray');
  4494. this.register('ray.cloudpickle.cloudpickle');
  4495. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4496. this.registerType('collections.Counter', class {});
  4497. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4498. return {};
  4499. });
  4500. this.registerFunction('copy.deepcopy');
  4501. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4502. // copyreg._reconstructor in Python 3
  4503. if (base === '__builtin__.object' || base === builtins.object) {
  4504. return self.invoke(cls, []);
  4505. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4506. const obj = self.invoke(cls, []);
  4507. for (let i = 0; i < state.length; i++) {
  4508. obj[i] = state[i];
  4509. }
  4510. return obj;
  4511. }
  4512. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4513. });
  4514. this.registerFunction('copy.deepcopy', (/* x */) => {
  4515. throw new python.Error('Unsupported copy.deepcopy().');
  4516. });
  4517. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4518. const array = f(...args);
  4519. if (array.__setstate__) {
  4520. array.__setstate__(state);
  4521. }
  4522. if (npdict) {
  4523. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4524. }
  4525. return array;
  4526. });
  4527. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4528. return function() {
  4529. };
  4530. });
  4531. this.registerFunction('dill._dill._create_code', (args) => {
  4532. return self.invoke('types.CodeType', [args]);
  4533. });
  4534. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4535. return function() {
  4536. };
  4537. });
  4538. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4539. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4540. if (obj) {
  4541. return obj;
  4542. }
  4543. return undefined;
  4544. });
  4545. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4546. const [name, bases, dict] = args;
  4547. const type = class extends bases[0] {};
  4548. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4549. return self.registerType(identifier, Object.assign(type, dict));
  4550. });
  4551. this.registerFunction('dill._dill._eval_repr');
  4552. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4553. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4554. return self[name];
  4555. }
  4556. return undefined;
  4557. });
  4558. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4559. try {
  4560. if (import_name.startsWith('__runtime__.')) {
  4561. return execution.module(import_name);
  4562. } else if (import_name.indexOf('.') === -1) {
  4563. return execution.__import__(import_name);
  4564. }
  4565. return execution.resolve(import_name);
  4566. } catch (error) {
  4567. if (safe) {
  4568. return null;
  4569. }
  4570. throw error;
  4571. }
  4572. });
  4573. this.registerFunction('dill._dill._load_type', (name) => {
  4574. const _dill = self.register('dill._dill');
  4575. if (!_dill._reverse_typemap) {
  4576. _dill._reverse_typemap = new Map();
  4577. for (const name of ['__builtin__', 'types']) {
  4578. const module = self.register(name);
  4579. for (const [name, obj] of Object.entries(module)) {
  4580. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4581. _dill._reverse_typemap.set(name, obj);
  4582. }
  4583. }
  4584. }
  4585. _dill._reverse_typemap.set('PartialType', functools.partial);
  4586. _dill._reverse_typemap.set('CellType', builtins.cell);
  4587. }
  4588. if (!_dill._reverse_typemap.has(name)) {
  4589. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4590. }
  4591. return _dill._reverse_typemap.get(name);
  4592. });
  4593. this.registerFunction('dill._dill.loads');
  4594. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4595. const np_value = fun(...args);
  4596. np_value.__setstate__(arr_state);
  4597. const jnp_value = jax.device_put(np_value);
  4598. jnp_value.aval = jnp_value.aval.update(aval_state);
  4599. return jnp_value;
  4600. });
  4601. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4602. this.registerFunction('jax.device_put', (x) => {
  4603. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4604. return new jax.Array(aval, x.data);
  4605. });
  4606. this.registerType('jax._src.core.AbstractValue', class {});
  4607. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4608. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4609. constructor(shape, dtype, weak_type) {
  4610. super();
  4611. this.shape = shape;
  4612. this.dtype = dtype;
  4613. this.weak_type = weak_type || false;
  4614. }
  4615. update(dict) {
  4616. const shape = dict.get('shape') || this.shape;
  4617. const dtype = dict.get('dtype') || this.dtype;
  4618. const weak_type = dict.get('weak_type') || this.weak_type;
  4619. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4620. }
  4621. });
  4622. this.registerType('jax.Array', class {
  4623. constructor(aval, data) {
  4624. this.aval = aval;
  4625. this.data = data;
  4626. }
  4627. get dtype() {
  4628. return this.aval.dtype;
  4629. }
  4630. get shape() {
  4631. return this.aval.shape;
  4632. }
  4633. tobytes() {
  4634. return this.data;
  4635. }
  4636. });
  4637. jax.numpy.ndarray = jax.Array;
  4638. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4639. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4640. });
  4641. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4642. this.registerFunction('lasagne.nonlinearities.rectify');
  4643. this.registerFunction('lasagne.nonlinearities.softmax');
  4644. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4645. this.registerFunction('lasagne.updates.nesterov_momentum');
  4646. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4647. const BinaryReader = class {
  4648. constructor(buffer, ext_hook) {
  4649. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4650. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4651. this._buffer = buffer;
  4652. this._position = 0;
  4653. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4654. this._ext_hook = ext_hook;
  4655. }
  4656. value() {
  4657. const c = this._view.getUint8(this.skip(1));
  4658. if (c >= 0xe0) {
  4659. return c - 0x100;
  4660. }
  4661. if (c < 0xC0) {
  4662. if (c < 0x80) {
  4663. return c;
  4664. }
  4665. if (c < 0x90) {
  4666. return this.map(c - 0x80);
  4667. }
  4668. if (c < 0xa0) {
  4669. return this.array(c - 0x90);
  4670. }
  4671. return this.string(c - 0xa0);
  4672. }
  4673. switch (c) {
  4674. case 0xC0: return null;
  4675. case 0xC2: return false;
  4676. case 0xC3: return true;
  4677. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4678. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4679. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4680. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4681. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4682. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4683. case 0xCA: return this._view.getFloat32(this.skip(4));
  4684. case 0xCB: return this._view.getFloat64(this.skip(8));
  4685. case 0xCC: return this._view.getUint8(this.skip(1));
  4686. case 0xCD: return this._view.getUint16(this.skip(2));
  4687. case 0xCE: return this._view.getUint32(this.skip(4));
  4688. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4689. case 0xD0: return this._view.getInt8(this.skip(1));
  4690. case 0xD1: return this._view.getInt16(this.skip(2));
  4691. case 0xD2: return this._view.getInt32(this.skip(4));
  4692. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4693. case 0xD4: return this.extension(1);
  4694. case 0xD5: return this.extension(2);
  4695. case 0xD6: return this.extension(4);
  4696. case 0xD7: return this.extension(8);
  4697. case 0xD8: return this.extension(16);
  4698. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4699. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4700. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4701. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4702. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4703. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4704. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4705. default: throw new python.Error(`Invalid code '${c}'.`);
  4706. }
  4707. }
  4708. map(size) {
  4709. const map = {};
  4710. for (let i = 0; i < size; i++) {
  4711. const key = this.value();
  4712. const value = this.value();
  4713. map[key] = value;
  4714. }
  4715. return map;
  4716. }
  4717. array(size) {
  4718. const array = new Array(size);
  4719. for (let i = 0; i < size; i++) {
  4720. array[i] = this.value();
  4721. }
  4722. return array;
  4723. }
  4724. extension(size) {
  4725. const code = this._view.getUint8(this.skip(1));
  4726. const data = this.read(size);
  4727. return this._ext_hook(code, data);
  4728. }
  4729. skip(offset) {
  4730. const position = this._position;
  4731. this._position += offset;
  4732. if (this._position > this._buffer.length) {
  4733. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4734. }
  4735. return position;
  4736. }
  4737. read(size) {
  4738. const data = this._buffer.subarray(this._position, this._position + size);
  4739. this._position += size;
  4740. return data;
  4741. }
  4742. string(size) {
  4743. const buffer = this.read(size);
  4744. this._decoder = this._decoder || new TextDecoder('utf8');
  4745. return this._decoder.decode(buffer);
  4746. }
  4747. };
  4748. return new BinaryReader(packed, ext_hook).value();
  4749. });
  4750. this.registerFunction('nolearn.lasagne.base.objective');
  4751. this.registerFunction('numpy.core._DType_reconstruct');
  4752. this.registerFunction('numpy.core._ufunc_reconstruct');
  4753. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4754. return numpy.ndarray.__new__(subtype, shape, dtype);
  4755. });
  4756. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4757. const shape = [buf.length / dtype.itemsize];
  4758. return new numpy.ndarray(shape, dtype, buf);
  4759. });
  4760. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  4761. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  4762. });
  4763. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4764. return new numpy.dtypes.StringDType();
  4765. });
  4766. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4767. let data = rawData;
  4768. if (typeof rawData === 'string' || rawData instanceof String) {
  4769. data = new Uint8Array(rawData.length);
  4770. for (let i = 0; i < rawData.length; i++) {
  4771. data[i] = rawData.charCodeAt(i);
  4772. }
  4773. }
  4774. switch (dtype.kind) {
  4775. case 'b': {
  4776. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4777. switch (dtype.itemsize) {
  4778. case 1: return view.getInt8(0) ? true : false;
  4779. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  4780. }
  4781. }
  4782. case 'f': {
  4783. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4784. switch (dtype.itemsize) {
  4785. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  4786. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  4787. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  4788. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  4789. }
  4790. }
  4791. case 'i': {
  4792. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4793. switch (dtype.itemsize) {
  4794. case 1: return view.getInt8(0);
  4795. case 2: return view.getInt16(0, dtype.byteorder === '<');
  4796. case 4: return view.getInt32(0, dtype.byteorder === '<');
  4797. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  4798. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  4799. }
  4800. }
  4801. case 'u': {
  4802. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4803. switch (dtype.itemsize) {
  4804. case 1: return view.getUint8(0);
  4805. case 2: return view.getUint16(0, dtype.byteorder === '<');
  4806. case 4: return view.getUint32(0, dtype.byteorder === '<');
  4807. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  4808. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  4809. }
  4810. }
  4811. case 'U': {
  4812. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4813. const list = [];
  4814. for (let i = 0; i < dtype.itemsize; i += 4) {
  4815. list.push(String.fromCodePoint(view.getUint32(i, true)));
  4816. }
  4817. return list.join('');
  4818. }
  4819. default: {
  4820. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  4821. }
  4822. }
  4823. });
  4824. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  4825. this.registerFunction('numpy.core._multiarray_umath.fmin');
  4826. this.registerFunction('numpy.core._multiarray_umath.fmax');
  4827. this.registerFunction('numpy.core._multiarray_umath.greater');
  4828. this.registerFunction('numpy.core._multiarray_umath.less');
  4829. this.registerFunction('numpy.core._multiarray_umath.log');
  4830. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  4831. let data = rawData;
  4832. if (typeof rawData === 'string') {
  4833. data = new Uint8Array(rawData.length);
  4834. for (let i = 0; i < rawData.length; i++) {
  4835. data[i] = rawData.charCodeAt(i);
  4836. }
  4837. }
  4838. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4839. switch (dtype.__name__) {
  4840. case 'uint8':
  4841. return dataView.getUint8(0);
  4842. case 'float32':
  4843. return dataView.getFloat32(0, true);
  4844. case 'float64':
  4845. return dataView.getFloat64(0, true);
  4846. case 'int8':
  4847. return dataView.getInt8(0, true);
  4848. case 'int16':
  4849. return dataView.getInt16(0, true);
  4850. case 'int32':
  4851. return dataView.getInt32(0, true);
  4852. case 'int64':
  4853. return dataView.getBigInt64(0, true);
  4854. default:
  4855. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  4856. }
  4857. });
  4858. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  4859. this.register('numpy._core.multiarray', numpy.core.multiarray);
  4860. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  4861. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  4862. this.register('numpy.core.numeric', numpy._core.numeric);
  4863. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  4864. this.registerFunction('numpy.load', (file) => {
  4865. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  4866. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  4867. if (!file.read(6).every((v, i) => v === signature[i])) {
  4868. throw new python.Error('Invalid signature.');
  4869. }
  4870. const version = file.read(2);
  4871. const [major, minor] = version;
  4872. if (major > 3) {
  4873. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  4874. }
  4875. const buffer = new Uint8Array([0, 0, 0, 0]);
  4876. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  4877. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  4878. let header = file.read(header_length);
  4879. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  4880. header = decoder.decode(header);
  4881. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',']').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  4882. if (!header.descr || header.descr.length < 2) {
  4883. throw new python.Error("Missing property 'descr'.");
  4884. }
  4885. if (!header.shape) {
  4886. throw new python.Error("Missing property 'shape'.");
  4887. }
  4888. const shape = header.shape;
  4889. const dtype = self.invoke('numpy.dtype', [header.descr.substring(1)]);
  4890. dtype.byteorder = header.descr.substring(0, 1);
  4891. let data = null;
  4892. switch (dtype.byteorder) {
  4893. case '|': {
  4894. data = file.read();
  4895. if (dtype.kind === 'O') {
  4896. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  4897. return unpickler.load();
  4898. }
  4899. break;
  4900. }
  4901. case '>':
  4902. case '<': {
  4903. if (header.descr.length !== 3 && header.descr[1] !== 'U' && header.descr.substring(1) !== 'c16') {
  4904. throw new python.Error(`Unsupported data type '${header.descr}'.`);
  4905. }
  4906. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  4907. const stream = file.getbuffer().nbytes > 0x1000000;
  4908. data = file.read(dtype.itemsize * count, stream);
  4909. break;
  4910. }
  4911. default: {
  4912. throw new python.Error(`Unsupported data type '${header.descr}'.`);
  4913. }
  4914. }
  4915. if (header.fortran_order) {
  4916. data = null;
  4917. }
  4918. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  4919. });
  4920. this.registerFunction('numpy.save', (file, arr) => {
  4921. const descr = arr.dtype.str;
  4922. if (descr[0] !== '<' && descr[0] !== '>') {
  4923. throw new python.Error(`Unsupported byte order '${descr}'.`);
  4924. }
  4925. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  4926. throw new python.Error(`Unsupported data type '${descr}'.`);
  4927. }
  4928. let shape = '';
  4929. switch (arr.shape.length) {
  4930. case 0: shape = '()'; break;
  4931. case 1: shape = `(${arr.shape[0]},)`; break;
  4932. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  4933. }
  4934. const properties = [
  4935. `'descr': '${descr}'`,
  4936. "'fortran_order': False",
  4937. `'shape': ${shape}`
  4938. ];
  4939. let header = `{ ${properties.join(', ')} }`;
  4940. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  4941. const encoder = new TextEncoder('ascii');
  4942. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  4943. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  4944. file.write(encoder.encode(header));
  4945. file.write(arr.tobytes());
  4946. });
  4947. this.registerFunction('numpy.amin');
  4948. this.registerFunction('numpy.amax');
  4949. this.registerFunction('numpy.std');
  4950. this.registerFunction('numpy.asarray', (a, dtype) => {
  4951. const encode = (context, data, dim) => {
  4952. const size = context.shape[dim];
  4953. const littleendian = context.littleendian;
  4954. if (dim === context.shape.length - 1) {
  4955. for (let i = 0; i < size; i++) {
  4956. switch (context.dtype) {
  4957. case 'f2':
  4958. context.view.setFloat16(context.position, data[i], littleendian);
  4959. break;
  4960. case 'f4':
  4961. context.view.setFloat32(context.position, data[i], littleendian);
  4962. break;
  4963. case 'f8':
  4964. context.view.setFloat64(context.position, data[i], littleendian);
  4965. break;
  4966. case 'i1':
  4967. context.view.setInt8(context.position, data[i], littleendian);
  4968. break;
  4969. case 'i2':
  4970. context.view.setInt16(context.position, data[i], littleendian);
  4971. break;
  4972. case 'i4':
  4973. context.view.setInt32(context.position, data[i], littleendian);
  4974. break;
  4975. case 'i8':
  4976. context.view.setBigInt64(context.position, data[i], littleendian);
  4977. break;
  4978. case 'u1':
  4979. context.view.setUint8(context.position, data[i], littleendian);
  4980. break;
  4981. case 'u2':
  4982. context.view.setUint16(context.position, data[i], littleendian);
  4983. break;
  4984. case 'u4':
  4985. context.view.setUint32(context.position, data[i], littleendian);
  4986. break;
  4987. case 'u8':
  4988. context.view.setBigUint64(context.position, data[i], littleendian);
  4989. break;
  4990. case 'c8':
  4991. context.view.setComplex64(context.position, data[i], littleendian);
  4992. break;
  4993. case 'c16':
  4994. context.view.setComplex128(context.position, data[i], littleendian);
  4995. break;
  4996. case 'b1':
  4997. context.view.setInt8(context.position, data[i] ? 1 : 0);
  4998. break;
  4999. default:
  5000. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5001. }
  5002. context.position += context.itemsize;
  5003. }
  5004. } else {
  5005. for (let j = 0; j < size; j++) {
  5006. encode(context, data[j], dim + 1);
  5007. }
  5008. }
  5009. };
  5010. const array_size = (value) => {
  5011. if (value.every((item) => Array.isArray(item))) {
  5012. const dims = value.map((item) => array_size(item));
  5013. const [dim] = dims;
  5014. for (let i = 1; i < dims.length; i++) {
  5015. if (dim.length === dims[i].length) {
  5016. if (!dims[i].every((value, i) => value === dim[i])) {
  5017. throw new python.Error('Invalid array shape.');
  5018. }
  5019. }
  5020. }
  5021. return [value.length].concat(dim);
  5022. }
  5023. return [value.length];
  5024. };
  5025. const shape = Array.isArray(a) ? array_size(a) : [];
  5026. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5027. const context = {
  5028. position: 0,
  5029. itemsize: dtype.itemsize,
  5030. dtype: dtype.str.substring(1),
  5031. littleendian: dtype.str[0],
  5032. shape,
  5033. data: new Uint8Array(size)
  5034. };
  5035. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5036. encode(context, a, 0);
  5037. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5038. });
  5039. this.registerFunction('numpy.max');
  5040. this.registerFunction('numpy.mean');
  5041. this.registerFunction('numpy.min');
  5042. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5043. const data = self.invoke(baseclass, [baseshape, basetype]);
  5044. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5045. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5046. return self.invoke(subtype, [data, mask, basetype]);
  5047. });
  5048. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5049. return {};
  5050. });
  5051. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5052. return {};
  5053. });
  5054. this.registerType('numpy.random.bit_generator.BitGenerator', class {});
  5055. this.registerType('numpy.random.bit_generator.SeedSequence', class {});
  5056. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence');
  5057. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5058. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5059. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5060. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5061. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5062. numpy.random._pickle.BitGenerators = {
  5063. 'MT19937': numpy.random._mt19937.MT19937,
  5064. 'PCG64': numpy.random._pcg64.PCG64,
  5065. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5066. 'Philox': numpy.random._philox.Philox,
  5067. 'SFC64': numpy.random._sfc64.SFC64,
  5068. };
  5069. this.registerType('numpy.random._generator.Generator', class {
  5070. constructor(bit_generator) {
  5071. this.bit_generator = bit_generator;
  5072. }
  5073. });
  5074. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator_name) => {
  5075. bit_generator_name = bit_generator_name || 'MT19937';
  5076. const bit_generator = numpy.random._pickle.BitGenerators[bit_generator_name];
  5077. if (bit_generator) {
  5078. return new bit_generator();
  5079. }
  5080. throw new python.Error(`Unknown bit generator '${bit_generator_name}'.`);
  5081. });
  5082. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5083. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5084. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5085. });
  5086. this.registerFunction('numpy.reshape');
  5087. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5088. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5089. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5090. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5091. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5092. this.registerFunction('sklearn.metrics._classification.f1_score');
  5093. this.registerFunction('sklearn.metrics._classification.log_loss');
  5094. this.registerFunction('sklearn.metrics._classification.precision_score');
  5095. this.registerFunction('sklearn.metrics._classification.recall_score');
  5096. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5097. return obj.__new__(obj);
  5098. });
  5099. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5100. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5101. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5102. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5103. this.registerFunction('sklearn.metrics._regression.r2_score');
  5104. sklearn.metrics.regression = sklearn.metrics._regression;
  5105. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5106. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5107. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5108. this.registerFunction('re._compile', (pattern, flags) => {
  5109. return self.invoke('re.Pattern', [pattern, flags]);
  5110. });
  5111. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5112. return function() {
  5113. return self.invoke(`types.${args[0]}`, args);
  5114. };
  5115. });
  5116. this.registerFunction('theano.scalar.basic.same_out');
  5117. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5118. this.registerFunction('theano.scalar.basic.upcast_out');
  5119. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5120. this.registerFunction('theano.tensor.nnet.conv2d');
  5121. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5122. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5123. this.registerType('torch.nn.modules.module.Module', class {
  5124. constructor() {
  5125. this._modules = execution.invoke('collections.OrderedDict', []);
  5126. this._parameters = execution.invoke('collections.OrderedDict', []);
  5127. this._buffers = execution.invoke('collections.OrderedDict', []);
  5128. }
  5129. __setattr__(name, value) {
  5130. if (value instanceof torch.nn.modules.module.Module) {
  5131. this._modules.set(name, value);
  5132. } else {
  5133. this[name] = value;
  5134. }
  5135. }
  5136. __getattr__(name) {
  5137. if (this._modules.has(name)) {
  5138. return this._modules.get(name);
  5139. }
  5140. return this[name];
  5141. }
  5142. __delattr__(name) {
  5143. if (this._modules.has(name)) {
  5144. this._modules.delete(name);
  5145. }
  5146. }
  5147. children() {
  5148. return this._modules.values();
  5149. }
  5150. named_modules(memo, prefix, remove_duplicate) {
  5151. memo = memo || new Set();
  5152. prefix = prefix || '';
  5153. const modules = new builtins.dict();
  5154. if (!memo.has(this)) {
  5155. if (remove_duplicate) {
  5156. memo.add(this);
  5157. }
  5158. modules.set(prefix, this);
  5159. for (const [name, module] of this._modules.items()) {
  5160. if (module && module.named_modules) {
  5161. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5162. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5163. modules.set(k, v);
  5164. }
  5165. }
  5166. }
  5167. }
  5168. return modules;
  5169. }
  5170. named_children() {
  5171. return this._modules;
  5172. }
  5173. parameters() {
  5174. return this._parameters.values();
  5175. }
  5176. named_parameters(recurse) {
  5177. if (recurse) {
  5178. throw new python.Error('Named parameters with recurse not implemented.');
  5179. }
  5180. return this._parameters;
  5181. }
  5182. buffers() {
  5183. return this._buffers.values();
  5184. }
  5185. named_buffers(recurse) {
  5186. if (recurse) {
  5187. throw new python.Error('Named parameters with recurse not implemented.');
  5188. }
  5189. return this._buffers;
  5190. }
  5191. _get_name() {
  5192. return this.__class__.__name__;
  5193. }
  5194. });
  5195. torch.nn.Module = torch.nn.modules.module.Module;
  5196. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5197. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5198. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5199. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5200. this.registerType('torch._C.OperatorRegistry', class {
  5201. constructor() {
  5202. this.to_register = [];
  5203. this.operators = new Map();
  5204. }
  5205. registerPendingOperators() {
  5206. for (const op of this.to_register) {
  5207. const sym = op.schema().name;
  5208. if (!this.operators.has(sym)) {
  5209. this.operators.set(sym, []);
  5210. }
  5211. this.operators.get(sym).push(op);
  5212. }
  5213. this.to_register = [];
  5214. }
  5215. registerOperator(op) {
  5216. this.to_register.push(op);
  5217. }
  5218. getOperators(name) {
  5219. this.registerPendingOperators();
  5220. if (this.operators.has(name)) {
  5221. return this.operators.get(name);
  5222. }
  5223. return [];
  5224. }
  5225. });
  5226. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  5227. return torch._C.getRegistry().getOperators(name);
  5228. });
  5229. this.registerType('torch._C.Operator', class {
  5230. constructor(schema) {
  5231. this._schema = schema;
  5232. }
  5233. schema() {
  5234. return this._schema;
  5235. }
  5236. getOperation(/* node */) {
  5237. return null;
  5238. }
  5239. aliasAnalysisKind() {
  5240. const schemaRef = this.schema();
  5241. const alias_analysis = schemaRef.aliasAnalysis();
  5242. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  5243. return alias_analysis;
  5244. }
  5245. });
  5246. this.registerFunction('torch._C.getRegistry', () => {
  5247. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  5248. return torch._C.r;
  5249. });
  5250. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  5251. const operations = torch._C.getAllOperatorsFor(op_name);
  5252. for (const op of operations) {
  5253. if (op.schema().overload_name === overload_name) {
  5254. return op.schema();
  5255. }
  5256. }
  5257. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  5258. });
  5259. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  5260. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  5261. });
  5262. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  5263. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  5264. if (sortedOps.length === 0) {
  5265. return [null, null];
  5266. }
  5267. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  5268. return [{}, overload_names];
  5269. });
  5270. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  5271. const operations = torch._C.getAllOperatorsFor(op_name);
  5272. for (const op of operations) {
  5273. if (op.schema().overload_name === overload_name) {
  5274. return [{}, {}, null];
  5275. }
  5276. }
  5277. return null;
  5278. });
  5279. this.registerType('torch._C.MatchedSchema', class {
  5280. constructor(inputs, return_types, return_field_names, schema_name) {
  5281. this.inputs = inputs;
  5282. this.return_types = return_types;
  5283. this.register_field_names = return_field_names;
  5284. this.schema_name = schema_name;
  5285. }
  5286. });
  5287. this.registerType('torch._C.Self', class {
  5288. });
  5289. this.registerFunction('torch._C.toValues', (g, nvs) => {
  5290. return nvs.map((v) => v.value(g));
  5291. });
  5292. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  5293. constructor(classType) {
  5294. super();
  5295. this._classType = classType;
  5296. }
  5297. makeSugared(v) {
  5298. v.setType(this._classType);
  5299. return new torch._C.SimpleValue(v);
  5300. }
  5301. getClassType() {
  5302. return this._classType;
  5303. }
  5304. });
  5305. this.registerType('torch._C.Function', class {
  5306. isGraphFunction() {
  5307. return false;
  5308. }
  5309. name() {
  5310. return this.qualname().name();
  5311. }
  5312. });
  5313. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  5314. constructor(qualname, schema) {
  5315. super();
  5316. this._name = qualname;
  5317. this._schema = schema;
  5318. }
  5319. qualname() {
  5320. return this._name;
  5321. }
  5322. getSchema() {
  5323. return this._schema;
  5324. }
  5325. ensure_defined() {
  5326. }
  5327. });
  5328. this.registerType('torch._C.DeadCodeEliminator', class {
  5329. constructor(...args) {
  5330. this._aliasDb = null;
  5331. this._useAliasDb = false;
  5332. this._memo = new Map();
  5333. this._marked = new Set();
  5334. this._liveValues = new Set();
  5335. this._deleteCallback = () => {};
  5336. if (args.length > 0 && args[0] instanceof torch.Graph) {
  5337. [this._graph, this._sideEffectPolicy] = args;
  5338. this._useAliasDb = true;
  5339. } else {
  5340. [this._sideEffectPolicy] = args;
  5341. }
  5342. }
  5343. run(block, recurse) {
  5344. this.eliminateDeadForkInputs(block, recurse);
  5345. this.mark(block.return_node());
  5346. this.mark(block);
  5347. this._deleteCallback(this._liveValues);
  5348. this.sweep(block, recurse);
  5349. }
  5350. setDeleteCallback(deleteCallback) {
  5351. this._deleteCallback = deleteCallback;
  5352. }
  5353. eliminateDeadForkInputs(block, recurse) {
  5354. for (const node of block.nodes()) {
  5355. if (recurse) {
  5356. for (const sb of node.blocks()) {
  5357. this.eliminateDeadForkInputs(sb, recurse);
  5358. }
  5359. }
  5360. if (node.kind() !== 'prim::fork') {
  5361. continue;
  5362. }
  5363. const g = node.g("Subgraph");
  5364. for (let i = 0; i < g.inputs().length; i++) {
  5365. if (!g.inputs()[i].hasUses()) {
  5366. g.eraseInput(i);
  5367. node.removeInput(i);
  5368. }
  5369. }
  5370. }
  5371. }
  5372. markReturnNode(node) {
  5373. if (this._marked.has(node)) {
  5374. return false;
  5375. }
  5376. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  5377. const outerNode = node.owningBlock().owningNode();
  5378. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  5379. return this.mark(node);
  5380. }
  5381. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  5382. const loop = new torch._C.LoopView(outerNode);
  5383. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  5384. if (outerNode.kind() === 'onnx::Loop') {
  5385. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  5386. continue;
  5387. }
  5388. const innerInput = loop.bodyCarriedInputs()[i];
  5389. const innerOutput = loop.bodyCarriedOutputs()[i];
  5390. const outerOutput = loop.carriedOutputs()[i];
  5391. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  5392. this._liveValues.add(innerOutput);
  5393. }
  5394. }
  5395. this._liveValues.add(loop.nextCond());
  5396. } else {
  5397. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  5398. for (let i = 0; i < outerNode.outputs().length; i++) {
  5399. const innerOutput = node.inputs()[i];
  5400. const outerOutput = outerNode.outputs()[i];
  5401. if (!this._liveValues.has(outerOutput)) {
  5402. this._liveValues.add(innerOutput);
  5403. }
  5404. }
  5405. }
  5406. this._marked.add(node);
  5407. return true;
  5408. }
  5409. markLoop(node) {
  5410. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  5411. let marked = false;
  5412. let anyMarked = false;
  5413. do {
  5414. marked = this.mark(node.blocks()[0]);
  5415. anyMarked = anyMarked || marked;
  5416. } while (marked);
  5417. return anyMarked;
  5418. }
  5419. mark(...args) {
  5420. if (args.length === 1 && args[0] instanceof torch.Block) {
  5421. const [block] = args;
  5422. let anyMarked = false;
  5423. for (const node of block.nodes()) {
  5424. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  5425. const marked = this.mark(node);
  5426. anyMarked = anyMarked || marked;
  5427. }
  5428. }
  5429. const marked = this.markReturnNode(block.return_node());
  5430. anyMarked = anyMarked || marked;
  5431. for (const node of block.nodes()) {
  5432. if (node.kind() === 'prim::Loop') {
  5433. const marked = this.markLoop(node);
  5434. anyMarked = anyMarked || marked;
  5435. } else {
  5436. for (const subBlock of node.blocks()) {
  5437. const marked = this.mark(subBlock);
  5438. anyMarked = anyMarked || marked;
  5439. }
  5440. }
  5441. const marked = this.markIfLive(node);
  5442. anyMarked = anyMarked || marked;
  5443. }
  5444. return anyMarked;
  5445. }
  5446. if (args.length === 1 && args[0] instanceof torch.Node) {
  5447. const [node] = args;
  5448. if (this._marked.has(node)) {
  5449. return false;
  5450. }
  5451. this._marked.add(node);
  5452. let curNode = node;
  5453. while (curNode && curNode.owningBlock()) {
  5454. this.mark(curNode);
  5455. curNode = curNode.owningBlock().owningNode();
  5456. }
  5457. for (const input of node.inputs()) {
  5458. if (!this._liveValues.has(input)) {
  5459. this._liveValues.add(input);
  5460. }
  5461. }
  5462. return true;
  5463. }
  5464. throw new python.Error('Not implemented.');
  5465. }
  5466. markIfLive(node) {
  5467. for (const output of node.outputs()) {
  5468. if (this._liveValues.has(output)) {
  5469. return this.mark(node);
  5470. }
  5471. }
  5472. if (this._useAliasDb) {
  5473. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  5474. return this.mark(node);
  5475. }
  5476. }
  5477. return false;
  5478. }
  5479. sweep(block, recurse) {
  5480. const nodes = Array.from(block.nodes()).reverse();
  5481. for (const node of nodes) {
  5482. this.removeDeadBlockOutputs(node);
  5483. this.removeDeadLoopOutputs(node);
  5484. if (recurse) {
  5485. for (const block of node.blocks()) {
  5486. this.sweep(block, true);
  5487. }
  5488. }
  5489. if (!this._marked.has(node) && !node.hasUses()) {
  5490. node.destroy();
  5491. }
  5492. }
  5493. }
  5494. hasUntrackedMutation(node) {
  5495. if (!this._useAliasDb) {
  5496. if (node.kind() === 'prim::SetAttr') {
  5497. return true;
  5498. }
  5499. const schema = node.maybeSchema();
  5500. return schema && schema.is_mutable();
  5501. }
  5502. return this.getOrCreateAliasDb().writesToWildcard(node);
  5503. }
  5504. hasSideEffects(node) {
  5505. const it = this._memo.get(node);
  5506. if (it) {
  5507. return it;
  5508. }
  5509. const has_side_effects = node.hasSideEffects() ||
  5510. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  5511. this.hasUntrackedMutation(node);
  5512. this._memo.set(node, has_side_effects);
  5513. return has_side_effects;
  5514. }
  5515. removeDeadBlockOutputs(node) {
  5516. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  5517. return;
  5518. }
  5519. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  5520. const i = i_1 - 1;
  5521. if (!node.outputs()[i].hasUses()) {
  5522. node.eraseOutput(i);
  5523. for (const b of node.blocks()) {
  5524. b.eraseOutput(i);
  5525. }
  5526. }
  5527. }
  5528. }
  5529. removeDeadLoopOutputs() {
  5530. }
  5531. getOrCreateAliasDb() {
  5532. if (!this._aliasDb) {
  5533. this._aliasDb = new torch._C.AliasDb(this._graph);
  5534. }
  5535. return this._aliasDb;
  5536. }
  5537. });
  5538. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  5539. if (args.length === 1 && args[0] instanceof torch.Graph) {
  5540. const [graph] = args;
  5541. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  5542. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  5543. worker.run(graph.block(), /*recurse=*/true);
  5544. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  5545. const [block] = args;
  5546. const recurse = false;
  5547. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  5548. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  5549. worker.run(block, recurse);
  5550. } else {
  5551. throw new python.Error('Not implemented.');
  5552. }
  5553. });
  5554. this.registerFunction('torch._C.removeTupleNodes', () => {
  5555. });
  5556. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  5557. if (args.length === 1 && args[0] instanceof torch.Graph) {
  5558. const [graph] = args;
  5559. torch._C.LowerSimpleTuples(graph.block());
  5560. torch._C.EliminateDeadCode(graph);
  5561. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  5562. const [block] = args;
  5563. for (const n of block.nodes()) {
  5564. torch._C.removeTupleNodes(n, false);
  5565. for (const b of n.blocks()) {
  5566. torch._C.LowerSimpleTuples(b);
  5567. }
  5568. }
  5569. } else {
  5570. throw new python.Error('Not implemented.');
  5571. }
  5572. });
  5573. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  5574. torch._C.AT_ASSERT(lhs !== null);
  5575. torch._C.AT_ASSERT(rhs !== null);
  5576. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  5577. return false;
  5578. }
  5579. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  5580. return true;
  5581. }
  5582. const lnames = lhs.attributeNames();
  5583. const rnames = rhs.attributeNames();
  5584. lnames.sort();
  5585. rnames.sort();
  5586. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  5587. return false;
  5588. }
  5589. for (const name of lnames) {
  5590. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  5591. return false;
  5592. }
  5593. const kind = lhs.kindOf(name);
  5594. switch (kind) {
  5595. case 'i':
  5596. case 'f':
  5597. case 's':
  5598. case 't': {
  5599. if (lhs[kind](name) !== rhs[kind](name)) {
  5600. return false;
  5601. }
  5602. break;
  5603. }
  5604. case 'ival': {
  5605. if (lhs[kind](name) !== rhs[kind](name)) {
  5606. return false;
  5607. }
  5608. break;
  5609. }
  5610. default: {
  5611. throw new python.Error('Not implemented.');
  5612. }
  5613. }
  5614. }
  5615. return true;
  5616. });
  5617. this.registerFunction('torch._C.get_hash', (...args) => {
  5618. let hash = 0;
  5619. for (const value of args) {
  5620. if (typeof value === 'number') {
  5621. hash += (value | 0);
  5622. } else if (typeof value === 'string') {
  5623. hash += (value.length | 0);
  5624. } else if (Array.isArray(value)) {
  5625. for (const item of value) {
  5626. hash += torch._C.get_hash(item);
  5627. }
  5628. }
  5629. }
  5630. return hash;
  5631. });
  5632. this.registerFunction('torch._C.HashNode', (k) => {
  5633. torch._C.AT_ASSERT(k !== null);
  5634. let constant_hash = 0;
  5635. if (k.kind() === 'prim::Constant') {
  5636. const type = k.output().type();
  5637. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  5638. constant_hash = k.i('value');
  5639. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  5640. constant_hash = k.f('value');
  5641. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  5642. constant_hash = k.c('value');
  5643. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  5644. constant_hash = k.i('value');
  5645. }
  5646. }
  5647. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  5648. });
  5649. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  5650. if (lhs === null && rhs === null) {
  5651. return true;
  5652. }
  5653. if (lhs === null || rhs === null) {
  5654. return false;
  5655. }
  5656. if (lhs.kind() !== rhs.kind()) {
  5657. return false;
  5658. }
  5659. const lhs_outputs = lhs.outputs();
  5660. const rhs_outputs = rhs.outputs();
  5661. if (lhs_outputs.length !== rhs_outputs.length) {
  5662. return false;
  5663. }
  5664. for (let i = 0; i < lhs_outputs.length; i++) {
  5665. const lt = lhs_outputs[i].type();
  5666. const rt = rhs_outputs[i].type();
  5667. if (!lt.equals(rt)) {
  5668. return false;
  5669. }
  5670. }
  5671. const lhs_inputs = lhs.inputs();
  5672. const rhs_inputs = rhs.inputs();
  5673. if (lhs_inputs.length !== rhs_inputs.length) {
  5674. return false;
  5675. }
  5676. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  5677. return false;
  5678. }
  5679. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  5680. return false;
  5681. }
  5682. if (lhs.blocks().length !== rhs.blocks().length) {
  5683. return false;
  5684. }
  5685. for (let i = 0; i < lhs.blocks().length; i++) {
  5686. if (lhs.blocks()[i] !== rhs.blocks()[i]) {
  5687. return false;
  5688. }
  5689. }
  5690. return true;
  5691. });
  5692. this.registerType('torch._C.NodeSet', class {
  5693. constructor() {
  5694. this._nodes = new Map();
  5695. }
  5696. insert(n) {
  5697. const key = torch._C.HashNode(n);
  5698. if (this._nodes.has(key)) {
  5699. this._nodes.get(key).push(n);
  5700. } else {
  5701. this._nodes.set(key, [n]);
  5702. }
  5703. }
  5704. get(n) {
  5705. const key = torch._C.HashNode(n);
  5706. if (this._nodes.has(key)) {
  5707. const nodes = this._nodes.get(key);
  5708. for (const node of nodes) {
  5709. if (torch._C.EqualNode(node, n)) {
  5710. return node;
  5711. }
  5712. }
  5713. }
  5714. return null;
  5715. }
  5716. has(n) {
  5717. return this.get(n) !== null;
  5718. }
  5719. });
  5720. this.registerFunction('torch._C.isinstance', (stack, types) => {
  5721. const ty = stack.pop().type();
  5722. for (const candidate of types) {
  5723. if (ty.isSubtypeOf(candidate)) {
  5724. stack.push(true);
  5725. return;
  5726. }
  5727. }
  5728. stack.push(false);
  5729. });
  5730. this.registerType('torch._C.Tuple', class {
  5731. constructor(elements) {
  5732. this._elements = elements;
  5733. }
  5734. static create(elements) {
  5735. return new torch._C.Tuple(elements);
  5736. }
  5737. elements() {
  5738. return this._elements;
  5739. }
  5740. });
  5741. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  5742. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  5743. switch (num_inputs) {
  5744. case 0: {
  5745. stack.push(new torch._C.IValue(torch._C.Tuple.create([])));
  5746. break;
  5747. }
  5748. case 1: {
  5749. const tuple = torch._C.Tuple.create([stack.pop()]);
  5750. stack.push(new torch._C.IValue(tuple));
  5751. break;
  5752. }
  5753. case 2: {
  5754. const tuple = torch._C.Tuple.create([stack[stack.length - 2], stack[stack.length - 1]]);
  5755. stack.pop();
  5756. stack.pop();
  5757. stack.push(new torch._C.IValue(tuple));
  5758. break;
  5759. }
  5760. case 3: {
  5761. throw new python.Error('Not implemented.');
  5762. /* auto tuple = c10::ivalue::Tuple::create(
  5763. std::move(stack[stack.size() - 3]),
  5764. std::move(stack[stack.size() - 2]),
  5765. std::move(stack[stack.size() - 1]));
  5766. stack.pop_back();
  5767. stack.pop_back();
  5768. stack.back() = std::move(tuple);
  5769. break; */
  5770. }
  5771. default: {
  5772. throw new python.Error('Not implemented.');
  5773. /* std::vector<IValue> elems{
  5774. std::make_move_iterator(stack.end() - num_inputs),
  5775. std::make_move_iterator(stack.end())};
  5776. drop(stack, num_inputs - 1);
  5777. stack.back() = c10::ivalue::Tuple::create(std::move(elems));
  5778. break; */
  5779. }
  5780. }
  5781. });
  5782. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  5783. let stack = [];
  5784. for (const input of n.inputs()) {
  5785. const ival = torch._C.toIValue(input);
  5786. if (ival) {
  5787. stack.push(ival);
  5788. } else {
  5789. return null;
  5790. }
  5791. }
  5792. switch (n.kind()) {
  5793. case 'prim::ListUnpack': {
  5794. if (stack.back().toList().size() !== n.outputs().length) {
  5795. return null;
  5796. }
  5797. torch._C.listUnpack(stack, n.outputs().length);
  5798. break;
  5799. }
  5800. case 'prim::TupleConstruct': {
  5801. const tt = n.output().type().expect(torch.TupleType);
  5802. if (tt.name()) {
  5803. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  5804. } else {
  5805. torch._C.tupleConstruct(stack, n.inputs().length);
  5806. }
  5807. break;
  5808. }
  5809. case 'prim::ListConstruct': {
  5810. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  5811. break;
  5812. }
  5813. case 'prim::DictConstruct': {
  5814. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  5815. break;
  5816. }
  5817. case 'prim::CreateObject': {
  5818. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  5819. break;
  5820. }
  5821. case 'prim::GetAttr': {
  5822. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  5823. torch._C.push(stack, attr);
  5824. break;
  5825. }
  5826. case 'prim::isinstance': {
  5827. torch._C.isinstance(stack, n.tys('types'));
  5828. break;
  5829. }
  5830. default: {
  5831. const maybe_schema = n.maybeSchema();
  5832. if (maybe_schema && maybe_schema.is_vararg) {
  5833. return null;
  5834. }
  5835. // try
  5836. // {
  5837. // const op = n.getOperation();
  5838. // op(stack);
  5839. const [module, name] = n.kind().split('::');
  5840. const obj = torch.ops[module];
  5841. if (!obj) {
  5842. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  5843. }
  5844. const fn = torch.ops[module][name];
  5845. if (!fn) {
  5846. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  5847. }
  5848. const args = stack.map((v) => v.value);
  5849. const result = fn(...args);
  5850. stack = result === undefined ? [] : [new torch._C.IValue(result)];
  5851. // } catch {
  5852. // stack = [];
  5853. // return null;
  5854. // }
  5855. break;
  5856. }
  5857. }
  5858. for (const v of stack) {
  5859. if (v.isTensor()) {
  5860. const t = v.toTensor();
  5861. if (t.defined() && t.requires_grad()) {
  5862. return null;
  5863. }
  5864. }
  5865. if (ignore_custom_classes) {
  5866. if (v.isCustomClass()) {
  5867. return null;
  5868. }
  5869. }
  5870. if (v.isCustomClass()) {
  5871. if (v.toObject().is_weak_compilation_ref()) {
  5872. continue;
  5873. }
  5874. if (!db) {
  5875. continue;
  5876. }
  5877. const n_non_const = n;
  5878. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  5879. continue;
  5880. }
  5881. const obj = v.toObject();
  5882. obj.unsafe_make_weak_compilation_ref();
  5883. }
  5884. if (v.isObject()) {
  5885. if (!v.toObject().is_weak_compilation_ref()) {
  5886. return null;
  5887. }
  5888. }
  5889. }
  5890. return stack;
  5891. });
  5892. this.registerType('torch._C.ConstantPropagator', class {
  5893. constructor(graph, aliasing_types, ignore_custom_classes) {
  5894. this._made_change = false;
  5895. this._graph = graph;
  5896. this._aliasing_types = aliasing_types;
  5897. this._ignore_custom_classes = ignore_custom_classes;
  5898. }
  5899. static NoAliasDb(graph) {
  5900. return new torch._C.ConstantPropagator(graph, false, false);
  5901. }
  5902. run() {
  5903. this.ConstantPropagation(this._graph.block());
  5904. return this._made_change;
  5905. }
  5906. propagateNode(n) {
  5907. let outputs = [];
  5908. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  5909. if (outputs_opt) {
  5910. outputs = outputs_opt;
  5911. const graph = n.owningGraph();
  5912. const guard = new torch._C.WithInsertPoint(n);
  5913. for (let i = 0; i < outputs.length; i++) {
  5914. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  5915. if (new_output) {
  5916. this._made_change = true;
  5917. if (outputs[i].isNone()) {
  5918. new_output.setType(n.outputs()[i].type());
  5919. }
  5920. n.outputs()[i].replaceAllUsesWith(new_output);
  5921. }
  5922. }
  5923. guard.dispose();
  5924. }
  5925. }
  5926. removeLoopNode(n) {
  5927. const loop_input_offset = 2;
  5928. for (let i = 0; i < n.outputs().length; i++) {
  5929. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  5930. }
  5931. this._made_change = true;
  5932. n.destroy();
  5933. }
  5934. loopWillNotRun(node) {
  5935. const [trip_count, start_cond] = node.inputs();
  5936. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  5937. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  5938. const loop_might_run = cond_val && iter_len > 0;
  5939. return !loop_might_run;
  5940. }
  5941. inlineIfBody(body) {
  5942. const n = body.owningNode();
  5943. for (const body_node of body.nodes()) {
  5944. body_node.moveBefore(n);
  5945. }
  5946. for (let i = 0; i < n.outputs().length; i++) {
  5947. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  5948. }
  5949. n.destroy();
  5950. }
  5951. inlineIf(n) {
  5952. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  5953. torch._C.AT_ASSERT(input_bool !== null);
  5954. const block_index = input_bool ? 0 : 1;
  5955. this.ConstantPropagation(n.blocks()[block_index]);
  5956. this.inlineIfBody(n.blocks()[block_index]);
  5957. this._made_change = true;
  5958. }
  5959. replaceAndRemoveIfOutput(n, i, replacement) {
  5960. n.outputs()[i].replaceAllUsesWith(replacement);
  5961. n.eraseOutput(i);
  5962. n.blocks()[0].eraseOutput(i);
  5963. n.blocks()[1].eraseOutput(i);
  5964. }
  5965. removeExtraIfOutputs(n) {
  5966. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  5967. const [true_block, false_block] = n.blocks();
  5968. const graph = n.owningGraph();
  5969. const initial_outputs = true_block.outputs().length;
  5970. const guard = new torch._C.WithInsertPoint(n);
  5971. for (let i = 0; i < true_block.outputs().length;) {
  5972. const t_out = true_block.outputs()[i];
  5973. const f_out = false_block.outputs()[i];
  5974. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  5975. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  5976. continue;
  5977. }
  5978. const maybe_const = torch._C.toIValue(t_out);
  5979. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  5980. const new_const = graph.insertConstant(maybe_const);
  5981. this.replaceAndRemoveIfOutput(n, i, new_const);
  5982. continue;
  5983. }
  5984. i++;
  5985. }
  5986. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  5987. guard.dispose();
  5988. }
  5989. removeExtraLoopOutputs(node) {
  5990. const initial_outputs = node.outputs().length;
  5991. const [loop_body] = node.blocks();
  5992. const loop_input_offset = 2;
  5993. const loop_body_offset = 1;
  5994. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  5995. const i = i_1 - 1;
  5996. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  5997. const node_input = node.inputs()[loop_input_offset + i];
  5998. node.outputs().at(i).replaceAllUsesWith(node_input);
  5999. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6000. node.eraseOutput(i);
  6001. node.removeInput(loop_input_offset + i);
  6002. loop_body.eraseInput(loop_body_offset + i);
  6003. loop_body.eraseOutput(loop_body_offset + i);
  6004. }
  6005. }
  6006. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6007. }
  6008. noMutableValues(values) {
  6009. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6010. }
  6011. getOrCreateAliasDb() {
  6012. if (!this._aliasDb) {
  6013. this._aliasDb = new torch._C.AliasDb(this._graph);
  6014. }
  6015. return this._aliasDb;
  6016. }
  6017. supportedNode(n) {
  6018. torch._C.skip_list = torch._C.skip_list || new Set([
  6019. 'prim::If',
  6020. 'prim::Loop',
  6021. 'prim::Closure',
  6022. 'prim::Constant',
  6023. 'prim::AutogradZero',
  6024. 'prim::Uninitialized',
  6025. 'prim::Guard',
  6026. 'prim::profile',
  6027. 'prim::profile_ivalue',
  6028. 'prim::unchecked_unwrap_optional',
  6029. 'prim::awaitable',
  6030. 'aten::dequantize'
  6031. ]);
  6032. let no_mutation = false;
  6033. if (this._aliasing_types) {
  6034. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  6035. } else {
  6036. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  6037. }
  6038. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  6039. }
  6040. ConstantPropagation(...args) {
  6041. if (args[0] instanceof torch.Graph) {
  6042. throw new python.Error('Not implemented.');
  6043. } else if (args[0] instanceof torch.Block) {
  6044. const [block] = args;
  6045. for (const n of block.nodes()) {
  6046. this.ConstantPropagation(n);
  6047. }
  6048. } else if (args[0] instanceof torch.Node) {
  6049. const [n] = args;
  6050. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  6051. if (n.kind() === 'prim::If') {
  6052. if (constant_inputs) {
  6053. this.inlineIf(n);
  6054. } else {
  6055. this.ConstantPropagation(n.blocks());
  6056. this.removeExtraIfOutputs(n);
  6057. }
  6058. } else if (n.kind() === 'prim::Loop') {
  6059. if (this.loopWillNotRun(n)) {
  6060. this.removeLoopNode(n);
  6061. } else {
  6062. this.ConstantPropagation(n.blocks());
  6063. this.removeExtraLoopOutputs(n);
  6064. }
  6065. } else if (constant_inputs && this.supportedNode(n)) {
  6066. this.propagateNode(n);
  6067. } else {
  6068. this.ConstantPropagation(n.blocks()); // not implemented
  6069. }
  6070. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  6071. const [blocks] = args;
  6072. for (const block of blocks) {
  6073. this.ConstantPropagation(block);
  6074. }
  6075. } else {
  6076. throw new python.Error('Not implemented.');
  6077. }
  6078. }
  6079. });
  6080. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  6081. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  6082. const made_change = cp.run();
  6083. if (made_change) {
  6084. torch._C.EliminateDeadCode(graph);
  6085. }
  6086. return made_change;
  6087. });
  6088. this.registerType('torch._C.MutableTypePtrHelper', class {
  6089. constructor(mutable_type_cache) {
  6090. this._mutable_type_cache = mutable_type_cache;
  6091. }
  6092. mapTypeToAliasTypeSet(type) {
  6093. if (this._mutable_type_cache) {
  6094. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  6095. if (result) {
  6096. return result;
  6097. }
  6098. }
  6099. return this.mapTypeToAliasTypeSetImpl(type);
  6100. }
  6101. mapTypeToAliasTypeSetImpl(type) {
  6102. if (type instanceof torch.ListType ||
  6103. type instanceof torch.DictType ||
  6104. type instanceof torch.ClassType ||
  6105. type instanceof torch.TensorType) {
  6106. return [torch._C.unshapedType(type)];
  6107. }
  6108. if (type instanceof torch.UnionType) {
  6109. const mutable_types = [];
  6110. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  6111. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  6112. if (maybe_inner_types) {
  6113. mutable_types.push(...maybe_inner_types);
  6114. }
  6115. }
  6116. if (mutable_types.length === 0) {
  6117. return null;
  6118. }
  6119. return mutable_types;
  6120. }
  6121. if (type instanceof torch.OptionalType) {
  6122. const inner = type.getElementType();
  6123. return this.mapTypeToAliasTypeSet(inner);
  6124. }
  6125. if (type instanceof torch.AnyType) {
  6126. return [torch._C.AliasTypeSet([type])];
  6127. }
  6128. if (type instanceof torch.FutureType) {
  6129. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  6130. if (maybe_mut_types) {
  6131. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  6132. }
  6133. return null;
  6134. }
  6135. if (type instanceof torch.AwaitType) {
  6136. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  6137. if (maybe_mut_types) {
  6138. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  6139. }
  6140. return null;
  6141. }
  6142. if (type instanceof torch.TupleType) {
  6143. const mutable_types = [];
  6144. for (const inner of type.elements()) {
  6145. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  6146. if (maybe_inner_types) {
  6147. mutable_types.push(...maybe_inner_types);
  6148. }
  6149. }
  6150. if (mutable_types.length === 0) {
  6151. return null;
  6152. }
  6153. return [[torch.TupleType.create(mutable_types)]];
  6154. }
  6155. return null;
  6156. }
  6157. });
  6158. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  6159. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  6160. type instanceof torch.ClassType || type instanceof torch.DictType) {
  6161. return true;
  6162. }
  6163. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  6164. if (mutable_type_cache) {
  6165. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  6166. }
  6167. return helper.mapTypeToAliasTypeSet(type) !== null;
  6168. });
  6169. this.registerType('torch._C.AliasDb', class {
  6170. constructor() {
  6171. this._writeIndex = new Map();
  6172. }
  6173. static isMutableType(...args) {
  6174. if (args[0] instanceof torch.Type) {
  6175. const [type] = args;
  6176. return torch._C.isMutableTypeImpl(type, null);
  6177. }
  6178. if (args[0] instanceof torch.Value) {
  6179. const [value] = args;
  6180. return torch._C.AliasDb.isMutableType(value.type());
  6181. }
  6182. throw new python.Error('Not implemented.');
  6183. }
  6184. writesToAlias(/* n, vs */) {
  6185. /*
  6186. const writtenTo = this.getWrites(n);
  6187. if (writtenTo.length === 0) {
  6188. return false;
  6189. }
  6190. MemoryLocations locs;
  6191. for (const v of vs) {
  6192. const it = elementMap_.find(v);
  6193. if (it != elementMap_.end()) {
  6194. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  6195. if (writtenTo.intersects(vlocs)) {
  6196. return true;
  6197. }
  6198. }
  6199. }
  6200. */
  6201. return false;
  6202. }
  6203. writesToWildcard(n) {
  6204. if (!this._writeIndex.has(n)) {
  6205. return false;
  6206. }
  6207. const writes = this._writeIndex.get(n);
  6208. for (const pr of this._wildcardIndex) {
  6209. const [, wildcardElement] = pr;
  6210. if (writes.test(wildcardElement.index)) {
  6211. return true;
  6212. }
  6213. }
  6214. return false;
  6215. }
  6216. safeToChangeAliasingRelationship(a, b) {
  6217. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  6218. return false;
  6219. }
  6220. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  6221. }
  6222. });
  6223. this.registerFunction('torch._C.hasWriters', () => {
  6224. });
  6225. this.registerFunction('torch._C.escapesScope', () => {
  6226. });
  6227. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  6228. constructor(graph) {
  6229. this._current = graph.block().nodes().front();
  6230. }
  6231. next() {
  6232. return null;
  6233. }
  6234. });
  6235. this.registerType('torch._C.ConcatCombiner', class {
  6236. constructor(graph) {
  6237. this._graph = graph;
  6238. this._aliasDb = new torch._C.AliasDb(graph);
  6239. this._combinable_concats = [];
  6240. }
  6241. collectOptimizableConcats() {
  6242. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  6243. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  6244. if (node.kind() === 'aten::cat') {
  6245. this.handleConcat(node);
  6246. }
  6247. }
  6248. }
  6249. combineConcats() {
  6250. if (this._combinable_concats.length === 0) {
  6251. return false;
  6252. }
  6253. const list_construct_inputs = this.getListConstructInputs();
  6254. for (const node_and_new_list of list_construct_inputs) {
  6255. const [node, inputs] = node_and_new_list;
  6256. const new_list_construct = this.createListConstruct(inputs);
  6257. const old_list_construct = node.input(0).node();
  6258. new_list_construct.output().setType(old_list_construct.output().type());
  6259. new_list_construct.insertBefore(node);
  6260. old_list_construct.replaceAllUsesWith(new_list_construct);
  6261. }
  6262. return true;
  6263. }
  6264. run() {
  6265. this.collectOptimizableConcats();
  6266. const changed = this.combineConcats();
  6267. if (changed) {
  6268. torch._C.EliminateDeadCode(this._graph);
  6269. }
  6270. return changed;
  6271. }
  6272. });
  6273. this.registerFunction('torch._C.CombineConcats', (graph) => {
  6274. const changed = new torch._C.ConcatCombiner(graph).run();
  6275. return changed;
  6276. });
  6277. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  6278. constructor(graph, disable_shape_peepholes) {
  6279. this._graph = graph;
  6280. this._shape_peepholes = !disable_shape_peepholes;
  6281. }
  6282. run() {
  6283. let changed = this.optimizeBlock(this._graph.block());
  6284. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  6285. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  6286. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  6287. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  6288. changed = changed || torch._C.CombineConcats(this._graph);
  6289. return changed;
  6290. }
  6291. optimizeBlock(block) {
  6292. let changed = false;
  6293. for (const node of block.nodes()) {
  6294. for (const sub_block of node.blocks()) {
  6295. changed = changed || this.optimizeBlock(sub_block);
  6296. }
  6297. if (node.kind() !== 'prim::Constant') {
  6298. const guard = new torch._C.WithInsertPoint(node);
  6299. for (const output of node.outputs()) {
  6300. if (output.type() instanceof torch.NoneType) {
  6301. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  6302. changed = true;
  6303. }
  6304. }
  6305. guard.dispose();
  6306. }
  6307. if (node.kind() === 'prim::If') {
  6308. // throw new python.Error('Not implemented.');
  6309. /*
  6310. const n = new torch._C.IfView(node);
  6311. // this handles redundant short circuits like "x and True" or "x or
  6312. // False"
  6313. for (const auto i : c10::irange(n.outputs().length)) {
  6314. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  6315. continue;
  6316. }
  6317. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  6318. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  6319. if (true_val && !false_val) {
  6320. n.outputs().at(i).replaceAllUsesWith(n.cond());
  6321. changed = true;
  6322. }
  6323. }
  6324. for (let i = 0; i < n.outputs().length; ++i) {
  6325. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  6326. const output_optional = n.outputs()[i].type();
  6327. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  6328. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  6329. if (unif) {
  6330. n.outputs()[i].setType(unif);
  6331. changed = true;
  6332. }
  6333. }
  6334. }
  6335. */
  6336. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  6337. torch._C.AT_ASSERT(node.inputs().length === 2);
  6338. for (const check_none_index of [0, 1]) {
  6339. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  6340. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  6341. if (input_must_be_none && other_must_not_be_none) {
  6342. const guard = new torch._C.WithInsertPoint(node);
  6343. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  6344. node.output().replaceAllUsesWith(output);
  6345. changed = true;
  6346. guard.dispose();
  6347. }
  6348. }
  6349. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  6350. throw new python.Error('Not implemented.');
  6351. /*
  6352. // we are unwrapping an input that can't be None, remove the unwrap
  6353. const input = node.input();
  6354. if (input.mustNotBeNone()) {
  6355. node.output().replaceAllUsesWith(node.input());
  6356. changed = true;
  6357. }
  6358. */
  6359. } else if (node.kind() === 'prim::unchecked_cast') {
  6360. const input_type = torch._C.unshapedType(node.input().type());
  6361. const output_type = torch._C.unshapedType(node.output().type());
  6362. if (input_type.isSubtypeOf(output_type)) {
  6363. node.output().replaceAllUsesWith(node.input());
  6364. changed = true;
  6365. }
  6366. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  6367. node.output().replaceAllUsesWith(node.input());
  6368. changed = true;
  6369. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  6370. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  6371. continue;
  6372. }
  6373. const inp_type = node.inputs()[0].type();
  6374. const immut_type = (type) => {
  6375. const kind = type.kind();
  6376. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  6377. return handled_immutable_types.has(kind);
  6378. };
  6379. let non_throwing_type = false;
  6380. if (inp_type instanceof torch.ListType) {
  6381. non_throwing_type = immut_type(inp_type.getElementType());
  6382. } else if (inp_type instanceof torch.DictType) {
  6383. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  6384. } else {
  6385. non_throwing_type = immut_type(inp_type);
  6386. }
  6387. if (non_throwing_type) {
  6388. const guard = new torch._C.WithInsertPoint(node);
  6389. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  6390. changed = true;
  6391. guard.dispose();
  6392. }
  6393. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  6394. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  6395. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  6396. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  6397. }
  6398. }
  6399. return changed;
  6400. }
  6401. });
  6402. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  6403. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  6404. const changed = peephole.run();
  6405. if (changed) {
  6406. torch._C.EliminateDeadCode(graph.block());
  6407. }
  6408. return changed;
  6409. });
  6410. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  6411. if (!cond) {
  6412. throw new python.Error('Assertion failed.');
  6413. }
  6414. });
  6415. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  6416. if (!cond) {
  6417. throw new python.Error('Assertion failed.');
  6418. }
  6419. });
  6420. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  6421. if (!cond) {
  6422. throw new python.Error('Assertion failed.');
  6423. }
  6424. });
  6425. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  6426. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  6427. for (let next_node = it.next(); next_node !== null;) {
  6428. const node = next_node;
  6429. next_node = it.next();
  6430. if (node.kind() === 'prim::EmptyListLiteral') {
  6431. if (node.hasUses()) {
  6432. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  6433. }
  6434. const li = graph.createList(torch.TensorType.get(), []);
  6435. li.insertBefore(node);
  6436. node.replaceAllUsesWith(li);
  6437. }
  6438. node.destroy();
  6439. }
  6440. });
  6441. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  6442. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6443. const [graph] = args;
  6444. const aliasDb = new torch._C.AliasDb(graph);
  6445. const constants = new torch._C.NodeSet();
  6446. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  6447. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  6448. const [block, constants, aliasDb] = args;
  6449. for (const node of block.nodes()) {
  6450. if (node.blocks().length > 0) {
  6451. for (const block of node.blocks()) {
  6452. torch._C.ConstantPooling(block, constants, aliasDb);
  6453. }
  6454. continue;
  6455. }
  6456. if (node.kind() !== 'prim::Constant') {
  6457. continue;
  6458. }
  6459. if (constants.has(node)) {
  6460. const existing = constants.get(node);
  6461. const old_ivalue = torch._C.toIValue(existing.output());
  6462. const new_ivalue = torch._C.toIValue(node.output());
  6463. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  6464. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  6465. continue;
  6466. }
  6467. node.replaceAllUsesWith(existing);
  6468. node.destroy();
  6469. continue;
  6470. } else {
  6471. constants.insert(node);
  6472. }
  6473. const [first_node] = node.owningGraph().block().nodes();
  6474. if (node !== first_node) {
  6475. node.moveBefore(first_node);
  6476. }
  6477. }
  6478. } else {
  6479. throw new python.Error('Not implemented.');
  6480. }
  6481. });
  6482. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  6483. /*
  6484. const autocast_stack = [];
  6485. let incompatible_amp = null;
  6486. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  6487. for (const node of block.nodes()) {
  6488. switch (node.kind()) {
  6489. case 'prim::CallFunction':
  6490. if (current_state() === initial_state) {
  6491. if (current_state()) {
  6492. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6493. }
  6494. break;
  6495. }
  6496. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  6497. incompatible_amp = true;
  6498. break;
  6499. case 'prim::CallMethod':
  6500. if (current_state() === initial_state) {
  6501. if (current_state()) {
  6502. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6503. }
  6504. break;
  6505. }
  6506. if (node.input(0).type() instanceof torch.ClassType) {
  6507. const class_type = node.input(0).type();
  6508. const name = node.s('name');
  6509. const fn = class_type.getMethod(name);
  6510. if (!fn.isGraphFunction()) {
  6511. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  6512. incompatible_amp = true;
  6513. }
  6514. } else {
  6515. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  6516. incompatible_amp = true;
  6517. }
  6518. break;
  6519. case 'prim::Enter': {
  6520. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  6521. if (autocast_scope) {
  6522. if (node.hasUses()) {
  6523. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  6524. }
  6525. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  6526. incompatible_amp = false;
  6527. autocast_stack.push(autocast_scope);
  6528. }
  6529. break;
  6530. }
  6531. case 'prim::Exit': {
  6532. if (torch._C.isAutocastNode(node.input(0))) {
  6533. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  6534. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  6535. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  6536. incompatible_amp = false;
  6537. autocast_stack.pop();
  6538. }
  6539. break;
  6540. }
  6541. case 'aten::is_autocast_enabled': {
  6542. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  6543. break;
  6544. }
  6545. case 'aten::is_autocast_cpu_enabled': {
  6546. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  6547. break;
  6548. }
  6549. case 'aten::_convolution':
  6550. case 'aten::conv1d':
  6551. case 'aten::conv2d':
  6552. case 'aten::conv3d':
  6553. case 'aten::conv_tbc':
  6554. case 'aten::conv_transpose1d':
  6555. case 'aten::convolution':
  6556. case 'aten::cudnn_convolution':
  6557. case 'aten::cudnn_convolution_transpose':
  6558. case 'aten::prelu':
  6559. case 'aten::addmm':
  6560. case 'aten::addmv':
  6561. case 'aten::addr':
  6562. case 'aten::matmul':
  6563. case 'aten::mm':
  6564. case 'aten::mv':
  6565. case 'aten::linear':
  6566. case 'aten::addbmm':
  6567. case 'aten::baddbmm':
  6568. case 'aten::bmm':
  6569. case 'aten::chain_matmul':
  6570. case 'aten::_thnn_fused_lstm_cell':
  6571. case 'aten::_thnn_fused_gru_cell':
  6572. case 'aten::lstm_cell':
  6573. case 'aten::gru_cell':
  6574. case 'aten::rnn_tanh_cell':
  6575. case 'aten::rnn_relu_cell': {
  6576. if (!node.schema().is_mutable()) {
  6577. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  6578. }
  6579. break;
  6580. }
  6581. case 'aten::native_layer_norm':
  6582. case 'aten::acos':
  6583. case 'aten::asin':
  6584. case 'aten::cosh':
  6585. case 'aten::erfinv':
  6586. case 'aten::exp':
  6587. case 'aten::expm1':
  6588. case 'aten::log':
  6589. case 'aten::log10':
  6590. case 'aten::log2':
  6591. case 'aten::log1p':
  6592. case 'aten::reciprocal':
  6593. case 'aten::rsqrt':
  6594. case 'aten::sinh':
  6595. case 'aten::tan':
  6596. case 'aten::pow':
  6597. case 'aten::softplus':
  6598. case 'aten::gelu':
  6599. case 'aten::layer_norm':
  6600. case 'aten::group_norm':
  6601. case 'aten::frobenius_norm':
  6602. case 'aten::nuclear_norm':
  6603. case 'aten::cosine_similarity':
  6604. case 'aten::cosine_embedding_loss':
  6605. case 'aten::nll_loss':
  6606. case 'aten::nll_loss2d':
  6607. case 'aten::hinge_embedding_loss':
  6608. case 'aten::kl_div':
  6609. case 'aten::l1_loss':
  6610. case 'aten::smooth_l1_loss':
  6611. case 'aten::mse_loss':
  6612. case 'aten::margin_ranking_loss':
  6613. case 'aten::multilabel_margin_loss':
  6614. case 'aten::soft_margin_loss':
  6615. case 'aten::triplet_margin_loss':
  6616. case 'aten::multi_margin_loss':
  6617. case 'aten::binary_cross_entropy_with_logits':
  6618. case 'aten::dist':
  6619. case 'aten::pdist':
  6620. case 'aten::cdist':
  6621. case 'aten::renorm':
  6622. case 'aten::logsumexp': {
  6623. if (!node.schema().is_mutable()) {
  6624. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6625. }
  6626. break;
  6627. }
  6628. case 'aten::prod':
  6629. case 'aten::log_softmax':
  6630. case 'aten::cumprod':
  6631. case 'aten::cumsum':
  6632. case 'aten::sum': {
  6633. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  6634. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6635. }
  6636. break;
  6637. }
  6638. case 'aten::softmax': {
  6639. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  6640. const context = current_state();
  6641. context.cpu_enabled = false;
  6642. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  6643. }
  6644. break;
  6645. }
  6646. case 'aten::addcdiv':
  6647. case 'aten::addcmul':
  6648. case 'aten::atan2':
  6649. case 'aten::bilinear':
  6650. case 'aten::cat':
  6651. case 'aten::cross':
  6652. case 'aten::dot':
  6653. case 'aten::equal':
  6654. case 'aten::index_put':
  6655. case 'aten::stack':
  6656. case 'aten::tensordot':
  6657. case 'aten::add':
  6658. case 'aten::sub':
  6659. case 'aten::mul':
  6660. case 'aten::div': {
  6661. if (!node.schema().is_mutable()) {
  6662. torch._C.castInputsToWidestType(node, current_state());
  6663. }
  6664. break;
  6665. }
  6666. case 'aten::binary_cross_entropy': {
  6667. if (current_state()) {
  6668. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  6669. }
  6670. break;
  6671. }
  6672. default: {
  6673. break;
  6674. }
  6675. }
  6676. for (const sub_block of node.blocks()) {
  6677. torch._C.handleBlock(sub_block, current_state());
  6678. }
  6679. }
  6680. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  6681. */
  6682. });
  6683. this.registerFunction('torch._C.autocastEnabled', () => {
  6684. return true;
  6685. });
  6686. this.registerFunction('torch._C.Autocast', (graph) => {
  6687. if (torch._C.autocastEnabled()) {
  6688. const init = null;
  6689. /* AutocastContext init = {
  6690. at::autocast::is_autocast_enabled(at::kCUDA),
  6691. at::autocast::is_autocast_enabled(at::kCPU),
  6692. at::autocast::get_autocast_dtype(at::kCUDA),
  6693. at::autocast::get_autocast_dtype(at::kCPU)}; */
  6694. torch._C.handleBlock(graph.block(), init);
  6695. }
  6696. });
  6697. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  6698. disable_autocast = disable_autocast || false;
  6699. torch._C.Inline(graph);
  6700. torch._C.PeepholeOptimize(graph, true);
  6701. torch._C.ConstantPropagationImmutableTypes(graph);
  6702. if (!disable_autocast) {
  6703. torch._C.Autocast(graph);
  6704. }
  6705. torch._C.ConstantPooling(graph);
  6706. });
  6707. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  6708. constructor(name, graph, function_creator, executor_execution_mode) {
  6709. super();
  6710. this._name = name;
  6711. this._graph = graph;
  6712. this._executor_execution_mode = executor_execution_mode || null;
  6713. this._function_creator = function_creator;
  6714. this._force_no_amp = false;
  6715. }
  6716. isGraphFunction() {
  6717. return true;
  6718. }
  6719. qualname() {
  6720. return this._name;
  6721. }
  6722. graph() {
  6723. return this._graph;
  6724. }
  6725. optimized_graph() {
  6726. const graph_ref = this._graph.copy();
  6727. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  6728. return graph_ref;
  6729. }
  6730. ensure_defined() {
  6731. if (this._function_creator) {
  6732. const creator = this._function_creator;
  6733. this._function_creator = () => {
  6734. throw new python.Error('Recursive method call.');
  6735. };
  6736. creator(this);
  6737. this._function_creator = null;
  6738. }
  6739. this.check_single_output();
  6740. }
  6741. check_single_output() {
  6742. if (this.graph().outputs().length !== 1) {
  6743. throw new python.Error('Graph must have a single output.');
  6744. }
  6745. }
  6746. getSchema() {
  6747. this._schema = this._schema || this.defaultSchemaFor(this);
  6748. return this._schema;
  6749. }
  6750. setSchema(schema) {
  6751. this._schema = schema;
  6752. }
  6753. num_inputs() {
  6754. return this.graph().inputs().length;
  6755. }
  6756. unshapedType(type) {
  6757. if (type.isSubtypeOf(torch.TensorType.get())) {
  6758. return torch.TensorType.get();
  6759. }
  6760. const contained = type.containedTypes();
  6761. if (contained.length === 0) {
  6762. return type;
  6763. }
  6764. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  6765. }
  6766. defaultSchemaFor(fn) {
  6767. const args = [];
  6768. const returns = [];
  6769. const g = fn.graph();
  6770. const num_inputs = fn.num_inputs();
  6771. for (let i = 0; i < num_inputs; i++) {
  6772. const v = g.inputs()[i];
  6773. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  6774. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  6775. args.push(argument);
  6776. }
  6777. const num_outputs = g.outputs().length;
  6778. for (let i = 0; i < num_outputs; i++) {
  6779. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  6780. returns.push(argument);
  6781. }
  6782. return new torch.FunctionSchema(fn.name(), '', args, returns);
  6783. }
  6784. });
  6785. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  6786. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  6787. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  6788. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  6789. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  6790. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  6791. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  6792. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  6793. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  6794. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  6795. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  6796. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  6797. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  6798. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  6799. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  6800. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  6801. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  6802. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  6803. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  6804. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  6805. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  6806. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  6807. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  6808. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  6809. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  6810. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  6811. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  6812. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  6813. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  6814. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  6815. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  6816. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  6817. this.registerType('torch._C._LegacyVariableBase', class {});
  6818. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  6819. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  6820. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  6821. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  6822. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  6823. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  6824. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  6825. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  6826. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  6827. this.registerType('torch.distributed.remote_device._remote_device', class {});
  6828. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  6829. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  6830. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  6831. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  6832. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  6833. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  6834. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  6835. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  6836. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  6837. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  6838. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  6839. this.registerType('torch.distributions.beta.Beta', class {});
  6840. this.registerType('torch.distributions.binomial.Binomial', class {});
  6841. this.registerType('torch.distributions.categorical.Categorical', class {});
  6842. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  6843. this.registerType('torch.distributions.constraints._Real', class {});
  6844. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  6845. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  6846. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  6847. this.registerType('torch.distributions.normal.Normal', class {});
  6848. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  6849. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  6850. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  6851. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  6852. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  6853. this.registerType('torch.distributions.uniform.Uniform', class {});
  6854. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  6855. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  6856. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  6857. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  6858. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  6859. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  6860. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  6861. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  6862. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  6863. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  6864. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  6865. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  6866. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  6867. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  6868. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  6869. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  6870. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  6871. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  6872. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  6873. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  6874. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  6875. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  6876. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  6877. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  6878. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  6879. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  6880. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  6881. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  6882. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  6883. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  6884. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  6885. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  6886. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  6887. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  6888. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  6889. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  6890. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  6891. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  6892. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  6893. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  6894. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  6895. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  6896. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  6897. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  6898. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6899. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6900. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6901. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  6902. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  6903. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  6904. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  6905. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  6906. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  6907. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  6908. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  6909. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  6910. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  6911. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  6912. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  6913. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  6914. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  6915. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  6916. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  6917. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  6918. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  6919. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  6920. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  6921. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  6922. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  6923. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  6924. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  6925. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  6926. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  6927. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  6928. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  6929. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  6930. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  6931. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  6932. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  6933. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  6934. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  6935. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  6936. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  6937. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  6938. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  6939. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  6940. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  6941. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  6942. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  6943. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  6944. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  6945. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  6946. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  6947. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  6948. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  6949. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  6950. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  6951. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6952. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  6953. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6954. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  6955. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  6956. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  6957. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  6958. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  6959. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  6960. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  6961. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  6962. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  6963. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  6964. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6965. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  6966. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6967. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  6968. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  6969. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  6970. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  6971. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  6972. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  6973. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  6974. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  6975. this.registerType('torch.nn.modules.module.PatchForward', class {});
  6976. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  6977. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  6978. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  6979. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  6980. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  6981. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  6982. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  6983. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  6984. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  6985. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  6986. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  6987. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  6988. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  6989. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  6990. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  6991. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  6992. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  6993. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  6994. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  6995. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  6996. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  6997. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  6998. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  6999. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7000. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7001. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7002. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  7003. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  7004. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  7005. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  7006. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  7007. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  7008. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  7009. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  7010. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  7011. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  7012. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  7013. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  7014. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7015. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7016. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7017. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  7018. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7019. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7020. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7021. this.registerType('torch.nn.modules.rnn.GRU', class {});
  7022. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  7023. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  7024. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  7025. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  7026. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  7027. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  7028. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  7029. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  7030. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  7031. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  7032. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  7033. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  7034. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  7035. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  7036. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  7037. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  7038. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  7039. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  7040. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  7041. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  7042. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  7043. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  7044. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  7045. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  7046. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  7047. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  7048. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  7049. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  7050. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  7051. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  7052. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  7053. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  7054. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  7055. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  7056. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  7057. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  7058. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  7059. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  7060. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  7061. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  7062. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  7063. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  7064. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  7065. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  7066. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  7067. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  7068. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  7069. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  7070. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  7071. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  7072. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  7073. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  7074. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  7075. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  7076. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  7077. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7078. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  7079. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  7080. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  7081. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7082. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  7083. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  7084. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  7085. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  7086. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  7087. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  7088. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  7089. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  7090. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  7091. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  7092. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  7093. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  7094. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  7095. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  7096. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  7097. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  7098. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  7099. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  7100. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  7101. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  7102. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  7103. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  7104. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  7105. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  7106. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  7107. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  7108. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  7109. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  7110. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  7111. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  7112. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  7113. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  7114. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  7115. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  7116. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  7117. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7118. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7119. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7120. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7121. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7122. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7123. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  7124. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  7125. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  7126. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  7127. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  7128. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  7129. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  7130. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  7131. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  7132. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  7133. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  7134. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  7135. this.registerType('torch.optim.optimizer.Optimizer', class {});
  7136. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  7137. this.registerType('torch.optim.adamw.AdamW', class {});
  7138. this.registerType('torch.optim.adagrad.Adagrad', class {});
  7139. this.registerType('torch.optim.adadelta.Adadelta', class {});
  7140. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  7141. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  7142. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  7143. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  7144. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  7145. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  7146. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  7147. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  7148. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  7149. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  7150. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  7151. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  7152. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  7153. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  7154. this.registerType('torch.optim.sgd.SGD', class {});
  7155. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  7156. this.registerType('torch.optim.swa_utils.SWALR', class {});
  7157. torch.optim.RAdam = torch.optim.radam.RAdam;
  7158. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  7159. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  7160. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  7161. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  7162. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  7163. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  7164. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7165. this.registerFunction('torch.quantization.observer._with_args');
  7166. this.registerType('torch.quantization.qconfig.QConfig', class {});
  7167. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  7168. this.registerType('torch.quantization.stubs.QuantStub', class {});
  7169. this.registerType('torch.utils._pytree.LeafSpec', class {});
  7170. this.registerType('torch.utils._pytree.TreeSpec', class {});
  7171. this.registerFunction('torch.utils._pytree.tree_map');
  7172. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7173. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7174. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7175. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7176. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7177. this.registerType('torch.utils.data.dataset.Subset', class {});
  7178. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7179. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7180. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7181. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7182. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7183. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7184. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  7185. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  7186. create_symintnode(/* sym, hint, source */) {
  7187. return new torch.SymInt();
  7188. }
  7189. });
  7190. this.registerType('torch.fx.proxy.TracerBase', class {
  7191. constructor() {
  7192. this.traced_func_name = 'forward';
  7193. }
  7194. });
  7195. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  7196. trace(root /*, concrete_args */) {
  7197. let fn = null;
  7198. if (root instanceof torch.nn.Module) {
  7199. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  7200. this.root = root;
  7201. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  7202. this.root_module_name = root._get_name();
  7203. this.submodule_paths = new builtins.dict(root.named_modules());
  7204. } else {
  7205. this.root = new torch.nn.Module();
  7206. fn = root;
  7207. }
  7208. const tracer_cls = builtins.getattr(this, '__class__', null);
  7209. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  7210. if (builtins.hasattr(this, '__code__')) {
  7211. const code = fn.__code__;
  7212. this.graph._co_fields = {
  7213. co_name: code.co_name,
  7214. co_filename: code.co_filename,
  7215. co_firstlineno: code.co_firstlineno,
  7216. };
  7217. }
  7218. return this.graph;
  7219. }
  7220. is_leaf_module(m /*, module_qualified_name */) {
  7221. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  7222. }
  7223. });
  7224. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  7225. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  7226. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  7227. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  7228. return new graph_module_cls(...args);
  7229. });
  7230. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  7231. let tracer_cls = body.get('_tracer_cls');
  7232. if (!tracer_cls) {
  7233. tracer_cls = torch.fx._symbolic_trace.Tracer;
  7234. }
  7235. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  7236. const cls_tracer = tracer_cls;
  7237. const KeepModules = class extends cls_tracer {
  7238. is_leaf_module() {
  7239. return true;
  7240. }
  7241. };
  7242. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  7243. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  7244. const graph = new KeepModules().trace(com, tracer_extras);
  7245. graph._tracer_cls = tracer_cls;
  7246. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  7247. for (const [k, v] of body.items()) {
  7248. if (!builtins.hasattr(gm, k)) {
  7249. builtins.setattr(gm, k, v);
  7250. }
  7251. }
  7252. return gm;
  7253. });
  7254. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  7255. globals = { ...globals };
  7256. const context = new python.Execution.Context(globals, null);
  7257. execution.exec(src, context);
  7258. const forward_fn = globals.forward;
  7259. delete globals.forward;
  7260. return forward_fn;
  7261. });
  7262. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  7263. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  7264. let fn_src = null;
  7265. if (body.has('_code')) {
  7266. fn_src = body.get('_code');
  7267. } else if (body.has('code')) {
  7268. fn_src = body.get('code');
  7269. } else {
  7270. fn_src = body._code || body.code;
  7271. }
  7272. const forward = execution.invoke('torch.fx.graph_module._forward_from_src', [import_block + fn_src, {}]);
  7273. return execution.invoke('torch.fx.graph_module._deserialize_graph_module', [forward, body]);
  7274. });
  7275. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  7276. const forward = importer.import_module(generated_module_name).forward;
  7277. return execution.invoke('torch.fx.graph_module._deserialize_graph_module', [forward, body]);
  7278. });
  7279. this.registerType('torch.fx.graph.CodeGen', class {});
  7280. this.registerType('torch.fx.graph._Namespace', class {
  7281. constructor() {
  7282. this._obj_to_name = new Map();
  7283. this._unassociated_names = new Set();
  7284. this._used_names = new Set();
  7285. this._base_count = {};
  7286. }
  7287. create_name(candidate, obj) {
  7288. if (obj && this._obj_to_name.has(obj)) {
  7289. return self._obj_to_name.get(obj);
  7290. }
  7291. candidate = candidate || '_unnamed';
  7292. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  7293. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  7294. const match = candidate.match(/(.*)_(\d+)$"/);
  7295. let base = candidate;
  7296. let num = null;
  7297. if (match) {
  7298. [, base] = match;
  7299. num = parseInt(match[2], 10);
  7300. }
  7301. candidate = num ? `${base}_${num}` : base;
  7302. if (!num) {
  7303. num = this._base_count[base] || 0;
  7304. }
  7305. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  7306. num += 1;
  7307. candidate = `${base}_${num}`;
  7308. }
  7309. this._used_names.add(candidate);
  7310. this._base_count[base] = num;
  7311. if (obj) {
  7312. this._obj_to_name[obj] = candidate;
  7313. } else {
  7314. this._unassociated_names.add(candidate);
  7315. }
  7316. return candidate;
  7317. }
  7318. _is_illegal_name(/* name, obj */) {
  7319. /*
  7320. if name in keyword.kwlist:
  7321. return True
  7322. if name in builtins.__dict__:
  7323. return obj is not builtins.__dict__[name]
  7324. if name in _custom_builtins:
  7325. return obj is not _custom_builtins[name].obj
  7326. */
  7327. return false;
  7328. }
  7329. associate_name_with_obj() {
  7330. }
  7331. });
  7332. this.registerType('torch.fx.node.Node', class {
  7333. constructor(graph, name, op, target, args, kwargs, return_type) {
  7334. this.graph = graph;
  7335. this.name = name;
  7336. this.op = op;
  7337. this.target = target;
  7338. this._input_nodes = new builtins.dict();
  7339. this.__update_args_kwargs(args, kwargs);
  7340. this.users = new builtins.dict();
  7341. this.type = return_type;
  7342. this._prev = this;
  7343. this._next = this;
  7344. this._erased = false;
  7345. this._repr_fn = null;
  7346. this.meta = new builtins.dict();
  7347. }
  7348. get args() {
  7349. return this._args;
  7350. }
  7351. get kwargs() {
  7352. return this._kwargs;
  7353. }
  7354. get next() {
  7355. return this._next;
  7356. }
  7357. prepend(x) {
  7358. x._remove_from_list();
  7359. const p = this._prev;
  7360. [p._next, x._prev] = [x, p];
  7361. [x._next, this._prev] = [this, x];
  7362. }
  7363. _remove_from_list() {
  7364. const [p, n] = [this._prev, this._next];
  7365. [p._next, n._prev] = [n, p];
  7366. }
  7367. __update_args_kwargs(new_args, new_kwargs) {
  7368. const update_users_and_input_nodes = (n) => {
  7369. if (n instanceof torch.fx.node.Node) {
  7370. this._input_nodes.setdefault(n);
  7371. n.users.setdefault(this);
  7372. }
  7373. return n;
  7374. };
  7375. const map_aggregate = (a, fn) => {
  7376. if (a instanceof builtins.tuple) {
  7377. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  7378. if (!builtins.hasattr(a, '_fields')) {
  7379. return t;
  7380. }
  7381. throw new python.Error('Not implemented.');
  7382. // return type(a)(*t);
  7383. } else if (Array.isArray(a)) {
  7384. return a.map((elem) => map_aggregate(elem, fn));
  7385. } else if (a instanceof builtins.dict) {
  7386. const rv = new builtins.dict();
  7387. for (const [k, v] of a) {
  7388. rv.__setitem__(k, map_aggregate(v, fn));
  7389. }
  7390. return rv;
  7391. } else if (a instanceof builtins.slice) {
  7392. throw new python.Error('Not implemented.');
  7393. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  7394. }
  7395. return fn(a);
  7396. };
  7397. for (const old_use of this._input_nodes.keys()) {
  7398. old_use.users.pop(this);
  7399. }
  7400. // object.__setattr__(self, "_input_nodes", {})
  7401. this._input_nodes = new builtins.dict();
  7402. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  7403. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  7404. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  7405. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  7406. }
  7407. });
  7408. torch.fx.Node = torch.fx.node.Node;
  7409. torch.fx.graph.Node = torch.fx.node.Node;
  7410. this.registerType('torch.fx.graph.Graph', class {
  7411. constructor(owning_module, tracer_cls, tracer_extras) {
  7412. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  7413. this._used_names = new Map();
  7414. this._len = 0;
  7415. this._graph_namespace = new torch.fx.graph._Namespace();
  7416. this._owning_module = owning_module;
  7417. this._tracer_cls = tracer_cls;
  7418. this._tracer_extras = tracer_extras;
  7419. // this._codegen = CodeGen()
  7420. // this._co_fields = {}
  7421. }
  7422. get nodes() {
  7423. const array = new Array(this._len);
  7424. let node = this._root.next;
  7425. for (let i = 0; node !== this._root; i++) {
  7426. array[i] = node;
  7427. node = node.next;
  7428. }
  7429. return array;
  7430. }
  7431. placeholder(name, type_expr /*, default_value */) {
  7432. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  7433. const kwargs = new builtins.dict();
  7434. return this.create_node('placeholder', name, args, kwargs, type_expr);
  7435. }
  7436. create_node(op, target, args, kwargs, name, type_expr) {
  7437. args = args || new builtins.tuple();
  7438. kwargs = kwargs || new builtins.dict();
  7439. const candidate = name || this._target_to_str(target);
  7440. name = this._graph_namespace.create_name(candidate, null);
  7441. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  7442. this._graph_namespace.associate_name_with_obj(name, n);
  7443. this._insert(n);
  7444. this._len += 1;
  7445. return n;
  7446. }
  7447. _insert(n) {
  7448. this._root.prepend(n);
  7449. }
  7450. output(result, type_expr) {
  7451. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  7452. }
  7453. _target_to_str(target) {
  7454. if (typeof target === 'string') {
  7455. if (target.startsWith('__') && target.endswith('__')) {
  7456. target = target.substring(2, target.length - 2);
  7457. }
  7458. } else {
  7459. target = target.__name__;
  7460. }
  7461. return this._snake_case(target);
  7462. }
  7463. _snake_case(s) {
  7464. const chars = [];
  7465. let prev_lower = false;
  7466. for (const c of s) {
  7467. const x = c.toLowerCase();
  7468. if (prev_lower && x !== c) {
  7469. chars.push('_');
  7470. } else {
  7471. prev_lower = true;
  7472. }
  7473. chars.push(x);
  7474. }
  7475. return chars.join('');
  7476. }
  7477. });
  7478. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  7479. constructor(body) {
  7480. super();
  7481. for (const [k, v] of body.items()) {
  7482. builtins.setattr(this, k, v);
  7483. }
  7484. }
  7485. });
  7486. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  7487. constructor(root, graph, class_name) {
  7488. super();
  7489. this.__class__.__name__ = class_name || 'GraphModule';
  7490. this.graph = graph;
  7491. }
  7492. });
  7493. torch.fx.Graph = torch.fx.graph.Graph;
  7494. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  7495. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  7496. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  7497. return fn_or_name;
  7498. });
  7499. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  7500. this.registerFunction('torchvision.datasets.folder.default_loader');
  7501. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  7502. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  7503. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  7504. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  7505. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  7506. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  7507. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  7508. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  7509. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  7510. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  7511. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  7512. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  7513. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  7514. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  7515. this.registerType('torchvision.ops.misc.Permute', class {});
  7516. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  7517. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  7518. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  7519. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  7520. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  7521. this.registerType('torchvision.models._api.Weights', class {});
  7522. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  7523. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  7524. this.registerType('torchvision.models.convnext.CNBlock', class {});
  7525. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  7526. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  7527. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  7528. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  7529. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  7530. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  7531. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  7532. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  7533. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  7534. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  7535. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  7536. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  7537. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  7538. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  7539. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  7540. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  7541. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  7542. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  7543. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  7544. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  7545. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  7546. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  7547. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  7548. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  7549. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  7550. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  7551. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  7552. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  7553. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  7554. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  7555. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  7556. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  7557. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  7558. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  7559. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  7560. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  7561. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  7562. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  7563. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  7564. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  7565. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  7566. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  7567. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  7568. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  7569. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  7570. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  7571. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  7572. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  7573. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  7574. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  7575. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  7576. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  7577. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  7578. this.registerType('torchvision.models.googlenet.Inception', class {});
  7579. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  7580. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  7581. this.registerType('torchvision.models.inception.Inception3', class {});
  7582. this.registerType('torchvision.models.inception.InceptionAux', class {});
  7583. this.registerType('torchvision.models.inception.InceptionA', class {});
  7584. this.registerType('torchvision.models.inception.InceptionB', class {});
  7585. this.registerType('torchvision.models.inception.InceptionC', class {});
  7586. this.registerType('torchvision.models.inception.InceptionD', class {});
  7587. this.registerType('torchvision.models.inception.InceptionE', class {});
  7588. this.registerFunction('torchvision.models.inception.inception_v3');
  7589. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  7590. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  7591. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  7592. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  7593. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  7594. this.registerType('torchvision.models.maxvit.MBConv', class {});
  7595. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  7596. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  7597. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  7598. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  7599. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  7600. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  7601. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  7602. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  7603. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  7604. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  7605. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  7606. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  7607. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  7608. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  7609. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  7610. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  7611. this.registerType('torchvision.models.regnet.RegNet', class {});
  7612. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  7613. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  7614. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  7615. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  7616. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  7617. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  7618. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  7619. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  7620. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  7621. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  7622. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  7623. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  7624. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  7625. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  7626. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  7627. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  7628. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  7629. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  7630. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  7631. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  7632. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  7633. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  7634. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  7635. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  7636. this.registerType('torchvision.models.squeezenet.Fire', class {});
  7637. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  7638. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  7639. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  7640. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  7641. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  7642. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  7643. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  7644. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  7645. this.registerType('torchvision.models.resnet.ResNet', class {});
  7646. this.registerType('torchvision.models.vgg.VGG', class {});
  7647. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  7648. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  7649. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  7650. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  7651. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  7652. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  7653. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  7654. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  7655. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  7656. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  7657. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  7658. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  7659. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  7660. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  7661. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  7662. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  7663. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  7664. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  7665. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  7666. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  7667. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  7668. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  7669. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  7670. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  7671. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  7672. this.registerType('torchvision.transforms.transforms.Compose', class {});
  7673. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  7674. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  7675. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  7676. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  7677. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  7678. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  7679. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  7680. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  7681. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  7682. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  7683. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  7684. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  7685. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  7686. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  7687. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  7688. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  7689. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  7690. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  7691. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  7692. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  7693. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  7694. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  7695. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  7696. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  7697. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  7698. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  7699. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  7700. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  7701. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  7702. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  7703. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  7704. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  7705. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  7706. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  7707. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  7708. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  7709. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  7710. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  7711. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  7712. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  7713. this.registerFunction('torchvision.ops.boxes.box_iou');
  7714. this.registerFunction('builtins.annotate', (type, value) => {
  7715. if (type === builtins.int) {
  7716. return Number.isInteger(value) ? value : NaN;
  7717. }
  7718. if (type === builtins.float) {
  7719. return typeof value === 'number' ? value : NaN;
  7720. }
  7721. if (type === builtins.number) {
  7722. // if (pytorch.Utility.isTensor(value)) {
  7723. // value.resize_([]);
  7724. // }
  7725. }
  7726. return value;
  7727. });
  7728. this.registerFunction('builtins.uninitialized', (/* type */) => {
  7729. return undefined;
  7730. });
  7731. this.registerFunction('ops.prim.unchecked_cast', (type, value) => {
  7732. return value;
  7733. });
  7734. this.registerFunction('ops.prim.data', (tensor) => {
  7735. return tensor;
  7736. });
  7737. this.registerFunction('ops.prim.device', (tensor) => {
  7738. return tensor.device;
  7739. });
  7740. this.registerFunction('ops.prim.dtype', (tensor) => {
  7741. return tensor.dtype.scalar_type();
  7742. });
  7743. this.registerFunction('ops.prim.is_quantized', (tensor) => {
  7744. return tensor.is_quantized;
  7745. });
  7746. this.registerFunction('ops.prim.is_cuda', (/* tensor */) => {
  7747. return false;
  7748. });
  7749. this.registerFunction('ops.prim.is_nested', (tensor) => {
  7750. return tensor.is_nested;
  7751. });
  7752. this.registerFunction('ops.prim.is_sparse', (tensor) => {
  7753. return tensor.is_sparse;
  7754. });
  7755. this.registerFunction('ops.prim.unchecked_unwrap_optional', (value) => {
  7756. return value;
  7757. });
  7758. this.registerFunction('ops.prim.NumToTensor', (value) => {
  7759. const tensor = self.invoke('torch.Tensor', []);
  7760. tensor.value = value;
  7761. return tensor;
  7762. });
  7763. this.registerFunction('ops.prim.min', (...args) => {
  7764. if (Array.isArray(args[0])) {
  7765. return Math.min.apply(null, args[0]);
  7766. }
  7767. return Math.min.apply(null, args);
  7768. });
  7769. this.registerFunction('ops.prim.max', (...args) => {
  7770. if (Array.isArray(args[0])) {
  7771. return Math.max.apply(null, args[0]);
  7772. }
  7773. return Math.max.apply(null, args);
  7774. });
  7775. this.registerFunction('ops.prim.shape', (tensor) => {
  7776. return tensor && tensor.size ? tensor.size() : undefined;
  7777. });
  7778. this.registerFunction('ops.quantized.conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7779. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7780. params.weight = weight;
  7781. params.bias = bias;
  7782. params.stride = stride;
  7783. params.padding = padding;
  7784. params.dilation = dilation;
  7785. params.groups = groups;
  7786. return params;
  7787. });
  7788. this.registerFunction('ops.quantized.conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7789. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7790. params.weight = weight;
  7791. params.bias = bias;
  7792. params.stride = stride;
  7793. params.padding = padding;
  7794. params.dilation = dilation;
  7795. params.groups = groups;
  7796. return params;
  7797. });
  7798. this.registerFunction('ops.quantized.conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7799. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7800. params.weight = weight;
  7801. params.bias = bias;
  7802. params.stride = stride;
  7803. params.padding = padding;
  7804. params.dilation = dilation;
  7805. params.groups = groups;
  7806. return params;
  7807. });
  7808. this.registerFunction('ops.quantized.conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7809. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  7810. params.weight = weight;
  7811. params.bias = bias;
  7812. params.stride = stride;
  7813. params.padding = padding;
  7814. params.dilation = dilation;
  7815. params.groups = groups;
  7816. return params;
  7817. });
  7818. this.registerFunction('ops.quantized.conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  7819. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7820. params.weight = weight;
  7821. params.bias = bias;
  7822. params.stride = stride;
  7823. params.padding = padding;
  7824. params.output_padding = output_padding;
  7825. params.dilation = dilation;
  7826. params.groups = groups;
  7827. return params;
  7828. });
  7829. this.registerFunction('ops.quantized.conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  7830. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7831. params.weight = weight;
  7832. params.bias = bias;
  7833. params.stride = stride;
  7834. params.padding = padding;
  7835. params.output_padding = output_padding;
  7836. params.dilation = dilation;
  7837. params.groups = groups;
  7838. return params;
  7839. });
  7840. this.registerFunction('ops.quantized.linear_prepack', (weight, bias) => {
  7841. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  7842. params.weight = weight;
  7843. params.bias = bias;
  7844. return params;
  7845. });
  7846. this.registerFunction('ops.prim.RaiseException', (message) => {
  7847. throw new python.Error(message);
  7848. });
  7849. this.registerFunction('builtins.range', (start, stop, step) => {
  7850. if (stop === undefined && step === undefined) {
  7851. if (Number.isInteger(start)) {
  7852. return Array(start).keys();
  7853. }
  7854. if (isNaN(start)) {
  7855. return [];
  7856. }
  7857. }
  7858. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  7859. });
  7860. builtins.xrange = builtins.range;
  7861. this.registerFunction('torch._C._nn.gelu');
  7862. this.registerFunction('torch._C._nn.avg_pool2d');
  7863. this.registerFunction('torch._C._nn.avg_pool3d');
  7864. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  7865. this.registerFunction('torch._C._nn.softplus');
  7866. this.registerFunction('torch._native_multi_head_attention');
  7867. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  7868. if (layout === torch.sparse_coo) {
  7869. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  7870. }
  7871. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  7872. });
  7873. this.registerFunction('torch._utils._rebuild_wrapper_subclass');
  7874. this.registerFunction('torch.from_numpy', (obj) => {
  7875. const dtypes = new Map([
  7876. ['<f2', torch.float16],
  7877. ['<f4', torch.float32],
  7878. ['<f8', torch.float64],
  7879. ['<i2', torch.int16],
  7880. ['<i4', torch.int32],
  7881. ['<i8', torch.int64],
  7882. ]);
  7883. if (!dtypes.has(obj.dtype.str)) {
  7884. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  7885. }
  7886. const dtype = dtypes.get(obj.dtype.str);
  7887. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  7888. const storage = execution.invoke('torch.storage.TypedStorage', [obj.size, dtype]);
  7889. storage._set_cdata(obj.data);
  7890. const tensor = execution.invoke('torch.Tensor', []);
  7891. tensor.__setstate__([storage, 0, obj.shape, strides]);
  7892. return tensor;
  7893. });
  7894. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  7895. const tensor = execution.invoke('torch.from_numpy', [data]);
  7896. // tensor = tensor.to(dtype, device)
  7897. tensor.requires_grad = requires_grad;
  7898. return tensor;
  7899. });
  7900. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  7901. const tensor = self.invoke('torch.Tensor', []);
  7902. tensor._layout = torch.sparse_coo;
  7903. tensor._indices = indices;
  7904. tensor._values = values;
  7905. tensor._shape = size;
  7906. return tensor;
  7907. });
  7908. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  7909. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  7910. });
  7911. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  7912. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  7913. const [, storage_type, , ,size] = storage;
  7914. storage = new storage_type(size);
  7915. }
  7916. const name = `${storage.__class__.__module__}.${storage.__class__.__name__.replace('Storage', 'Tensor')}`;
  7917. const tensor = self.invoke(name, []);
  7918. tensor.__setstate__([storage, storage_offset, size, stride]);
  7919. return tensor;
  7920. });
  7921. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks) => {
  7922. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, storage_offset, size, stride]);
  7923. tensor.requires_grad = requires_grad;
  7924. tensor.backward_hooks = backward_hooks;
  7925. return tensor;
  7926. });
  7927. this.registerFunction('torch._utils._rebuild_tensor_v3');
  7928. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  7929. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  7930. param.backward_hooks = backward_hooks;
  7931. return param;
  7932. });
  7933. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  7934. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  7935. param.backward_hooks = backward_hooks;
  7936. torch._utils._set_obj_state(param, state);
  7937. return param;
  7938. });
  7939. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  7940. const _set_obj_state = (obj, state) => {
  7941. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  7942. if (dict_state) {
  7943. for (const [k, v] of Object.entries(dict_state)) {
  7944. builtins.setattr(obj, k, v);
  7945. }
  7946. }
  7947. if (slots_state) {
  7948. for (const [k, v] of Object.entries(slots_state)) {
  7949. builtins.setattr(obj, k, v);
  7950. }
  7951. }
  7952. };
  7953. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  7954. param._backward_hooks = backward_hooks;
  7955. _set_obj_state(param, state);
  7956. return param;
  7957. });
  7958. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  7959. const tensor = execution.invoke('torch._utils._rebuild_tensor_v2', [storage, storage_offset, size, stride, requires_grad, backward_hooks]);
  7960. tensor.quantizer_params = quantizer_params;
  7961. return tensor;
  7962. });
  7963. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  7964. let dict_state = state;
  7965. let slots_state = null;
  7966. if (state instanceof self.builtins.tuple) {
  7967. if (state.length !== 2) {
  7968. throw new python.Error(`Invalid serialized state: '${state}'.`);
  7969. }
  7970. [dict_state, slots_state] = state;
  7971. }
  7972. if (dict_state) {
  7973. for (const [name, value] of Object.entries(dict_state)) {
  7974. builtins.setattr(obj, name, value);
  7975. }
  7976. }
  7977. if (slots_state) {
  7978. for (const [name, value] of Object.entries(slots_state)) {
  7979. builtins.setattr(obj, name, value);
  7980. }
  7981. }
  7982. return obj;
  7983. });
  7984. this.registerFunction('torch._set_item', (dict, key, value) => {
  7985. dict[key] = value;
  7986. });
  7987. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  7988. let ret = func(...args);
  7989. if (ret.__class__ !== new_type) {
  7990. // ret = ret.as_subclass(new_type);
  7991. }
  7992. const setstate = execution.invoke('builtins.getattr', [ret.__class__, '__setstate__', torch.Tensor.__setstate__]);
  7993. if (setstate === torch.Tensor.__setstate__) {
  7994. ret = execution.invoke('torch._utils._set_obj_state', [ret, state]);
  7995. } else {
  7996. ret.__setstate__(state);
  7997. }
  7998. return ret;
  7999. });
  8000. this.registerFunction('ops.aten.is_scripting', () => {
  8001. return true;
  8002. });
  8003. this.registerFunction('ops.aten.__and__', (left, right) => {
  8004. return left && right;
  8005. });
  8006. this.registerFunction('ops.aten.__contains__', (dict, key) => {
  8007. return builtins.hasattr(dict, key);
  8008. });
  8009. this.registerFunction('torch.__derive_index', (index, start, step) => {
  8010. return start + index * step;
  8011. });
  8012. this.registerFunction('ops.aten.__is__', (left, right) => {
  8013. return left === right;
  8014. });
  8015. this.registerFunction('ops.aten.__isnot__', (left, right) => {
  8016. return left !== right;
  8017. });
  8018. this.registerFunction('ops.aten.__not__', (value) => {
  8019. if (Number.isInteger(value)) {
  8020. value = Boolean(value);
  8021. }
  8022. if (typeof value === 'boolean') {
  8023. return !value;
  8024. }
  8025. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  8026. });
  8027. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  8028. if (step === 0) {
  8029. throw new python.Error('range() arg 3 must not be zero');
  8030. }
  8031. if (step > 0 && lo < hi) {
  8032. return 1 + (hi - 1 - lo) / step;
  8033. } else if (step < 0 && lo > hi) {
  8034. return 1 + (lo - 1 - hi) / (0 - step);
  8035. }
  8036. return 0;
  8037. });
  8038. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  8039. this.registerFunction('ops.aten._unwrap_optional', (value) => {
  8040. return value;
  8041. });
  8042. this.registerFunction('torch.get_default_dtype', () => {
  8043. torch._default_type = torch._default_type || torch.float32;
  8044. return torch._default_type;
  8045. });
  8046. this.registerFunction('torch.set_default_dtype', (value) => {
  8047. torch._default_type = value;
  8048. });
  8049. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  8050. return value || torch.get_default_dtype();
  8051. });
  8052. this.registerFunction('torch.empty_strided', (size, stride, dtype /*, layout, device, pin_memory, requires_grad */) => {
  8053. const shape = size;
  8054. dtype = torch._prims_common.dtype_or_default(dtype);
  8055. size = shape.reduce((a, b) => a * b, 1);
  8056. const storage = execution.invoke('torch.storage.TypedStorage', [size, dtype]);
  8057. const tensor = execution.invoke('torch.Tensor', []);
  8058. tensor.__setstate__([storage, 0, shape, stride]);
  8059. return tensor;
  8060. });
  8061. this.registerFunction('ops.aten.add', (left, right) => {
  8062. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8063. return left + right;
  8064. }
  8065. if (Array.isArray(left) && Array.isArray(right)) {
  8066. return left.concat(right);
  8067. }
  8068. if (typeof left === 'string' && typeof right === 'string') {
  8069. return left + right;
  8070. }
  8071. throw new python.Error('Unsupported ops.aten.add expression type.');
  8072. });
  8073. this.registerFunction('torch.all', (input) => {
  8074. if (Array.isArray(input) && input.length === 0) {
  8075. return true;
  8076. }
  8077. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  8078. });
  8079. this.registerFunction('torch.append', (list, value) => {
  8080. list.push(value);
  8081. return value;
  8082. });
  8083. this.registerFunction('torch.clear', (value) => {
  8084. if (value instanceof torch.Value) {
  8085. throw new python.Error('Invalid value.');
  8086. }
  8087. if (Object(value) === value) {
  8088. for (const key of Object.keys(value)) {
  8089. delete value[key];
  8090. }
  8091. }
  8092. });
  8093. this.registerFunction('ops.aten..cosine_similarity');
  8094. this.registerFunction('ops.aten..extend', (list, value) => {
  8095. list.push(...value);
  8096. });
  8097. this.registerFunction('ops.aten..insert', (list, index, value) => {
  8098. list.splice(index, 0, value);
  8099. return value;
  8100. });
  8101. this.registerFunction('ops.aten..replace', (value, oldvalue, newvalue /*, max */) => {
  8102. return value.replace(oldvalue, newvalue);
  8103. });
  8104. this.registerFunction('torch.dict', (args) => {
  8105. const obj = {};
  8106. if (args) {
  8107. if (Array.isArray(args)) {
  8108. for (const [key, value] of args) {
  8109. obj[key] = value;
  8110. }
  8111. } else {
  8112. throw new python.Error("'torch.dict' arguments not supported.");
  8113. }
  8114. }
  8115. return obj;
  8116. });
  8117. this.registerFunction('ops.aten..dim', (tensor) => {
  8118. if (tensor && tensor.size) {
  8119. const size = tensor.size();
  8120. if (size) {
  8121. return size.length;
  8122. }
  8123. }
  8124. return NaN;
  8125. });
  8126. this.registerFunction('ops.aten..numel', (tensor) => {
  8127. if (tensor && tensor.size) {
  8128. const size = tensor.size();
  8129. if (size) {
  8130. return size.reduce((a, b) => a * b, 1);
  8131. }
  8132. }
  8133. return NaN;
  8134. });
  8135. this.registerFunction('ops.aten.eq', (left, right) => {
  8136. if (typeof left === 'string' && typeof right === 'string') {
  8137. return left === right;
  8138. }
  8139. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8140. if (isNaN(left) && isNaN(right)) {
  8141. return true;
  8142. }
  8143. return left === right;
  8144. }
  8145. if (left === undefined || right === undefined) {
  8146. return true;
  8147. }
  8148. if (Array.isArray(left) && Array.isArray(right)) {
  8149. return left.length === right.length && left.every((item, index) => item === right[index]);
  8150. }
  8151. throw new python.Error("Unsupported 'torch.eq' expression type.");
  8152. });
  8153. this.registerFunction('ops.aten.floor', (value) => {
  8154. return Math.floor(value);
  8155. });
  8156. this.registerFunction('ops.aten.ceil', (value) => {
  8157. return Math.ceil(value);
  8158. });
  8159. this.registerFunction('ops.aten.floordiv', (left, right) => {
  8160. return Math.floor(left / right);
  8161. });
  8162. this.registerFunction('ops.aten..format', (...args) => {
  8163. const list = args.shift().split(/({}D?)/);
  8164. return list.map((text) => {
  8165. if (text === '{}' || text === '{}D') {
  8166. const arg = args.shift();
  8167. if (Array.isArray(arg)) {
  8168. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  8169. }
  8170. return arg ? arg.toString() : '?';
  8171. }
  8172. return text;
  8173. }).join('');
  8174. });
  8175. this.registerFunction('ops.aten.strip', (self, chars) => {
  8176. chars = chars || '\\n\\t\\f\\v';
  8177. const regex = new RegExp(`[${chars}]`, 'g');
  8178. return self.replace(regex, '');
  8179. });
  8180. this.registerFunction('ops.aten.gt', (left, right) => {
  8181. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8182. if (!isNaN(left) && !isNaN(right)) {
  8183. return left > right;
  8184. }
  8185. }
  8186. if (isNaN(left) && !isNaN(right)) {
  8187. return true;
  8188. }
  8189. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  8190. });
  8191. this.registerFunction('ops.aten.ge', (left, right) => {
  8192. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8193. if (!isNaN(left) && !isNaN(right)) {
  8194. return left > right;
  8195. }
  8196. }
  8197. if (isNaN(left) && !isNaN(right)) {
  8198. return true;
  8199. }
  8200. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  8201. });
  8202. this.registerFunction('ops.aten.is_floating_point', (tensor) => {
  8203. const type = tensor.dtype.scalar_type();
  8204. return (type === 5 || type === 6 || type === 7);
  8205. });
  8206. this.registerFunction('ops.aten.is_grad_enabled', () => {
  8207. return false;
  8208. });
  8209. this.registerFunction('ops.aten.is_autocast_enabled', () => {
  8210. return false;
  8211. });
  8212. this.registerFunction('ops.aten.isfinite');
  8213. this.registerFunction('ops.aten.set_grad_enabled', (/* value */) => {
  8214. });
  8215. this.registerFunction('torch.serialization._get_layout', (name) => {
  8216. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  8217. return value instanceof torch.layout ? value : null;
  8218. });
  8219. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  8220. return torch.load(b);
  8221. });
  8222. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  8223. return data;
  8224. });
  8225. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  8226. return data;
  8227. });
  8228. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  8229. return data;
  8230. });
  8231. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  8232. return data;
  8233. });
  8234. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  8235. return self.builtins.CONSTANTS[`c${data}`];
  8236. });
  8237. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  8238. return value;
  8239. });
  8240. this.registerFunction('ops.aten..keys', (dict) => {
  8241. return Object.keys(dict);
  8242. });
  8243. this.registerFunction('ops.aten..len', (value) => {
  8244. if (Array.isArray(value)) {
  8245. return value.length;
  8246. }
  8247. if (value && value.shape && value.__len__) {
  8248. return value.__len__();
  8249. }
  8250. return NaN;
  8251. });
  8252. this.registerFunction('ops.aten..le', (left, right) => {
  8253. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8254. if (isNaN(left) || isNaN(right)) {
  8255. return false;
  8256. }
  8257. return left <= right;
  8258. }
  8259. if (left === undefined || right === undefined) {
  8260. return true;
  8261. }
  8262. throw new python.Error("Unsupported 'torch.le' expression type.");
  8263. });
  8264. this.registerFunction('ops.aten..list', (args) => {
  8265. return args;
  8266. });
  8267. this.registerFunction('ops.aten..list_with_default', (size /*, defaults */) => {
  8268. return size;
  8269. });
  8270. this.registerType('torch.PyTorchFileReader', class {
  8271. constructor(entries) {
  8272. let prefix = 0;
  8273. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  8274. for (let set = new Set(); set && paths.length > 0;) {
  8275. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  8276. set = set.size > 1 || set.keys().next().value === null ? null : set;
  8277. prefix += set ? set.keys().next().value.length + 1 : 0;
  8278. }
  8279. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  8280. this._version = 0;
  8281. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  8282. if (stream) {
  8283. const decoder = new TextDecoder('utf-8');
  8284. const buffer = stream.peek();
  8285. const text = decoder.decode(buffer);
  8286. this._version = Number(text.split('\n').shift().trim());
  8287. }
  8288. }
  8289. has_record(name) {
  8290. return this._records.has(name);
  8291. }
  8292. get_record(name) {
  8293. return this._records.get(name);
  8294. }
  8295. get_all_records() {
  8296. return Array.from(this._records.keys());
  8297. }
  8298. version() {
  8299. return this._version;
  8300. }
  8301. });
  8302. this.registerFunction('torch.load', (f) => {
  8303. const legacy_load = (entries) => {
  8304. const deserialized_objects = {};
  8305. if (entries.has('storages')) {
  8306. const data = entries.get('storages');
  8307. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  8308. const num_storages = unpickler.load();
  8309. for (let i = 0; i < num_storages; i++) {
  8310. const args = unpickler.load();
  8311. const [key, , storage_type] = args;
  8312. const obj = storage_type._new_with_file(unpickler);
  8313. deserialized_objects[key] = obj;
  8314. }
  8315. /*
  8316. let storage_views = unpickler.load();
  8317. for target_cdata, root_cdata, offset, size in storage_views:
  8318. root = deserialized_objects[root_cdata]
  8319. deserialized_objects[target_cdata] = root[offset:offset + size]
  8320. */
  8321. }
  8322. if (entries.has('tensors')) {
  8323. const data = entries.get('tensors');
  8324. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  8325. const num_tensors = unpickler.load();
  8326. const int32 = (unpickler) => {
  8327. const buffer = unpickler.read(4);
  8328. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  8329. };
  8330. const int64 = (unpickler) => {
  8331. const buffer = unpickler.read(8);
  8332. if (buffer[6] !== 0 && buffer[7] !== 0) {
  8333. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  8334. }
  8335. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  8336. };
  8337. for (let i = 0; i < num_tensors; i++) {
  8338. const args = unpickler.load();
  8339. const [key, storage_id] = args;
  8340. const storage = deserialized_objects[storage_id];
  8341. const ndim = int32(unpickler);
  8342. unpickler.read(4);
  8343. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  8344. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  8345. const storage_offset = int64(unpickler);
  8346. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, storage_offset, shape, stride]);
  8347. deserialized_objects[key] = tensor;
  8348. }
  8349. }
  8350. const data = entries.get('pickle');
  8351. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  8352. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  8353. return unpickler.load();
  8354. };
  8355. const _legacy_load = () => {
  8356. const unpickler = execution.invoke('pickle.Unpickler', [f]);
  8357. unpickler.load(); // magic_number
  8358. const protocol_version = unpickler.load();
  8359. if (protocol_version !== 1001) {
  8360. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  8361. }
  8362. const sys_info = unpickler.load();
  8363. if (sys_info.get('protocol_version') !== 1001) {
  8364. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  8365. }
  8366. if (sys_info.get('little_endian') === false) {
  8367. throw new python.Error("Unsupported big-endian storage data.");
  8368. }
  8369. const module_source_map = new Map();
  8370. const deserialized_objects = new Map();
  8371. unpickler.persistent_load = (saved_id) => {
  8372. switch (saved_id[0]) {
  8373. case 'module': {
  8374. const [, module, ,source] = saved_id;
  8375. module_source_map.set(module, source);
  8376. return saved_id[1];
  8377. }
  8378. case 'storage': {
  8379. const [, storage_type, key, , size, view_metadata] = saved_id;
  8380. if (!deserialized_objects.has(key)) {
  8381. const obj = new storage_type(size);
  8382. deserialized_objects.set(key, obj);
  8383. }
  8384. if (view_metadata) {
  8385. const view_key = view_metadata.shift();
  8386. view_metadata.shift(); // view_offset
  8387. view_metadata.shift(); // view_size
  8388. if (!deserialized_objects.has(view_key)) {
  8389. const view = null; // storage.slice(view_offset, view_offset + view_size);
  8390. deserialized_objects.set(view_key, view);
  8391. }
  8392. return deserialized_objects.get(view_key);
  8393. }
  8394. return deserialized_objects.get(key);
  8395. }
  8396. default: {
  8397. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  8398. }
  8399. }
  8400. };
  8401. const obj = unpickler.load();
  8402. const deserialized_storage_keys = unpickler.load();
  8403. for (const deserialized_storage_key of deserialized_storage_keys) {
  8404. const storage = deserialized_objects.get(deserialized_storage_key);
  8405. storage._set_from_file(unpickler);
  8406. }
  8407. if (!obj) {
  8408. throw new python.Error('File format is not PyTorch.');
  8409. }
  8410. if (obj === 'None') {
  8411. throw new python.Error("File contains 'None' root object.");
  8412. }
  8413. return obj;
  8414. };
  8415. const _load = (entries) => {
  8416. if (f.has('constant.pkl')) {
  8417. throw python.Error("TorchScript 'torch.load' not supported.");
  8418. }
  8419. const loaded_storages = new Map();
  8420. const persistent_load = (saved_id) => {
  8421. switch (saved_id[0]) {
  8422. case 'storage': {
  8423. const [, storage_type, key, , numel] = saved_id;
  8424. if (!loaded_storages.has(key)) {
  8425. const storage = new storage_type(numel);
  8426. const name = `data/${key}`;
  8427. const stream = entries.get(name);
  8428. storage._set_cdata(stream);
  8429. loaded_storages.set(key, storage);
  8430. }
  8431. return loaded_storages.get(key);
  8432. }
  8433. default: {
  8434. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  8435. }
  8436. }
  8437. };
  8438. const data_file = entries.get('data.pkl');
  8439. const unpickler = execution.invoke('pickle.Unpickler', [data_file]);
  8440. unpickler.persistent_load = persistent_load;
  8441. const result = unpickler.load();
  8442. return result;
  8443. };
  8444. if (f instanceof Map) {
  8445. const reader = new torch.PyTorchFileReader(f);
  8446. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  8447. f = new Map(records);
  8448. if (f.has('pickle')) {
  8449. return legacy_load(f);
  8450. }
  8451. if (f.has('data.pkl')) {
  8452. return _load(f);
  8453. }
  8454. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  8455. }
  8456. return _legacy_load(f);
  8457. });
  8458. this.registerFunction('ops.aten.log10', (value) => {
  8459. return Math.log10(value);
  8460. });
  8461. this.registerFunction('ops.aten.device', (type, index) => {
  8462. return new torch.device(type, index);
  8463. });
  8464. this.registerFunction('ops.aten.lt', (left, right) => {
  8465. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8466. return left < right;
  8467. }
  8468. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  8469. });
  8470. this.registerFunction('ops.aten.mul', (left, right) => {
  8471. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8472. return left * right;
  8473. }
  8474. if (isNaN(left) || isNaN(right)) {
  8475. return NaN;
  8476. }
  8477. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8478. return left.map((value) => value * right);
  8479. }
  8480. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  8481. });
  8482. this.registerFunction('ops.aten.div', (left, right) => {
  8483. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8484. return left / right;
  8485. }
  8486. if (isNaN(left) || isNaN(right)) {
  8487. return NaN;
  8488. }
  8489. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  8490. });
  8491. this.registerFunction('torch.round', (value) => {
  8492. if (typeof value === 'number' || value instanceof Number) {
  8493. return Math.round(value);
  8494. }
  8495. if (isNaN(value)) {
  8496. return value;
  8497. }
  8498. throw new python.Error("Unsupported 'torch.round' expression type.");
  8499. });
  8500. this.registerFunction('ops.aten.remainder', (left, right) => {
  8501. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8502. return left % right;
  8503. }
  8504. if (isNaN(left) || isNaN(right)) {
  8505. return NaN;
  8506. }
  8507. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  8508. });
  8509. this.registerFunction('ops.aten.ne', (left, right) => {
  8510. if (typeof left === 'boolean' && typeof right === 'boolean') {
  8511. return left !== right;
  8512. }
  8513. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8514. if (isNaN(left) || isNaN(right)) {
  8515. return false;
  8516. }
  8517. return left !== right;
  8518. }
  8519. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  8520. return false;
  8521. }
  8522. if (typeof left === 'string' && typeof right === 'string') {
  8523. return left !== right;
  8524. }
  8525. if (left === undefined || right === undefined) {
  8526. return true;
  8527. }
  8528. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  8529. });
  8530. this.registerFunction('ops.aten.neg', (value) => {
  8531. if (typeof value === 'number') {
  8532. return -value;
  8533. }
  8534. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  8535. });
  8536. this.registerFunction('ops.aten.pow', (left, right) => {
  8537. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8538. return Math.pow(left, right);
  8539. }
  8540. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  8541. });
  8542. this.registerFunction('torch.q_scale', (/* tensor */) => {
  8543. return -1;
  8544. });
  8545. this.registerFunction('torch.t', (tensor) => {
  8546. return tensor;
  8547. });
  8548. this.registerFunction('ops.aten.size', (tensor, dim) => {
  8549. if (tensor && tensor.size) {
  8550. const size = tensor.size();
  8551. if (Array.isArray(size)) {
  8552. if (dim === undefined) {
  8553. return size;
  8554. }
  8555. if (Number.isInteger(dim)) {
  8556. if (dim >= 0 && dim < size.length) {
  8557. return size[dim];
  8558. }
  8559. if (dim < 0 && -dim < size.length) {
  8560. return size[size.length + dim];
  8561. }
  8562. }
  8563. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  8564. }
  8565. }
  8566. if (Number.isInteger(dim)) {
  8567. return NaN;
  8568. }
  8569. return [];
  8570. });
  8571. this.registerFunction('ops.aten.sqrt', (x) => {
  8572. return Math.sqrt(x);
  8573. });
  8574. this.registerFunction('ops.aten.slice', (l, start, end, step) => {
  8575. if (!Array.isArray(l)) {
  8576. throw new python.Error('Slicing expected array');
  8577. }
  8578. step = step || 1;
  8579. if (step !== 1) {
  8580. throw new python.Error('Slicing only supports step=1');
  8581. }
  8582. start = Math.max(0, start >= 0 ? start : l.length + start);
  8583. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  8584. return l.slice(start, end);
  8585. });
  8586. this.registerFunction('ops.aten.sub', (left, right) => {
  8587. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8588. return left - right;
  8589. }
  8590. throw new python.Error("Unsupported 'torch.sub' expression type.");
  8591. });
  8592. this.registerFunction('torch.sym_int');
  8593. this.registerFunction('torch.sym_ite');
  8594. this.registerFunction('torch.sym_max');
  8595. this.registerFunction('torch.sym_min');
  8596. this.registerFunction('torch.sym_not');
  8597. this.registerFunction('torch.sym_sqrt');
  8598. this.registerFunction('torch.sym_sqrt');
  8599. this.registerFunction('torch.functional.einsum');
  8600. this.registerFunction('torch.functional.norm');
  8601. this.registerFunction('torch.functional.split');
  8602. this.registerFunction('torch.nn.init.constant_');
  8603. this.registerFunction('torch.nn.init.normal_');
  8604. this.registerFunction('torch.nn.init.xavier_uniform_');
  8605. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  8606. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  8607. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  8608. this.registerFunction('torch.nn.functional.cross_entropy');
  8609. this.registerFunction('torch.nn.functional.elu');
  8610. this.registerFunction('torch.nn.functional.gelu');
  8611. this.registerFunction('torch.nn.functional.hardsigmoid');
  8612. this.registerFunction('torch.nn.functional.hardswish');
  8613. this.registerFunction('torch.nn.functional.hardtanh');
  8614. this.registerFunction('torch.nn.functional.interpolate');
  8615. this.registerFunction('torch.nn.functional.leaky_relu');
  8616. this.registerFunction('torch.nn.functional.l1_loss');
  8617. this.registerFunction('torch.nn.functional.linear');
  8618. this.registerFunction('torch.nn.functional.log_softmax');
  8619. this.registerFunction('torch.nn.functional._max_pool2d');
  8620. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  8621. this.registerFunction('torch.nn.functional.mse_loss');
  8622. this.registerFunction('torch.nn.functional.pad');
  8623. this.registerFunction('torch.nn.functional.relu');
  8624. this.registerFunction('torch.nn.functional.relu6');
  8625. this.registerFunction('torch.nn.functional.sigmoid');
  8626. this.registerFunction('torch.nn.functional.silu');
  8627. this.registerFunction('torch.nn.functional.softmax');
  8628. this.registerFunction('torch.nn.functional.tanh');
  8629. this.registerFunction('torch.values', (dict) => {
  8630. return Object.values(dict);
  8631. });
  8632. this.registerFunction('torch.warn', () => {
  8633. });
  8634. this.registerType('torch._ops.OperatorBase', class {
  8635. constructor() {
  8636. this.functorch_table = {};
  8637. }
  8638. });
  8639. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  8640. constructor(name, cacheable) {
  8641. super();
  8642. this._name = name;
  8643. this.__name__ = name;
  8644. // _higher_order_ops[name] = this;
  8645. this._ns = 'higher_order';
  8646. this.__module__ = 'torch.ops.higher_order';
  8647. this._cacheable = cacheable;
  8648. }
  8649. });
  8650. this.registerType('torch.Type', class {
  8651. constructor(kind, annotation_str) {
  8652. this._kind = kind;
  8653. if (annotation_str) {
  8654. this._annotation_str = annotation_str;
  8655. }
  8656. }
  8657. static get(kind, annotation_str) {
  8658. return new torch.Type(kind, annotation_str);
  8659. }
  8660. kind() {
  8661. return this._kind;
  8662. }
  8663. get annotation_str() {
  8664. return this._annotation_str;
  8665. }
  8666. equals(rhs) {
  8667. return this.kind() === rhs.kind();
  8668. }
  8669. isSubtypeOf(rhs) {
  8670. if (rhs.kind() === 'AnyType' || this === rhs) {
  8671. return true;
  8672. }
  8673. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  8674. return this.isSubtypeOf(rhs.getElementType());
  8675. }
  8676. if (rhs instanceof torch.UnionType) {
  8677. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  8678. }
  8679. if (rhs instanceof torch._C.DynamicType) {
  8680. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  8681. }
  8682. return this.equals(rhs);
  8683. }
  8684. containedTypes() {
  8685. return [];
  8686. }
  8687. withContained(contained_types) {
  8688. const current_contained = this.containedTypes();
  8689. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  8690. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  8691. return this;
  8692. }
  8693. return this.createWithContained(contained_types);
  8694. }
  8695. createWithContained(/* createWithContained */) {
  8696. throw new python.Error('Not implemented.');
  8697. }
  8698. isUnionType() {
  8699. return false;
  8700. }
  8701. hasFreeVariables() {
  8702. return false;
  8703. }
  8704. is_module() {
  8705. return false;
  8706. }
  8707. expect(type) {
  8708. torch._C.AT_ASSERT(this instanceof type);
  8709. return this;
  8710. }
  8711. str() {
  8712. if (this instanceof torch._C.VarType && this._annotation_str) {
  8713. return this._annotation_str;
  8714. } else if (this._kind === 'ScalarTypeType') {
  8715. return 'ScalarType';
  8716. } else if (this._kind === 'QSchemeType') {
  8717. return 'QScheme';
  8718. } else if (this._kind) {
  8719. return this._kind;
  8720. }
  8721. throw new python.Error(`Not implemented '${this.kind()}'.`);
  8722. }
  8723. __str__() {
  8724. return this.str();
  8725. }
  8726. toString() {
  8727. return this.__str__();
  8728. }
  8729. });
  8730. this.registerType('torch.ClassType', class extends torch.Type {
  8731. constructor(qualified_name, cu, is_module) {
  8732. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  8733. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  8734. this._is_module = is_module;
  8735. this._attributes = [];
  8736. this._attributeTypes = [];
  8737. this._methods = [];
  8738. this._staticmethods = new Map();
  8739. this._forward_hooks = [];
  8740. this._forward_pre_hooks = [];
  8741. this._properties = [];
  8742. this._constants = new Map();
  8743. }
  8744. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  8745. return new torch.ClassType(qualifiedName, cu, is_module);
  8746. }
  8747. qualified_name() {
  8748. return this.annotation_str;
  8749. }
  8750. name() {
  8751. return this._name;
  8752. }
  8753. is_module() {
  8754. return this._is_module;
  8755. }
  8756. is_parameter(slot) {
  8757. return this._attributes[slot].is_parameter === true;
  8758. }
  8759. is_buffer(slot) {
  8760. return this._attributes[slot].is_buffer === true;
  8761. }
  8762. addMethod(method) {
  8763. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  8764. this._methods.push(method);
  8765. }
  8766. findMethod(name) {
  8767. for (const method of this._methods) {
  8768. if (name === method.name()) {
  8769. return method;
  8770. }
  8771. }
  8772. return null;
  8773. }
  8774. getMethod(name) {
  8775. const method = this.findMethod(name);
  8776. if (!method) {
  8777. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  8778. }
  8779. return method;
  8780. }
  8781. methods() {
  8782. return this._methods;
  8783. }
  8784. addStaticMethod(func) {
  8785. this._staticmethods.set(func.name, func);
  8786. }
  8787. findStaticMethod(name) {
  8788. return this._staticmethods.get(name);
  8789. }
  8790. findHook(name) {
  8791. let hook = this.findForwardHook(name);
  8792. if (hook === null) {
  8793. hook = this.findForwardPreHook(name);
  8794. }
  8795. return hook;
  8796. }
  8797. findForwardHook(name) {
  8798. for (const hook of this._forward_hooks) {
  8799. if (name === hook.name()) {
  8800. return hook;
  8801. }
  8802. }
  8803. return null;
  8804. }
  8805. findForwardPreHook(name) {
  8806. for (const pre_hook of this._forward_pre_hooks) {
  8807. if (name === pre_hook.name()) {
  8808. return pre_hook;
  8809. }
  8810. }
  8811. return null;
  8812. }
  8813. numAttributes() {
  8814. return this._attributes.length;
  8815. }
  8816. addAttribute(name, type, is_parameter, is_buffer) {
  8817. is_parameter = is_parameter || false;
  8818. is_buffer = is_buffer || false;
  8819. const slot = this._attributes.length;
  8820. this._attributes.push({ name, type, is_parameter, is_buffer });
  8821. this._attributeTypes.push(type);
  8822. return slot;
  8823. }
  8824. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  8825. is_parameter = is_parameter || false;
  8826. is_buffer = is_buffer || false;
  8827. const slot_idx = this.findAttributeSlot(name);
  8828. if (slot_idx === null) {
  8829. return this.addAttribute(name, ty, is_parameter, is_buffer);
  8830. }
  8831. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  8832. // const TypePtr& atype = getAttribute(*slot_idx);
  8833. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  8834. return slot_idx;
  8835. }
  8836. findAttributeSlot(name) {
  8837. for (let pos = 0; pos < this._attributes.length; pos++) {
  8838. if (name === this._attributes[pos].name) {
  8839. return pos;
  8840. }
  8841. }
  8842. return null;
  8843. }
  8844. findAttribute(name) {
  8845. const slot = this.findAttributeSlot(name);
  8846. if (slot !== null) {
  8847. return this._attributes[slot].type;
  8848. }
  8849. return null;
  8850. }
  8851. hasAttribute(name) {
  8852. return this._attributes.find((attr) => attr.name === name);
  8853. }
  8854. getAttribute(arg) {
  8855. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  8856. return this._attributes[slot].type;
  8857. }
  8858. getAttributeName(slot) {
  8859. return this._attributes[slot].name;
  8860. }
  8861. addConstant(name, value) {
  8862. this._constants.set(name, value);
  8863. }
  8864. hasConstant(name) {
  8865. return this._constants.has(name);
  8866. }
  8867. getProperty(name) {
  8868. for (const prop of this._properties) {
  8869. if (name === prop.name) {
  8870. return prop;
  8871. }
  8872. }
  8873. return null;
  8874. }
  8875. containedTypes() {
  8876. return this._attributeTypes;
  8877. }
  8878. createWithContained(contained_types) {
  8879. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  8880. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  8881. for (let i = 0; i < this._attributes.length; i++) {
  8882. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  8883. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  8884. }
  8885. for (const method of this.methods()) {
  8886. ptr.addMethod(method);
  8887. }
  8888. return ptr;
  8889. }
  8890. str() {
  8891. return this.qualified_name();
  8892. }
  8893. });
  8894. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  8895. if (args.length === 1) {
  8896. const [to_flatten] = args;
  8897. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  8898. const to_fill = [];
  8899. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  8900. to_flatten.splice(0, to_flatten.length);
  8901. to_flatten.push(...to_fill);
  8902. } else if (args.length === 2) {
  8903. const [reference, to_fill] = args;
  8904. for (const type of reference) {
  8905. torch._C.flattenUnion(type, to_fill);
  8906. }
  8907. torch._C.filterDuplicateSubtypes(to_fill);
  8908. torch._C.sortUnion(to_fill);
  8909. } else {
  8910. throw new python.Error('Not implemented.');
  8911. }
  8912. });
  8913. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  8914. if (type instanceof torch.UnionType) {
  8915. for (const inner of type.containedTypes()) {
  8916. torch._C.flattenUnion(inner, to_fill);
  8917. }
  8918. } else if (type instanceof torch.OptionalType) {
  8919. const inner = type.getElementType();
  8920. torch._C.flattenUnion(inner, to_fill);
  8921. to_fill.push(torch.NoneType.get());
  8922. } else if (type instanceof torch.NumberType) {
  8923. to_fill.push(torch.IntType.get());
  8924. to_fill.push(torch.FloatType.get());
  8925. to_fill.push(torch.ComplexType.get());
  8926. } else {
  8927. to_fill.push(type);
  8928. }
  8929. });
  8930. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  8931. if (types.length === 0) {
  8932. // return;
  8933. }
  8934. /*
  8935. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  8936. // We don't want nested Optionals. Also, prematurely unifying to
  8937. // `Optional` could prevent us from coalescing other types
  8938. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  8939. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  8940. return null;
  8941. } else {
  8942. return unifyTypes(t1, t2, default_to_union=false);
  8943. }
  8944. };
  8945. size_t end_idx = types->size()-1;
  8946. for (size_t i = types->size()-1; i > 0; --i) {
  8947. for (size_t j = std::min(i-1, end_idx); ; --j) {
  8948. std::optional<TypePtr> unified;
  8949. unified = get_supertype((*types)[i], (*types)[j]);
  8950. if (unified) {
  8951. (*types)[j] = *unified;
  8952. (*types)[i] = (*types)[end_idx];
  8953. --end_idx;
  8954. break;
  8955. }
  8956. if (j == 0) {
  8957. break;
  8958. }
  8959. }
  8960. }
  8961. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  8962. */
  8963. });
  8964. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  8965. /*
  8966. std::sort(types->begin(), types->end(),
  8967. [](const TypePtr& a, const TypePtr& b) -> bool {
  8968. if (a->kind() != b->kind()) {
  8969. return a->kind() < b->kind();
  8970. }
  8971. return a->str() < b->str();
  8972. });
  8973. */
  8974. });
  8975. this.registerType('torch.UnionType', class extends torch.Type {
  8976. constructor(reference, kind) {
  8977. super(kind || 'UnionType');
  8978. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  8979. this._types = [];
  8980. torch._C.standardizeVectorForUnion(reference, this._types);
  8981. if (this._types.length === 1) {
  8982. throw new python.Error('Invalid union type reference.');
  8983. }
  8984. this._can_hold_none = false;
  8985. this._has_free_variables = false;
  8986. for (const type of this._types) {
  8987. if (type instanceof torch.NoneType) {
  8988. this._can_hold_none = true;
  8989. }
  8990. if (type.hasFreeVariables()) {
  8991. this._has_free_variables = true;
  8992. }
  8993. }
  8994. }
  8995. static create(reference) {
  8996. const union_type = new torch.UnionType(reference);
  8997. /*
  8998. bool int_found = false;
  8999. bool float_found = false;
  9000. bool complex_found = false;
  9001. bool nonetype_found = false;
  9002. const update_is_opt_flags = [&](const TypePtr& t) {
  9003. if (t == IntType::get()) {
  9004. int_found = true;
  9005. } else if (t == FloatType::get()) {
  9006. float_found = true;
  9007. } else if (t == ComplexType::get()) {
  9008. complex_found = true;
  9009. } else if (t == NoneType::get()) {
  9010. nonetype_found = true;
  9011. }
  9012. };
  9013. for (const auto& t : union_type->containedTypes()) {
  9014. update_is_opt_flags(t);
  9015. }
  9016. bool numbertype_found = int_found && float_found && complex_found;
  9017. if (nonetype_found) {
  9018. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  9019. return OptionalType::create(NumberType::get());
  9020. }
  9021. if (union_type->containedTypes().size() == 2) {
  9022. const not_none = union_type->containedTypes()[0] != NoneType::get()
  9023. ? union_type->containedTypes()[0]
  9024. : union_type->containedTypes()[1];
  9025. return OptionalType::create(not_none);
  9026. }
  9027. }
  9028. */
  9029. return union_type;
  9030. }
  9031. containedTypes() {
  9032. return this._types;
  9033. }
  9034. isUnionType() {
  9035. return true;
  9036. }
  9037. hasFreeVariables() {
  9038. return this._has_free_variables;
  9039. }
  9040. equals(rhs) {
  9041. if (rhs instanceof torch.UnionType) {
  9042. if (rhs.containedTypes().length !== this.containedTypes().length) {
  9043. return false;
  9044. }
  9045. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  9046. } else if (rhs instanceof torch.OptionalType) {
  9047. if (rhs.getElementType() === torch.NumberType.get()) {
  9048. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  9049. }
  9050. const optional_lhs = this.toOptional();
  9051. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  9052. } else if (rhs instanceof torch.NumberType) {
  9053. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  9054. }
  9055. return false;
  9056. }
  9057. isSubtypeOf(rhs) {
  9058. const rhs_types = [];
  9059. if (rhs instanceof torch.UnionType) {
  9060. if (this.containedTypes() === rhs.containedTypes()) {
  9061. return true;
  9062. }
  9063. for (const typePtr of rhs.containedTypes()) {
  9064. rhs_types.push(typePtr);
  9065. }
  9066. } else if (rhs instanceof torch.OptionalType) {
  9067. rhs_types.push(torch.NoneType.get());
  9068. if (rhs.getElementType() === torch.NumberType.get()) {
  9069. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  9070. rhs_types.push(...number_types);
  9071. } else {
  9072. rhs_types.push(rhs.getElementType());
  9073. }
  9074. } else if (rhs instanceof torch.NumberType) {
  9075. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  9076. rhs_types.push(...number_types);
  9077. } else {
  9078. rhs_types.push(rhs);
  9079. }
  9080. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  9081. }
  9082. });
  9083. this.registerType('torch.OptionalType', class extends torch.UnionType {
  9084. constructor(contained) {
  9085. super([contained, torch.NoneType.get()], 'OptionalType');
  9086. let is_numbertype = false;
  9087. if (contained instanceof torch.UnionType) {
  9088. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  9089. }
  9090. if (super.containedTypes().length === 2) {
  9091. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  9092. } else if (contained === torch.NumberType.get() || is_numbertype) {
  9093. this._contained = torch.NumberType.get();
  9094. this._types.splice(0, this._types.length);
  9095. this._types.push(torch.NumberType.get());
  9096. this._types.push(torch.NoneType.get());
  9097. } else {
  9098. const to_subtract = [torch.NoneType.get()];
  9099. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  9100. this._contained = torch.UnionType.create([without_none]);
  9101. }
  9102. this._has_free_variables = contained.hasFreeVariables();
  9103. }
  9104. static create(elem) {
  9105. return new torch.OptionalType(elem);
  9106. }
  9107. getElementType() {
  9108. return this._contained;
  9109. }
  9110. equals(rhs) {
  9111. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  9112. }
  9113. isSubtypeOf(rhs) {
  9114. if (rhs instanceof torch.OptionalType) {
  9115. return this.getElementType().isSubtypeOf(rhs.getElementType());
  9116. } else if (rhs instanceof torch.UnionType) {
  9117. throw new python.Error('Not implemented.');
  9118. }
  9119. // return super.isSubtypeOf(rhs);
  9120. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  9121. }
  9122. containedTypes() {
  9123. return [this._contained];
  9124. }
  9125. createWithContained(contained_types) {
  9126. torch._C.AT_ASSERT(contained_types.length === 1);
  9127. return torch.OptionalType.create(contained_types[0]);
  9128. }
  9129. subtractTypeSetFrom(to_subtract, from) {
  9130. const types = [];
  9131. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  9132. for (const t of from) {
  9133. if (!should_subtract(t)) {
  9134. types.push(t);
  9135. }
  9136. }
  9137. if (types.length === 0) {
  9138. return null;
  9139. } else if (types.length === 1) {
  9140. return types[0];
  9141. }
  9142. return torch.UnionType.create(types);
  9143. }
  9144. str() {
  9145. return `${this.getElementType().str()}?`;
  9146. }
  9147. __str__() {
  9148. return `Optional[${this.getElementType().__str__()}]`;
  9149. }
  9150. });
  9151. this.registerType('torch.ListType', class extends torch.Type {
  9152. constructor(elem) {
  9153. super('ListType');
  9154. this._elem = elem;
  9155. }
  9156. static create(elem) {
  9157. return new torch.ListType(elem);
  9158. }
  9159. getElementType() {
  9160. return this._elem;
  9161. }
  9162. equals(rhs) {
  9163. if (rhs instanceof torch.ListType) {
  9164. return this.getElementType().equals(rhs.getElementType());
  9165. }
  9166. return false;
  9167. }
  9168. isSubtypeOf(rhs) {
  9169. if (super.isSubtypeOf(rhs)) {
  9170. return true;
  9171. }
  9172. if (rhs.kind() === 'AnyListType') {
  9173. return true;
  9174. }
  9175. return false;
  9176. }
  9177. containedTypes() {
  9178. return [this._elem];
  9179. }
  9180. createWithContained(contained_types) {
  9181. return new torch.ListType(contained_types[0]);
  9182. }
  9183. hasFreeVariables() {
  9184. return this.getElementType().hasFreeVariables();
  9185. }
  9186. str() {
  9187. return `${this.getElementType().str()}[]`;
  9188. }
  9189. __str__() {
  9190. return `List[${this.getElementType().__str__()}]`;
  9191. }
  9192. });
  9193. this.registerType('torch.FutureType', class extends torch.Type {
  9194. constructor(elem) {
  9195. super('FutureType');
  9196. this._elem = elem;
  9197. }
  9198. static get(elem) {
  9199. return new torch.FutureType(elem);
  9200. }
  9201. getElementType() {
  9202. return this._elem;
  9203. }
  9204. containedTypes() {
  9205. throw new python.Error('Not implemented.');
  9206. }
  9207. str() {
  9208. return `Future(${this.getElementType().str()})`;
  9209. }
  9210. __str__() {
  9211. return `Future[${this.getElementType().__str__()}]`;
  9212. }
  9213. });
  9214. this.registerType('torch.RRefType', class extends torch.Type {
  9215. constructor(elem) {
  9216. super('RRefType');
  9217. this._elem = elem;
  9218. }
  9219. get(elem) {
  9220. return new torch.RRefType(elem);
  9221. }
  9222. getElementType() {
  9223. return this._elem;
  9224. }
  9225. containedTypes() {
  9226. throw new python.Error('Not implemented.');
  9227. }
  9228. str() {
  9229. return `RRef(${this.getElementType().str()})`;
  9230. }
  9231. __str__() {
  9232. return `RRef[${this.getElementType().__str__()}]`;
  9233. }
  9234. });
  9235. this.registerType('torch.AwaitType', class extends torch.Type {
  9236. constructor(elem) {
  9237. super('AwaitType');
  9238. this._elem = elem;
  9239. }
  9240. static get(elem) {
  9241. return new torch.AwaitType(elem);
  9242. }
  9243. getElementType() {
  9244. return this._elem;
  9245. }
  9246. containedTypes() {
  9247. throw new python.Error('Not implemented.');
  9248. }
  9249. str() {
  9250. return `Await(${this.getElementType().str()})`;
  9251. }
  9252. __str__() {
  9253. return `Await[${this.getElementType().__str__()}]`;
  9254. }
  9255. });
  9256. this.registerType('torch.TupleType', class extends torch.Type {
  9257. constructor(elements, annotation_str, schema) {
  9258. super('TupleType', annotation_str);
  9259. this._elements = elements;
  9260. this._has_free_variables = elements.some((v) => {
  9261. if (!v) {
  9262. throw new python.Error('Can not create tuple with None type');
  9263. }
  9264. return v.hasFreeVariables();
  9265. });
  9266. this._schema = schema;
  9267. }
  9268. static create(elements) {
  9269. return new torch.TupleType(elements, null, null);
  9270. }
  9271. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  9272. const args = [];
  9273. for (let i = 0; i < field_names.length; i++) {
  9274. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  9275. args.push(arg);
  9276. }
  9277. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  9278. return new torch.TupleType(field_types, qualified_name, schema);
  9279. }
  9280. elements() {
  9281. return this._elements;
  9282. }
  9283. name() {
  9284. return this.annotation_str;
  9285. }
  9286. containedTypes() {
  9287. return this._elements;
  9288. }
  9289. createWithContained(createWithContained) {
  9290. return new torch.TupleType(createWithContained, this.name(), this.schema());
  9291. }
  9292. hasFreeVariables() {
  9293. return this._has_free_variables;
  9294. }
  9295. schema() {
  9296. return this._schema;
  9297. }
  9298. str() {
  9299. if (this._schema) {
  9300. return `NamedTuple(...)`;
  9301. }
  9302. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  9303. }
  9304. __str__() {
  9305. if (this.annotation_str) {
  9306. return this.annotation_str;
  9307. }
  9308. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  9309. }
  9310. });
  9311. this.registerType('torch.AnyType', class extends torch.Type {
  9312. constructor() {
  9313. super('AnyType');
  9314. }
  9315. static get() {
  9316. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  9317. return torch.AnyType.value;
  9318. }
  9319. str() {
  9320. return 'Any';
  9321. }
  9322. __str__() {
  9323. return 'Any';
  9324. }
  9325. });
  9326. this.registerType('torch.NoneType', class extends torch.Type {
  9327. constructor() {
  9328. super('NoneType');
  9329. }
  9330. static get() {
  9331. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  9332. return torch.NoneType.value;
  9333. }
  9334. equals(rhs) {
  9335. return this.kind() === rhs.kind();
  9336. }
  9337. isSubtypeOf(rhs) {
  9338. if (rhs.kind() === 'OptionalType') {
  9339. return true;
  9340. }
  9341. return super.isSubtypeOf(rhs);
  9342. }
  9343. str() {
  9344. return 'NoneType';
  9345. }
  9346. __str__() {
  9347. return 'NoneType';
  9348. }
  9349. });
  9350. this.registerType('torch.TensorType', class extends torch.Type {
  9351. constructor() {
  9352. super('TensorType');
  9353. this._is_inferred = false;
  9354. }
  9355. static get() {
  9356. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  9357. return torch.TensorType.value;
  9358. }
  9359. equals(rhs) {
  9360. return this.kind() === rhs.kind();
  9361. }
  9362. isInferredType() {
  9363. return this._is_inferred;
  9364. }
  9365. str() {
  9366. return 'Tensor';
  9367. }
  9368. __str__() {
  9369. return 'Tensor';
  9370. }
  9371. });
  9372. this.registerType('torch.NumberType', class extends torch.Type {
  9373. constructor() {
  9374. super('NumberType');
  9375. }
  9376. static get() {
  9377. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  9378. return torch.NumberType.value;
  9379. }
  9380. str() {
  9381. return 'Scalar';
  9382. }
  9383. __str__() {
  9384. return 'number';
  9385. }
  9386. });
  9387. this.registerType('torch.BoolType', class extends torch.Type {
  9388. constructor() {
  9389. super('BoolType');
  9390. }
  9391. static get() {
  9392. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  9393. return torch.BoolType.value;
  9394. }
  9395. equals(rhs) {
  9396. return this.kind() === rhs.kind();
  9397. }
  9398. str() {
  9399. return 'bool';
  9400. }
  9401. __str__() {
  9402. return 'bool';
  9403. }
  9404. });
  9405. this.registerType('torch.IntType', class extends torch.Type {
  9406. constructor() {
  9407. super('IntType');
  9408. }
  9409. static get() {
  9410. torch.IntType.value = torch.IntType.value || new torch.IntType();
  9411. return torch.IntType.value;
  9412. }
  9413. equals(rhs) {
  9414. return this.kind() === rhs.kind();
  9415. }
  9416. isSubtypeOf(rhs) {
  9417. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  9418. }
  9419. str() {
  9420. return 'int';
  9421. }
  9422. __str__() {
  9423. return 'int';
  9424. }
  9425. });
  9426. this.registerType('torch.SymIntType', class extends torch.Type {
  9427. constructor() {
  9428. super('SymIntType');
  9429. }
  9430. static get() {
  9431. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  9432. return torch.SymIntType.value;
  9433. }
  9434. equals(rhs) {
  9435. return this.kind() === rhs.kind();
  9436. }
  9437. str() {
  9438. return 'SymInt';
  9439. }
  9440. __str__() {
  9441. return 'int';
  9442. }
  9443. });
  9444. this.registerType('torch.FloatType', class extends torch.Type {
  9445. constructor() {
  9446. super('FloatType');
  9447. }
  9448. static get() {
  9449. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  9450. return torch.FloatType.value;
  9451. }
  9452. equals(rhs) {
  9453. return this.kind() === rhs.kind();
  9454. }
  9455. isSubtypeOf(rhs) {
  9456. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  9457. }
  9458. str() {
  9459. return 'float';
  9460. }
  9461. __str__() {
  9462. return 'float';
  9463. }
  9464. });
  9465. this.registerType('torch.StringType', class extends torch.Type {
  9466. constructor() {
  9467. super('StringType');
  9468. }
  9469. static get() {
  9470. torch.StringType.value = torch.StringType.value || new torch.StringType();
  9471. return torch.StringType.value;
  9472. }
  9473. equals(rhs) {
  9474. return this.kind() === rhs.kind();
  9475. }
  9476. str() {
  9477. return 'str';
  9478. }
  9479. __str__() {
  9480. return 'str';
  9481. }
  9482. });
  9483. this.registerType('torch.ComplexType', class extends torch.Type {
  9484. constructor() {
  9485. super('ComplexType');
  9486. }
  9487. static get() {
  9488. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  9489. return torch.ComplexType.value;
  9490. }
  9491. equals(rhs) {
  9492. return this.kind() === rhs.kind();
  9493. }
  9494. isSubtypeOf(rhs) {
  9495. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  9496. }
  9497. str() {
  9498. return 'complex';
  9499. }
  9500. __str__() {
  9501. return 'complex';
  9502. }
  9503. });
  9504. this.registerType('torch.DictType', class extends torch.Type {
  9505. constructor(key, value) {
  9506. super('DictType');
  9507. this.types = [key, value];
  9508. }
  9509. static create(key, value) {
  9510. let kind = key.kind();
  9511. if (key instanceof torch._C.DynamicType) {
  9512. kind = key.dynamicKind();
  9513. }
  9514. switch (kind) {
  9515. case 'AnyType':
  9516. case 'IntType':
  9517. case 'BoolType':
  9518. case 'FloatType':
  9519. case 'ComplexType':
  9520. case 'StringType':
  9521. case 'TensorType':
  9522. case 'DeviceObjType':
  9523. return new torch.DictType(key, value);
  9524. default:
  9525. throw new python.Error(`Invalid dict key type '${kind}'.`);
  9526. }
  9527. }
  9528. createWithContained(contained_types) {
  9529. if (contained_types.length !== 2) {
  9530. throw new python.Error('Expected 2 contained types.');
  9531. }
  9532. return torch.DictType.create(contained_types[0], contained_types[1]);
  9533. }
  9534. getKeyType() {
  9535. return this.types[0];
  9536. }
  9537. getValueType() {
  9538. return this.types[1];
  9539. }
  9540. hasFreeVariables() {
  9541. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  9542. }
  9543. containedTypes() {
  9544. return this.types;
  9545. }
  9546. equals(rhs) {
  9547. if (rhs instanceof torch.DictType) {
  9548. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  9549. }
  9550. return false;
  9551. }
  9552. str() {
  9553. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  9554. }
  9555. __str__() {
  9556. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  9557. }
  9558. });
  9559. this.registerType('torch.DeviceObjType', class extends torch.Type {
  9560. constructor() {
  9561. super('DeviceObjType');
  9562. }
  9563. static get() {
  9564. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  9565. return torch.DeviceObjType.value;
  9566. }
  9567. str() {
  9568. return 'Device';
  9569. }
  9570. __str__() {
  9571. return 'Device';
  9572. }
  9573. });
  9574. this.registerType('torch.StreamObjType', class extends torch.Type {
  9575. constructor() {
  9576. super('StreamObjType');
  9577. }
  9578. str() {
  9579. return 'Stream';
  9580. }
  9581. __str__() {
  9582. return 'Stream';
  9583. }
  9584. });
  9585. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  9586. constructor() {
  9587. super('GeneratorType');
  9588. }
  9589. static get() {
  9590. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  9591. return torch._C._GeneratorType.value;
  9592. }
  9593. str() {
  9594. return 'Generator';
  9595. }
  9596. __str__() {
  9597. return 'Generator';
  9598. }
  9599. });
  9600. this.registerType('torch.InterfaceType', class extends torch.Type {
  9601. constructor() {
  9602. super('InterfaceType');
  9603. }
  9604. });
  9605. this.registerType('torch._C.DynamicType', class extends torch.Type {
  9606. constructor() {
  9607. super('DynamicType');
  9608. }
  9609. });
  9610. this.registerType('torch._C.FunctionType', class extends torch.Type {
  9611. constructor(func) {
  9612. super('FunctionType');
  9613. this._func = func;
  9614. }
  9615. static create(func) {
  9616. return new torch._C.FunctionType(func);
  9617. }
  9618. function() {
  9619. return this._func;
  9620. }
  9621. });
  9622. this.registerType('torch._C.VarType', class extends torch.Type {
  9623. constructor(name) {
  9624. super('VarType', name);
  9625. }
  9626. static create(name) {
  9627. return new torch._C.VarType(name);
  9628. }
  9629. name() {
  9630. return this._annotation_str;
  9631. }
  9632. hasFreeVariables() {
  9633. return true;
  9634. }
  9635. });
  9636. this.registerType('torch._C.AliasInfo', class {
  9637. constructor() {
  9638. this.is_write = false;
  9639. this.before_set = [];
  9640. this.after_set = [];
  9641. this.containedTypes = [];
  9642. }
  9643. addBeforeSet(value) {
  9644. this.before_set.push(value);
  9645. }
  9646. addAfterSet(value) {
  9647. this.after_set.push(value);
  9648. }
  9649. addContainedType(alias_info) {
  9650. this.containedTypes.push(alias_info);
  9651. }
  9652. str() {
  9653. const list = ['('];
  9654. list.push(this.before_set.join('|'));
  9655. if (this.after_set.length > 0) {
  9656. list.push(' -> ');
  9657. list.push(this.after_set.join('|'));
  9658. }
  9659. if (this.is_write) {
  9660. list.push('!');
  9661. }
  9662. list.push(')');
  9663. return list.join('');
  9664. }
  9665. });
  9666. this.registerType('torch._C.Lexer', class {
  9667. constructor(buffer) {
  9668. this.buffer = buffer;
  9669. this.position = 0;
  9670. this.value = '';
  9671. this.next();
  9672. }
  9673. eat(kind) {
  9674. if (this.kind !== kind) {
  9675. return null;
  9676. }
  9677. const value = this.value;
  9678. this.next();
  9679. return value;
  9680. }
  9681. expect(kind) {
  9682. if (this.kind !== kind) {
  9683. throw new python.Error(`Unexpected '${this.kind}' instead of '${kind}'.`);
  9684. }
  9685. const value = this.value;
  9686. this.next();
  9687. return value;
  9688. }
  9689. whitespace(count) {
  9690. if (this.kind !== ' ') {
  9691. if (count > this.value.length) {
  9692. throw new python.Error();
  9693. }
  9694. return false;
  9695. }
  9696. this.next();
  9697. return true;
  9698. }
  9699. next() {
  9700. this.position += this.value.length;
  9701. let i = this.position;
  9702. if (i >= this.buffer.length) {
  9703. this.kind = '\0';
  9704. this.value = '';
  9705. } else if (this.buffer[i] === ' ') {
  9706. while (this.buffer[i] === ' ') {
  9707. i += 1;
  9708. }
  9709. this.kind = ' ';
  9710. this.value = this.buffer.slice(this.position, i);
  9711. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  9712. this.kind = '...';
  9713. this.value = '...';
  9714. } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  9715. this.kind = '[]';
  9716. this.value = '[]';
  9717. } 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] === '|') {
  9718. this.kind = this.buffer[i];
  9719. this.value = this.buffer[i];
  9720. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  9721. i += 1;
  9722. 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] === '_')) {
  9723. i += 1;
  9724. }
  9725. this.kind = 'id';
  9726. this.value = this.buffer.slice(this.position, i);
  9727. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  9728. this.kind = '->';
  9729. this.value = '->';
  9730. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  9731. i += 1;
  9732. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  9733. i += 1;
  9734. }
  9735. this.kind = '#';
  9736. this.value = this.buffer.slice(this.position, i);
  9737. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  9738. const quote = this.buffer[i];
  9739. i += 1;
  9740. while (i < this.buffer.length && this.buffer[i] !== quote) {
  9741. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  9742. }
  9743. i += 1;
  9744. this.kind = 'string';
  9745. this.value = this.buffer.slice(this.position, i);
  9746. } else {
  9747. throw new python.Error(`Unsupported token at '${this.position}'.`);
  9748. }
  9749. }
  9750. });
  9751. this.registerType('torch._C.SchemaTypeParser', class {
  9752. constructor(L, complete_tensor_types, allow_typevars) {
  9753. this.L = L;
  9754. this.complete_tensor_types = complete_tensor_types;
  9755. this._allow_typevars = allow_typevars;
  9756. }
  9757. parseType() {
  9758. const r = this.parseFakeAndRealType();
  9759. return { first: r[0], second: r[2] };
  9760. }
  9761. parseBaseType() {
  9762. const L = this.L;
  9763. const value = L.value;
  9764. L.next();
  9765. switch (value) {
  9766. case 'Tensor': return torch.TensorType.get();
  9767. case 'bool': return torch.BoolType.get();
  9768. case 'int': return torch.IntType.get();
  9769. case 'float': return torch.FloatType.get();
  9770. case 'complex': return torch.ComplexType.get();
  9771. case 'str': return torch.StringType.get();
  9772. case 'SymInt': return torch.SymIntType.get();
  9773. case 'Scalar': return torch.NumberType.get();
  9774. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  9775. case 'Device': return torch.DeviceObjType.get();
  9776. case 'Layout': return torch.Type.get('Layout');
  9777. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  9778. case 'Generator': return torch._C._GeneratorType.get();
  9779. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(value);
  9780. case 'Any': return torch.AnyType.get();
  9781. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  9782. case 'Dimname': return torch.StringType.get();
  9783. case 'QScheme': return torch.Type.get('QSchemeType');
  9784. case 'Stream': return torch.StreamObjType.get();
  9785. case 'Storage': return torch.Type.get('Storage');
  9786. case 'AnyClassType': return torch.Type.get('AnyClassType');
  9787. case 'NoneType': return torch.NoneType.get();
  9788. default: throw new python.Error(`Unsupported type '${value}'.`);
  9789. }
  9790. }
  9791. parseFakeAndRealType() {
  9792. const L = this.L;
  9793. let fake_value = null;
  9794. let real_value = null;
  9795. let alias_info = null;
  9796. if (L.eat('(')) {
  9797. const types = [];
  9798. L.whitespace(0);
  9799. while (!L.eat(')')) {
  9800. const r = this.parseType();
  9801. types.push(r.first);
  9802. if (alias_info && r.second) {
  9803. alias_info.addContainedType(r.second);
  9804. }
  9805. L.whitespace(0);
  9806. L.eat(',');
  9807. L.whitespace(0);
  9808. }
  9809. real_value = torch.TupleType.create(types);
  9810. fake_value = real_value;
  9811. } else if (L.value === 'Future') {
  9812. L.next();
  9813. L.expect('(');
  9814. const p = this.parseType();
  9815. const subtype = p.first;
  9816. // const subalias = p.second;
  9817. L.expect(')');
  9818. real_value = torch.FutureType.get(subtype);
  9819. fake_value = real_value;
  9820. } else if (L.value === 'Await') {
  9821. L.next();
  9822. L.expect('(');
  9823. const p = this.parseType();
  9824. const subtype = p.first;
  9825. // const subalias = p.second;
  9826. L.expect(')');
  9827. real_value = torch.AwaitType.get(subtype);
  9828. fake_value = real_value;
  9829. } else if (L.value === 'RRef') {
  9830. L.next();
  9831. L.expect('(');
  9832. const p = this.parseType();
  9833. const subtype = p.first;
  9834. // const subalias = p.second;
  9835. L.expect(')');
  9836. real_value = torch.RRefType.get(subtype);
  9837. fake_value = real_value;
  9838. } else if (L.value === 'Tensor') {
  9839. L.next();
  9840. real_value = torch.TensorType.get();
  9841. fake_value = real_value;
  9842. alias_info = this.parseAliasAnnotation();
  9843. } else if (L.value === 'Dict') {
  9844. L.next();
  9845. L.expect('(');
  9846. const key_type = this.parseType().first;
  9847. L.expect(',');
  9848. L.whitespace(0);
  9849. const value_type = this.parseType().first;
  9850. L.expect(')');
  9851. alias_info = this.parseAliasAnnotation();
  9852. real_value = torch.DictType.create(key_type, value_type);
  9853. fake_value = real_value;
  9854. } else if (L.eat('Union')) {
  9855. L.next();
  9856. L.expect('(');
  9857. const types = [];
  9858. types.push(this.parseType().first);
  9859. while (L.cur().kind !== ')') {
  9860. L.expect(',');
  9861. types.push(this.parseType().first);
  9862. }
  9863. L.expect(')');
  9864. alias_info = this.parseAliasAnnotation();
  9865. real_value = new torch.UnionType(types);
  9866. fake_value = real_value;
  9867. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  9868. fake_value = real_value = parseRefinedTensor();
  9869. alias_info = parseAliasAnnotation(); */
  9870. } else if (L.value === '__torch__') {
  9871. L.next();
  9872. L.expect('.');
  9873. const torch_tok = L.expect('id');
  9874. if (torch_tok !== 'torch') {
  9875. throw new python.Error('Expected classes namespace.');
  9876. }
  9877. L.expect('.');
  9878. const classes_tok = L.expect('id');
  9879. if (classes_tok !== 'classes') {
  9880. throw new python.Error('Expected classes namespace.');
  9881. }
  9882. L.expect('.');
  9883. const ns_tok = L.expect('id');
  9884. L.expect('.');
  9885. const class_tok = L.expect('id');
  9886. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok}.${class_tok}`);
  9887. fake_value = real_value;
  9888. if (!fake_value) {
  9889. throw new python.Error(`Unknown custom class type '${ns_tok}.${class_tok}'.`);
  9890. }
  9891. } else {
  9892. real_value = this.parseBaseType();
  9893. fake_value = real_value;
  9894. if (real_value.kind() === 'ScalarTypeType' ||
  9895. real_value.kind() === 'MemoryFormat' ||
  9896. real_value.kind() === 'Layout' ||
  9897. real_value.kind() === 'SymIntType') {
  9898. fake_value = torch.IntType.get();
  9899. }
  9900. alias_info = this.parseAliasAnnotation();
  9901. }
  9902. while (true) {
  9903. if (L.kind === '[]') {
  9904. L.expect('[]');
  9905. fake_value = torch.ListType.create(fake_value);
  9906. real_value = torch.ListType.create(real_value);
  9907. let container = this.parseAliasAnnotation();
  9908. if (alias_info) {
  9909. if (!container) {
  9910. container = new torch._C.AliasInfo();
  9911. container.is_write = alias_info.is_write;
  9912. }
  9913. container.addContainedType(alias_info);
  9914. }
  9915. alias_info = container;
  9916. } else if (L.eat('?')) {
  9917. fake_value = torch.OptionalType.create(fake_value);
  9918. real_value = torch.OptionalType.create(real_value);
  9919. } else {
  9920. break;
  9921. }
  9922. }
  9923. return [fake_value, real_value, alias_info];
  9924. }
  9925. parseAliasAnnotation() {
  9926. const L = this.L;
  9927. let alias_info = null;
  9928. if (L.eat('(')) {
  9929. alias_info = new torch._C.AliasInfo();
  9930. do {
  9931. alias_info.addBeforeSet(L.value);
  9932. L.next();
  9933. if (L.eat('!')) {
  9934. alias_info.is_write = true;
  9935. }
  9936. L.whitespace(0);
  9937. }
  9938. while (L.eat('|'));
  9939. if (L.eat('->')) {
  9940. L.whitespace(0);
  9941. do {
  9942. alias_info.addAfterSet(L.value);
  9943. L.next();
  9944. L.whitespace(0);
  9945. }
  9946. while (L.eat('|'));
  9947. }
  9948. L.expect(')');
  9949. }
  9950. return alias_info;
  9951. }
  9952. });
  9953. this.registerType('torch.Argument', class {
  9954. constructor(...args) {
  9955. // torch/aten/src/ATen/core/function_schema.h
  9956. this.N = null;
  9957. this.default_value = null;
  9958. this.kwarg_only = false;
  9959. this.alias_info = null;
  9960. if (args.length === 2) {
  9961. [this.name, this.type] = args;
  9962. this.real_type = this.type;
  9963. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  9964. [this.name, this.type, this.real_type] = args;
  9965. } else if (args.length === 6) {
  9966. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  9967. } else if (args.length === 7) {
  9968. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  9969. } else {
  9970. throw new python.Error('Invalid arguments.');
  9971. }
  9972. const is_alias = this.alias_info && this.alias_info.is_write;
  9973. this.is_out = this.kwarg_only && is_alias;
  9974. }
  9975. has_default_value() {
  9976. return this.default_value !== undefined;
  9977. }
  9978. is_inferred_type() {
  9979. if (this.type instanceof torch.TensorType) {
  9980. return this.type.isInferredType();
  9981. }
  9982. return false;
  9983. }
  9984. static parse(L, is_return, kwarg_only) {
  9985. const type_parser = new torch._C.SchemaTypeParser(L);
  9986. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  9987. L.whitespace(0);
  9988. let N = null;
  9989. if (L.eat('[')) {
  9990. fake_type = torch.ListType.create(fake_type);
  9991. real_type = torch.ListType.create(real_type);
  9992. if (L.kind === '#') {
  9993. N = Number(L.value);
  9994. L.next();
  9995. }
  9996. L.expect(']');
  9997. let container = type_parser.parseAliasAnnotation();
  9998. if (alias_info) {
  9999. if (!container) {
  10000. container = new torch._C.AliasInfo();
  10001. container.is_write = alias_info.is_write;
  10002. }
  10003. container.addContainedType(alias_info);
  10004. }
  10005. alias_info = container;
  10006. if (L.eat('?')) {
  10007. fake_type = torch.OptionalType.create(fake_type);
  10008. real_type = torch.OptionalType.create(real_type);
  10009. }
  10010. }
  10011. let name = null;
  10012. /* eslint-disable no-undef-init */
  10013. let default_value = undefined;
  10014. /* eslint-enable no-undef-init */
  10015. if (is_return) {
  10016. L.whitespace(0);
  10017. kwarg_only = false;
  10018. if (L.kind === 'id') {
  10019. name = L.expect('id');
  10020. }
  10021. } else {
  10022. L.whitespace(1);
  10023. name = L.expect('id');
  10024. L.whitespace(0);
  10025. if (L.eat('=')) {
  10026. L.whitespace(0);
  10027. default_value = torch.Argument._parse_value(L);
  10028. }
  10029. }
  10030. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  10031. }
  10032. static _parse_value(L) {
  10033. /* eslint-disable no-undef-init */
  10034. let value = undefined;
  10035. /* eslint-enable no-undef-init */
  10036. if (L.kind === 'id') {
  10037. if (L.value === 'True' || L.value === 'False') {
  10038. value = L.value === 'True';
  10039. } else if (L.value === 'None') {
  10040. value = null;
  10041. } else if (L.value === 'Mean' || L.value === 'contiguous_format' || L.value === 'long') {
  10042. value = L.value;
  10043. } else if (typeof L.value === 'string') {
  10044. value = L.value;
  10045. } else if (typeof L.value === 'number') {
  10046. value = L.value;
  10047. } else {
  10048. throw new python.Error(`Unsupported default value '${L.value}'.`);
  10049. }
  10050. } else if (L.kind === '#') {
  10051. value = Number(L.value);
  10052. } else if (L.kind === 'string') {
  10053. value = L.value.slice(1, -1);
  10054. } else if (L.kind === '[]') {
  10055. value = [];
  10056. } else if (L.eat('[')) {
  10057. value = [];
  10058. if (!L.eat(']')) {
  10059. while (true) {
  10060. L.whitespace(0);
  10061. value.push(torch.Argument._parse_value(L));
  10062. L.whitespace(0);
  10063. if (!L.eat(',')) {
  10064. break;
  10065. }
  10066. }
  10067. L.expect(']');
  10068. }
  10069. return value;
  10070. } else {
  10071. throw new python.Error(`Unsupported default value '${L.kind}'.`);
  10072. }
  10073. L.next();
  10074. return value;
  10075. }
  10076. str() {
  10077. const list = [];
  10078. const type = this.real_type;
  10079. const is_opt = type instanceof torch.OptionalType;
  10080. const unopt_type = is_opt ? type.getElementType() : type;
  10081. if (unopt_type instanceof torch.ListType) {
  10082. list.push(unopt_type.getElementType().str());
  10083. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  10084. list.push(this.alias_info.containedTypes[0].str());
  10085. }
  10086. list.push(this.N === null ? `[]` : `[${this.N}]`);
  10087. } else {
  10088. list.push(unopt_type.str());
  10089. }
  10090. if (this.alias_info && this.alias_info.before_set.length > 0) {
  10091. list.push(this.alias_info.str());
  10092. }
  10093. if (is_opt) {
  10094. list.push('?');
  10095. }
  10096. if (this.name) {
  10097. list.push(' ');
  10098. list.push(this.name);
  10099. }
  10100. if (this.default_value !== undefined) {
  10101. const value = this.default_value;
  10102. if (value === null) {
  10103. list.push('=None');
  10104. } else if (typeof value === 'boolean') {
  10105. list.push('=');
  10106. list.push(value ? 'True' : 'False');
  10107. } else if (typeof value === 'string') {
  10108. list.push(`="${value}"`);
  10109. } else if (typeof value === 'number') {
  10110. list.push(`=${value}`);
  10111. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  10112. list.push(`.`);
  10113. }
  10114. } else if (Array.isArray(value)) {
  10115. list.push(`=[${value.join(', ')}]`);
  10116. }
  10117. }
  10118. return list.join('');
  10119. }
  10120. });
  10121. this.registerType('torch._C.SchemaParser', class {
  10122. constructor(str, allow_typevars) {
  10123. this.L = new torch._C.Lexer(str);
  10124. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  10125. }
  10126. parseName() {
  10127. const L = this.L;
  10128. let name = L.expect('id').text();
  10129. if (L.nextIf(':')) {
  10130. L.expect(':');
  10131. name = `${name}::${L.expect('ident').text()}`;
  10132. }
  10133. let overload_name = '';
  10134. if (L.nextIf('.')) {
  10135. overload_name = L.expect('ident').text();
  10136. }
  10137. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  10138. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  10139. return new torch._C.OperatorName(name, overload_name);
  10140. }
  10141. parseDeclaration() {
  10142. const L = this.L;
  10143. const name = this.parseName();
  10144. if (L.cur().kind !== '(') {
  10145. return name;
  10146. }
  10147. throw new python.Error('Not implemented.');
  10148. }
  10149. parseExactlyOneDeclaration() {
  10150. // const L = this.L;
  10151. const result = this.parseDeclaration();
  10152. // L.nextIf(TK_NEWLINE);
  10153. // L.expect(TK_EOF);
  10154. return result;
  10155. }
  10156. parseArgument() {
  10157. throw new python.Error('Not implemented.');
  10158. }
  10159. });
  10160. this.registerType('torch.FunctionSchema', class {
  10161. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  10162. const index = name.indexOf('(');
  10163. if (index === -1) {
  10164. this._name = name;
  10165. this._overload_name = overload_name || '';
  10166. this._arguments = args || [];
  10167. this._returns = returns || [];
  10168. this._is_vararg = is_vararg || false;
  10169. this._is_varret = is_varret || false;
  10170. } else {
  10171. const value = name.substring(0, index).trim();
  10172. const dot = value.indexOf('.');
  10173. if (dot === -1) {
  10174. this._name = value;
  10175. this._overload_name = '';
  10176. } else {
  10177. this._name = value.substring(0, dot);
  10178. this._overload_name = value.substring(dot + 1, value.length);
  10179. }
  10180. this._buffer = name.substring(index, name.length);
  10181. }
  10182. }
  10183. static parse(schema) {
  10184. return new torch.FunctionSchema(schema);
  10185. }
  10186. get name() {
  10187. return this._name;
  10188. }
  10189. get overload_name() {
  10190. return this._overload_name;
  10191. }
  10192. get arguments() {
  10193. this._parse();
  10194. return this._arguments;
  10195. }
  10196. get returns() {
  10197. this._parse();
  10198. return this._returns;
  10199. }
  10200. get is_vararg() {
  10201. this._parse();
  10202. return this._is_vararg;
  10203. }
  10204. get is_varret() {
  10205. this._parse();
  10206. return this._is_varret;
  10207. }
  10208. _parse() {
  10209. if (this._buffer) {
  10210. const L = new torch._C.Lexer(this._buffer);
  10211. this._arguments = [];
  10212. this._is_vararg = false;
  10213. this._kwarg_only = false;
  10214. L.expect('(');
  10215. if (!L.eat(')')) {
  10216. while (true) {
  10217. L.whitespace(0);
  10218. if (this._is_vararg) {
  10219. throw new python.Error();
  10220. }
  10221. if (L.eat('*')) {
  10222. this._kwarg_only = true;
  10223. } else if (L.eat('...')) {
  10224. this._is_vararg = true;
  10225. } else {
  10226. const argument = torch.Argument.parse(L, false, this._kwarg_only);
  10227. this._arguments.push(argument);
  10228. }
  10229. L.whitespace(0);
  10230. if (!L.eat(',')) {
  10231. break;
  10232. }
  10233. }
  10234. L.expect(')');
  10235. }
  10236. L.whitespace(0);
  10237. L.expect('->');
  10238. L.whitespace(0);
  10239. this._returns = [];
  10240. this._is_varret = false;
  10241. if (L.eat('...')) {
  10242. this._is_varret = true;
  10243. } else if (L.eat('(')) {
  10244. L.whitespace(0);
  10245. if (!L.eat(')')) {
  10246. while (true) {
  10247. L.whitespace(0);
  10248. if (this._is_varret) {
  10249. throw new python.Error();
  10250. }
  10251. if (L.eat('...')) {
  10252. this._is_varret = true;
  10253. } else {
  10254. const argument = torch.Argument.parse(L, true, false);
  10255. this._returns.push(argument);
  10256. }
  10257. L.whitespace(0);
  10258. if (!L.eat(',')) {
  10259. break;
  10260. }
  10261. }
  10262. L.expect(')');
  10263. }
  10264. L.whitespace(0);
  10265. } else {
  10266. this._returns.push(torch.Argument.parse(L, true, false));
  10267. }
  10268. delete this._buffer;
  10269. }
  10270. }
  10271. __str__() {
  10272. const list = [this.name];
  10273. const overload_name = this.overload_name;
  10274. if (overload_name !== '' && overload_name !== 'default') {
  10275. list.push(`.${this.overload_name}`);
  10276. }
  10277. list.push('(');
  10278. let first = true;
  10279. let kwarg_only = false;
  10280. for (const argument of this.arguments) {
  10281. if (!first) {
  10282. list.push(', ');
  10283. }
  10284. if (argument.kwarg_only && !kwarg_only) {
  10285. list.push('*, ');
  10286. kwarg_only = true;
  10287. }
  10288. first = false;
  10289. list.push(argument.str());
  10290. }
  10291. if (this.is_vararg) {
  10292. if (!first) {
  10293. list.push(', ');
  10294. }
  10295. first = true;
  10296. list.push('...');
  10297. }
  10298. list.push(') -> ');
  10299. const returns = this.returns;
  10300. const braces = !this.is_varret &&
  10301. (returns.length !== 1 ||
  10302. returns[0].name ||
  10303. returns[0].real_type instanceof torch.TupleType ||
  10304. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  10305. if (braces) {
  10306. list.push('(');
  10307. }
  10308. first = true;
  10309. for (const argument of this.returns) {
  10310. if (!first) {
  10311. list.push(', ');
  10312. }
  10313. first = false;
  10314. list.push(argument.str());
  10315. }
  10316. if (this.is_varret) {
  10317. if (!first) {
  10318. list.push(', ');
  10319. }
  10320. first = true;
  10321. list.push('...');
  10322. }
  10323. if (braces) {
  10324. list.push(')');
  10325. }
  10326. return list.join('');
  10327. }
  10328. aliasAnalysis() {
  10329. return this._alias_kind || 'CONSERVATIVE';
  10330. }
  10331. setAliasAnalysis(v) {
  10332. this._alias_kind = v;
  10333. }
  10334. hasAnyAliasInfo() {
  10335. for (const arg of this.arguments) {
  10336. if (arg.alias_info !== null) {
  10337. return true;
  10338. }
  10339. }
  10340. for (const ret of this.returns) {
  10341. if (ret.alias_info !== null) {
  10342. return true;
  10343. }
  10344. }
  10345. return false;
  10346. }
  10347. is_mutable() {
  10348. return this.arguments.some((arg) => {
  10349. const aliasInfo = arg.alias_info;
  10350. return aliasInfo && aliasInfo.is_write;
  10351. });
  10352. }
  10353. });
  10354. this.registerType('torch._C.SchemaInfo', class {
  10355. constructor(schema) {
  10356. this._schema = schema;
  10357. this._alias_maps_current = false;
  10358. this._has_init = false;
  10359. }
  10360. is_nondeterministic() {
  10361. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  10362. //
  10363. }
  10364. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  10365. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  10366. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  10367. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  10368. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  10369. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  10370. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  10371. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  10372. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  10373. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  10374. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  10375. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  10376. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  10377. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  10378. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  10379. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  10380. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  10381. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  10382. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  10383. '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',
  10384. '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',
  10385. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  10386. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  10387. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  10388. ]);
  10389. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  10390. return true;
  10391. }
  10392. /*
  10393. const auto& op = c10::Dispatcher::singleton().findOp(
  10394. c10::OperatorName(schema_.name(), schema_.overload_name()));
  10395. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  10396. */
  10397. return false;
  10398. }
  10399. });
  10400. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  10401. return new Map();
  10402. });
  10403. this.registerFunction('torch._C.string_to_type_lut', () => {
  10404. if (!torch._C.string_to_type_lut.basePythonTypes) {
  10405. const map = new Map();
  10406. map.set('Tensor', torch.TensorType.get());
  10407. map.set('int', torch.IntType.get());
  10408. map.set('float', torch.FloatType.get());
  10409. map.set('bool', torch.BoolType.get());
  10410. map.set('complex', torch.ComplexType.get());
  10411. map.set('str', torch.StringType.get());
  10412. map.set('Device', torch.DeviceObjType.get());
  10413. map.set('number', torch.NumberType.get());
  10414. map.set('None', torch.NoneType.get());
  10415. map.set('NoneType', torch.NoneType.get());
  10416. map.set('Any', torch.AnyType.get());
  10417. map.set('list', torch.Type.get('AnyListType'));
  10418. map.set('tuple', torch.Type.get('AnyTupleType'));
  10419. torch._C.string_to_type_lut.basePythonTypes = map;
  10420. }
  10421. return torch._C.string_to_type_lut.basePythonTypes;
  10422. });
  10423. this.registerType('torch._C.ScriptTypeParser', class {
  10424. constructor(resolver) {
  10425. this._resolver = resolver;
  10426. }
  10427. parseSchemaFromDef(def, skip_self) {
  10428. const name = def.name;
  10429. const args = this.parseArgsFromDecl(def, skip_self);
  10430. const returns = this.parseReturnFromDecl(def);
  10431. return new torch.FunctionSchema(name, '', args, returns, false, false);
  10432. }
  10433. parseArgsFromDecl(decl, skip_self) {
  10434. const retval = [];
  10435. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  10436. throw new python.Error('Unsupported function argument.');
  10437. }
  10438. const params = decl.args.args.slice();
  10439. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  10440. const start = skip_self ? 1 : 0;
  10441. for (let i = start; i < params.length; i++) {
  10442. const decl_arg = params[i];
  10443. const N = null;
  10444. const default_value = undefined;
  10445. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  10446. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  10447. retval.push(arg);
  10448. }
  10449. return retval;
  10450. }
  10451. parseReturnFromDecl(decl) {
  10452. if (!decl.returns) {
  10453. return [];
  10454. }
  10455. if (this.parseBroadcastList(decl.returns)) {
  10456. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  10457. }
  10458. const parsed_type = this.parseTypeFromExpr(decl.returns);
  10459. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  10460. }
  10461. parseTypeFromExpr(expr) {
  10462. if (this._resolver) {
  10463. if (expr instanceof ast.Name) {
  10464. const type = this._resolver.resolveType(expr.id);
  10465. if (type) {
  10466. return type;
  10467. }
  10468. }
  10469. }
  10470. return this.parseTypeFromExprImpl(expr);
  10471. }
  10472. parseTypeFromExprImpl(expr) {
  10473. if (expr instanceof ast.Subscript) {
  10474. const value_name = this.parseBaseTypeName(expr.value);
  10475. if (!value_name) {
  10476. throw new python.Error('Subscripted type must be a type identifier.');
  10477. }
  10478. return this.subscriptToType(value_name, expr);
  10479. }
  10480. const name = this.parseBaseTypeName(expr);
  10481. if (name) {
  10482. const itr = torch._C.string_to_type_lut().get(name);
  10483. if (itr) {
  10484. return itr;
  10485. }
  10486. if (this._resolver) {
  10487. const typePtr = this._resolver.resolveType(name, expr);
  10488. if (typePtr) {
  10489. return typePtr;
  10490. }
  10491. }
  10492. }
  10493. throw new python.Error(`Unknown type name '${name}'.`);
  10494. }
  10495. parseBaseTypeName(expr) {
  10496. if (expr instanceof ast.Name) {
  10497. return expr.id;
  10498. } else if (expr instanceof ast.Constant && expr.value === null) {
  10499. return 'None';
  10500. } else if (expr instanceof ast.Attribute) {
  10501. const name = expr.attr;
  10502. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  10503. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  10504. return name;
  10505. }
  10506. return torch._C.collectQualname(expr);
  10507. }
  10508. throw new python.Error('Unsupported type.');
  10509. }
  10510. parseBroadcastList(/* expr */) {
  10511. return null;
  10512. }
  10513. parseType(str) {
  10514. const expr = ast.parse(str);
  10515. return this.parseTypeFromExpr(expr.body[0].value);
  10516. }
  10517. subscriptToType(typeName, subscript) {
  10518. if (typeName === 'Tuple' || typeName === 'tuple') {
  10519. const subscript_expr_types = [];
  10520. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  10521. for (const expr of elts) {
  10522. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  10523. }
  10524. return torch.TupleType.create(subscript_expr_types);
  10525. } else if (typeName === 'List' || typeName === 'list') {
  10526. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  10527. throw new python.Error('List type must have exactly one element type.');
  10528. }
  10529. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  10530. return torch.ListType.create(elem_type);
  10531. } else if (typeName === 'Optional') {
  10532. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  10533. throw new python.Error('Optional type must have exactly one element type.');
  10534. }
  10535. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  10536. return torch.OptionalType.create(elem_type);
  10537. } else if (typeName === 'Union') {
  10538. const subscript_expr_types = [];
  10539. for (const expr of subscript.slice.elts) {
  10540. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  10541. }
  10542. return torch.UnionType.create(subscript_expr_types);
  10543. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  10544. if (subscript.slice.elts.length !== 1) {
  10545. throw new python.Error('Future type must have exactly one element type.');
  10546. }
  10547. const elem_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10548. return torch.FutureType.create(elem_type);
  10549. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  10550. if (subscript.slice.elts.length !== 1) {
  10551. throw new python.Error('Await type must have exactly one element type.');
  10552. }
  10553. const elem_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10554. return torch.AwaitType.create(elem_type);
  10555. } else if (typeName === 'RRef') {
  10556. if (subscript.slice.elts.length !== 1) {
  10557. throw new python.Error('RRef type must have exactly one element type.');
  10558. }
  10559. const elem_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10560. return torch.RRefType.create(elem_type);
  10561. } else if (typeName === 'Dict' || typeName === 'dict') {
  10562. if (subscript.slice.elts.length !== 2) {
  10563. throw new python.Error('Dict type must have exactly two element types.');
  10564. }
  10565. const key_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10566. const value_type = this.parseTypeFromExprImpl(subscript.slice.elts[1]);
  10567. return torch.DictType.create(key_type, value_type);
  10568. }
  10569. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  10570. }
  10571. });
  10572. this.registerFunction('torch._C.isTorch', (expr) => {
  10573. return expr instanceof ast.Name && expr.id === 'torch';
  10574. });
  10575. this.registerFunction('torch._C.collectQualname', (select) => {
  10576. const base = select.value;
  10577. if (base instanceof ast.Name) {
  10578. return `${base.id}.${select.attr}`;
  10579. }
  10580. const basename = torch._C.collectQualname(base);
  10581. return `${basename}.${select.attr}`;
  10582. });
  10583. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  10584. constructor(overloadpacket, op, op_dk, schema, tags) {
  10585. super();
  10586. this._op = op;
  10587. this._op_dk = op_dk;
  10588. this._schema = schema;
  10589. this._overloadpacket = overloadpacket;
  10590. this._tags = tags;
  10591. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  10592. this._name = this._schema.name;
  10593. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  10594. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  10595. this.__module__ = overloadpacket.__module__;
  10596. op.__module__ = overloadpacket.__module__;
  10597. this.__qualname__ = self._name;
  10598. this.__annotations__ = {};
  10599. // this._defined_in_python = this.__qualname__ in torch.library._defs
  10600. let is_write = null;
  10601. for (const a of this._schema.arguments) {
  10602. if (a.alias_info) {
  10603. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  10604. }
  10605. }
  10606. this.is_view = is_write !== null && !is_write;
  10607. }
  10608. get name() {
  10609. return this._name;
  10610. }
  10611. });
  10612. this.registerType('torch._ops.OpOverloadPacket', class {
  10613. constructor(qualified_op_name, op_name, op, overload_names) {
  10614. this._qualified_op_name = qualified_op_name;
  10615. this.__name__ = op_name;
  10616. this._op = op;
  10617. this._overload_names = overload_names;
  10618. this._dir = [];
  10619. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  10620. }
  10621. get _schemas() {
  10622. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  10623. }
  10624. __getattr__(key) {
  10625. key = key === 'default' ? '' : key;
  10626. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  10627. const [op_, op_dk_, tags] = op_dk_tags;
  10628. const schema = torch._C._get_schema(this._qualified_op_name, key);
  10629. const overload = this._has_script_object_arg(schema) ?
  10630. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  10631. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  10632. builtins.setattr(self, key, overload);
  10633. this._dir.push(key);
  10634. return overload;
  10635. }
  10636. _has_script_object_arg(schema) {
  10637. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  10638. }
  10639. });
  10640. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  10641. constructor(name) {
  10642. super(`torch.ops.${name}`);
  10643. this.name = name;
  10644. this._dir = [];
  10645. }
  10646. __getattr__(op_name) {
  10647. const namespace_name = this.name;
  10648. const qualified_op_name = `${namespace_name}::${op_name}`;
  10649. const module_name = `${this.__module__}.${namespace_name}`;
  10650. let op = null;
  10651. let overload_names = null;
  10652. try {
  10653. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  10654. } catch {
  10655. // continue regardless of error
  10656. }
  10657. if (!op) {
  10658. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  10659. }
  10660. op.__module__ = module_name;
  10661. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  10662. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  10663. builtins.setattr(this, op_name, opoverloadpacket);
  10664. this._dir.push(op_name);
  10665. return opoverloadpacket;
  10666. }
  10667. _get_packet(qualname, op_module) {
  10668. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  10669. if (op) {
  10670. // torch.jit._builtins._register_builtin(op, qualname);
  10671. }
  10672. op.__module__ = op_module;
  10673. return [op, overload_names];
  10674. }
  10675. });
  10676. this.registerType('torch._C.graph_node_list', class {
  10677. constructor(head) {
  10678. this.head = head;
  10679. }
  10680. front() {
  10681. return this.head.next;
  10682. }
  10683. end() {
  10684. return this.head.prev;
  10685. }
  10686. [Symbol.iterator]() {
  10687. let current = this.head.next;
  10688. const prev = this.head.prev;
  10689. return {
  10690. next() {
  10691. if (current !== prev) {
  10692. const value = current;
  10693. current = current.next;
  10694. return { value, done: false };
  10695. }
  10696. return { done: true };
  10697. }
  10698. };
  10699. }
  10700. });
  10701. this.registerType('torch.Graph', class {
  10702. constructor() {
  10703. this._next_unique = 0;
  10704. this._unique_names = new Map();
  10705. this._name_base_suffix = new Map();
  10706. this.all_nodes = new Set();
  10707. this.all_values = new Set();
  10708. this.all_blocks = new Set();
  10709. this._block = new torch.Block(this, null);
  10710. this._insert_before = this.return_node();
  10711. }
  10712. insert(opname, args, kwargs, range) {
  10713. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  10714. }
  10715. create(kind, ...args) {
  10716. let inputs = null;
  10717. let num_outputs = 1;
  10718. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  10719. [inputs, num_outputs] = args;
  10720. } else if (args.length === 1) {
  10721. if (typeof args[0] === 'number') {
  10722. [num_outputs] = args;
  10723. } else if (Array.isArray(args[0])) {
  10724. [inputs] = args;
  10725. }
  10726. }
  10727. const n = new torch.Node(this, kind);
  10728. if (inputs) {
  10729. for (const i of inputs) {
  10730. n.addInput(i);
  10731. }
  10732. }
  10733. for (let i = 0; i < num_outputs; i++) {
  10734. n.addOutput();
  10735. }
  10736. return n;
  10737. }
  10738. createClone(n, value_map, copy_blocks) {
  10739. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  10740. const r = n.allocNewInstance(this);
  10741. for (const o of n.outputs()) {
  10742. r.addOutput().copyMetadata(o);
  10743. }
  10744. r.cloneFrom(n);
  10745. for (const i of n.inputs()) {
  10746. r.addInput(value_map(i));
  10747. }
  10748. if (copy_blocks) {
  10749. for (const b of n.blocks()) {
  10750. r.addBlock().cloneFrom(b, value_map);
  10751. }
  10752. }
  10753. return r;
  10754. }
  10755. createNone() {
  10756. const n = this.create('prim::Constant');
  10757. n.output().setType(torch.NoneType.get());
  10758. return n;
  10759. }
  10760. createUninitialized(typ) {
  10761. const n = this.create('prim::Uninitialized');
  10762. n.output().setType(typ);
  10763. return n;
  10764. }
  10765. createList(contained_type, values) {
  10766. const n = this.create('prim::ListConstruct', values);
  10767. for (const v of values) {
  10768. if (!v.type().isSubtypeOf(contained_type)) {
  10769. throw new python.Error('Invalid list item.');
  10770. }
  10771. }
  10772. n.output().setType(torch.ListType.create(contained_type));
  10773. return n;
  10774. }
  10775. createListUnpack(v, size) {
  10776. const list_type = v.type().expect(torch.ListType);
  10777. const elem_type = list_type.getElementType();
  10778. const n = this.create('prim::ListUnpack', [v], 0);
  10779. for (let i = 0; i < size; i++) {
  10780. n.addOutput().setType(elem_type);
  10781. }
  10782. return n;
  10783. }
  10784. createTuple(values, tuple_type) {
  10785. if (!tuple_type) {
  10786. const types = values.map((v) => v.type());
  10787. tuple_type = torch.TupleType.create(types);
  10788. }
  10789. const n = this.create('prim::TupleConstruct', values);
  10790. n.output().setType(tuple_type);
  10791. return n;
  10792. }
  10793. createTupleUnpack(v) {
  10794. const tt = v.type().expect(torch.TupleType);
  10795. const n = this.create('prim::TupleUnpack', [v], 0);
  10796. for (const element of tt.elements()) {
  10797. n.addOutput().setType(element);
  10798. }
  10799. return n;
  10800. }
  10801. createTupleIndex(tup, idx, output_type) {
  10802. const n = this.create('prim::TupleIndex', [tup, idx]);
  10803. n.output().setType(output_type);
  10804. return n;
  10805. }
  10806. createTupleSlice(tup, beg, step_size, num_values) {
  10807. const new_vals = [];
  10808. const tt = tup.type().expect(torch.TupleType);
  10809. let i = beg;
  10810. for (let j = 0; j < num_values; j++) {
  10811. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  10812. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  10813. new_vals.push(tupleIndex.output());
  10814. i += step_size;
  10815. }
  10816. const n = this.createTuple(new_vals);
  10817. return n;
  10818. }
  10819. createDict(key_type, value_type, keys, values) {
  10820. if (keys.length !== values.length) {
  10821. throw new python.Error('Invalid dictionary size.');
  10822. }
  10823. const n = this.create('prim::DictConstruct');
  10824. const length = keys.length;
  10825. for (let i = 0; i < length; i++) {
  10826. if (!keys[i].type().isSubtypeOf(key_type)) {
  10827. throw new python.Error('Invalid key.');
  10828. }
  10829. if (!values[i].type().isSubtypeOf(value_type)) {
  10830. throw new python.Error('Invalid value.');
  10831. }
  10832. n.addInput(keys[i]);
  10833. n.addInput(values[i]);
  10834. }
  10835. n.output().setType(torch.DictType.create(key_type, value_type));
  10836. return n;
  10837. }
  10838. createObject(type) {
  10839. const node = this.create('prim::CreateObject');
  10840. node.output().setType(type);
  10841. return node;
  10842. }
  10843. createIsInstance(v, types) {
  10844. const n = this.create('prim::isinstance', [v], 1);
  10845. n.tys_('types', types);
  10846. n.output().setType(torch.BoolType.get());
  10847. return n;
  10848. }
  10849. createSetAttr(obj, field, newValue) {
  10850. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  10851. n.s_('name', field);
  10852. return n;
  10853. }
  10854. createGetAttr(obj, field) {
  10855. const n = this.create('prim::GetAttr', [obj]);
  10856. n.s_('name', field);
  10857. const classType = obj.type();
  10858. const outputType = classType.getAttribute(field);
  10859. n.output().setType(outputType);
  10860. n.output().setDebugName(torch._C.normalizeAttrName(field));
  10861. return n;
  10862. }
  10863. createLoad(name, type) {
  10864. const n = this.create('prim::Load', [], 1);
  10865. n.s_('name', name);
  10866. n.output().setType(type);
  10867. return n;
  10868. }
  10869. createStore(name, v) {
  10870. const n = this.create('prim::Store', [v], 0);
  10871. n.s_('name', name);
  10872. return n;
  10873. }
  10874. inputs() {
  10875. return this._block.inputs();
  10876. }
  10877. outputs() {
  10878. return this._block.outputs();
  10879. }
  10880. nodes() {
  10881. return this._block.nodes();
  10882. }
  10883. param_node() {
  10884. return this._block.param_node();
  10885. }
  10886. return_node() {
  10887. return this._block.return_node();
  10888. }
  10889. block() {
  10890. return this._block;
  10891. }
  10892. addInput(name) {
  10893. return this._block.addInput(name);
  10894. }
  10895. insertNode(node) {
  10896. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  10897. return node.insertBefore(this._insert_before);
  10898. }
  10899. insertConstant(val, loc, scope) {
  10900. return torch._C.insertConstant(this, val, loc, scope);
  10901. }
  10902. insertMethodCall(method_name, matched) {
  10903. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  10904. .s_('name', method_name)
  10905. .output().setType(matched.return_types[0]);
  10906. return result;
  10907. }
  10908. insertUncheckedCast(v, type) {
  10909. const n = this.create('prim::unchecked_cast', [v]);
  10910. this.insertNode(n);
  10911. n.output().setType(type);
  10912. return n.output();
  10913. }
  10914. insertToList(v, type) {
  10915. let dim = 0;
  10916. let ptr = type;
  10917. while (ptr instanceof torch.ListType) {
  10918. ptr = ptr.getElementType();
  10919. dim += 1;
  10920. }
  10921. let elem_ty = 0;
  10922. if (ptr instanceof torch.IntType) {
  10923. elem_ty = 0;
  10924. } else if (ptr instanceof torch.FloatType) {
  10925. elem_ty = 1;
  10926. } else if (ptr instanceof torch.BoolType) {
  10927. elem_ty = 2;
  10928. } else if (ptr instanceof torch.ComplexType) {
  10929. elem_ty = 3;
  10930. } else {
  10931. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  10932. }
  10933. const dim_val = this.insertConstant(dim);
  10934. const elem_ty_val = this.insertConstant(elem_ty);
  10935. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  10936. n.output().setType(type);
  10937. return n.output();
  10938. }
  10939. insertFunctionCall(callee, matched) {
  10940. const func_name = callee.name();
  10941. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  10942. const inputs = [fn_constant, ...matched.inputs];
  10943. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  10944. return result;
  10945. }
  10946. insertPoint() {
  10947. return this._insert_before;
  10948. }
  10949. setInsertPoint(node) {
  10950. if (node instanceof torch.Block) {
  10951. node = node.return_node();
  10952. }
  10953. this._insert_before = node;
  10954. }
  10955. freeNode(n) {
  10956. this.all_nodes.delete(n);
  10957. }
  10958. freeValue(v) {
  10959. v.setDebugName('');
  10960. this.all_values.delete(v);
  10961. }
  10962. freeBlock(b) {
  10963. this.all_blocks.delete(b);
  10964. }
  10965. copy() {
  10966. const new_g = new torch.Graph();
  10967. new_g.cloneFrom(this);
  10968. return new_g;
  10969. }
  10970. cloneFrom(src) {
  10971. const env = (v) => {
  10972. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  10973. };
  10974. this.block().cloneFrom(src.block(), env);
  10975. }
  10976. set_op_version(version) {
  10977. this._op_version = version;
  10978. }
  10979. get_op_version() {
  10980. return this._op_version;
  10981. }
  10982. print(out, print_source_locations) {
  10983. out.write('graph(');
  10984. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  10985. out.write('):\n');
  10986. const groups = [];
  10987. for (const node of this.nodes()) {
  10988. node.print(out, 1, groups, print_source_locations);
  10989. }
  10990. out.write(' return (');
  10991. torch._C.printValueRefs(out, this.outputs());
  10992. out.write(')\n');
  10993. for (let i = 0; i < groups.length; i++) {
  10994. const fg = groups[i];
  10995. out.write('with ');
  10996. out.write(fg.kind());
  10997. out.write(`_${i} = `);
  10998. out.write(fg.g('Subgraph'));
  10999. }
  11000. return out;
  11001. }
  11002. toString() {
  11003. const out = new io.StringIO();
  11004. this.print(out, true);
  11005. return out.toString();
  11006. }
  11007. });
  11008. this.registerType('torch.Block', class {
  11009. constructor(graph, node) {
  11010. this._graph = graph;
  11011. this._input = graph.create('prim::Param', 0);
  11012. this._output = graph.create('prim::Return', 0);
  11013. this._owning_node = node;
  11014. this._input.next = this._output;
  11015. this._input.prev = this._output;
  11016. this._output.next = this._input;
  11017. this._output.prev = this._input;
  11018. this._graph.all_blocks.add(this);
  11019. this._output._owning_block = this;
  11020. // output_.topo_position_ = kUpperBound;
  11021. this._input._owning_block = this;
  11022. // input_.topo_position_ = kLowerBound;
  11023. }
  11024. inputs() {
  11025. return this._input.outputs();
  11026. }
  11027. outputs() {
  11028. return this._output.inputs();
  11029. }
  11030. nodes() {
  11031. return new torch._C.graph_node_list(this._input);
  11032. }
  11033. return_node() {
  11034. return this._output;
  11035. }
  11036. param_node() {
  11037. return this._input;
  11038. }
  11039. owningNode() {
  11040. return this._owning_node;
  11041. }
  11042. owningGraph() {
  11043. return this._graph;
  11044. }
  11045. addInput(name) {
  11046. const value = this._input.addOutput();
  11047. value.setDebugName(name || '');
  11048. return value;
  11049. }
  11050. registerOutput(value) {
  11051. this._output.addInput(value);
  11052. return this.outputs().length - 1;
  11053. }
  11054. appendNode(n) {
  11055. if (n._graph !== this._graph || n.inBlockList()) {
  11056. throw new python.Error('Node not in graph.');
  11057. }
  11058. n.insertBefore(this._output);
  11059. return n;
  11060. }
  11061. cloneFrom(src, value_map) {
  11062. const local_map = new Map();
  11063. const env = (v) => {
  11064. if (local_map.has(v)) {
  11065. return local_map.get(v);
  11066. }
  11067. return value_map(v);
  11068. };
  11069. const graph = this.owningGraph();
  11070. for (const input of src.inputs()) {
  11071. local_map.set(input, this.addInput().copyMetadata(input));
  11072. }
  11073. for (const node of src.nodes()) {
  11074. const new_node = this.appendNode(graph.createClone(node, env));
  11075. for (let i = 0; i < node.outputs().length; i++) {
  11076. const oo = node.outputs()[i];
  11077. const no = new_node.outputs()[i];
  11078. local_map.set(oo, no);
  11079. no.copyMetadata(oo);
  11080. }
  11081. }
  11082. for (const output of src.outputs()) {
  11083. this.registerOutput(env(output));
  11084. }
  11085. }
  11086. eraseOutput(i) {
  11087. this._output.removeInput(i);
  11088. }
  11089. destroy() {
  11090. this._output.removeAllInputs();
  11091. for (const n of this.nodes()) {
  11092. n.destroy();
  11093. }
  11094. this._output.destroy();
  11095. this._input.destroy();
  11096. this._graph.freeBlock(this);
  11097. }
  11098. });
  11099. this.registerType('torch.Node', class {
  11100. constructor(graph, kind) {
  11101. this._kind = kind;
  11102. this._graph = graph;
  11103. this._owning_block = null;
  11104. this._values = new Map();
  11105. this._inputs = [];
  11106. this._outputs = [];
  11107. this._blocks = [];
  11108. this._graph.all_nodes.add(this);
  11109. this._prev = null;
  11110. this._next = null;
  11111. this._source_range = null;
  11112. this._op = null;
  11113. }
  11114. owningGraph() {
  11115. return this._graph;
  11116. }
  11117. owningBlock() {
  11118. return this._owning_block;
  11119. }
  11120. kind() {
  11121. return this._kind;
  11122. }
  11123. schema() {
  11124. if (this._op) {
  11125. return this._op.schema();
  11126. }
  11127. // Node::schema() throws while torch.Node.schema() does not.
  11128. const op = this.maybeOperator();
  11129. if (op) {
  11130. return op.schema();
  11131. }
  11132. return null;
  11133. // return this.getOperator().schema();
  11134. }
  11135. hasNamedInput(name) {
  11136. for (const argument of this.schema().arguments) {
  11137. if (argument.name === name) {
  11138. return true;
  11139. }
  11140. }
  11141. return false;
  11142. }
  11143. matches(schema) {
  11144. if (torch._C.isBlockListedSchema(schema)) {
  11145. return false;
  11146. }
  11147. if (this.kind() !== schema.name) {
  11148. return false;
  11149. }
  11150. const actuals = this.inputs();
  11151. const formals = schema.arguments;
  11152. if (actuals.length < formals.length) {
  11153. return false;
  11154. }
  11155. const type_env = new Map();
  11156. for (let i = 0; i < formals.length; i++) {
  11157. let formal = formals[i].type;
  11158. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  11159. if (!matched_type.success()) {
  11160. return false;
  11161. }
  11162. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  11163. if (resolved) {
  11164. formal = resolved;
  11165. }
  11166. if (!actuals[i].type().isSubtypeOf(formal)) {
  11167. return false;
  11168. }
  11169. }
  11170. if (!schema.is_vararg && actuals.length !== formals.length) {
  11171. return false;
  11172. }
  11173. return true;
  11174. }
  11175. mustBeNone() {
  11176. return this._kind === 'prim::AutogradZero' ||
  11177. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  11178. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  11179. }
  11180. maybeSchema() {
  11181. const op = this.maybeOperator();
  11182. if (op) {
  11183. return op.schema();
  11184. }
  11185. return null;
  11186. }
  11187. maybeOperator() {
  11188. if (!this._op) {
  11189. const candidates = torch._C.getAllOperatorsFor(this.kind());
  11190. for (const candidate of candidates) {
  11191. if (this.matches(candidate.schema())) {
  11192. this._op = candidate;
  11193. break;
  11194. }
  11195. }
  11196. }
  11197. return this._op;
  11198. }
  11199. getOperator() {
  11200. const maybe = this.maybeOperator();
  11201. if (maybe) {
  11202. return maybe;
  11203. }
  11204. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  11205. }
  11206. getOperation() {
  11207. return this.getOperator().getOperation(this);
  11208. }
  11209. isNondeterministic() {
  11210. const schema = this.maybeSchema();
  11211. if (!this.kind().startsWith('aten::')) {
  11212. return false;
  11213. }
  11214. if (!schema) {
  11215. return false;
  11216. }
  11217. const schema_info = new torch._C.SchemaInfo(schema);
  11218. if (this.hasNamedInput('train')) {
  11219. throw new python.Error('Not Implemented.');
  11220. // const value = constant_as<bool>(this.namedInput("train"));
  11221. // if (value) {
  11222. // schema_info.addArgumentValue('train', value);
  11223. // }
  11224. }
  11225. return schema_info.is_nondeterministic();
  11226. }
  11227. hasSideEffects() {
  11228. switch (this._kind) {
  11229. case 'prim::PythonOp':
  11230. case 'prim::IgnoredPythonOp':
  11231. case 'prim::Print':
  11232. case 'prim::RaiseException':
  11233. case 'aten::warn':
  11234. case 'aten::save':
  11235. case 'aten::manual_seed':
  11236. case 'prim::AddStatValue':
  11237. case 'prim::TimePoint':
  11238. case 'prim::CallFunction':
  11239. case 'prim::CallMethod':
  11240. case 'prim::BailoutTemplate':
  11241. case 'prim::BailOut':
  11242. case 'prim::rpc_async':
  11243. case 'prim::rpc_sync':
  11244. case 'prim::rpc_remote':
  11245. case 'aten::wait':
  11246. case 'cuda::set_stream':
  11247. case 'cuda::_set_device':
  11248. case 'cuda::_current_device':
  11249. case 'cuda::synchronize':
  11250. case 'prim::Enter':
  11251. case 'prim::Exit':
  11252. return true;
  11253. default:
  11254. break;
  11255. }
  11256. const op = this.maybeOperator();
  11257. if (!op) {
  11258. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  11259. return false;
  11260. }
  11261. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  11262. torch._C.TORCH_INTERNAL_ASSERT(
  11263. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  11264. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  11265. op.aliasAnalysisKind() === 'CONSERVATIVE');
  11266. }
  11267. switch (op.aliasAnalysisKind()) {
  11268. case 'PURE_FUNCTION':
  11269. case 'FROM_SCHEMA':
  11270. case 'INTERNAL_SPECIAL_CASE':
  11271. return false;
  11272. case 'CONSERVATIVE':
  11273. return true;
  11274. default:
  11275. break;
  11276. }
  11277. torch._C.TORCH_INTERNAL_ASSERT(false);
  11278. return false;
  11279. }
  11280. inputs() {
  11281. return this._inputs;
  11282. }
  11283. outputs() {
  11284. return this._outputs;
  11285. }
  11286. input(i) {
  11287. if (i === undefined) {
  11288. torch._C.AT_ASSERT(this._inputs.length === 1);
  11289. return this._inputs[0];
  11290. }
  11291. return this._inputs[i];
  11292. }
  11293. output(i) {
  11294. if (i === undefined) {
  11295. torch._C.AT_ASSERT(this._outputs.length === 1);
  11296. return this._outputs[0];
  11297. }
  11298. return this._outputs[i];
  11299. }
  11300. hasUses() {
  11301. for (const o of this.outputs()) {
  11302. if (o.uses().length > 0) {
  11303. return true;
  11304. }
  11305. }
  11306. return false;
  11307. }
  11308. blocks() {
  11309. return this._blocks;
  11310. }
  11311. insertInput(i, value) {
  11312. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  11313. this._op = null;
  11314. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  11315. const use = this.findUseForInput(use_itr);
  11316. use.offset += 1;
  11317. }
  11318. this._inputs.splice(i, 0, value);
  11319. value._uses.push(new torch.Use(this, i));
  11320. return value;
  11321. }
  11322. addInput(value) {
  11323. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  11324. this._op = null;
  11325. const use = new torch.Use(this, this._inputs.length);
  11326. value.uses().push(use);
  11327. this._inputs.push(value);
  11328. return value;
  11329. }
  11330. addOutput() {
  11331. const value = new torch.Value(this, this._outputs.length);
  11332. this._outputs.push(value);
  11333. return value;
  11334. }
  11335. addBlock() {
  11336. this._op = null;
  11337. this._blocks.push(new torch.Block(this.owningGraph(), this));
  11338. return this._blocks[this._blocks.length - 1];
  11339. }
  11340. get prev() {
  11341. return this._prev;
  11342. }
  11343. set prev(value) {
  11344. this._prev = value;
  11345. }
  11346. get next() {
  11347. return this._next;
  11348. }
  11349. set next(value) {
  11350. this._next = value;
  11351. }
  11352. insertBefore(n) {
  11353. if (!n.inBlockList()) {
  11354. throw new python.Error('Node not in block.');
  11355. }
  11356. this.insertAfter(n.prev);
  11357. return this;
  11358. }
  11359. insertAfter(n) {
  11360. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  11361. torch._C.AT_ASSERT(n.owningBlock());
  11362. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  11363. this._owning_block = n.owningBlock();
  11364. const next = n.next;
  11365. n.next = this;
  11366. this.prev = n;
  11367. this.next = next;
  11368. next.prev = this;
  11369. // this.assignTopoPosition();
  11370. return this;
  11371. }
  11372. allocNewInstance(g) {
  11373. return new torch.Node(g, this.kind());
  11374. }
  11375. cloneFrom(s) {
  11376. this._source_range = s._source_range;
  11377. if (s._scope && !s._scope.isBlank()) {
  11378. this._scope = s._scope;
  11379. }
  11380. this.copyAttributes(s);
  11381. this._callstack = s._callstack;
  11382. }
  11383. copyAttributes(rhs) {
  11384. this._values = new Map(rhs._values);
  11385. return this;
  11386. }
  11387. dropInput(i) {
  11388. torch._C.AT_ASSERT(i < this._inputs.length);
  11389. const input_node = this._inputs[i];
  11390. const use_it = this.findUseForInput(i);
  11391. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  11392. this._inputs[i] = null;
  11393. return input_node;
  11394. }
  11395. eraseOutput(i) {
  11396. torch._C.AT_ASSERT(i < this._outputs.length);
  11397. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  11398. this._op = null;
  11399. const n = this._outputs[i];
  11400. this._outputs.splice(i, 1);
  11401. this.owningGraph().freeValue(n);
  11402. for (let j = i; j < this._outputs.length; j++) {
  11403. this._outputs[j]._offset--;
  11404. }
  11405. }
  11406. eraseBlock(i) {
  11407. this._op = null;
  11408. const n = this._blocks[i];
  11409. this._blocks.splice(i, 1);
  11410. n.destroy();
  11411. }
  11412. findUseForInput(i) {
  11413. const input_uses = this._inputs[i]._uses;
  11414. for (const use_it of input_uses) {
  11415. if (use_it.user === this && use_it.offset === i) {
  11416. return use_it;
  11417. }
  11418. }
  11419. throw new python.Error('Input use not found.');
  11420. }
  11421. moveBefore(n) {
  11422. this.removeFromList();
  11423. this.insertBefore(n);
  11424. }
  11425. removeInput(i) {
  11426. this._op = null;
  11427. this.dropInput(i);
  11428. for (let j = i + 1; j < this._inputs.length; j++) {
  11429. const it = this.findUseForInput(j);
  11430. it.offset--;
  11431. }
  11432. this._inputs.splice(i, 1);
  11433. }
  11434. removeAllInputs() {
  11435. this._op = null;
  11436. for (let i = 0; i < this._inputs.length; i++) {
  11437. this.dropInput(i);
  11438. }
  11439. this._inputs = [];
  11440. }
  11441. inBlockList() {
  11442. return this.next !== null;
  11443. }
  11444. removeFromList() {
  11445. this._owning_block = null;
  11446. const next = this.next;
  11447. const prev = this.prev;
  11448. prev.next = next;
  11449. next.prev = prev;
  11450. this.next = null;
  11451. this.prev = null;
  11452. }
  11453. destroy() {
  11454. while (this.outputs().length > 0) {
  11455. this.eraseOutput(this.outputs().length - 1);
  11456. }
  11457. while (this.blocks().length > 0) {
  11458. this.eraseBlock(this.blocks().length - 1);
  11459. }
  11460. this.removeAllInputs();
  11461. if (this.inBlockList()) {
  11462. this.removeFromList();
  11463. }
  11464. this._graph.freeNode(this);
  11465. }
  11466. replaceAllUsesWith(n) {
  11467. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  11468. const nOutputs = this.outputs().length;
  11469. for (let i = 0; i < nOutputs; i++) {
  11470. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  11471. }
  11472. }
  11473. s_(name, value) {
  11474. this._values.set(name, [value, 's']);
  11475. return this;
  11476. }
  11477. s(name) {
  11478. return this._values.get(name)[0];
  11479. }
  11480. ss_(name, value) {
  11481. this._values.set(name, [value, 'ss']);
  11482. return this;
  11483. }
  11484. ss(name) {
  11485. return this._values.get(name)[0];
  11486. }
  11487. i_(name, value) {
  11488. this._values.set(name, [value, 'i']);
  11489. return this;
  11490. }
  11491. i(name) {
  11492. return this._values.get(name)[0];
  11493. }
  11494. f_(name, value) {
  11495. this._values.set(name, [value, 'f']);
  11496. return this;
  11497. }
  11498. f(name) {
  11499. return this._values.get(name)[0];
  11500. }
  11501. t_(name, value) {
  11502. this._values.set(name, [value, 't']);
  11503. return this;
  11504. }
  11505. t(name) {
  11506. return this._values.get(name)[0];
  11507. }
  11508. tys_(name, value) {
  11509. this._values.set(name, [value, 'tys']);
  11510. return this;
  11511. }
  11512. tys(name) {
  11513. return this._values.get(name)[0];
  11514. }
  11515. ival_(name, value) {
  11516. this._values.set(name, [value, 'ival']);
  11517. return this;
  11518. }
  11519. ival(name) {
  11520. return this._values.get(name)[0];
  11521. }
  11522. hasAttribute(name) {
  11523. return this._values.has(name);
  11524. }
  11525. hasAttributes() {
  11526. return this._values.size > 0;
  11527. }
  11528. attributeNames() {
  11529. return Array.from(this._values.keys());
  11530. }
  11531. kindOf(name) {
  11532. return this._values.get(name)[1];
  11533. }
  11534. setSourceRange(r) {
  11535. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  11536. this._source_range = r;
  11537. return this;
  11538. }
  11539. sourceRange() {
  11540. if (this._source_range) {
  11541. return this._source_range;
  11542. }
  11543. return new torch._C.SourceRange();
  11544. }
  11545. print_attributes(out, ignore_subgraph) {
  11546. ignore_subgraph = ignore_subgraph || false;
  11547. out.write('[');
  11548. const names = this.attributeNames();
  11549. for (let i = 0; i < names.length; i++) {
  11550. const name = names[i];
  11551. if (ignore_subgraph && name === 'Subgraph') {
  11552. continue;
  11553. }
  11554. if (i > 0) {
  11555. out.write(', ');
  11556. }
  11557. out.write(`${name}=`);
  11558. this.printAttrValue(out, name);
  11559. }
  11560. out.write(']');
  11561. }
  11562. printTypeList(out, items) {
  11563. out.write('[');
  11564. for (let i = 0; i < items.length; i++) {
  11565. const item = items[i];
  11566. if (i++ > 0) {
  11567. out.write(', ');
  11568. }
  11569. out.write(item.str());
  11570. }
  11571. out.write(']');
  11572. }
  11573. printAttrValue(out, name) {
  11574. const kind = this.kindOf(name);
  11575. switch (kind) {
  11576. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  11577. case 'ss': case 'ival': case 'ty':
  11578. out.write(this[kind](name));
  11579. break;
  11580. case 's':
  11581. out.write(`"${this.s(name)}"`);
  11582. break;
  11583. case 't':
  11584. out.write(`"{}"`);
  11585. break;
  11586. case 'ts': out.write('[<Tensors>]'); break;
  11587. case 'g': out.write('[<Graph>]'); break;
  11588. case 'gs': out.write('[<Graphs>]'); break;
  11589. case 'tys': this.printTypeList(out, this.tys(name)); break;
  11590. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  11591. }
  11592. }
  11593. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  11594. print_source_locations = print_source_locations === false ? false : true;
  11595. print_attributes = print_attributes === false ? false : true;
  11596. print_scopes = print_scopes === false ? false : true;
  11597. print_body = print_body === false ? false : true;
  11598. const outs = this.outputs();
  11599. torch._C.indent(out, level);
  11600. torch._C.const_value_list_with_types(out, outs, ', ');
  11601. out.write(' = ');
  11602. if (this.kind() === 'prim::PythonOp') {
  11603. throw new python.Error('Not implemented.');
  11604. } else if (this.hasAttribute('Subgraph') && groups) {
  11605. throw new python.Error('Not implemented.');
  11606. } else {
  11607. out.write(this.kind());
  11608. if (print_attributes && this.hasAttributes()) {
  11609. this.print_attributes(out);
  11610. }
  11611. }
  11612. out.write('(');
  11613. torch._C.printValueRefs(out, this.inputs());
  11614. out.write(')');
  11615. if (print_scopes) {
  11616. //
  11617. }
  11618. if (print_source_locations) {
  11619. let r = this.sourceRange();
  11620. if (r.source()) {
  11621. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  11622. if (orig) {
  11623. r = orig;
  11624. }
  11625. }
  11626. const file_line_col = r.file_line_col();
  11627. if (file_line_col !== null) {
  11628. const [filename, line, col] = file_line_col;
  11629. out.write(` # ${filename}:${line}:${col}`);
  11630. }
  11631. }
  11632. if (!print_body) {
  11633. return out;
  11634. }
  11635. out.write('\n');
  11636. for (let i = 0; i < this.blocks().length; i++) {
  11637. const b = this.blocks()[i];
  11638. torch._C.indent(out, level + 1);
  11639. out.write(`block${i}(`);
  11640. torch._C.const_value_list_with_types(out, b.inputs());
  11641. out.write('):\n');
  11642. for (const nested of b.nodes()) {
  11643. nested.print(out, level + 2, groups);
  11644. }
  11645. torch._C.indent(out, level + 2);
  11646. out.write('-> (');
  11647. torch._C.printValueRefs(out, b.outputs());
  11648. out.write(')\n');
  11649. }
  11650. return out;
  11651. }
  11652. toString() {
  11653. const out = new io.StringIO();
  11654. this.print(out, 0, true);
  11655. return out.toString();
  11656. }
  11657. });
  11658. this.registerType('torch.Value', class {
  11659. constructor(node, offset) {
  11660. this._node = node;
  11661. this._offset = offset;
  11662. this._unique = node._graph._next_unique++;
  11663. this._uses = [];
  11664. this._node._graph.all_values.add(this);
  11665. }
  11666. unique() {
  11667. return this._unique;
  11668. }
  11669. node() {
  11670. return this._node;
  11671. }
  11672. owningGraph() {
  11673. return this._node.owningGraph();
  11674. }
  11675. uses() {
  11676. return this._uses;
  11677. }
  11678. hasUses() {
  11679. return this._uses.length > 0;
  11680. }
  11681. mustBeNone() {
  11682. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  11683. }
  11684. mustNotBeNone() {
  11685. return this._node.kind() !== 'prim::AutogradAdd' &&
  11686. this.type() !== torch.NoneType.get() &&
  11687. !(this.type() instanceof torch.OptionalType) &&
  11688. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  11689. }
  11690. isValidName(name) {
  11691. if (name.length === 0) {
  11692. return true;
  11693. }
  11694. if (torch._C.isNumber(name)) {
  11695. return false;
  11696. }
  11697. return true;
  11698. }
  11699. hasDebugName() {
  11700. return this._unique_name && this._unique_name.length > 0;
  11701. }
  11702. setDebugName(name) {
  11703. if (!this.isValidName(name)) {
  11704. throw new python.Error(`Invalid name '${name}'.`);
  11705. }
  11706. const names = this.node().owningGraph()._unique_names;
  11707. if (this.hasDebugName()) {
  11708. names.delete(this._unique_name);
  11709. this._unique_name = '';
  11710. }
  11711. if (!name) {
  11712. return this;
  11713. }
  11714. const old_owner_of_name = names.get(name);
  11715. if (old_owner_of_name) {
  11716. let suffix = 1;
  11717. let name_base = name;
  11718. const last_dot_pos = name.lastIndexOf('.');
  11719. if (last_dot_pos !== -1) {
  11720. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  11721. suffix = Number(name.substring(last_dot_pos + 1));
  11722. name_base = name.substring(0, last_dot_pos);
  11723. }
  11724. }
  11725. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  11726. if (names_suffixes.has(name_base)) {
  11727. suffix = Math.max(suffix, names_suffixes.get(name_base));
  11728. }
  11729. let replacement_name = null;
  11730. do {
  11731. replacement_name = `${name_base}.${suffix++}`;
  11732. } while (names.has(replacement_name));
  11733. names_suffixes.set(name_base, suffix);
  11734. old_owner_of_name.setDebugName(replacement_name);
  11735. }
  11736. names.set(name, this);
  11737. this._unique_name = name;
  11738. return this;
  11739. }
  11740. debugName() {
  11741. if (this.hasDebugName()) {
  11742. return this._unique_name;
  11743. }
  11744. return this.unique().toString();
  11745. }
  11746. type() {
  11747. return this._type;
  11748. }
  11749. setType(type) {
  11750. // torch._C.AT_ASSERT(type instanceof torch.Type);
  11751. if (type instanceof torch._C.DynamicType) {
  11752. type = type.fallback();
  11753. }
  11754. this._type = type;
  11755. for (const use of this._uses) {
  11756. use.user._op = null;
  11757. }
  11758. return this;
  11759. }
  11760. set value(value) { // remove
  11761. if (value instanceof torch.Value) {
  11762. throw new python.Error('Value cannot be a value.');
  11763. }
  11764. this._value = value;
  11765. }
  11766. get value() { // remove
  11767. return this._value;
  11768. }
  11769. replaceFirstUseWith(newValue) {
  11770. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  11771. const [u] = this.uses();
  11772. u.user._inputs[u.offset] = newValue;
  11773. newValue._uses.push(u);
  11774. this._uses.shift();
  11775. }
  11776. replaceAllUsesWith(newValue) {
  11777. while (this.uses().length > 0) {
  11778. this.replaceFirstUseWith(newValue);
  11779. }
  11780. }
  11781. copyMetadata(from) {
  11782. this.setType(from.type());
  11783. if (from.hasDebugName()) {
  11784. this.setDebugName(from.debugName());
  11785. }
  11786. return this;
  11787. }
  11788. toString() {
  11789. return `${this.debugName()} : ${this.type().toString()}`;
  11790. }
  11791. });
  11792. this.registerType('torch.Use', class {
  11793. constructor(user, offset) {
  11794. this.user = user;
  11795. this.offset = offset;
  11796. }
  11797. });
  11798. this.registerType('torch._C.IValue', class {
  11799. constructor(value, tag) {
  11800. this.value = value;
  11801. if (tag) {
  11802. this.tag = tag;
  11803. } else if (value === undefined) {
  11804. this.tag = 'None';
  11805. this.value = 'None';
  11806. } else if (typeof value === 'boolean') {
  11807. this.tag = 'Bool';
  11808. } else if (typeof value === 'string') {
  11809. this.tag = 'String';
  11810. } else if (value instanceof torch.Tensor) {
  11811. this.tag = 'Tensor';
  11812. } else if (value instanceof torch.ScriptObject) {
  11813. this.tag = 'Object';
  11814. } else if (Array.isArray(value)) {
  11815. this.tag = 'GenericList';
  11816. } else if (value instanceof torch._C.Tuple) {
  11817. this.tag = 'Tuple';
  11818. } else if (value instanceof torch.device) {
  11819. this.tag = 'Device';
  11820. } else if (Number.isInteger(value)) {
  11821. this.tag = 'Int';
  11822. } else if (typeof value === 'number') {
  11823. this.tag = 'Double';
  11824. } else {
  11825. throw new python.Error('Unsupported type.');
  11826. }
  11827. }
  11828. isNone() {
  11829. return this.tag === 'None';
  11830. }
  11831. isBool() {
  11832. return this.tag === 'Bool';
  11833. }
  11834. toBool() {
  11835. return this.value;
  11836. }
  11837. isObject() {
  11838. return this.tag === 'Object';
  11839. }
  11840. toObject() {
  11841. return this.value;
  11842. }
  11843. isTensor() {
  11844. return this.tag === 'Tensor';
  11845. }
  11846. toTensor() {
  11847. return this.value;
  11848. }
  11849. isDouble() {
  11850. return this.tag === 'Double';
  11851. }
  11852. toDouble() {
  11853. return this.value;
  11854. }
  11855. isComplexDouble() {
  11856. return this.tag === 'ComplexDouble';
  11857. }
  11858. isInt() {
  11859. return this.tag === 'Int';
  11860. }
  11861. toInt() {
  11862. if (this.isInt()) {
  11863. return this.value;
  11864. } else if (this.isSymInt()) {
  11865. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  11866. }
  11867. throw new python.Error('Expected int.');
  11868. }
  11869. isString() {
  11870. return this.tag === 'String';
  11871. }
  11872. toStringRef() {
  11873. return this.value;
  11874. }
  11875. isList() {
  11876. return this.tag === 'GenericList';
  11877. }
  11878. toList() {
  11879. return this.value;
  11880. }
  11881. isDevice() {
  11882. return this.tag === 'Device';
  11883. }
  11884. toDevice() {
  11885. return this.value;
  11886. }
  11887. isGenerator() {
  11888. return this.tag === 'Generator';
  11889. }
  11890. isStream() {
  11891. return this.tag === 'Stream';
  11892. }
  11893. isEnum() {
  11894. return this.tag === 'Enum';
  11895. }
  11896. isTuple() {
  11897. return this.tag === 'Tuple';
  11898. }
  11899. toTupleRef() {
  11900. return this.value;
  11901. }
  11902. isCustomClass() {
  11903. return torch._C.isCustomClass(this);
  11904. }
  11905. equals(rhs) {
  11906. const lhs = this;
  11907. switch (lhs.tag) {
  11908. case 'None': return rhs.isNone();
  11909. case 'Bool': return rhs.isBool() && lhs.toBool() === rhs.toBool();
  11910. case 'Int': return rhs.isInt() && lhs.toInt() === rhs.toInt();
  11911. case 'Double': return rhs.isDouble() && lhs.toDouble() === rhs.toDouble();
  11912. case 'String': return rhs.isString() && lhs.toString() === rhs.toString();
  11913. case 'Tensor': return rhs.isTensor() && lhs.toTensor() === rhs.toTensor();
  11914. case 'Object': return rhs.isObject() && lhs.toObject() === rhs.toObject();
  11915. case 'Device': return rhs.isObject() && lhs.toDevice() === rhs.toDevice();
  11916. case 'GenericList': {
  11917. if (rhs.isList()) {
  11918. const a = lhs.toList();
  11919. const b = rhs.toList();
  11920. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  11921. }
  11922. return false;
  11923. }
  11924. default: throw new python.Error(`IValue.equals() not implemented for '${lhs.tag}.`);
  11925. }
  11926. }
  11927. is(rhs) {
  11928. const lhs = this;
  11929. return lhs.equals(rhs);
  11930. }
  11931. type() {
  11932. switch (this.tag) {
  11933. case 'Int': return torch.IntType.get();
  11934. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  11935. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  11936. }
  11937. }
  11938. });
  11939. this.registerFunction('torch._C.indent', (out, level) => {
  11940. for (let i = 0; i < level; i++) {
  11941. out.write(' ');
  11942. }
  11943. return out;
  11944. });
  11945. this.registerFunction('torch._C.printValueRef', (out, n) => {
  11946. out.write(`%${n.debugName()}`);
  11947. });
  11948. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  11949. for (let i = 0; i < nodes.length; i++) {
  11950. const n = nodes[i];
  11951. if (i > 0) {
  11952. out.write(', ');
  11953. }
  11954. torch._C.printValueRef(out, n);
  11955. }
  11956. return out;
  11957. });
  11958. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  11959. for (let i = 0; i < values.length; i++) {
  11960. const n = values[i];
  11961. if (i > 0) {
  11962. out.write(delim);
  11963. }
  11964. torch._C.printValueRef(out, n);
  11965. out.write(' : ');
  11966. out.write(n.type().str());
  11967. }
  11968. });
  11969. this.register('torch.jit._script');
  11970. this.register('torch.jit._trace');
  11971. this.registerType('torch._C.Parser', class {
  11972. constructor(source) {
  11973. this.L = source;
  11974. }
  11975. parse() {
  11976. const p = ast.parse(this.L.text_str(), this.L.filename());
  11977. return p;
  11978. }
  11979. parseExp() {
  11980. const expr = ast.parse(this.L.text_str());
  11981. return expr.body[0].value;
  11982. }
  11983. });
  11984. this.registerType('torch._C.StringCordView', class {
  11985. });
  11986. this.registerType('torch._C.Source', class {
  11987. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  11988. if (text_view instanceof Uint8Array) {
  11989. const decoder = new TextDecoder('utf-8');
  11990. this._text_view = decoder.decode(text_view);
  11991. } else if (typeof text_view === 'string') {
  11992. this._text_view = text_view;
  11993. } else {
  11994. throw new python.Error('Invalid text view.');
  11995. }
  11996. this._filename = filename;
  11997. this._starting_line_no = starting_line_no;
  11998. this._gen_ranges = gen_ranges;
  11999. this.calc_line_start_offsets();
  12000. }
  12001. text_str() {
  12002. return this._text_view;
  12003. }
  12004. size() {
  12005. return this._text_view.length;
  12006. }
  12007. filename() {
  12008. return this._filename;
  12009. }
  12010. calc_line_start_offsets() {
  12011. let pos = 0;
  12012. this._line_starting_offsets = [0];
  12013. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  12014. pos += 1;
  12015. this._line_starting_offsets.push(pos);
  12016. }
  12017. }
  12018. offset_for_line(line) {
  12019. return this._line_starting_offsets[line];
  12020. }
  12021. lineno_for_offset(offset) {
  12022. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  12023. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  12024. }
  12025. lineno_to_source_lineno(lineno) {
  12026. if (this._filename) {
  12027. return lineno + this._starting_line_no;
  12028. }
  12029. return lineno;
  12030. }
  12031. findSourceRangeThatGenerated(range) {
  12032. if (!this._gen_ranges) {
  12033. return null;
  12034. }
  12035. return this._gen_ranges.findSourceRangeThatGenerated(range);
  12036. }
  12037. });
  12038. this.registerType('torch._C.SourceRange', class {
  12039. constructor(...args) {
  12040. if (args.length === 0) {
  12041. this._source_view = null;
  12042. } else if (args.length === 2) {
  12043. let node = null;
  12044. [this._source_view, node] = args;
  12045. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  12046. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  12047. } else if (args.length === 3) {
  12048. [this._source_view, this._start, this._end] = args;
  12049. } else {
  12050. throw new python.Error('Not implemented.');
  12051. }
  12052. }
  12053. source() {
  12054. return this._source_view;
  12055. }
  12056. file_line_col() {
  12057. if (!this._source_view || this.source().filename() === null) {
  12058. return null;
  12059. }
  12060. const lineno = this._source_view.lineno_for_offset(this._start);
  12061. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  12062. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  12063. }
  12064. start() {
  12065. return this._start;
  12066. }
  12067. toString() {
  12068. const loc = this.file_line_col();
  12069. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  12070. }
  12071. });
  12072. this.registerType('torch._C.QualifiedName', class {
  12073. constructor(...args) {
  12074. let name = null;
  12075. if (args.length === 1 && typeof args[0] === 'string') {
  12076. [name] = args;
  12077. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  12078. name = args[0].join('.');
  12079. } else {
  12080. name = `${args[0].qualifiedName()}.${args[1]}`;
  12081. }
  12082. const index = name.lastIndexOf('.');
  12083. this._qualifiedName = name;
  12084. this._prefix = index === -1 ? '' : name.substring(0, index);
  12085. this._name = index === -1 ? name : name.substring(index + 1);
  12086. }
  12087. qualifiedName() {
  12088. return this._qualifiedName; // "foo.bar.baz"
  12089. }
  12090. prefix() {
  12091. return this._prefix; // "foo.bar"
  12092. }
  12093. name() {
  12094. return this._name; // "baz"
  12095. }
  12096. atoms() {
  12097. return this._qualifiedName.split('.');
  12098. }
  12099. });
  12100. this.registerType('torch._C.Resolver', class {
  12101. resolveValue() {
  12102. throw new python.Error('Not implemented.');
  12103. }
  12104. resolveType() {
  12105. throw new python.Error('Not implemented.');
  12106. }
  12107. });
  12108. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  12109. torch._C.customClasses = torch._C.customClasses || new Map();
  12110. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  12111. const name = class_type.name().qualifiedName();
  12112. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  12113. torch._C.customClasses.set(name, class_type);
  12114. });
  12115. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  12116. torch._C.customClasses = torch._C.customClasses || new Map();
  12117. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  12118. return ret;
  12119. });
  12120. this.registerFunction('torch._C.isCustomClass', (v) => {
  12121. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  12122. });
  12123. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  12124. constructor(cu, constant_table, source_loader, version) {
  12125. super();
  12126. this._cu = cu;
  12127. this._constant_table = constant_table;
  12128. this._source_loader = source_loader;
  12129. this._version = version;
  12130. this._loaded_sources = new Set();
  12131. this._sources = new Map();
  12132. const sources = this._sources;
  12133. ast.AST.prototype.range = function() {
  12134. if (!this._range) {
  12135. if (sources.has(this.filename)) {
  12136. const source_view = sources.get(this.filename);
  12137. this._range = new torch._C.SourceRange(source_view, this);
  12138. } else {
  12139. this._range = new torch._C.SourceRange();
  12140. }
  12141. }
  12142. return this._range;
  12143. };
  12144. this._to_be_defined = new Map();
  12145. this._env = new Map([
  12146. ['torch', new torch._C.BuiltinModule('aten', version)],
  12147. ['ops', new torch._C.OpsValue(version)],
  12148. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  12149. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  12150. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  12151. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  12152. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  12153. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  12154. ]);
  12155. }
  12156. loadType(name) {
  12157. const type_parser = new torch._C.ScriptTypeParser(this);
  12158. return type_parser.parseType(name.qualifiedName());
  12159. }
  12160. resolveType(name) {
  12161. name = new torch._C.QualifiedName(name);
  12162. return this.findNamedType(name);
  12163. }
  12164. resolveValue(name, m, loc) {
  12165. if (this._env.has(name)) {
  12166. return this._env.get(name);
  12167. }
  12168. const graph = m.graph();
  12169. switch (name) {
  12170. case 'inf': return new torch._C.SimpleValue(graph.insertConstant('std::numeric_limits<double>::infinity()', loc));
  12171. case 'nan': return new torch._C.SimpleValue(graph.insertConstant('std::numeric_limits<double>::quiet_NaN()', loc));
  12172. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  12173. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  12174. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  12175. default: return null;
  12176. }
  12177. }
  12178. findNamedType(name) {
  12179. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  12180. if (custom_class) {
  12181. return custom_class;
  12182. }
  12183. this.parseSourceIfNeeded(name.prefix());
  12184. const key = name.qualifiedName();
  12185. const it = this._to_be_defined.get(key);
  12186. if (it && it instanceof ast.ClassDef) {
  12187. this._to_be_defined.delete(key);
  12188. this.importNamedType(name.prefix(), it);
  12189. }
  12190. return this._cu.get_type(name);
  12191. }
  12192. importNamedType(qualifier, class_def) {
  12193. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  12194. if (class_def.bases.length === 0) {
  12195. this.importClass(qualified_name, class_def, false);
  12196. return;
  12197. }
  12198. const superclass_name = class_def.bases[0].id;
  12199. if (superclass_name === 'Module') {
  12200. this.importClass(qualified_name, class_def, true);
  12201. } else if (superclass_name === 'NamedTuple') {
  12202. this.importNamedTuple(qualified_name, class_def);
  12203. } else if (superclass_name === 'Interface') {
  12204. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  12205. } else if (superclass_name === 'ModuleInterface') {
  12206. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  12207. } else if (superclass_name === 'Enum') {
  12208. // importEnum(qualified_name, class_def);
  12209. } else {
  12210. throw new python.Error('TorchScript does not support class inheritance.');
  12211. }
  12212. }
  12213. importClass(qualified_classname, class_def, is_module) {
  12214. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  12215. return;
  12216. }
  12217. const parameter_names = new Set();
  12218. const buffer_names = new Set();
  12219. const methods = [];
  12220. const method_resolvers = [];
  12221. const attributes = [];
  12222. const constants = [];
  12223. const pre_hook_names = new Set();
  12224. const pre_hook_def_map = new Map();
  12225. const hook_names = new Set();
  12226. const hook_def_map = new Map();
  12227. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  12228. for (const stmt of class_def.body) {
  12229. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  12230. let target = null;
  12231. let annotation = null;
  12232. let value = null;
  12233. if (stmt instanceof ast.Assign) {
  12234. [target] = stmt.targets;
  12235. value = stmt.value;
  12236. } else {
  12237. target = stmt.target;
  12238. annotation = stmt.annotation;
  12239. value = stmt.value;
  12240. }
  12241. if (target instanceof ast.Name) {
  12242. const name = this._cu.execution.identifier(target);
  12243. switch (name) {
  12244. case '__annotations__': {
  12245. continue;
  12246. }
  12247. case '__parameters__': {
  12248. for (const elt of value.elts) {
  12249. parameter_names.add(elt.value);
  12250. }
  12251. break;
  12252. }
  12253. case '__buffers__': {
  12254. for (const elt of value.elts) {
  12255. buffer_names.add(elt.value);
  12256. }
  12257. break;
  12258. }
  12259. case '__forward_pre_hooks__': {
  12260. for (const elt of value.elts) {
  12261. pre_hook_names.add(elt.value);
  12262. }
  12263. break;
  12264. }
  12265. case '__forward_hooks__': {
  12266. for (const elt of value.elts) {
  12267. hook_names.add(elt.value);
  12268. }
  12269. break;
  12270. }
  12271. default: {
  12272. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  12273. if (fixed_up) {
  12274. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  12275. } else if (value) {
  12276. constants.push({ name, value, annotation });
  12277. } else {
  12278. attributes.push({ name, value, annotation });
  12279. }
  12280. break;
  12281. }
  12282. }
  12283. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  12284. const name = target.slice.value;
  12285. attributes.push({ name, value, annotation: stmt.value });
  12286. continue;
  12287. } else {
  12288. throw new python.Error('Unexpected statement kind in module metadata.');
  12289. }
  12290. } else if (stmt instanceof ast.FunctionDef) {
  12291. const def = stmt;
  12292. const def_name = def.name;
  12293. if (pre_hook_names.has(def_name)) {
  12294. pre_hook_def_map.set(def_name, def);
  12295. } else if (hook_names.has(def_name)) {
  12296. hook_def_map.set(def_name, def);
  12297. } else {
  12298. methods.push(def);
  12299. method_resolvers.push(this);
  12300. }
  12301. } else {
  12302. throw new python.Error('Unexpected statement kind in class body.');
  12303. }
  12304. }
  12305. const type_parser = new torch._C.ScriptTypeParser(this);
  12306. for (const assign of attributes) {
  12307. const name = assign.name;
  12308. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  12309. const is_parameter = parameter_names.has(name);
  12310. const is_buffer = buffer_names.has(name);
  12311. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  12312. }
  12313. for (const constant of constants) {
  12314. class_type.addConstant(constant.name, constant.value);
  12315. }
  12316. this._cu.register_type(class_type);
  12317. const self = new torch._C.SimpleSelf(class_type);
  12318. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  12319. }
  12320. importNamedTuple(qualified_name, named_tuple_def) {
  12321. const type_parser = new torch._C.ScriptTypeParser(this);
  12322. const field_names = [];
  12323. const field_types = [];
  12324. const field_defaults = [];
  12325. for (const stmt of named_tuple_def.body) {
  12326. if (stmt instanceof ast.AnnAssign === false) {
  12327. throw new python.Error('Unexpected statement in NamedTuple body.');
  12328. }
  12329. const assign = stmt;
  12330. const target = this._cu.execution.identifier(stmt.target);
  12331. // const annotation = this._cu.execution.type(stmt.annotation);
  12332. const type = type_parser.parseTypeFromExpr(assign.annotation);
  12333. field_names.push(target);
  12334. // field_types.push(annotation);
  12335. field_types.push(type);
  12336. }
  12337. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  12338. this._cu.register_type(tt);
  12339. }
  12340. importFunction(qualifier, def) {
  12341. const definitions = [def];
  12342. const resolvers = [this];
  12343. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  12344. }
  12345. parseSourceIfNeeded(qualifier) {
  12346. if (!qualifier || this._loaded_sources.has(qualifier)) {
  12347. return;
  12348. }
  12349. this._loaded_sources.add(qualifier);
  12350. const src = this._source_loader(qualifier);
  12351. if (!src) {
  12352. return;
  12353. }
  12354. this._sources.set(src.filename(), src);
  12355. const p = new torch._C.Parser(src);
  12356. const L = p.parse();
  12357. this.parsePossibleVersionNumber(p);
  12358. for (const stmt of L.body) {
  12359. if (stmt instanceof ast.ClassDef) {
  12360. const name = `${qualifier}.${stmt.name}`;
  12361. this._to_be_defined.set(name, stmt);
  12362. } else if (stmt instanceof ast.FunctionDef) {
  12363. const name = `${qualifier}.${stmt.name}`;
  12364. this._to_be_defined.set(name, stmt);
  12365. }
  12366. }
  12367. }
  12368. parsePossibleVersionNumber(/* p */) {
  12369. }
  12370. parseImports(/* p */) {
  12371. }
  12372. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  12373. const replacements = new Map([
  12374. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  12375. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  12376. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  12377. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  12378. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  12379. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  12380. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  12381. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  12382. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  12383. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  12384. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  12385. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  12386. ]);
  12387. const mangleRe = /\.___torch_mangle_\d+/g;
  12388. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  12389. if (replacements.has(demangled_classname)) {
  12390. const lhs = assign.target;
  12391. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  12392. return null;
  12393. }
  12394. const type = assign.annotation.id;
  12395. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  12396. if (lhs.id === attr_name && type === expected_type) {
  12397. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  12398. const typename_expr = p.parseExp();
  12399. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  12400. }
  12401. }
  12402. return null;
  12403. }
  12404. LEGACY_import_methods(mod, src) {
  12405. const self = new torch._C.SimpleSelf(mod.type());
  12406. const prefix = mod.type().name();
  12407. const p = new torch._C.Parser(src);
  12408. const L = p.parse();
  12409. this.parsePossibleVersionNumber(L);
  12410. this.parseImports(L);
  12411. const definitions = [];
  12412. const resolvers = [];
  12413. for (const def of L.body) {
  12414. if (def instanceof ast.FunctionDef) {
  12415. definitions.push(def);
  12416. resolvers.push(this);
  12417. }
  12418. }
  12419. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  12420. }
  12421. findFunction(name) {
  12422. this.parseSourceIfNeeded(name.prefix());
  12423. const key = name.qualifiedName();
  12424. const it = this._to_be_defined.get(key);
  12425. if (it && it instanceof ast.FunctionDef) {
  12426. this._to_be_defined.delete(key);
  12427. this.importFunction(name.prefix(), it);
  12428. }
  12429. return this._cu.find_function(name);
  12430. }
  12431. });
  12432. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  12433. constructor(otherResolver, functionTable) {
  12434. super();
  12435. this._otherResolver = otherResolver;
  12436. this._functionTable = functionTable;
  12437. }
  12438. resolveValue(name, m, loc) {
  12439. const it = this._functionTable.get(name);
  12440. if (it) {
  12441. return new torch._C.FunctionValue(it);
  12442. }
  12443. return this._otherResolver.resolveValue(name, m, loc);
  12444. }
  12445. resolveType(name, loc) {
  12446. return this._otherResolver.resolveType(name, loc);
  12447. }
  12448. });
  12449. this.registerType('torch._C.SourceRangeDeserializer', class {
  12450. constructor(text_table) {
  12451. this.cached_sources = new Map();
  12452. this._text_table = text_table || [];
  12453. }
  12454. deserialize(iv) {
  12455. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  12456. const [file, start, end] = iv;
  12457. const source = this.deserialize_source(file);
  12458. return new torch._C.SourceRange(source, start, end);
  12459. }
  12460. deserialize_source(iv) {
  12461. const tup = iv;
  12462. if (this.cached_sources.has(tup)) {
  12463. return this.cached_sources.get(tup);
  12464. }
  12465. let source = null;
  12466. const tup_elems = tup;
  12467. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  12468. if (this._text_table.length > 0) {
  12469. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  12470. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  12471. const filename = this._text_table[fnameIndex];
  12472. const pieces = [];
  12473. const strs = [];
  12474. for (const i of textIndex) {
  12475. pieces.push(this._text_table[i]);
  12476. strs.push(this._text_table[i]);
  12477. }
  12478. // const str_cord = new torch._C.StringCordView(pieces, strs);
  12479. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  12480. } else {
  12481. const [text, filename, starting_line_no] = tup_elems;
  12482. source = new torch._C.Source(text, filename, starting_line_no);
  12483. }
  12484. this.cached_sources.set(tup, source);
  12485. return source;
  12486. }
  12487. });
  12488. this.registerType('torch._C.SourceRangeUnpickler', class {
  12489. });
  12490. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  12491. constructor (data) {
  12492. super();
  12493. this.data = data;
  12494. this.deserializer = null;
  12495. this.unpickled_records = null;
  12496. }
  12497. unpickle() {
  12498. if (this.unpickled_records) {
  12499. return;
  12500. }
  12501. const unpickler = new pickle.Unpickler(this.data);
  12502. const ivalues = unpickler.load();
  12503. torch._C.TORCH_CHECK(ivalues.length > 0);
  12504. this.unpickled_records = [];
  12505. let lines = null;
  12506. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  12507. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  12508. /* eslint-disable prefer-destructuring */
  12509. lines = ivalues[2];
  12510. /* eslint-enable prefer-destructuring */
  12511. } else {
  12512. this.deserializer = new torch._C.SourceRangeDeserializer();
  12513. lines = ivalues;
  12514. }
  12515. for (const tup_elems of lines) {
  12516. const [offset, range] = tup_elems;
  12517. const source_range = this.deserializer.deserialize(range);
  12518. this.unpickled_records.push([offset, source_range]);
  12519. }
  12520. }
  12521. findSourceRangeThatGenerated(range) {
  12522. this.unpickle();
  12523. const start = range.start();
  12524. const records = this.unpickled_records;
  12525. for (let i = 0; i < records.length; i++) {
  12526. const [offset, target] = records[i];
  12527. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  12528. if (start >= offset && start < next) {
  12529. return target;
  12530. }
  12531. }
  12532. return null;
  12533. }
  12534. });
  12535. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  12536. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  12537. });
  12538. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  12539. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  12540. if (!reader.has_record(path)) {
  12541. return null;
  12542. }
  12543. const stream = reader.get_record(path);
  12544. let gen_ranges = null;
  12545. const debug_file = `${path}.debug_pkl`;
  12546. if (reader.has_record(debug_file)) {
  12547. const debug_stream = reader.get_record(debug_file);
  12548. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  12549. }
  12550. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  12551. });
  12552. this.registerType('torch._C.ScriptModuleDeserializer', class {
  12553. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  12554. this._compilation_unit = cu;
  12555. this._reader = reader;
  12556. this._storage_context = storage_context;
  12557. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  12558. this._pickle_dir_prefix = pickle_dir_prefix || '';
  12559. this._tensor_dir_prefix = tensor_dir_prefix || '';
  12560. this._constant_table = [];
  12561. const SourceLoader = (qualifier) => {
  12562. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  12563. };
  12564. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  12565. }
  12566. deserialize() {
  12567. const execution = this._compilation_unit.execution;
  12568. const code_prefix = this._code_prefix;
  12569. for (const name of this._reader.get_all_records()) {
  12570. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  12571. const file = name.substring(code_prefix.length);
  12572. const stream = this._reader.get_record(name);
  12573. const buffer = stream.peek();
  12574. execution.add(file, buffer);
  12575. }
  12576. }
  12577. const torch = execution.import('torch');
  12578. execution.builtins.torch = torch;
  12579. execution.builtins.Tensor = torch.Tensor;
  12580. execution.builtins.ops = torch.ops;
  12581. execution.builtins.inf = torch.inf;
  12582. execution.builtins.CONSTANTS = {};
  12583. execution._resolver = this._source_importer;
  12584. const known_types = [
  12585. { name: '__torch__.torch.classes._nnapi.Compilation', methods: [
  12586. '__init__(__torch__.torch.classes._nnapi.Compilation self) -> NoneType',
  12587. 'init(__torch__.torch.classes._nnapi.Compilation self, Tensor serialized_model_tensor, Tensor[] parameter_buffers) -> NoneType',
  12588. 'init2(__torch__.torch.classes._nnapi.Compilation self, Tensor serialized_model_tensor, Tensor[] parameter_buffers, int compilation_preference, bool relax_f32_to_f16) -> NoneType',
  12589. 'run(__torch__.torch.classes._nnapi.Compilation self, Tensor[] inputs, Tensor[] outputs) -> NoneType'
  12590. ] },
  12591. { name: '__torch__.torch.classes.quantized.Conv2dPackedParamsBase', attributes: 'Tensor weight, Tensor bias, int[] stride, int[] padding, int[] dilation, int groups', methods: ['unpack(__torch__.torch.classes.quantized.Conv2dPackedParamsBase self) -> ((Tensor, Tensor?))'] },
  12592. { name: '__torch__.torch.classes.quantized.Conv3dPackedParamsBase', attributes: 'Tensor weight, Tensor bias, int[] stride, int[] padding, int[] dilation, int groups', methods: ['unpack(__torch__.torch.classes.quantized.Conv3dPackedParamsBase self) -> ((Tensor, Tensor?))'] },
  12593. { name: '__torch__.torch.classes.quantized.LinearPackedParamsBase', attributes: 'Tensor weight, Tensor? bias' },
  12594. { name: '__torch__.torch.classes.rnn.CellParamsBase', attributes: 'str type, Tensor[] tensors, float[] doubles, int[] longs, __torch__.torch.classes.quantized.LinearPackedParamsBase[] packed_params' },
  12595. { name: '__torch__.torch.classes.xnnpack.Conv2dOpContext', attributes: 'Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups, int[] output_min, int[] output_max' },
  12596. { name: '__torch__.torch.classes.xnnpack.LinearOpContext', attributes: 'Tensor weight, Tensor bias, int[] output_min, int[] output_max' },
  12597. { name: '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext', attributes: 'Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int[] dilation, int groups, int[] output_min, int[] output_max' },
  12598. { name: '__torch__.torch.classes.tensorrt.Engine' }
  12599. ];
  12600. for (const known_type of known_types) {
  12601. const prefix = new torch._C.QualifiedName(known_type.name);
  12602. const type = torch.ClassType.create(known_type.name, this._compilation_unit, false);
  12603. for (const known_method of known_type.methods || []) {
  12604. const schema = new torch.FunctionSchema(known_method);
  12605. const name = new torch._C.QualifiedName(prefix, schema.name);
  12606. const fn = new torch._C.BuiltinOpFunction(name, schema);
  12607. type.addMethod(fn);
  12608. }
  12609. if (known_type.attributes) {
  12610. const schema = new torch.FunctionSchema(`(${known_type.attributes}) -> ()`);
  12611. for (const arg of schema.arguments) {
  12612. type.addAttribute(arg.name, arg.real_type);
  12613. }
  12614. }
  12615. torch._C.registerCustomClass(type);
  12616. // this._compilation_unit.register_type(type);
  12617. }
  12618. if (this._reader.has_record('model.json')) {
  12619. return this.LEGACY_deserialize();
  12620. }
  12621. const constants = this.readArchive('constants');
  12622. for (let i = 0; i < constants.length; i++) {
  12623. let val = constants[i];
  12624. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  12625. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  12626. const obj = torch.ScriptObject.create(type);
  12627. obj._ivalue = val;
  12628. val = obj;
  12629. }
  12630. execution.builtins.CONSTANTS[`c${i}`] = val;
  12631. this._constant_table.push(val);
  12632. }
  12633. const obj = this.readArchive('data');
  12634. const convertObject = (obj) => {
  12635. if (obj.__class__) {
  12636. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  12637. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  12638. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  12639. for (let i = 0; i < type.numAttributes(); i++) {
  12640. const k = type.getAttributeName(i);
  12641. const t = type.getAttribute(i);
  12642. const v = obj[k];
  12643. if (t instanceof torch.ClassType) {
  12644. module.__setattr__(k, convertObject(v));
  12645. } else {
  12646. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  12647. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  12648. type._attributes[i].type = this._source_importer.resolveType(name);
  12649. }
  12650. module.__setattr__(k, obj[k]);
  12651. }
  12652. }
  12653. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  12654. if (value && value.__class__ === builtins.method) {
  12655. module[key] = value;
  12656. }
  12657. }
  12658. return module;
  12659. }
  12660. throw new python.Error('Module class not found.');
  12661. };
  12662. return convertObject(obj);
  12663. }
  12664. LEGACY_deserialize() {
  12665. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  12666. const execution = this._compilation_unit.execution;
  12667. const caffe2 = execution.proto.caffe2;
  12668. const torch = execution.import('torch');
  12669. const stream = this._reader.get_record('model.json');
  12670. const buffer = stream.peek();
  12671. const decoder = new TextDecoder('utf-8');
  12672. const content = decoder.decode(buffer);
  12673. const obj = JSON.parse(content);
  12674. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  12675. const tensorTypeMap = new Map([
  12676. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  12677. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  12678. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  12679. [caffe2.TensorProto.DataType.INT8, 'Char'],
  12680. [caffe2.TensorProto.DataType.INT32, 'Int'],
  12681. [caffe2.TensorProto.DataType.INT64, 'Long']
  12682. ]);
  12683. const tensor_table = (model.tensors || []).map((constant) => {
  12684. const key = constant.data.key;
  12685. if (!tensorTypeMap.has(constant.data_type)) {
  12686. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  12687. }
  12688. const type = tensorTypeMap.get(constant.data_type);
  12689. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  12690. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  12691. const storage_type = execution.resolve(`torch.${type}Storage`);
  12692. const size = (shape || []).reduce((a, b) => a * b, 1);
  12693. const offset = parseInt(constant.offset, 10) || 0;
  12694. const storage = new storage_type(size);
  12695. const itemsize = storage.dtype.itemsize();
  12696. const stream = this._reader.get_record(key);
  12697. if (stream) {
  12698. const buffer = stream.peek();
  12699. const length = size * itemsize;
  12700. const data = buffer.slice(offset, offset + length);
  12701. storage._set_cdata(data);
  12702. }
  12703. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  12704. tensor.name = key;
  12705. return tensor;
  12706. });
  12707. execution.builtins.CONSTANTS = {};
  12708. for (let i = 0; i < tensor_table.length; i++) {
  12709. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  12710. }
  12711. const attributes = [];
  12712. if (this._reader.has_record('attributes.pkl')) {
  12713. const stream = this._reader.get_record('attributes.pkl');
  12714. const buffer = stream.peek();
  12715. const unpickler = new pickle.Unpickler(buffer);
  12716. const obj = unpickler.load();
  12717. attributes.push(...obj);
  12718. }
  12719. this._LEGACY_moduleStack = ['__torch__'];
  12720. const module_def = model.main_module;
  12721. for (const tensor of tensor_table) {
  12722. this._constant_table.push(tensor);
  12723. }
  12724. return this.LEGACY_convertModule(module_def);
  12725. }
  12726. LEGACY_convertModule(module_def) {
  12727. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  12728. const numPushed = atoms.length;
  12729. for (const atom of atoms) {
  12730. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  12731. this._LEGACY_moduleStack.push(sanitized);
  12732. }
  12733. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  12734. const module = new torch.ScriptModule(qn, this._compilation_unit);
  12735. for (const sub_def of module_def.submodules || []) {
  12736. const submodule = this.LEGACY_convertModule(sub_def);
  12737. module.register_module(sub_def.name, submodule);
  12738. }
  12739. for (const param_def of module_def.parameters || []) {
  12740. const tensor = this._constant_table[Number(param_def.tensor_id)];
  12741. if (param_def.isBuffer) {
  12742. module.register_buffer(param_def.name, tensor);
  12743. } else {
  12744. module.register_parameter(param_def.name, tensor, false);
  12745. }
  12746. }
  12747. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  12748. for (const attr_def of module_def.attributes || []) {
  12749. if (module.hasattr(attr_def.name)) {
  12750. continue;
  12751. }
  12752. throw new python.Error('Not implemented.');
  12753. // IValue ivalue;
  12754. // if (attr_def.id() >= 0) {
  12755. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  12756. // }
  12757. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  12758. }
  12759. if (module_def.torchscript_arena) {
  12760. const key = module_def.torchscript_arena.key;
  12761. const file = key.substring('code/'.length);
  12762. const name = file.replace(/\.py$/, '').split('/').join('.');
  12763. const code = execution.import(name);
  12764. if (code.forward.__class__ === execution.builtins.function) {
  12765. module.forward = code.forward;
  12766. }
  12767. }
  12768. // let gen_ranges = null;
  12769. if (module_def.torchscript_debug_arena) {
  12770. throw new python.Error('Not implemented.');
  12771. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  12772. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  12773. }
  12774. if (module_def.torchscript_arena) {
  12775. const filename = module_def.torchscript_arena.key;
  12776. const stream = this._reader.get_record(filename);
  12777. const data = stream.peek();
  12778. const src = new torch._C.Source(data, filename);
  12779. this._source_importer.LEGACY_import_methods(module, src);
  12780. }
  12781. if (module_def.get_state_attribute_id) {
  12782. throw new python.Error('Not implemented.');
  12783. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  12784. }
  12785. /*
  12786. const module_type = module._ivalue().type();
  12787. const N = module_type.numAttributes();
  12788. for (let i = 0; i < N; ++i) {
  12789. const v = module._ivalue().getSlot(i);
  12790. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  12791. torch._C.TORCH_CHECK(!v.isNone());
  12792. }
  12793. }
  12794. */
  12795. for (let i = 0; i < numPushed; i++) {
  12796. this._LEGACY_moduleStack.pop();
  12797. }
  12798. return module;
  12799. }
  12800. readArchive(archive_name) {
  12801. const type_resolver = (qn) => {
  12802. const cls = this._source_importer.loadType(qn);
  12803. return cls;
  12804. };
  12805. const ObjLoaderFunc = (/* type, ivalue */) => {
  12806. };
  12807. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  12808. }
  12809. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  12810. const picklename = `${pickle_prefix + archive_name}.pkl`;
  12811. const stream = stream_reader.get_record(picklename);
  12812. if (!stream) {
  12813. throw new python.Error(`File '${picklename}' is not found.`);
  12814. }
  12815. const buffer = stream.peek();
  12816. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  12817. const read_record = (name) => {
  12818. const stream = stream_reader.get_record(tensor_dir_path + name);
  12819. return stream.length <= 0x40000 ? stream.peek() : stream;
  12820. };
  12821. const execution = this._compilation_unit.execution;
  12822. const pickle = execution.__import__('pickle');
  12823. const Unpickler = class extends pickle.Unpickler {
  12824. find_class(module, name) {
  12825. return super.find_class(module, name);
  12826. }
  12827. };
  12828. const unpickler = new Unpickler(buffer);
  12829. unpickler.persistent_load = (saved_id) => {
  12830. if (saved_id[0] !== 'storage') {
  12831. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  12832. }
  12833. const [, storage_type, key, , size] = saved_id;
  12834. if (storage_context && storage_context.has_storage(key)) {
  12835. return storage_context.get_storage(key);
  12836. }
  12837. const storage = new storage_type(size);
  12838. const storage_ptr = read_record(key);
  12839. storage._set_cdata(storage_ptr);
  12840. if (storage_context) {
  12841. storage_context.add_storage(key);
  12842. }
  12843. return storage;
  12844. };
  12845. return unpickler.load();
  12846. }
  12847. });
  12848. this.registerType('torch._C.WithInsertPoint', class {
  12849. constructor(...args) {
  12850. let n = null;
  12851. if (args.length === 1 && args[0] instanceof torch.Block) {
  12852. const [b] = args;
  12853. n = b.return_node();
  12854. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  12855. [n] = args;
  12856. } else {
  12857. throw new python.Error('Invalid arguments.');
  12858. }
  12859. this._prev = n.owningGraph().insertPoint();
  12860. n.owningGraph().setInsertPoint(n);
  12861. }
  12862. dispose() {
  12863. this._prev.owningGraph().setInsertPoint(this._prev);
  12864. }
  12865. });
  12866. this.registerType('torch._C.Environment', class {
  12867. constructor(method, resolver, b, next) {
  12868. this.method = method;
  12869. this.resolver = resolver;
  12870. this.b = b;
  12871. this.next = next;
  12872. this.value_table = new Map();
  12873. this.type_table = new Map();
  12874. this.error_messages = new Map();
  12875. }
  12876. setVariableTypeError(name, msg) {
  12877. let runner = this;
  12878. while (runner.next) {
  12879. runner = runner.next;
  12880. }
  12881. runner.error_messages.set(name, msg);
  12882. }
  12883. insertLoad(name, type) {
  12884. const g = this.b.owningGraph();
  12885. const load = g.insertNode(g.createLoad(name, type));
  12886. if (torch._C.meaningfulName(name)) {
  12887. load.output().setDebugName(name);
  12888. }
  12889. return new torch._C.SimpleValue(load.output());
  12890. }
  12891. insertStore(name, loc, v, type) {
  12892. const g = this.b.owningGraph();
  12893. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  12894. this.type_table.set(name, type);
  12895. }
  12896. findInThisFrame(name) {
  12897. if (this.value_table.has(name)) {
  12898. return this.value_table.get(name);
  12899. }
  12900. if (this.type_table.has(name)) {
  12901. return this.insertLoad(name, this.type_table.get(name));
  12902. }
  12903. return null;
  12904. }
  12905. findInParentFrame(name) {
  12906. return this.next ? this.next.findInAnyFrame(name) : null;
  12907. }
  12908. setType(name, type) {
  12909. this.type_table.set(name, type);
  12910. }
  12911. findInAnyFrame(name) {
  12912. for (let runner = this; runner; runner = runner.next) {
  12913. const r = runner.findInThisFrame(name);
  12914. if (r) {
  12915. return r;
  12916. }
  12917. }
  12918. return null;
  12919. }
  12920. block() {
  12921. return this.b;
  12922. }
  12923. setVar(loc, name, value) {
  12924. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  12925. }
  12926. setSugaredVar(loc, name, value, annotated_type) {
  12927. let as_simple_value = torch._C.asSimple(value);
  12928. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  12929. as_simple_value.setDebugName(name);
  12930. }
  12931. const parent = this.findInParentFrame(name);
  12932. if (parent) {
  12933. if (annotated_type) {
  12934. throw new python.Error('Type already defined in an outer block.');
  12935. }
  12936. if (!as_simple_value) {
  12937. throw new python.Error('Only reassignments to first-class values are allowed.');
  12938. }
  12939. const simple_parent = torch._C.asSimple(parent);
  12940. if (!simple_parent) {
  12941. throw new python.Error('Only reassignments to first-class values are allowed.');
  12942. }
  12943. const parent_type = torch._C.unshapedType(simple_parent.type());
  12944. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  12945. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  12946. throw new python.Error('Incompatible types.');
  12947. }
  12948. }
  12949. if (as_simple_value) {
  12950. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  12951. throw new python.Error('Invalid type.');
  12952. }
  12953. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  12954. this.insertStore(name, loc, as_simple_value, value_store_type);
  12955. } else {
  12956. this.value_table.set(name, value);
  12957. }
  12958. }
  12959. getSugaredVar(ident, range, required) {
  12960. required = required || true;
  12961. let retval = this.findInAnyFrame(ident);
  12962. if (!retval) {
  12963. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  12964. ['print', new torch._C.PrintValue()],
  12965. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  12966. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  12967. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  12968. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  12969. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  12970. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  12971. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  12972. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  12973. ['range', torch._C.SpecialFormValue.create('prim::range')],
  12974. ]);
  12975. if (torch._C.Environment.globals.has(ident)) {
  12976. retval = torch._C.Environment.globals.get(ident);
  12977. }
  12978. }
  12979. if (!retval) {
  12980. const type = this.resolver.resolveType(ident, range);
  12981. if (type instanceof torch.TupleType) {
  12982. retval = new torch.jit.NamedTupleConstructor(type);
  12983. }
  12984. }
  12985. if (!retval) {
  12986. retval = this.resolver.resolveValue(ident, this.method, range);
  12987. }
  12988. if (!retval) {
  12989. const type = this.resolver.resolveType(ident, range);
  12990. if (type instanceof torch.ClassType) {
  12991. retval = new torch.jit.ClassValue(type);
  12992. }
  12993. }
  12994. if (!retval && required) {
  12995. throw new python.Error(`The name '${ident}' is not defined.`);
  12996. }
  12997. return retval;
  12998. }
  12999. getVar(ident, range) {
  13000. return this.getSugaredVar(ident, range).asValue(range, this.method);
  13001. }
  13002. definedVariables() {
  13003. return Array.from(this.type_table.keys());
  13004. }
  13005. });
  13006. this.registerType('torch._C.Refinement', class {
  13007. constructor(identifier, type) {
  13008. this._identifier = identifier;
  13009. this._type = type;
  13010. }
  13011. identifier() {
  13012. return this._identifier;
  13013. }
  13014. type() {
  13015. return this._type;
  13016. }
  13017. });
  13018. this.registerType('torch._C.RefinementSet', class {
  13019. constructor(...args) {
  13020. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  13021. this._true_refinements = [args[0]];
  13022. this._false_refinements = [];
  13023. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  13024. this._true_refinements = [args[0]];
  13025. this._false_refinements = [args[1]];
  13026. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  13027. [this._true_refinements, this._false_refinements] = args;
  13028. } else {
  13029. throw new python.Error('Not implemented.');
  13030. }
  13031. }
  13032. Not() {
  13033. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  13034. }
  13035. activeRefinements() {
  13036. return this._true_refinements;
  13037. }
  13038. });
  13039. this.registerFunction('torch._C.CondValue', class {
  13040. constructor(...args) {
  13041. if (args.length === 3) {
  13042. [this._value, this._refinements, this._static_if] = args;
  13043. } else if (args.length === 4) {
  13044. const [g, loc, static_value, refinements] = args;
  13045. this._value = g.insertConstant(static_value, loc);
  13046. this._refinements = refinements;
  13047. this._static_if = static_value;
  13048. } else {
  13049. throw new python.Error('Invalid number of arguments.');
  13050. }
  13051. }
  13052. value() {
  13053. return this._value;
  13054. }
  13055. staticIf() {
  13056. return this._static_if;
  13057. }
  13058. refinements() {
  13059. return this._refinements;
  13060. }
  13061. });
  13062. this.registerFunction('torch._C.asSimple', (value) => {
  13063. if (value instanceof torch._C.SimpleValue) {
  13064. return value.getValue();
  13065. }
  13066. return null;
  13067. });
  13068. this.registerFunction('torch._C.isNumber', (str) => {
  13069. return /^[0-9]+$/.test(str);
  13070. });
  13071. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  13072. if (torch._C.isNumber(field)) {
  13073. return `_${field}`;
  13074. }
  13075. return field;
  13076. });
  13077. this.registerFunction('torch._C.meaningfulName', (name) => {
  13078. if (name.length === 0 && name[0] === '$') {
  13079. return false;
  13080. }
  13081. if (name[0] !== '_') {
  13082. return true;
  13083. }
  13084. return !/\d+/.test(name.slice(1));
  13085. });
  13086. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  13087. const key = `${val.value}:${val.tag}`;
  13088. const existing_constant = map.get(key);
  13089. if (existing_constant) {
  13090. return existing_constant;
  13091. }
  13092. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  13093. const new_constant = graph.insertConstant(val, r);
  13094. map.set(key, new_constant);
  13095. guard.dispose();
  13096. return new_constant;
  13097. });
  13098. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  13099. if (schema.overload_name) {
  13100. return `${schema.name}.${schema.overload_name}`;
  13101. }
  13102. return schema.name;
  13103. });
  13104. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  13105. const value_map_func = (v) => value_map.get(v);
  13106. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  13107. for (let i = 0; i < inputs.length; i++) {
  13108. value_map.set(callee.inputs()[i], inputs[i]);
  13109. }
  13110. for (const node of callee.nodes()) {
  13111. const new_node = g.insertNode(g.createClone(node, value_map_func));
  13112. for (let i = 0; i < node.outputs().length; i++) {
  13113. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  13114. }
  13115. }
  13116. const outputs = [];
  13117. for (const output of callee.outputs()) {
  13118. outputs.push(value_map_func(output));
  13119. }
  13120. return outputs;
  13121. });
  13122. this.registerType('TemplateEnv', class {
  13123. });
  13124. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  13125. constructor() {
  13126. this.state = 'UNINITIALIZED';
  13127. this._builtins_by_name = new Map();
  13128. }
  13129. getAllBuiltinFunctionsFor(name) {
  13130. if (this.state === 'UNINITIALIZED') {
  13131. this.loadBuiltinFunctions();
  13132. this.state = 'INITIALIZED';
  13133. }
  13134. if (!this._builtins_by_name.has(name)) {
  13135. return [];
  13136. }
  13137. return this._builtins_by_name.get(name);
  13138. }
  13139. loadBuiltinFunctions() {
  13140. /*
  13141. for (const scalar of ['float', 'int', 'complex']) {
  13142. const env = new torch.C.TemplateEnv();
  13143. env.s('Scalar', scalar);
  13144. this.loadSource(scalar_operators_source.format(env), 'aten');
  13145. }
  13146. for (const scalar of ['float', 'int']) {
  13147. const env = new torch.C.TemplateEnv();
  13148. env.s('Scalar', scalar);
  13149. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  13150. }
  13151. using str_pair = std::pair<std::string, std::string>;
  13152. const std::vector<str_pair> name_len = {
  13153. str_pair('single', '1'),
  13154. str_pair('pair', '2'),
  13155. str_pair('triple', '3'),
  13156. str_pair('quadruple', '4'),
  13157. };
  13158. for (const auto scalar : {'float', 'int'}) {
  13159. for (const auto& pair : name_len) {
  13160. const env = new torch.C.TemplateEnv();
  13161. env.s('Scalar', scalar);
  13162. env.s('name', pair.first);
  13163. env.s('Length', pair.second);
  13164. this.loadSource(_ntuple_ops.format(env), 'aten');
  13165. }
  13166. }
  13167. for (auto rhs : {'number', 'Tensor'}) {
  13168. at::jit::TemplateEnv env;
  13169. env.s('Rhs_Type', rhs);
  13170. this.loadSource(floordiv.format(env), 'aten');
  13171. }
  13172. this.loadSource(aten_ops, 'aten');
  13173. this.loadSource(aten_ops_additional, 'aten');
  13174. this.loadSource(tensor_properties, 'prim');
  13175. */
  13176. }
  13177. loadSource(/* source, the_namespace */) {
  13178. }
  13179. });
  13180. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  13181. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  13182. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  13183. });
  13184. this.registerFunction('torch._C.get_operator_version_map', () => {
  13185. return new Map();
  13186. });
  13187. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  13188. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  13189. let arg_type = arg.type;
  13190. if (arg_type instanceof torch._C.DynamicType) {
  13191. arg_type = arg_type.fallback();
  13192. }
  13193. const argument_is_list = arg_type instanceof torch.ListType;
  13194. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  13195. const arg_is_broadcasting_list = arg.N > 0;
  13196. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  13197. });
  13198. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  13199. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  13200. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  13201. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  13202. return true;
  13203. }
  13204. return false;
  13205. });
  13206. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  13207. if (opt_type instanceof torch._C.DynamicType) {
  13208. return torch._C.unwrapOptional(opt_type.fallback());
  13209. }
  13210. if (opt_type instanceof torch.OptionalType) {
  13211. return opt_type.getElementType();
  13212. }
  13213. return opt_type;
  13214. });
  13215. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  13216. const possibleSchemas = [];
  13217. if (version === undefined) {
  13218. return possibleSchemas;
  13219. }
  13220. for (const entry of torch._C.get_operator_version_map()) {
  13221. const old_symbol_name = entry.first;
  13222. const base_name = old_symbol_name.substr(0, old_symbol_name.find('.'));
  13223. if (base_name === name) {
  13224. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  13225. if (possibleUpgrader.has_value()) {
  13226. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  13227. }
  13228. }
  13229. }
  13230. return possibleSchemas;
  13231. });
  13232. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  13233. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  13234. return current_version < latest_update;
  13235. });
  13236. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  13237. const it = torch._C.get_operator_version_map().get(name);
  13238. if (it) {
  13239. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  13240. }
  13241. return true;
  13242. });
  13243. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  13244. if (values.length === 1) {
  13245. return values[0];
  13246. }
  13247. let named_tuple = null;
  13248. if (field_names) {
  13249. const types = values.map((v) => v.type());
  13250. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  13251. }
  13252. return g.insertNode(g.createTuple(values, named_tuple)).output();
  13253. });
  13254. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  13255. const v_type = value.type();
  13256. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  13257. return false;
  13258. }
  13259. const arg_type = torch._C.unwrapOptional(arg.type);
  13260. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  13261. });
  13262. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  13263. const list_type = list_type_;
  13264. if (list_type instanceof torch.ListType === false) {
  13265. return false;
  13266. }
  13267. if (type.isSubtypeOf(list_type_)) {
  13268. return true;
  13269. }
  13270. if (type instanceof torch.TupleType) {
  13271. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  13272. }
  13273. return false;
  13274. });
  13275. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  13276. for (let i = 0; i < kwargs.length; i++) {
  13277. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  13278. return i;
  13279. }
  13280. if (kwargs[i].name() === name) {
  13281. return i;
  13282. }
  13283. }
  13284. return null;
  13285. });
  13286. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  13287. const elem_arg = new torch.Argument('<varargs>', elem_type);
  13288. const list_elements = [];
  13289. for (const named_value of varargs) {
  13290. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  13291. if (!matched_value) {
  13292. return null;
  13293. }
  13294. list_elements.push(matched_value);
  13295. }
  13296. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  13297. });
  13298. this.registerType('torch._C.MatchTypeReturn', class {
  13299. constructor(reason) {
  13300. this._reason = reason;
  13301. }
  13302. static Success() {
  13303. return new torch._C.MatchTypeReturn(null);
  13304. }
  13305. success() {
  13306. return this._reason === null;
  13307. }
  13308. });
  13309. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  13310. if (!formal.hasFreeVariables()) {
  13311. if (formal instanceof torch._C.DynamicType) {
  13312. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  13313. }
  13314. return torch._C.MatchTypeReturn.Success();
  13315. }
  13316. if (formal instanceof torch._C.VarType) {
  13317. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  13318. if (it === null) {
  13319. type_env.set(formal.name(), actual);
  13320. return torch._C.MatchTypeReturn.Success();
  13321. } else if (torch._C.unifyTypes(it, actual)) {
  13322. return torch._C.MatchTypeReturn.Success();
  13323. }
  13324. return new torch._C.MatchTypeReturn('Cannot match var.');
  13325. } else if (formal instanceof torch.ListType) {
  13326. if (actual instanceof torch.ListType) {
  13327. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  13328. if (!innerMatch.success()) {
  13329. return innerMatch;
  13330. }
  13331. return torch._C.MatchTypeReturn.Success();
  13332. } else if (actual instanceof torch.TupleType) {
  13333. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  13334. if (maybe_tuple_unified) {
  13335. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  13336. }
  13337. }
  13338. return new torch._C.MatchTypeReturn('Cannot match list.');
  13339. } else if (formal instanceof torch.TupleType) {
  13340. if (actual instanceof torch.TupleType) {
  13341. if (formal.elements().length !== actual.elements().length) {
  13342. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  13343. }
  13344. for (let i = 0; i < formal.elements().length; i++) {
  13345. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  13346. if (!result.success()) {
  13347. return result;
  13348. }
  13349. }
  13350. return torch._C.MatchTypeReturn.Success();
  13351. }
  13352. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  13353. } else if (formal instanceof torch.FutureType) {
  13354. if (actual instanceof torch.FutureType) {
  13355. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  13356. if (!innerMatch.success()) {
  13357. return innerMatch;
  13358. }
  13359. return torch._C.MatchTypeReturn.Success();
  13360. }
  13361. return new torch._C.MatchTypeReturn('Cannot match future.');
  13362. } else if (formal instanceof torch.AwaitType) {
  13363. if (actual instanceof torch.AwaitType) {
  13364. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  13365. if (!innerMatch.success()) {
  13366. return innerMatch;
  13367. }
  13368. return torch._C.MatchTypeReturn.Success();
  13369. }
  13370. return new torch._C.MatchTypeReturn('Cannot match await.');
  13371. } else if (formal instanceof torch.RRefType) {
  13372. if (actual instanceof torch.RRefType) {
  13373. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  13374. if (!innerMatch.success()) {
  13375. return innerMatch;
  13376. }
  13377. return torch._C.MatchTypeReturn.Success();
  13378. }
  13379. return new torch._C.MatchTypeReturn('Cannot match rref.');
  13380. } else if (formal instanceof torch.OptionalType) {
  13381. if (actual instanceof torch.OptionalType) {
  13382. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  13383. if (!optionedMatch.success()) {
  13384. return optionedMatch;
  13385. }
  13386. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  13387. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  13388. }
  13389. return torch._C.MatchTypeReturn.Success();
  13390. } else if (formal instanceof torch.DictType) {
  13391. if (actual instanceof torch.DictType) {
  13392. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  13393. if (!key_match.success()) {
  13394. return key_match;
  13395. }
  13396. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  13397. if (!value_match.success()) {
  13398. return value_match;
  13399. }
  13400. return torch._C.MatchTypeReturn.Success();
  13401. }
  13402. return new torch._C.MatchTypeReturn('Cannot match dict.');
  13403. }
  13404. throw new python.Error('Unhandled free variable container.');
  13405. });
  13406. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  13407. let value = named_value.value(graph);
  13408. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  13409. const repeated = Array(arg.N).fill(value);
  13410. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  13411. }
  13412. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  13413. if (!matched.success()) {
  13414. if (failure_messages) {
  13415. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  13416. }
  13417. return null;
  13418. }
  13419. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  13420. if (!concrete_type) {
  13421. if (failure_messages) {
  13422. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  13423. }
  13424. return null;
  13425. }
  13426. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  13427. if (!value.type().isSubtypeOf(concrete_type)) {
  13428. if (failure_messages) {
  13429. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  13430. }
  13431. return null;
  13432. }
  13433. return value;
  13434. });
  13435. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  13436. if (concrete_type instanceof torch.OptionalType) {
  13437. const op = concrete_type;
  13438. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  13439. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  13440. }
  13441. }
  13442. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  13443. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  13444. }
  13445. if (value.type() instanceof torch.TupleType) {
  13446. const value_tuple = value.type();
  13447. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  13448. const unpacked = torch._C.createTupleUnpack(value);
  13449. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  13450. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  13451. }
  13452. if (concrete_type instanceof torch.TupleType) {
  13453. const concrete_tuple = concrete_type;
  13454. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  13455. concrete_tuple.elements().length === value_tuple.elements().length) {
  13456. const unpacked = torch._C.createTupleUnpack(value);
  13457. const converted = [];
  13458. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  13459. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  13460. }
  13461. value = graph.insertNode(graph.createTuple(converted)).output();
  13462. }
  13463. }
  13464. }
  13465. if (allow_conversions) {
  13466. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  13467. const value_equals_number = value.type() === torch.NumberType.get();
  13468. const concrete_float = concrete_type === torch.FloatType.get();
  13469. const concrete_complex = concrete_type === torch.ComplexType.get();
  13470. const concrete_int = concrete_type === torch.IntType.get();
  13471. const concrete_number = concrete_type === torch.NumberType.get();
  13472. if (value_isa_tensor) {
  13473. if (concrete_float) {
  13474. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  13475. } else if (concrete_complex) {
  13476. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  13477. } else if (concrete_int) {
  13478. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  13479. } else if (concrete_number) {
  13480. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  13481. }
  13482. } else if (value_equals_number) {
  13483. if (concrete_float) {
  13484. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  13485. } else if (concrete_complex) {
  13486. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  13487. } else if (concrete_int) {
  13488. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  13489. }
  13490. } else if (value.type() === torch.BoolType.get()) {
  13491. if (concrete_float) {
  13492. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  13493. } else if (concrete_int || concrete_number) {
  13494. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  13495. }
  13496. }
  13497. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  13498. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  13499. }
  13500. }
  13501. return value;
  13502. });
  13503. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  13504. if (!type.hasFreeVariables()) {
  13505. if (type instanceof torch._C.DynamicType) {
  13506. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  13507. }
  13508. return type;
  13509. }
  13510. if (type instanceof torch._C.VarType) {
  13511. return type_env.get(type.annotation_str);
  13512. }
  13513. const contained = type.containedTypes();
  13514. if (contained.length === 0) {
  13515. return type;
  13516. }
  13517. const new_contained = [];
  13518. for (const t of contained) {
  13519. const r = torch._C.tryEvalTypeVariables(t, type_env);
  13520. if (!r) {
  13521. return null;
  13522. }
  13523. new_contained.push(r);
  13524. }
  13525. return type.withContained(new_contained);
  13526. });
  13527. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  13528. if (torch._C.isBlockListedSchema(schema)) {
  13529. return null;
  13530. }
  13531. const err = null;
  13532. const type_env = new Map();
  13533. const positional_inputs = [];
  13534. const used_kwarg = kwargs.map(() => false);
  13535. const is_aten = schema.name.startsWith('aten::');
  13536. let used_args = 0;
  13537. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  13538. const arg = schema.arguments[schema_i];
  13539. let actual_named_value = null;
  13540. if (arg.name === 'self' && self) {
  13541. actual_named_value = self;
  13542. self = null;
  13543. } else if (!arg.kwarg_only && used_args < args.length) {
  13544. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  13545. const value = args[used_args].value(graph);
  13546. const actual_type = value.type();
  13547. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  13548. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  13549. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  13550. if (!list) {
  13551. return null;
  13552. }
  13553. used_args = args.length;
  13554. positional_inputs.push(list);
  13555. continue;
  13556. }
  13557. }
  13558. actual_named_value = args[used_args];
  13559. used_args++;
  13560. } else {
  13561. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  13562. if (Number.isInteger(kwarg_idx)) {
  13563. const nv = kwargs[kwarg_idx];
  13564. if (used_kwarg[kwarg_idx]) {
  13565. if (failure_messages) {
  13566. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  13567. }
  13568. return null;
  13569. }
  13570. used_kwarg[kwarg_idx] = true;
  13571. actual_named_value = nv;
  13572. } else if (arg.has_default_value()) {
  13573. actual_named_value = new torch._C.NamedValue(arg.default_value);
  13574. } else {
  13575. if (failure_messages) {
  13576. throw new python.Error(`Argument '${arg.name}' not provided.`);
  13577. }
  13578. return null;
  13579. }
  13580. }
  13581. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  13582. if (!positional) {
  13583. return null;
  13584. }
  13585. positional_inputs.push(positional);
  13586. }
  13587. if (self !== null) {
  13588. if (failure_messages) {
  13589. throw new python.Error('Provided self argument not used in schema.');
  13590. }
  13591. return null;
  13592. }
  13593. if (schema.is_vararg) {
  13594. for (; used_args < args.length; used_args++) {
  13595. positional_inputs.push(args[used_args].value(graph));
  13596. }
  13597. }
  13598. if (used_args < args.length) {
  13599. if (failure_messages) {
  13600. throw new python.Error('Too many positional arguments.');
  13601. }
  13602. return null;
  13603. }
  13604. for (let i = 0; i < kwargs.length; i++) {
  13605. const nv = kwargs[i];
  13606. if (!used_kwarg[i]) {
  13607. if (failure_messages) {
  13608. if (schema.argumentIndexWithName(nv.name())) {
  13609. throw new python.Error('Keyword argument specified twice.');
  13610. } else {
  13611. throw new python.Error('Keyword argument unknown.');
  13612. }
  13613. }
  13614. return null;
  13615. }
  13616. }
  13617. const returns = schema.returns;
  13618. const return_types = returns.map((r) => {
  13619. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  13620. if (!result) {
  13621. throw new python.Error('Unbound type variable.');
  13622. }
  13623. return result;
  13624. });
  13625. const return_has_field_names = returns.every((r) => !r.name);
  13626. let return_field_names = null;
  13627. if (return_has_field_names) {
  13628. return_field_names = returns.map((r) => r.name);
  13629. }
  13630. const schema_name = torch._C.getFullSchemaName(schema);
  13631. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  13632. });
  13633. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  13634. self = self || null;
  13635. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  13636. if (result) {
  13637. return result;
  13638. }
  13639. throw new python.Error(`No matching schema '${schema.name}' found.`);
  13640. });
  13641. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  13642. self = self || null;
  13643. render_errors = render_errors || false;
  13644. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  13645. if (schemas.length === 1) {
  13646. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  13647. }
  13648. for (const allow_conversions of [false, true]) {
  13649. for (let i = 0; i < schemas.length; i++) {
  13650. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  13651. if (matched_schema) {
  13652. return [i, matched_schema];
  13653. }
  13654. }
  13655. }
  13656. if (!render_errors) {
  13657. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  13658. }
  13659. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  13660. });
  13661. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  13662. const variants = torch._C.getAllOperatorsFor(name);
  13663. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  13664. const graph_version = graph.get_op_version();
  13665. const schemas = [];
  13666. const upgrader_schemas = [];
  13667. for (const op of variants) {
  13668. let found_upgrader = false;
  13669. const op_name = torch._C.getFullSchemaName(op.schema());
  13670. if (Number.isInteger(graph_version)) {
  13671. const version_entry = torch._C.get_operator_version_map().get(op_name);
  13672. if (version_entry) {
  13673. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  13674. if (old_schema_entry.has_value()) {
  13675. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  13676. upgrader_schemas.push(old_schema);
  13677. found_upgrader = true;
  13678. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  13679. throw new python.Error('Valid upgrader must be present.');
  13680. }
  13681. }
  13682. }
  13683. if (!found_upgrader) {
  13684. schemas.push(op.schema());
  13685. }
  13686. }
  13687. if (variants.length === 0) {
  13688. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  13689. for (const old_schema_entry of oldSchemas) {
  13690. const old_schema = torch._C.parseSchema(old_schema_entry);
  13691. upgrader_schemas.push(old_schema);
  13692. }
  13693. }
  13694. for (const schema of upgrader_schemas) {
  13695. schemas.push(schema);
  13696. }
  13697. for (const method of builtin_functions) {
  13698. method.ensure_defined();
  13699. schemas.push(method.getSchema());
  13700. }
  13701. if (schemas.length === 0) {
  13702. const user_function_name = name;
  13703. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  13704. }
  13705. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  13706. if (matched[0] < variants.length + upgrader_schemas.length) {
  13707. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  13708. }
  13709. const fn = builtin_functions[matched.first - variants.size()];
  13710. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  13711. });
  13712. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  13713. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  13714. for (const ret of matched_schema.return_types) {
  13715. n.addOutput().setType(ret);
  13716. }
  13717. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  13718. n.getOperation();
  13719. } else {
  13720. n.setHistoricSchemaName(matched_schema.schema_name);
  13721. }
  13722. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  13723. });
  13724. this.registerFunction('torch._C.unshapedType', (type) => {
  13725. if (type.isSubtypeOf(torch.TensorType.get())) {
  13726. return torch.TensorType.get();
  13727. }
  13728. const contained = type.containedTypes();
  13729. if (contained.length === 0) {
  13730. return type;
  13731. }
  13732. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  13733. });
  13734. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  13735. default_to_union = default_to_union || false;
  13736. type_hint = type_hint || null;
  13737. if (t1.isSubtypeOf(t2)) {
  13738. return t2;
  13739. } else if (t2.isSubtypeOf(t1)) {
  13740. return t1;
  13741. }
  13742. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  13743. return t1.merge(t2);
  13744. }
  13745. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  13746. return torch.OptionalType.create(t2);
  13747. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  13748. return torch.OptionalType.create(t1);
  13749. }
  13750. if (t1 instanceof torch.OptionalType) {
  13751. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  13752. if (elem) {
  13753. return torch.OptionalType.create(elem);
  13754. }
  13755. } else if (t2 instanceof torch.OptionalType) {
  13756. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  13757. if (elem) {
  13758. return torch.OptionalType.create(elem);
  13759. }
  13760. }
  13761. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  13762. if (t1.elements().size() !== t2.elements().size()) {
  13763. return null;
  13764. }
  13765. const elements = [];
  13766. for (let i = 0; i < t1.elements().length; i++) {
  13767. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  13768. if (elem) {
  13769. elements.push(elem);
  13770. } else {
  13771. return null;
  13772. }
  13773. }
  13774. return torch.TupleType.create(elements);
  13775. }
  13776. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  13777. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  13778. if (elem) {
  13779. return torch.FutureType.create(elem);
  13780. }
  13781. }
  13782. const t1_unshaped = torch._C.unshapedType(t1);
  13783. const t2_unshaped = torch._C.unshapedType(t2);
  13784. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  13785. return t2_unshaped;
  13786. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  13787. return t1_unshaped;
  13788. }
  13789. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  13790. return type_hint;
  13791. }
  13792. return null;
  13793. });
  13794. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  13795. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  13796. if (default_to_union && !unified) {
  13797. return torch.UnionType.create([t1, t2]);
  13798. }
  13799. return unified;
  13800. });
  13801. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  13802. if (elements.length === 0) {
  13803. return null;
  13804. }
  13805. let [ret_type] = elements;
  13806. for (let i = 1; i < elements.length && ret_type; i++) {
  13807. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  13808. if (!maybe_unified) {
  13809. return null;
  13810. }
  13811. ret_type = maybe_unified;
  13812. }
  13813. return ret_type;
  13814. });
  13815. this.registerFunction('torch._C.insertableTensor', (ten) => {
  13816. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  13817. });
  13818. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  13819. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  13820. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  13821. ivalue.isDevice() || ivalue.isEnum()) {
  13822. return true;
  13823. }
  13824. if (ivalue.isTensor()) {
  13825. return torch._C.insertableTensor(ivalue.toTensor());
  13826. }
  13827. if (ivalue.isList() || ivalue.isTuple()) {
  13828. let elems = [];
  13829. if (ivalue.isTuple()) {
  13830. elems = ivalue.toTupleRef().elements();
  13831. } else {
  13832. elems = ivalue.toListRef();
  13833. }
  13834. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  13835. }
  13836. if (ivalue.isGenericDict()) {
  13837. const dict = ivalue.toGenericDict();
  13838. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  13839. }
  13840. return false;
  13841. });
  13842. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  13843. loc = loc || null;
  13844. scope = scope || null;
  13845. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  13846. if (value !== undefined) {
  13847. return value;
  13848. }
  13849. throw new python.Error('Unsupported value kind.');
  13850. });
  13851. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  13852. if (val instanceof torch._C.IValue) {
  13853. const n = g.create('prim::Constant');
  13854. if (val.isTensor()) {
  13855. const ref = val.toTensor();
  13856. if (!torch._C.insertableTensor(val.toTensor())) {
  13857. n.destroy();
  13858. return null;
  13859. }
  13860. if (!ref.defined()) {
  13861. n.destroy();
  13862. return g.insertNode(g.createNone()).output();
  13863. }
  13864. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  13865. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  13866. n.t_('value', ref);
  13867. } else if (val.isInt()) {
  13868. n.i_('value', val.toInt());
  13869. n.output().setType(torch.IntType.get());
  13870. } else if (val.isDouble()) {
  13871. n.f_('value', val.toDouble());
  13872. n.output().setType(torch.FloatType.get());
  13873. } else if (val.isComplexDouble()) {
  13874. n.c_('value', val.toComplexDouble());
  13875. n.output().setType(torch.ComplexType.get());
  13876. } else if (val.isBool()) {
  13877. n.i_('value', val.toBool());
  13878. n.output().setType(torch.BoolType.get());
  13879. } else if (val.isList()) {
  13880. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  13881. if (fast_path_list || torch._C.insertableIValue(val)) {
  13882. n.ival_('value', val);
  13883. n.output().setType(val.type());
  13884. } else {
  13885. n.destroy();
  13886. return null;
  13887. }
  13888. } else if (val.isString()) {
  13889. n.s_('value', val.toStringRef());
  13890. n.output().setType(torch.StringType.get());
  13891. } else if (val.isDevice()) {
  13892. n.s_('value', val.toDevice().__str__());
  13893. n.output().setType(torch.DeviceObjType.get());
  13894. } else if (val.isGenerator()) {
  13895. n.ival_('value', val.toGenerator());
  13896. n.output().setType(torch._C_._GeneratorType.get());
  13897. } else if (val.isStream()) {
  13898. n.ival_('value', val);
  13899. n.output().setType(torch.StreamObjType.get());
  13900. } else if (val.isNone()) {
  13901. n.output().setType(torch.NoneType.get());
  13902. } else if (val.isTuple()) {
  13903. if (torch._C.insertableIValue(val)) {
  13904. n.ival_('value', val);
  13905. n.output().setType(val.type());
  13906. } else {
  13907. n.destroy();
  13908. return null;
  13909. }
  13910. } else if (val.isObject()) {
  13911. const ref = val.toObjectRef();
  13912. // see: [Constant Object Weak CompilationUnit Reference]
  13913. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  13914. n.ival_('value', val);
  13915. n.output().setType(val.type());
  13916. } else {
  13917. n.destroy();
  13918. return null;
  13919. }
  13920. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  13921. n.ival_('value', val);
  13922. n.output().setType(val.type());
  13923. } else {
  13924. n.destroy();
  13925. return null;
  13926. }
  13927. if (loc) {
  13928. n.setSourceRange(loc);
  13929. }
  13930. if (scope) {
  13931. n.setScope(scope);
  13932. }
  13933. return g.insertNode(n).output();
  13934. }
  13935. const n = g.create('prim::Constant');
  13936. let type = null;
  13937. if (val === null) {
  13938. n.ival_('value', val);
  13939. type = torch.NoneType.get();
  13940. } else if (typeof val === 'string') {
  13941. n.s_('value', val);
  13942. type = torch.StringType.get();
  13943. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  13944. n.ss_('value', val);
  13945. type = torch.ListType.create(torch.StringType.get());
  13946. } else if (typeof val === 'boolean') {
  13947. n.i_('value', val === true ? 1 : 0);
  13948. type = torch.BoolType.get();
  13949. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  13950. n.i_('value', val);
  13951. type = torch.IntType.get();
  13952. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  13953. n.f_('value', val);
  13954. type = torch.FloatType.get();
  13955. } else if (val instanceof torch.Tensor) {
  13956. n.t_('value', val);
  13957. type = torch.TensorType.get();
  13958. } else if (val instanceof torch.ScriptObject) {
  13959. n.ival_('value', val);
  13960. type = val.type();
  13961. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  13962. n.ival_('value', val);
  13963. type = torch.ListType.create(torch.IntType.get());
  13964. } else {
  13965. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  13966. }
  13967. if (type) {
  13968. n.output().setType(type);
  13969. }
  13970. if (loc) {
  13971. n.setSourceRange(loc);
  13972. }
  13973. if (scope) {
  13974. n.setScope(scope);
  13975. }
  13976. return g.insertNode(n).output();
  13977. });
  13978. this.registerFunction('torch._C.toIValue', (v) => {
  13979. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  13980. return null;
  13981. }
  13982. const node = v.node();
  13983. const type = v.type();
  13984. if (type.isSubtypeOf(torch.TensorType.get())) {
  13985. return new torch._C.IValue(node.t('value'), 'Tensor');
  13986. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  13987. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  13988. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  13989. return new torch._C.IValue(node.i('value'), 'Int');
  13990. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  13991. return new torch._C.IValue(node.f('value'), 'Double');
  13992. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'c') {
  13993. return new torch._C.IValue(node.c('value'), 'Complex');
  13994. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  13995. const list = new torch._C.IValue(node.ival('value'));
  13996. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  13997. return list;
  13998. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  13999. const dict = node.ival('value');
  14000. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  14001. return dict;
  14002. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  14003. const tup = node.ival('value');
  14004. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  14005. return tup;
  14006. } else if (type === torch.StringType.get()) {
  14007. const s = new torch._C.IValue(node.s('value'), 'String');
  14008. return s;
  14009. } else if (type === torch.DeviceObjType.get()) {
  14010. const d = new torch.device(node.s('value'));
  14011. return new torch._C.IValue(d);
  14012. } else if (type === torch._C._GeneratorType.get()) {
  14013. throw new python.Error('Not implemented.');
  14014. // const generator = node.ival('value').toGenerator();
  14015. // return generator;
  14016. } else if (type === torch.StreamObjType.get()) {
  14017. throw new python.Error('Not implemented.');
  14018. // const s = node.ival('value').toStream();
  14019. // return s;
  14020. } else if (node.mustBeNone()) {
  14021. return new torch._C.IValue();
  14022. } else if (type.kind() === 'EnumType') {
  14023. const enum_val = node.ival('value');
  14024. return enum_val;
  14025. } else if (type instanceof torch.ClassType && !type.is_module()) {
  14026. const class_val = node.ival('value');
  14027. return new torch._C.IValue(class_val, 'Object');
  14028. }
  14029. throw new python.Error('Unsupported constant literal.');
  14030. });
  14031. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  14032. const ivalue = torch._C.toIValue(v);
  14033. if (ivalue) {
  14034. return ivalue[target]();
  14035. }
  14036. return default_value === undefined ? null : default_value;
  14037. });
  14038. this.registerType('torch._C.NamedValue', class {
  14039. constructor(...args) {
  14040. if (args.length === 1) {
  14041. if (args[0] instanceof torch.Value) {
  14042. [this._value] = args;
  14043. } else {
  14044. [this._ivalue] = args;
  14045. }
  14046. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  14047. [this._loc, this._name, this._value] = args;
  14048. } else {
  14049. throw new python.Error('Invalid argument.');
  14050. }
  14051. }
  14052. name() {
  14053. return this._name;
  14054. }
  14055. value(g) {
  14056. if (!this._value) {
  14057. return torch._C.insertConstant(g, this._ivalue);
  14058. }
  14059. return this._value;
  14060. }
  14061. });
  14062. this.registerType('torch._C.SugaredValue', class {
  14063. kind() {
  14064. throw new python.Error('Not implemented.');
  14065. }
  14066. shouldEmitUnrolled() {
  14067. return this.staticLen() !== null;
  14068. }
  14069. });
  14070. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  14071. constructor(value) {
  14072. super();
  14073. this._value = value;
  14074. }
  14075. kind() {
  14076. return `value of type '${this._value.type().annotation_str}'`;
  14077. }
  14078. asValue(/* range, m */) {
  14079. return this._value;
  14080. }
  14081. getValue() {
  14082. return this._value;
  14083. }
  14084. asTuple(loc, m, size_hint) {
  14085. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  14086. if (this._value.type() instanceof torch.TupleType) {
  14087. const outputs = torch._C.createTupleUnpack(this._value);
  14088. return outputs.map((v) => make_simple_value(v));
  14089. } else if (this._value.type() instanceof torch.ListType) {
  14090. if (!size_hint) {
  14091. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  14092. }
  14093. const graph = this._value.owningGraph();
  14094. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  14095. return unpack.outputs().map((v) => make_simple_value(v));
  14096. } else if (this._value.type().kind() === 'AnyTupleType') {
  14097. throw new python.Error('Provided tuple is not fully defined including its element types.');
  14098. }
  14099. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  14100. }
  14101. attr(loc, m, field) {
  14102. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  14103. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  14104. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  14105. }
  14106. }
  14107. if (this._value.type() instanceof torch.TupleType) {
  14108. throw new python.Error('Not implemented.');
  14109. }
  14110. if (this._value.type() instanceof torch.AwaitType) {
  14111. throw new python.Error('Not implemented.');
  14112. }
  14113. if (this._value.type() instanceof torch.ClassType) {
  14114. const classType = this._value.type();
  14115. if (classType.findMethod(field)) {
  14116. return new torch._C.MethodValue(this.getValue(), [field]);
  14117. }
  14118. if (classType.hasAttribute(field)) {
  14119. const g = m.graph();
  14120. const n = g.insertNode(g.createGetAttr(this._value, field));
  14121. return new torch._C.SimpleValue(n.output());
  14122. }
  14123. const prop = classType.getProperty(field);
  14124. if (prop) {
  14125. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  14126. }
  14127. } else if (this._value.type() instanceof torch.InterfaceType) {
  14128. throw new python.Error('Not implemented.');
  14129. } /* else if (this._value.type() instanceof torch.EnumType) {
  14130. const g = m.graph();
  14131. if (field == 'name') {
  14132. const n = g.insertNode(g.createEnumName(value_));
  14133. return std::make_shared<SimpleValue>(n->output());
  14134. }
  14135. if (field == 'value') {
  14136. const n = g.insertNode(g.createEnumValue(value_));
  14137. return std::make_shared<SimpleValue>(n->output());
  14138. }
  14139. } */
  14140. if (field === 'type') {
  14141. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  14142. if (builtin) {
  14143. return builtin;
  14144. }
  14145. }
  14146. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  14147. if (builtin) {
  14148. return builtin;
  14149. }
  14150. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  14151. return torch._C.SpecialFormValue.create('prim::tolist');
  14152. }
  14153. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  14154. return torch._C.SpecialFormValue.create('aten::index');
  14155. }
  14156. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  14157. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  14158. if (builtin) {
  14159. return builtin;
  14160. }
  14161. }
  14162. throw new python.Error('Object has no attribute or method.');
  14163. }
  14164. setAttr(loc, m, field, newValue) {
  14165. const type = this._value.type();
  14166. if (type instanceof torch.ClassType === false) {
  14167. throw new python.Error('Cannot set attribute on non-class type.');
  14168. }
  14169. const classType = type;
  14170. let expectedType = classType.findAttribute(field);
  14171. if (!expectedType) {
  14172. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  14173. if (isInitializing) {
  14174. if (this.isRecursive(classType, newValue.type())) {
  14175. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  14176. }
  14177. classType.addAttribute(field, newValue.type());
  14178. expectedType = newValue.type();
  14179. const insertPoint = m.graph().insertPoint();
  14180. const topLevelBlock = m.graph().block();
  14181. if (insertPoint.owningBlock() !== topLevelBlock) {
  14182. throw new python.Error('First assignment cannot be in a control-flow block.');
  14183. }
  14184. } else {
  14185. const prop = classType.getProperty(field);
  14186. if (prop && prop.setter) {
  14187. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  14188. return;
  14189. }
  14190. if (prop && !prop.setter) {
  14191. throw new python.Error('Tried to set read-only attribute.');
  14192. }
  14193. throw new python.Error('Tried to set nonexistent attribute.');
  14194. }
  14195. }
  14196. torch._C.AT_ASSERT(expectedType);
  14197. const newType = newValue.type();
  14198. if (!newType.isSubtypeOf(expectedType)) {
  14199. throw new python.Error('Wrong type for attribute assignment.');
  14200. }
  14201. const g = m.graph();
  14202. g.insertNode(g.createSetAttr(this._value, field, newValue));
  14203. }
  14204. getitem(loc, m, idx, type_hint) {
  14205. const val = this.getValue();
  14206. const val_type = val.type();
  14207. const g = m.graph();
  14208. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  14209. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  14210. } else if (val_type instanceof torch.DictType) {
  14211. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  14212. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  14213. 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));
  14214. } else if (val_type instanceof torch.ClassType) {
  14215. const class_type = val_type;
  14216. if (class_type.is_module() && type_hint) {
  14217. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  14218. res.setType(type_hint);
  14219. return new torch._C.SimpleValue(res);
  14220. }
  14221. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  14222. }
  14223. throw new python.Error('Object is not subscriptable.');
  14224. }
  14225. });
  14226. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  14227. constructor(self, method_names) {
  14228. super();
  14229. this._self = self;
  14230. this._method_names = method_names;
  14231. }
  14232. call(loc, f, args, kwargs /*, n_binders */) {
  14233. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  14234. const schemas = [];
  14235. for (const method_name of this._method_names) {
  14236. const type = this._self.type();
  14237. if (type instanceof torch.ClassType) {
  14238. const class_type = type;
  14239. const method = class_type.getMethod(method_name);
  14240. method.ensure_defined();
  14241. schemas.push(method.getSchema());
  14242. } else if (type instanceof torch.InterfaceType) {
  14243. const interface_type = type;
  14244. schemas.push(interface_type.getMethod(method_name));
  14245. } else {
  14246. throw new python.Error('Method constructed that is not a class or interface.');
  14247. }
  14248. }
  14249. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  14250. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  14251. output.node().setSourceRange(loc);
  14252. return new torch._C.SimpleValue(output);
  14253. }
  14254. });
  14255. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  14256. constructor(type) {
  14257. super();
  14258. this._type = type;
  14259. }
  14260. attr(loc, m, field) {
  14261. const hook = this._type.findHook(field);
  14262. if (hook) {
  14263. return new torch._C.FunctionValue(hook);
  14264. }
  14265. if (field !== '__new__') {
  14266. throw new python.Error('Tried to lookup unknown attribute on class.');
  14267. }
  14268. return torch._C.SpecialFormValue.create('prim::CreateObject');
  14269. }
  14270. });
  14271. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  14272. constructor(type) {
  14273. super();
  14274. this._type = type;
  14275. }
  14276. call(loc, m, args, kwargs /*, n_binders */) {
  14277. const g = m.graph();
  14278. const schema = this._type.schema();
  14279. torch._C.TORCH_INTERNAL_ASSERT(schema);
  14280. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  14281. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  14282. self.setType(this._type);
  14283. return new torch._C.SimpleValue(self);
  14284. }
  14285. });
  14286. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  14287. constructor(...args) {
  14288. super();
  14289. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  14290. this._callees = [args[0]];
  14291. } else {
  14292. throw new python.Error('Not implemented.');
  14293. }
  14294. }
  14295. call(loc, f, args, kwargs /*, n_binders */) {
  14296. const schemas = [];
  14297. for (const callee of this._callees) {
  14298. callee.ensure_defined();
  14299. schemas.push(callee.getSchema());
  14300. }
  14301. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  14302. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  14303. output.node().setSourceRange(loc);
  14304. return new torch._C.SimpleValue(output);
  14305. }
  14306. });
  14307. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  14308. });
  14309. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  14310. call(loc, m, args, kwargs /*, n_binders */) {
  14311. const g = m.graph();
  14312. if (kwargs.length > 0) {
  14313. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  14314. }
  14315. const lowered_inputs = torch._C.toValues(m.graph(), args);
  14316. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  14317. return new torch._C.NoneValue();
  14318. }
  14319. });
  14320. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  14321. constructor(form) {
  14322. super();
  14323. this._form = form;
  14324. }
  14325. form() {
  14326. return this._form;
  14327. }
  14328. static create(form) {
  14329. return new torch._C.SpecialFormValue(form);
  14330. }
  14331. });
  14332. this.registerFunction('torch._C.makeMagic', (name, base) => {
  14333. return new torch._C.MagicMethod(name, base);
  14334. });
  14335. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  14336. constructor(symbol, self) {
  14337. super();
  14338. this.symbol = symbol;
  14339. this.self = self;
  14340. }
  14341. call(loc, m, args, kwargs /*, n_binders */) {
  14342. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  14343. }
  14344. static tryCreate(symbol, self) {
  14345. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  14346. if (!self) {
  14347. return new torch._C.BuiltinFunction(symbol, null);
  14348. }
  14349. const index = op.schema().argumentIndexWithName('self');
  14350. if (index) {
  14351. const type_env = new Map();
  14352. const formal_type = op.schema().arguments()[index].type();
  14353. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  14354. if (!matched.success()) {
  14355. continue;
  14356. }
  14357. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  14358. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  14359. continue;
  14360. }
  14361. return new torch._C.BuiltinFunction(symbol, self);
  14362. }
  14363. }
  14364. return null;
  14365. }
  14366. });
  14367. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  14368. constructor(name, version) {
  14369. super();
  14370. this.name = name;
  14371. this.version = version || null;
  14372. }
  14373. attr(loc, m, field) {
  14374. if (field === 'autograd') {
  14375. return new torch._C.BuiltinModule('aten', this.version);
  14376. }
  14377. const sym = `${this.name}::${field}`;
  14378. return new torch._C.BuiltinFunction(sym, null);
  14379. }
  14380. });
  14381. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  14382. constructor(version) {
  14383. super();
  14384. this._version = version;
  14385. }
  14386. attr(loc, m, field) {
  14387. return new torch._C.BuiltinModule(field, this._version);
  14388. }
  14389. });
  14390. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  14391. constructor(constants) {
  14392. super();
  14393. this._constants = constants;
  14394. this.non_holding_object_cache = new Map();
  14395. }
  14396. attr(loc, m, field) {
  14397. const offset = parseInt(field.substring(1), 10);
  14398. if (!Number.isInteger(offset)) {
  14399. throw new python.Error(`Invalid constant identifier '${field}.`);
  14400. }
  14401. if (offset < 0 || offset >= this._constants.length) {
  14402. throw new python.Error('Invalid constant index.');
  14403. }
  14404. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  14405. let value = null;
  14406. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  14407. const obj = ivalue.toObject();
  14408. if (!this.non_holding_object_cache.has(obj)) {
  14409. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  14410. }
  14411. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  14412. } else {
  14413. value = m.graph().insertConstant(this._constants[offset], loc);
  14414. }
  14415. value.setType(torch._C.unshapedType(value.type()));
  14416. return new torch._C.SimpleValue(value);
  14417. }
  14418. });
  14419. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  14420. constructor(type, method) {
  14421. super(method, null);
  14422. this._type = type;
  14423. }
  14424. call(loc, m, args, kwargs, n_binders) {
  14425. if (args.length === 1 && kwargs.length === 0) {
  14426. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  14427. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  14428. const zero = m.graph().insertConstant(0);
  14429. const v = args[0].value(m.graph());
  14430. if (v.type().isSubtypeOf(this._type)) {
  14431. return new torch._C.SimpleValue(v);
  14432. } 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)) {
  14433. const len = len_op.call(loc, m, [v], [], 1);
  14434. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  14435. }
  14436. }
  14437. return super.call(loc, m, args, kwargs, n_binders);
  14438. }
  14439. });
  14440. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  14441. constructor(desugared_name, base) {
  14442. super();
  14443. this._base_value = base;
  14444. this._desugared_name = desugared_name;
  14445. }
  14446. call(loc, m, args, kwargs, n_binders) {
  14447. if (args.length > 0) {
  14448. const self = args[0].value(m.graph());
  14449. if (self.type() instanceof torch.ClassType) {
  14450. return new torch._C.SimpleValue(self)
  14451. .attr(loc, m, this._desugared_name)
  14452. .call(loc, m, args.slice(1), kwargs, n_binders);
  14453. }
  14454. }
  14455. if (!this._base_value) {
  14456. throw new python.Error('Invalid magic method.');
  14457. }
  14458. return this._base_value.call(loc, m, args, kwargs, n_binders);
  14459. }
  14460. });
  14461. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  14462. constructor(loc, m, inputs, static_len) {
  14463. super();
  14464. static_len = static_len || null;
  14465. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  14466. throw new python.Error('Invalid range inputs.');
  14467. }
  14468. const g = m.graph();
  14469. if (inputs.length === 1) {
  14470. [this._end] = inputs;
  14471. this._start = g.insertConstant(0, loc);
  14472. this._step = g.insertConstant(1, loc);
  14473. this._has_only_end = true;
  14474. } else {
  14475. [this._start, this._end] = inputs;
  14476. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  14477. this._has_only_end = false;
  14478. }
  14479. this._static_len = static_len;
  14480. }
  14481. staticLen() {
  14482. return this._static_len;
  14483. }
  14484. iter() {
  14485. return this;
  14486. }
  14487. len(loc, m) {
  14488. if (this._static_len) {
  14489. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  14490. }
  14491. if (this._has_only_end) {
  14492. return this._end;
  14493. }
  14494. const g = m.graph();
  14495. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  14496. }
  14497. getitem(loc, m, idx /*, type_hint */) {
  14498. if (this._has_only_end) {
  14499. return new torch._C.SimpleValue(idx);
  14500. }
  14501. const g = m.graph();
  14502. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  14503. }
  14504. });
  14505. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  14506. });
  14507. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  14508. constructor(name, si) {
  14509. super();
  14510. this._basename = name;
  14511. this._si = si;
  14512. }
  14513. attr(loc, m, name) {
  14514. const fullName = new torch._C.QualifiedName(this._basename, name);
  14515. const serializable_type = this._si.findNamedType(fullName);
  14516. if (serializable_type) {
  14517. if (serializable_type instanceof torch.ClassType) {
  14518. return new torch._C.ClassValue(serializable_type);
  14519. } else if (serializable_type instanceof torch.TupleType) {
  14520. return new torch._C.NamedTupleConstructor(serializable_type);
  14521. } else if (serializable_type instanceof torch.EnumType) {
  14522. return new torch._C.SugaredEnumClass(serializable_type);
  14523. }
  14524. }
  14525. const fn = this._si.findFunction(fullName);
  14526. if (fn) {
  14527. return new torch._C.FunctionValue(fn);
  14528. }
  14529. return new torch._C.ClassNamespaceValue(fullName, this._si);
  14530. }
  14531. });
  14532. this.registerType('torch.package.PackageImporter', class {
  14533. constructor(reader) {
  14534. this.zip_reader = reader;
  14535. }
  14536. load_pickle(module, resource) {
  14537. const name = `${module.replace(/\./, '/')}/${resource}`;
  14538. const stream = this.zip_reader.get_record(name);
  14539. const loaded_reduces = new Map();
  14540. this.storage_context = new torch._C.DeserializationStorageContext();
  14541. const unpickler = new pickle.Unpickler(stream);
  14542. unpickler.persistent_load = (saved_id) => {
  14543. switch (saved_id[0]) {
  14544. case 'storage': {
  14545. const [, storage_type, key, , size] = saved_id;
  14546. if (!this.storage_context.has_storage(key)) {
  14547. const storage = new storage_type(size);
  14548. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  14549. const buffer = stream.peek();
  14550. storage._set_cdata(buffer);
  14551. this.storage_context.add_storage(key, storage);
  14552. }
  14553. return this.storage_context.get_storage(key);
  14554. }
  14555. case 'reduce_package': {
  14556. if (saved_id.length === 2) {
  14557. const [, func, args] = saved_id;
  14558. return execution.invoke(func, args);
  14559. }
  14560. const [, reduce_id, func, args] = saved_id;
  14561. if (!loaded_reduces.has(reduce_id)) {
  14562. const value = execution.invoke(func, [this].concat(args));
  14563. loaded_reduces.set(reduce_id, value);
  14564. }
  14565. return loaded_reduces.get(reduce_id);
  14566. }
  14567. default: {
  14568. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  14569. }
  14570. }
  14571. };
  14572. const obj = unpickler.load();
  14573. this.storage_context = null;
  14574. return obj;
  14575. }
  14576. import_module(name) {
  14577. return execution.import(name);
  14578. }
  14579. });
  14580. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  14581. const cu = new torch.jit.CompilationUnit();
  14582. cu.execution = execution;
  14583. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  14584. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  14585. module.forward = cpp_module.forward; // remove
  14586. return module;
  14587. });
  14588. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  14589. switch (arguments.length) {
  14590. case 4: {
  14591. const [device, extra_files] = args;
  14592. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  14593. return deserializer.deserialize(device, extra_files);
  14594. }
  14595. case 5: {
  14596. const [storage_context, device, ts_id] = args;
  14597. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  14598. return deserializer.deserialize(device, null);
  14599. }
  14600. default: {
  14601. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  14602. }
  14603. }
  14604. });
  14605. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  14606. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  14607. });
  14608. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  14609. if (value instanceof torch.Node) {
  14610. const n = value;
  14611. if (n.kind() === 'prim::CallFunction') {
  14612. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  14613. const function_constant = n.input(0).node();
  14614. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  14615. return torch._C.tryToGraphFunction(fun_type.function());
  14616. }
  14617. if (n.kind() === 'prim::CallMethod') {
  14618. const name = n.s('name');
  14619. const class_type = n.input(0).type();
  14620. if (class_type instanceof torch.ClassType) {
  14621. const fn = class_type.getMethod(name);
  14622. return torch._C.tryToGraphFunction(fn);
  14623. }
  14624. }
  14625. return null;
  14626. } else if (value instanceof torch._C.Function) {
  14627. const fn = value;
  14628. if (!fn.isGraphFunction()) {
  14629. return null;
  14630. }
  14631. return fn;
  14632. }
  14633. throw new python.Error('Not implemented.');
  14634. });
  14635. this.registerType('torch._C.ModuleInstanceInfo', class {
  14636. constructor(module_type, instance_name) {
  14637. this._module_type = module_type;
  14638. this._instance_name = instance_name;
  14639. }
  14640. });
  14641. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  14642. torch._C.TORCH_CHECK(step !== 0);
  14643. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  14644. if (start._ === Number.MAX_SAFE_INTEGER) {
  14645. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  14646. }
  14647. if (stop._ === Number.MAX_SAFE_INTEGER) {
  14648. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  14649. }
  14650. if (start._ < 0) {
  14651. start._ += length;
  14652. if (start._ < 0) {
  14653. start._ = (step < 0) ? -1 : 0;
  14654. }
  14655. } else if (start._ >= length) {
  14656. start._ = (step < 0) ? length - 1 : length;
  14657. }
  14658. if (stop._ < 0) {
  14659. stop._ += length;
  14660. if (stop._ < 0) {
  14661. stop._ = (step < 0) ? -1 : 0;
  14662. }
  14663. } else if (stop._ >= length) {
  14664. stop._ = (step < 0) ? length - 1 : length;
  14665. }
  14666. if (step < 0) {
  14667. if (stop._ < start._) {
  14668. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  14669. }
  14670. } else if (start._ < stop._) {
  14671. return Math.floor((stop._ - start._ - 1) / step + 1);
  14672. }
  14673. return 0;
  14674. });
  14675. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  14676. if (v.node().kind() === 'prim::TupleConstruct') {
  14677. return v.node().inputs();
  14678. }
  14679. const g = v.owningGraph();
  14680. return g.insertNode(g.createTupleUnpack(v)).outputs();
  14681. });
  14682. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  14683. /*
  14684. const new_node_cs = new_node.callstack();
  14685. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  14686. if (!new_cs_entries.has(raw_callstack_ptr)) {
  14687. if (new_node_cs) {
  14688. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  14689. } else {
  14690. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  14691. }
  14692. }
  14693. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  14694. for (const block of new_node.blocks()) {
  14695. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  14696. }
  14697. */
  14698. });
  14699. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  14700. if (arg === undefined || typeof arg === 'boolean') {
  14701. const inline_optimized_graph = arg === undefined ? true : arg;
  14702. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  14703. return torch._C.inlineCallTo(to_replace, callee, graph);
  14704. }
  14705. if (arg instanceof torch.Graph === false) {
  14706. throw new python.Error('Invalid argument.');
  14707. }
  14708. const callee_graph = arg;
  14709. const guard = new torch._C.WithInsertPoint(to_replace);
  14710. const value_map = new Map();
  14711. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  14712. const new_callstack_entries = new Map();
  14713. let module_instance_info = null;
  14714. if (to_replace.kind() === 'prim::CallMethod') {
  14715. const class_type_ptr = to_replace.input(0).type();
  14716. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  14717. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  14718. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  14719. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  14720. } else {
  14721. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  14722. }
  14723. }
  14724. const updated_nodes = new Set();
  14725. for (const kv of value_map) {
  14726. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  14727. if (is_graph_input === -1) {
  14728. continue;
  14729. }
  14730. const new_node = kv[1].node();
  14731. if (updated_nodes.has(new_node)) {
  14732. continue;
  14733. }
  14734. updated_nodes.add(new_node);
  14735. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  14736. }
  14737. const old_outputs = to_replace.outputs();
  14738. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  14739. for (let i = 0; i < old_outputs.length; i++) {
  14740. if (old_outputs[i].hasDebugName()) {
  14741. new_outputs[i].setDebugName(old_outputs[i].debugName());
  14742. }
  14743. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  14744. }
  14745. to_replace.destroy();
  14746. guard.dispose();
  14747. return new_outputs;
  14748. });
  14749. this.registerFunction('torch._C.inlineCalls', (block) => {
  14750. for (const cur of block.nodes()) {
  14751. switch (cur.kind()) {
  14752. case 'prim::CallFunction': {
  14753. const graphFunction = torch._C.tryToGraphFunction(cur);
  14754. if (graphFunction) {
  14755. const function_constant = cur.input(0).node();
  14756. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  14757. cur.removeInput(0);
  14758. let g = null;
  14759. const fallback = function_constant.hasAttribute('fallback');
  14760. if (fallback && graphFunction.get_executor().isOptimized()) {
  14761. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  14762. if (!exec_plans.empty()) {
  14763. g = exec_plans.begin().second.graph;
  14764. torch._C.Inline(g);
  14765. }
  14766. }
  14767. if (g === null) {
  14768. g = graphFunction.optimized_graph();
  14769. }
  14770. torch._C.inlineCallTo(cur, graphFunction, g);
  14771. }
  14772. break;
  14773. }
  14774. case 'prim::CallMethod': {
  14775. const graphFunction = torch._C.tryToGraphFunction(cur);
  14776. if (graphFunction) {
  14777. torch._C.inlineCallTo(cur, graphFunction);
  14778. }
  14779. break;
  14780. }
  14781. default: {
  14782. for (const b of cur.blocks()) {
  14783. torch._C.inlineCalls(b);
  14784. }
  14785. }
  14786. }
  14787. }
  14788. });
  14789. this.registerFunction('torch._C.Inline', (graph) => {
  14790. torch._C.inlineCalls(graph.block());
  14791. });
  14792. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  14793. torch._C.Inline(graph);
  14794. });
  14795. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  14796. const cu = new torch.jit.CompilationUnit();
  14797. cu.execution = execution;
  14798. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  14799. return torch.jit._script.wrap_cpp_module(cpp_module);
  14800. });
  14801. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  14802. const init_fn = (script_module) => {
  14803. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  14804. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  14805. }
  14806. };
  14807. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  14808. });
  14809. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  14810. has_storage(name) {
  14811. return this.has(name);
  14812. }
  14813. get_storage(name) {
  14814. return this.get(name);
  14815. }
  14816. add_storage(name, storage) {
  14817. return this.set(name, storage);
  14818. }
  14819. });
  14820. this.registerType('torch.ScriptFunction', class {
  14821. constructor(name, graph /*, function_creator */) {
  14822. this._name = name;
  14823. this._graph = graph;
  14824. }
  14825. });
  14826. this.registerType('torch.ScriptMethod', class {
  14827. constructor(owner, value) {
  14828. this._owner = owner;
  14829. this._function = value;
  14830. }
  14831. get name() {
  14832. return this._function.name();
  14833. }
  14834. get owner() {
  14835. return this._owner;
  14836. }
  14837. __call__(/* args, kwargs */) {
  14838. throw new python.Error();
  14839. }
  14840. get graph() {
  14841. return this._function.graph();
  14842. }
  14843. get schema() {
  14844. // return this.function().getSchema();
  14845. throw new python.Error();
  14846. }
  14847. get code() {
  14848. throw new python.Error();
  14849. }
  14850. get code_with_constants() {
  14851. throw new python.Error();
  14852. }
  14853. });
  14854. this.registerType('torch.ScriptObject', class {
  14855. constructor(type) {
  14856. this._typ = type;
  14857. this._ivalue = {};
  14858. }
  14859. static create(type) {
  14860. if (type.is_module()) {
  14861. return new torch.ScriptModule(type);
  14862. }
  14863. return new torch.ScriptObject(type);
  14864. }
  14865. type() {
  14866. return this._typ;
  14867. }
  14868. _type() {
  14869. return this._typ; // torch.ClassType
  14870. }
  14871. find_method(basename) {
  14872. for (const fn of this.type().methods()) {
  14873. if (fn.name() === basename) {
  14874. return new torch.ScriptMethod(this /* _value() */, fn);
  14875. }
  14876. }
  14877. return null;
  14878. }
  14879. _get_method(name) {
  14880. const method = this.find_method(name);
  14881. if (method) {
  14882. return method;
  14883. }
  14884. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  14885. return null;
  14886. }
  14887. _has_method(name) {
  14888. return this.find_method(name) ? true : false;
  14889. }
  14890. __setattr__(name, value) {
  14891. // if (this._type.hasContant(name))
  14892. this._ivalue[name] = value;
  14893. }
  14894. __getattr__(name) {
  14895. return this._ivalue[name];
  14896. }
  14897. hasattr(name) {
  14898. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  14899. }
  14900. getattr(name) {
  14901. return this.__getattr__(name);
  14902. }
  14903. _properties() {
  14904. throw new python.Error();
  14905. }
  14906. is_weak_compilation_ref() {
  14907. return true; // not implemented
  14908. }
  14909. });
  14910. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  14911. constructor(...args) {
  14912. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  14913. const [class_name, cu, shouldMangle] = args;
  14914. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  14915. } else {
  14916. super(...args);
  14917. }
  14918. }
  14919. get qualified_name() {
  14920. return this.type().qualified_name();
  14921. }
  14922. get code_with_constants() {
  14923. const const_map = {};
  14924. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  14925. return [null, const_map];
  14926. }
  14927. get graph() {
  14928. if (!this._graph) {
  14929. const fn = this._typ.getMethod('forward');
  14930. this._graph = fn.graph();
  14931. }
  14932. return this._graph;
  14933. }
  14934. static create_module_object(class_name, cu, shouldMangle) {
  14935. shouldMangle = shouldMangle || false;
  14936. if (!class_name.prefix()) {
  14937. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  14938. }
  14939. if (shouldMangle && cu.get_class(class_name)) {
  14940. class_name = cu.mangle(class_name);
  14941. }
  14942. const cls = torch.ClassType.create(class_name, cu, true);
  14943. cu.register_type(cls);
  14944. return [cls, cu];
  14945. }
  14946. register_module(name, module) {
  14947. this.type().addOrCheckAttribute(name, module.type());
  14948. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  14949. }
  14950. register_buffer(name, v) {
  14951. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  14952. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  14953. }
  14954. register_parameter(name, v, is_buffer) {
  14955. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  14956. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  14957. }
  14958. register_attribute(name, t, v, is_param, is_buffer) {
  14959. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  14960. // _ivalue()->setAttr(name, v);
  14961. }
  14962. });
  14963. this.registerType('torch.ModuleDict', class {
  14964. constructor(mod) {
  14965. this._module = mod;
  14966. }
  14967. items() {
  14968. const result = new Map();
  14969. const type = this._module.type();
  14970. for (let i = 0; i < type.numAttributes(); i++) {
  14971. const k = type.getAttributeName(i);
  14972. const t = type.getAttribute(i);
  14973. if (t && t.is_module()) {
  14974. result.set(k, this._module.__getattr__(k));
  14975. }
  14976. }
  14977. return result;
  14978. }
  14979. });
  14980. this.registerType('torch.ParameterDict', class {
  14981. constructor(mod) {
  14982. this._module = mod;
  14983. }
  14984. items() {
  14985. const result = new Map();
  14986. const type = this._module.type();
  14987. for (let i = 0; i < type.numAttributes(); i++) {
  14988. if (type.is_parameter(i)) {
  14989. const k = type.getAttributeName(i);
  14990. const v = this._module.__getattr__(k);
  14991. if (v instanceof torch.Tensor) {
  14992. result.set(k, v);
  14993. }
  14994. }
  14995. }
  14996. return result;
  14997. }
  14998. });
  14999. this.registerType('torch.BufferDict', class {
  15000. constructor(mod) {
  15001. this._module = mod;
  15002. }
  15003. items() {
  15004. const result = new Map();
  15005. const type = this._module.type();
  15006. for (let i = 0; i < type.numAttributes(); i++) {
  15007. if (type.is_buffer(i)) {
  15008. const t = type.getAttribute(i);
  15009. if (t.isSubtypeOf(torch.TensorType.get())) {
  15010. const k = type.getAttributeName(i);
  15011. const v = this._module.__getattr__(k);
  15012. result.set(k, v);
  15013. }
  15014. }
  15015. }
  15016. return result;
  15017. }
  15018. });
  15019. this.registerType('torch._C.to_ir', class {
  15020. constructor(def, _resolver, self, method) {
  15021. this.method = method;
  15022. this.graph = method.graph();
  15023. this.resolver = _resolver;
  15024. this.integral_constants = new Map();
  15025. this.fp_constants = new Map();
  15026. this.complex_constants = new Map();
  15027. this.exit_blocks = new Set();
  15028. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  15029. this._loop_status = 'NOT_IN_LOOP';
  15030. this.environment_stack = null;
  15031. this._def_stack = [];
  15032. this._temp_name_count = 0;
  15033. torch._C.AT_ASSERT(this.resolver);
  15034. this.pushFrame(this.graph.block(), true);
  15035. if (self && def && def.args.args.length === 0) {
  15036. throw new python.Error('Method must have a self argument.');
  15037. }
  15038. method.setSchema(this.emitDef(def, self, this.graph.block()));
  15039. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  15040. torch._C.ConvertToSSA(this.graph);
  15041. torch._C.CanonicalizeModifiedLoops(this.graph);
  15042. torch._C.NormalizeOps(this.graph.block());
  15043. torch._C.runCleanupPasses(this.graph);
  15044. }
  15045. pushFrame(b, starts_def) {
  15046. starts_def = starts_def || false;
  15047. if (starts_def) {
  15048. this._def_stack.push({});
  15049. }
  15050. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  15051. }
  15052. popFrame(ends_def) {
  15053. const old_frame = this.environment_stack;
  15054. this.environment_stack = this.environment_stack.next;
  15055. if (ends_def) {
  15056. this._def_stack.pop();
  15057. }
  15058. return old_frame;
  15059. }
  15060. emitDef(def, self, block) {
  15061. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  15062. if (schema.returns.length === 1) {
  15063. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  15064. }
  15065. const args = this.emitFormalArguments(def, self, schema, block);
  15066. this.emitStatements(def.body);
  15067. this.handleMaybeNoReturn(def, block);
  15068. const returns = [this.emitOutput(def, schema, block)];
  15069. return new torch.FunctionSchema(def.name, '', args, returns);
  15070. }
  15071. emitFormalArguments(def, self, schema, block) {
  15072. const args = [];
  15073. const params = def.args.args;
  15074. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  15075. if (schema.arguments.length !== expected_annotation_size) {
  15076. throw new python.Error('Invalid formal arguments.');
  15077. }
  15078. let it = 0;
  15079. if (self) {
  15080. const param = params[it];
  15081. const name = param.arg;
  15082. const new_input = block.addInput().setDebugName(name);
  15083. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  15084. args.push(new torch.Argument(name, new_input.type()));
  15085. it++;
  15086. }
  15087. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  15088. let arg_annotation_idx = 0;
  15089. for (; it < params.length; it++) {
  15090. const param = params[it];
  15091. const name = param.arg;
  15092. const new_input = block.addInput();
  15093. if (torch._C.meaningfulName(name)) {
  15094. new_input.setDebugName(name);
  15095. }
  15096. let arg = schema.arguments[arg_annotation_idx++];
  15097. if (shouldDeriveType) {
  15098. if (schema.arguments.length === 1) {
  15099. throw new python.Error('Invalid schema.');
  15100. }
  15101. const inferredStateType = this.getTypeForSetStateArg(def, self);
  15102. arg = arg.cloneWithType(inferredStateType);
  15103. }
  15104. args.push(arg);
  15105. new_input.setType(arg.type);
  15106. this.environment_stack.setVar(param.range(), name, new_input);
  15107. }
  15108. return args;
  15109. }
  15110. emitOutput(range, schema, block) {
  15111. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  15112. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  15113. block.registerOutput(placeholder_return);
  15114. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  15115. }
  15116. emitStatements(stmts) {
  15117. for (let i = 0; i < stmts.length; i++) {
  15118. const stmt = stmts[i];
  15119. if (stmt instanceof ast.If) {
  15120. this.emitIf(stmt);
  15121. } else if (stmt instanceof ast.While) {
  15122. this.emitWhile(stmt);
  15123. } else if (stmt instanceof ast.For) {
  15124. this.emitFor(stmt);
  15125. } else if (stmt instanceof ast.Assign) {
  15126. this.emitAssignment(stmt);
  15127. } else if (stmt instanceof ast.AnnAssign) {
  15128. this.emitAssignment(stmt);
  15129. } else if (stmt instanceof ast.Expr) {
  15130. this.emitSugaredExpr(stmt.value, 0);
  15131. } else if (stmt instanceof ast.Return) {
  15132. this.emitReturn(stmt);
  15133. } else if (stmt instanceof ast.Pass) {
  15134. // pass
  15135. } else if (stmt instanceof ast.With) {
  15136. this.emitWith(stmt);
  15137. } else {
  15138. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  15139. }
  15140. if (this.exit_blocks.has(this.environment_stack.block())) {
  15141. return;
  15142. }
  15143. }
  15144. }
  15145. emitWith(stmt) {
  15146. const targets = stmt.items;
  15147. const entered = [];
  15148. for (const target of targets) {
  15149. const e = target.context_expr;
  15150. const rhs = this.emitExpr(e);
  15151. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  15152. entered.push(rhs);
  15153. if (rhs.type() instanceof torch.ClassType === false) {
  15154. throw new python.Error('With item expression must return an object.');
  15155. }
  15156. const rhsClass = rhs.type();
  15157. const enterMethod = rhsClass.findMethod('__enter__');
  15158. const exitMethod = rhsClass.findMethod('__exit__');
  15159. if (!enterMethod || !exitMethod) {
  15160. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  15161. }
  15162. const enterSchema = enterMethod.getSchema();
  15163. if (enterSchema.arguments.length !== 1) {
  15164. throw new python.Error('__enter__ must have only one argument and one return value.');
  15165. }
  15166. const exitSchema = exitMethod.getSchema();
  15167. if (exitSchema.arguments.length === 4) {
  15168. for (let i = 1; i < 4; i++) {
  15169. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  15170. throw new python.Error('Argument of __exit__ must have Any type.');
  15171. }
  15172. }
  15173. } else {
  15174. throw new python.Error('__exit__ must have four arguments');
  15175. }
  15176. n.output(0).setType(enterSchema.returns[0].type);
  15177. if (target.optional_vars) {
  15178. throw new python.Error('Not implemented.');
  15179. // Var i = target.var().get();
  15180. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  15181. }
  15182. }
  15183. this.emitStatements(stmt.body);
  15184. while (entered.length > 0) {
  15185. const input = entered.pop();
  15186. const n = this.graph.create('prim::Exit');
  15187. this.graph.insertNode(n);
  15188. n.addInput(input);
  15189. }
  15190. }
  15191. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  15192. let max_trip_count_val = null;
  15193. if (iter_val === null) {
  15194. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  15195. } else {
  15196. max_trip_count_val = iter_val.len(range, this.method);
  15197. }
  15198. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  15199. const body_block = n.addBlock();
  15200. {
  15201. const condition_block = n.addBlock();
  15202. this.pushFrame(condition_block);
  15203. let out = null;
  15204. if (cond) {
  15205. const insert = new torch._C.WithInsertPoint(condition_block);
  15206. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  15207. insert.dispose();
  15208. } else {
  15209. const insert = new torch._C.WithInsertPoint(n);
  15210. out = this.graph.insertConstant(true, range);
  15211. insert.dispose();
  15212. }
  15213. condition_block.registerOutput(out);
  15214. this.popFrame();
  15215. }
  15216. n.addInput(max_trip_count_val);
  15217. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  15218. const trip_count = body_block.addInput().setType(torch.IntType.get());
  15219. {
  15220. this.pushFrame(body_block);
  15221. const guard = new torch._C.WithInsertPoint(body_block);
  15222. if (iter_val !== null && targets) {
  15223. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  15224. const sv = new torch._C.SimpleValue(cur_elem);
  15225. const target_exprs = targets;
  15226. this.validateAssignLhsExpr(target_exprs, range);
  15227. if (target_exprs.length > 1) {
  15228. throw new python.Error('Not implemented.');
  15229. // const tl = torch.TupleLiteral.create(range, target_exprs);
  15230. // target_exprs = ListExpr.create(range, [tl]);
  15231. }
  15232. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  15233. }
  15234. emit_body();
  15235. this.popFrame();
  15236. guard.dispose();
  15237. }
  15238. loop_guard.dispose();
  15239. }
  15240. emitFor(...args) {
  15241. if (args.length === 1 && args[0] instanceof ast.For) {
  15242. const [stmt] = args;
  15243. const emit_body = () => this.emitStatements(stmt.body);
  15244. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  15245. } else if (args.length === 4) {
  15246. const [targets, itrs, loc, emit_body] = args;
  15247. if (itrs instanceof ast.Tuple) {
  15248. throw new python.Error('List of iterables is not supported currently.');
  15249. }
  15250. const sv = this.emitSugaredExpr(itrs, 1);
  15251. const iterable = sv.iter(loc, this.method);
  15252. if (iterable.shouldEmitUnrolled()) {
  15253. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  15254. } else {
  15255. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  15256. }
  15257. } else {
  15258. throw new python.Error('Not implemented.');
  15259. }
  15260. }
  15261. emitWhile(stmt) {
  15262. const cond = stmt.test;
  15263. const emit_body = () => this.emitStatements(stmt.body);
  15264. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  15265. }
  15266. emitIsInstance(obj, classinfo) {
  15267. const lhs_val = this.emitExpr(obj);
  15268. const lhs_types = [];
  15269. const rhs_types = [];
  15270. const gather_rhs = (expr) => {
  15271. if (expr instanceof ast.Tuple) {
  15272. for (const e of expr.elts) {
  15273. gather_rhs(e);
  15274. }
  15275. return;
  15276. }
  15277. const type = this._typeParser.parseTypeFromExpr(expr);
  15278. rhs_types.push(type);
  15279. };
  15280. lhs_types.push(lhs_val.type());
  15281. gather_rhs(classinfo);
  15282. torch._C.standardizeVectorForUnion(lhs_types);
  15283. torch._C.standardizeVectorForUnion(rhs_types);
  15284. let refinement = new torch._C.RefinementSet([], []);
  15285. let unified_true = null;
  15286. let unified_false = null;
  15287. const isinstance_types = [];
  15288. const not_isinstance_types = [];
  15289. let true_refinements = [];
  15290. let false_refinements = [];
  15291. let all_lhs_subtype_some_rhs = true;
  15292. for (const lhs_type of lhs_types) {
  15293. if (lhs_type === torch.AnyType.get()) {
  15294. isinstance_types.push(...rhs_types);
  15295. not_isinstance_types.push(torch.AnyType.get());
  15296. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  15297. all_lhs_subtype_some_rhs = false;
  15298. }
  15299. break;
  15300. }
  15301. const get_smaller_type = (t1, t2) => {
  15302. if (t1.isSubtypeOf(t2)) {
  15303. return t1;
  15304. } else if (t2.isSubtypeOf(t1)) {
  15305. return t2;
  15306. }
  15307. return null;
  15308. };
  15309. let found_refinement = null;
  15310. for (const rhs_type of rhs_types) {
  15311. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  15312. if (!maybe_smaller_type) {
  15313. continue;
  15314. } else if (maybe_smaller_type === lhs_type) {
  15315. found_refinement = lhs_type;
  15316. } else if (maybe_smaller_type === rhs_type) {
  15317. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  15318. }
  15319. }
  15320. if (found_refinement) {
  15321. if (found_refinement === lhs_type) {
  15322. all_lhs_subtype_some_rhs &= true;
  15323. }
  15324. isinstance_types.push(found_refinement);
  15325. } else {
  15326. not_isinstance_types.push(lhs_type);
  15327. all_lhs_subtype_some_rhs = false;
  15328. }
  15329. }
  15330. if (isinstance_types.length > 0) {
  15331. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  15332. }
  15333. if (obj instanceof ast.Name && unified_true) {
  15334. const ident = obj.id;
  15335. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  15336. }
  15337. if (not_isinstance_types.length > 0) {
  15338. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  15339. }
  15340. if (obj instanceof ast.Name && unified_false) {
  15341. const ident = obj.id;
  15342. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  15343. }
  15344. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  15345. const is_statically_false = isinstance_types.length === 0;
  15346. if (all_lhs_subtype_some_rhs) {
  15347. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  15348. }
  15349. if (is_statically_false) {
  15350. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  15351. }
  15352. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  15353. return new torch._C.CondValue(result, refinement, null);
  15354. }
  15355. emitIf(stmt) {
  15356. const cond_value = this.emitCondExpr(stmt.test);
  15357. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  15358. }
  15359. emitCondExpr(expr) {
  15360. /*
  15361. switch (expr.kind()) {
  15362. case TK_AND:
  15363. case TK_OR: {
  15364. const binop = BinOp(expr);
  15365. return emitShortCircuitLogical(
  15366. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  15367. }
  15368. case TK_NOT: {
  15369. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  15370. Value* result = emitBuiltinCall(
  15371. expr.range(), *graph, aten::__not__, {v.value()}, {});
  15372. std::optional<bool> static_if;
  15373. if (v.staticIf()) {
  15374. static_if = !*v.staticIf();
  15375. }
  15376. return CondValue(result, v.refinements().Not(), static_if);
  15377. } break;
  15378. case TK_IS:
  15379. case TK_ISNOT: {
  15380. // meta programming on AST for is/is not cases and emit branches base on
  15381. const cond_op = BinOp(expr);
  15382. Value* lhs_val = emitExpr(cond_op.lhs());
  15383. Value* rhs_val = emitExpr(cond_op.rhs());
  15384. const lhs_none = canBeNone(lhs_val);
  15385. const rhs_none = canBeNone(rhs_val);
  15386. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  15387. // AA, -> statically IS always holds, IS_NOT never holds
  15388. // AN , NA-> statically IS_NOT always holds, IS never holds
  15389. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  15390. bool its_is = expr.kind() == TK_IS;
  15391. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  15392. return CondValue(*graph, expr.range(), its_is, {});
  15393. } else if (
  15394. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  15395. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  15396. // lhs_val/rhs_val with A/M: only emit never_none_branch
  15397. return CondValue(*graph, expr.range(), !its_is, {});
  15398. } else {
  15399. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  15400. Value* cond_value = emitBuiltinCall(
  15401. expr.get()->range(),
  15402. *method.graph(),
  15403. kind,
  15404. {lhs_val, rhs_val},
  15405. {});
  15406. const refinements = RefinementSet(findIsNoneRefinements(
  15407. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  15408. return CondValue(cond_value, refinements, null);
  15409. }
  15410. } break;
  15411. */
  15412. if (expr instanceof ast.UnaryOp) {
  15413. throw new python.Error('Not implemented.');
  15414. }
  15415. if (expr instanceof ast.Call) {
  15416. const apply = expr;
  15417. const callee = expr.func;
  15418. if (callee instanceof ast.Name) {
  15419. if (callee.id === 'isinstance') {
  15420. this.checkApplyNumInputs(apply, 2);
  15421. return this.emitIsInstance(apply.args[0], apply.args[1]);
  15422. }
  15423. if (callee.id === 'hasattr') {
  15424. this.checkApplyNumInputs(apply, 2);
  15425. return this.emitHasAttr(apply.args[0], apply.args[1]);
  15426. }
  15427. const sv = this.emitSugaredExpr(callee, 1);
  15428. if (sv instanceof torch._C.SpecialFormValue) {
  15429. if (sv.form() === 'prim::isinstance') {
  15430. this.checkApplyNumInputs(apply, 2);
  15431. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  15432. }
  15433. }
  15434. }
  15435. }
  15436. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  15437. let static_if = null;
  15438. const kind = expr_out.node().kind();
  15439. if (kind === 'aten::is_scripting') {
  15440. static_if = true;
  15441. } else if (kind === 'aten::has_torch_function') {
  15442. static_if = false;
  15443. }
  15444. const maybe_ivalue = torch._C.toIValue(expr_out);
  15445. if (maybe_ivalue) {
  15446. static_if = maybe_ivalue.toBool();
  15447. }
  15448. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  15449. }
  15450. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  15451. if (cond_value.staticIf() !== null) {
  15452. if (cond_value.staticIf()) {
  15453. this.insertRefinements(loc, cond_value.refinements());
  15454. this.emitStatements(trueBranch);
  15455. } else {
  15456. this.insertRefinements(loc, cond_value.refinements().Not());
  15457. this.emitStatements(falseBranch);
  15458. }
  15459. return;
  15460. }
  15461. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  15462. n.addInput(cond_value.value());
  15463. const true_block = n.addBlock();
  15464. const false_block = n.addBlock();
  15465. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  15466. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  15467. const true_exits = this.exit_blocks.has(true_block);
  15468. const false_exits = this.exit_blocks.has(false_block);
  15469. if (true_exits && false_exits) {
  15470. this.exit_blocks.add(n.owningBlock());
  15471. }
  15472. const mutated_variables = new Set();
  15473. for (const v of save_true.definedVariables()) {
  15474. const insert = new torch._C.WithInsertPoint(false_block);
  15475. if (save_false.findInAnyFrame(v) || false_exits) {
  15476. mutated_variables.add(v);
  15477. } else {
  15478. this.environment_stack.setVariableTypeError(v, () => 'Value is is not defined in the false branch.');
  15479. }
  15480. insert.dispose();
  15481. }
  15482. for (const v of save_false.definedVariables()) {
  15483. const insert = new torch._C.WithInsertPoint(true_block);
  15484. if (save_true.findInAnyFrame(v) || true_exits) {
  15485. mutated_variables.add(v);
  15486. } else {
  15487. this.environment_stack.setVariableTypeError(v, () => 'Value is is not defined in the true branch.');
  15488. }
  15489. insert.dispose();
  15490. }
  15491. for (const x of mutated_variables) {
  15492. let tv = null;
  15493. let fv = null;
  15494. {
  15495. const insert = new torch._C.WithInsertPoint(true_block);
  15496. if (!true_exits) {
  15497. tv = save_true.getVar(x, loc);
  15498. }
  15499. insert.dispose();
  15500. }
  15501. {
  15502. const insert = new torch._C.WithInsertPoint(false_block);
  15503. if (!false_exits) {
  15504. fv = save_false.getVar(x, loc);
  15505. }
  15506. insert.dispose();
  15507. }
  15508. if (true_exits && false_exits) {
  15509. continue;
  15510. } else if (true_exits) {
  15511. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  15512. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  15513. } else if (false_exits) {
  15514. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  15515. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  15516. }
  15517. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  15518. let full_type = null;
  15519. if (maybe_sugared_x) {
  15520. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  15521. if (maybe_simple) {
  15522. full_type = maybe_simple.type();
  15523. }
  15524. }
  15525. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  15526. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  15527. if (!unified) {
  15528. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  15529. throw new python.Error('Type mismatch.');
  15530. } else {
  15531. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  15532. continue;
  15533. }
  15534. }
  15535. this.environment_stack.setType(x, unified);
  15536. }
  15537. }
  15538. emitSingleIfBranch(b, branch, refinements) {
  15539. this.pushFrame(b);
  15540. const guard = new torch._C.WithInsertPoint(b);
  15541. this.insertRefinements(branch, refinements);
  15542. this.emitStatements(branch);
  15543. const frame = this.popFrame();
  15544. guard.dispose();
  15545. return frame;
  15546. }
  15547. create(kind, loc, n_outputs) {
  15548. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  15549. }
  15550. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  15551. is_dict_constructor = is_dict_constructor || false;
  15552. if (refined_type_hint_ptr instanceof torch.UnionType) {
  15553. throw new python.Error('Not implemented.');
  15554. } else if (refined_type_hint_ptr instanceof torch.OptionalType) {
  15555. refined_type_hint_ptr = refined_type_hint_ptr.getElementType();
  15556. }
  15557. if (is_dict_constructor) {
  15558. return;
  15559. }
  15560. if (all_candidates.length === 0) {
  15561. if (type_match(refined_type_hint_ptr)) {
  15562. do_if_match();
  15563. } else if (refined_type_hint_ptr.kind() === 'AnyType') {
  15564. do_if_anytype();
  15565. } else {
  15566. throw new python.Error('Invalid annotation type.');
  15567. }
  15568. }
  15569. }
  15570. emitToBool(loc, v) {
  15571. let out = null;
  15572. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  15573. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  15574. if (!out) {
  15575. throw new python.Error('Could not cast value to bool.');
  15576. }
  15577. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  15578. throw new python.Error('Expected a bool expression for condition.');
  15579. }
  15580. return out;
  15581. }
  15582. emitUnaryOp(tree, magicMethod, opSymbol) {
  15583. const inputs = [tree.operand];
  15584. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  15585. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  15586. if (val.node().kind() !== opSymbol) {
  15587. return val;
  15588. }
  15589. const maybe_out_stack = this.runNodeIfInputsAreConstant(val.node());
  15590. if (!maybe_out_stack) {
  15591. return val;
  15592. }
  15593. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  15594. return this.graph.insertConstant(maybe_out_stack[0], tree);
  15595. }
  15596. emitAssignment(stmt) {
  15597. if (stmt instanceof ast.AnnAssign) {
  15598. return this.emitSingleAssignment(stmt);
  15599. }
  15600. if (stmt.targets.length === 1) {
  15601. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  15602. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  15603. for (const [key, value] of entries) {
  15604. assign[key] = value;
  15605. }
  15606. return this.emitSingleAssignment(assign);
  15607. }
  15608. if (stmt.targets.length <= 1) {
  15609. throw new python.Error('Invalid assignment.');
  15610. }
  15611. throw new python.Error('Not implemented.');
  15612. /*
  15613. const tmp_name = this.createTempName('$tmp_assign_');
  15614. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  15615. const ident = new ast.Name(tmp_name);
  15616. for (const expr of lhs_list) {
  15617. const assign = new ast.Assign(targets, value, ctx);
  15618. this.emitSingleAssignment(Assign.create(stmt,
  15619. List<Expr>.create(expr.range(), [expr]),
  15620. Maybe<Expr>::create(stmt.rhs().range(), ident),
  15621. Maybe<Expr>::create(stmt.range())));
  15622. }
  15623. */
  15624. }
  15625. emitSingleAssignment(stmt) {
  15626. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  15627. const rhs = stmt.value;
  15628. const lhs = stmt.target;
  15629. if (lhs instanceof ast.Name) {
  15630. let type = null;
  15631. if (stmt.annotation) {
  15632. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  15633. }
  15634. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  15635. // BC HACK
  15636. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  15637. } else if (lhs instanceof ast.Tuple) {
  15638. this.emitTupleAssign(lhs, rhs);
  15639. } else if (lhs instanceof ast.Attribute) {
  15640. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  15641. } else {
  15642. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  15643. }
  15644. }
  15645. emitSelectAssign(lhs, rhs, type, loc) {
  15646. if (!rhs) {
  15647. throw new python.Error('Expected RHS for assignment.');
  15648. }
  15649. let type_hint = null;
  15650. if (type) {
  15651. type_hint = this._typeParser.parseTypeFromExpr(type);
  15652. }
  15653. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  15654. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  15655. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  15656. }
  15657. emitTupleAssign(...args) {
  15658. if (args.length === 2) {
  15659. const [tl, rhs] = args;
  15660. let n_binders = tl.elts.length;
  15661. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  15662. if (starred_unpack) {
  15663. n_binders--;
  15664. }
  15665. const output = this.emitSugaredExpr(rhs, n_binders);
  15666. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  15667. } else if (args.length === 5) {
  15668. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  15669. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  15670. if (outputs.length < n_binders) {
  15671. throw new python.Error('Not enough values to unpack.');
  15672. }
  15673. if (outputs.length > n_binders && !starred_unpack) {
  15674. throw new python.Error('Too many values to unpack.');
  15675. }
  15676. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  15677. } else {
  15678. throw new python.Error('Not implemented.');
  15679. }
  15680. }
  15681. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  15682. let i = 0;
  15683. for (const assignee of lhs_exprs) {
  15684. if (assignee instanceof ast.Subscript) {
  15685. throw new python.Error('Not implemented.');
  15686. /*
  15687. this.emitSubscriptAssign(
  15688. rhs_loc,
  15689. Subscript(assignee),
  15690. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  15691. i++;
  15692. */
  15693. } else if (assignee instanceof ast.Name) {
  15694. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  15695. i++;
  15696. } else if (assignee instanceof ast.Starred) {
  15697. throw new python.Error('Not implemented.');
  15698. /*
  15699. const var = Starred(assignee).expr();
  15700. if (var.kind() != TK_VAR) {
  15701. throw(
  15702. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  15703. }
  15704. size_t n_matched = outputs.size() - n_binders;
  15705. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  15706. const values = fmap(
  15707. outputs_ref.slice(i, n_matched),
  15708. [&](const std::shared_ptr<SugaredValue>& v) {
  15709. return v.asValue(assignee.range(), method);
  15710. });
  15711. const tup = graph.insertNode(graph.createTuple(values)).output();
  15712. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  15713. i += n_matched;
  15714. */
  15715. } else if (assignee instanceof ast.Tuple) {
  15716. throw new python.Error('Not implemented.');
  15717. /*
  15718. // recursively emit tuple assignments on tuple literal input
  15719. TupleLiteral sub_tl = TupleLiteral(assignee);
  15720. size_t sub_n_binders = sub_tl.inputs().length;
  15721. bool sub_starred_unpack =
  15722. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  15723. if (sub_starred_unpack)
  15724. sub_n_binders--;
  15725. emitTupleAssign(
  15726. sub_tl,
  15727. outputs.at(i),
  15728. rhs_loc,
  15729. sub_n_binders,
  15730. sub_starred_unpack);
  15731. i++;
  15732. */
  15733. } else if (assignee instanceof ast.Attribute) {
  15734. throw new python.Error('Not implemented.');
  15735. /*
  15736. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  15737. i++;
  15738. */
  15739. } else {
  15740. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  15741. }
  15742. }
  15743. }
  15744. emitReturn(stmt) {
  15745. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  15746. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  15747. if (declared_return_type) {
  15748. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  15749. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  15750. }
  15751. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  15752. throw new python.Error(`Invalid return type.`);
  15753. }
  15754. } else {
  15755. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  15756. if (!declared_return_type) {
  15757. declared_return_type = actual_return.type();
  15758. }
  15759. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  15760. if (!merged_return_type) {
  15761. throw new python.Error(`Invalid return type.`);
  15762. }
  15763. declared_return_type = merged_return_type;
  15764. }
  15765. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  15766. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  15767. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  15768. }
  15769. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  15770. this.exit_blocks.add(this.environment_stack.block());
  15771. }
  15772. getNamedValues(trees, maybe_unpack) {
  15773. const values = [];
  15774. for (const tree of trees) {
  15775. if (maybe_unpack && tree instanceof ast.Starred) {
  15776. throw new python.Error('Starred argument not supported.');
  15777. } else {
  15778. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  15779. }
  15780. }
  15781. return values;
  15782. }
  15783. getValues(trees, maybe_unpack) {
  15784. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  15785. }
  15786. emitExpr(tree, type_hint) {
  15787. type_hint = type_hint || null;
  15788. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  15789. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  15790. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  15791. }
  15792. return out_val;
  15793. }
  15794. emitSugaredExpr(tree, n_binders, type_hint) {
  15795. if (tree instanceof ast.Name) { // TK_VAR
  15796. return this.environment_stack.getSugaredVar(tree.id);
  15797. } else if (tree instanceof ast.Attribute) {
  15798. const sv = this.emitSugaredExpr(tree.value, 1);
  15799. return sv.attr(tree.range(), this.method, tree.attr);
  15800. } else if (tree instanceof ast.Call) { // TK_APPLY
  15801. return this.emitApplyExpr(tree, n_binders, type_hint);
  15802. } if (tree instanceof ast.Subscript) {
  15803. return this.emitSubscript(tree, type_hint);
  15804. }
  15805. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  15806. }
  15807. emitApplyExpr(apply, n_binders, type_hint) {
  15808. type_hint = type_hint || null;
  15809. const sv = this.emitSugaredExpr(apply.func, 1);
  15810. const loc = apply.func.range();
  15811. if (sv instanceof torch._C.SpecialFormValue) {
  15812. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  15813. }
  15814. const args = this.getNamedValues(apply.args, true);
  15815. const kwargs = this.emitAttributes(apply.keywords);
  15816. return sv.call(loc, this.method, args, kwargs, n_binders);
  15817. }
  15818. emitAttributes(attributes) {
  15819. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  15820. }
  15821. emitApplySpecialForm(form, apply, sv, type_hint) {
  15822. switch (form) {
  15823. case 'prim::fork': {
  15824. throw new python.Error('Not implemented.');
  15825. }
  15826. case 'prim::awaitable': {
  15827. throw new python.Error('Not implemented.');
  15828. }
  15829. case 'prim::annotate': {
  15830. this.checkApplyNumInputs(apply, 2);
  15831. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  15832. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  15833. if (!expr.type().isSubtypeOf(type)) {
  15834. throw new python.Error('Invalid expression type.');
  15835. }
  15836. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  15837. const none = this.graph.createNone();
  15838. none.output().setType(type);
  15839. this.graph.insertNode(none);
  15840. expr = none.output();
  15841. }
  15842. return new torch._C.SimpleValue(expr);
  15843. }
  15844. case 'prim::unchecked_cast': {
  15845. this.checkApplyNumInputs(apply, 2);
  15846. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  15847. let v = this.emitExpr(apply.args[1]);
  15848. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  15849. v = this.graph.insertUncheckedCast(v, type);
  15850. }
  15851. return new torch._C.SimpleValue(v);
  15852. }
  15853. case 'prim::GetAttr': {
  15854. this.checkApplyNumInputsRange(apply, 2, 3);
  15855. const obj = this.emitSugaredExpr(apply.args[0], 1);
  15856. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  15857. throw new python.Error('Invalid argument.');
  15858. }
  15859. const name = apply.args[1].value;
  15860. if (apply.args.length === 2) {
  15861. return obj.attr(apply, this.method, name);
  15862. } else if (obj.hasAttr(apply, this.method, name)) {
  15863. return obj.attr(apply, this.method, name);
  15864. }
  15865. return this.emitSugaredExpr(apply.inputs()[2], 1);
  15866. }
  15867. case 'prim::Uninitialized': {
  15868. this.checkApplyNumInputs(apply, 1);
  15869. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  15870. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  15871. return new torch._C.SimpleValue(out.output());
  15872. }
  15873. case 'prim::TupleConstruct': {
  15874. throw new python.Error('Not implemented.');
  15875. }
  15876. case 'prim::isinstance': {
  15877. this.checkApplyNumInputs(apply, 2);
  15878. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  15879. return new torch._C.SimpleValue(result.value());
  15880. }
  15881. case 'prim::tolist': {
  15882. const value = apply.func.value;
  15883. const operand = this.emitSugaredExpr(value, 1);
  15884. if (!type_hint) {
  15885. throw new python.Error('Expected type hint for result of tolist().');
  15886. }
  15887. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  15888. }
  15889. case 'prim::HasAttr': {
  15890. throw new python.Error('Not implemented.');
  15891. }
  15892. case 'prim::CreateObject': {
  15893. if (apply.args.length !== 1) {
  15894. throw python.Error('Only one argument to __new__ allowed.');
  15895. }
  15896. const arg = this.emitSugaredExpr(apply.args[0], 1);
  15897. if (arg instanceof torch._C.ClassValue === false) {
  15898. throw python.Error('Expected class value as argument to __new__.');
  15899. }
  15900. const class_arg = arg;
  15901. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  15902. createNode.setSourceRange(apply.range());
  15903. return new torch._C.SimpleValue(createNode.output());
  15904. }
  15905. case 'prim::range': {
  15906. const input_vals = this.getValues(apply.args, true);
  15907. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  15908. }
  15909. case 'prim::enumerate': {
  15910. throw new python.Error('Not implemented.');
  15911. }
  15912. case 'prim::zip': {
  15913. throw new python.Error('Not implemented.');
  15914. }
  15915. case 'prim::list': {
  15916. throw new python.Error('Not implemented.');
  15917. }
  15918. case 'prim::dict': {
  15919. throw new python.Error('Not implemented.');
  15920. }
  15921. case 'aten::index': {
  15922. throw new python.Error('Not implemented.');
  15923. }
  15924. default: {
  15925. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  15926. }
  15927. }
  15928. }
  15929. emitSimpleExpr(tree, type_hint) {
  15930. if (tree instanceof ast.Constant) {
  15931. if (tree.value === true) {
  15932. return this.graph.insertConstant(true, tree.range());
  15933. } else if (tree.value === false) {
  15934. return this.graph.insertConstant(false, tree.range());
  15935. } else if (tree.value === null) {
  15936. return this.graph.insertConstant(null, tree.range()); // IValue()
  15937. } else if (typeof tree.value === 'string') {
  15938. return this.emitStringLiteral(tree);
  15939. }
  15940. return this.emitConst(tree);
  15941. } else if (tree instanceof ast.List) {
  15942. return this.emitListLiteral(tree, type_hint);
  15943. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  15944. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  15945. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  15946. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  15947. } else if (tree instanceof ast.Dict) {
  15948. return this.emitDictLiteral(tree, type_hint);
  15949. } else if (tree instanceof ast.Tuple) {
  15950. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  15951. return this.graph.insertNode(this.graph.createTuple(values)).output();
  15952. }
  15953. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  15954. }
  15955. emitDictLiteral(dl, type_hint) {
  15956. const key_trees = dl.keys;
  15957. const value_trees = dl.values;
  15958. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  15959. const keys = [];
  15960. const values = [];
  15961. let rhs_value_type = null;
  15962. for (let i = 0; i < key_trees.length; i++) {
  15963. keys.push(this.emitExpr(key_trees[i]));
  15964. values.push(this.emitExpr(value_trees[i]));
  15965. if (i === 0) {
  15966. rhs_value_type = values[i].type();
  15967. } else {
  15968. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  15969. throw new python.Error('Dict keys must contain only a single type.');
  15970. }
  15971. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  15972. }
  15973. }
  15974. let refined_type_hint = type_hint;
  15975. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  15976. const all_candidates = [];
  15977. const default_refined_type_hint_setter = () => {
  15978. if (keys.length === 0) {
  15979. refined_type_hint = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  15980. } else {
  15981. refined_type_hint = torch.DictType.create(keys[0].type(), rhs_value_type);
  15982. if (rhs_value_type instanceof torch.UnionType) {
  15983. throw new python.Error('Dict values consist of heterogeneous types.');
  15984. }
  15985. }
  15986. };
  15987. if (type_hint) {
  15988. const type_match = (t) => t instanceof torch.DictType;
  15989. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  15990. if (all_candidates.length > 0 && values.length === 0) {
  15991. throw new python.Error('Cannot assign an empty dict.');
  15992. }
  15993. } else {
  15994. default_refined_type_hint_setter();
  15995. }
  15996. torch._C.TORCH_INTERNAL_ASSERT(all_candidates.length > 0 || refined_type_hint);
  15997. if (values.length > 0) {
  15998. if (all_candidates.length > 0) {
  15999. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  16000. }
  16001. if (refined_type_hint.getKeyType() !== keys[0].type()) {
  16002. throw new python.Error('Type annotation does not match key type.');
  16003. }
  16004. if (!rhs_value_type.isSubtypeOf(refined_type_hint.getValueType())) {
  16005. throw new python.Error('Type annotation does not match value type.');
  16006. }
  16007. }
  16008. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint.getKeyType(), refined_type_hint.getValueType(), keys, values));
  16009. if (annotated_union_type) {
  16010. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  16011. n.output().setType(annotated_union_type);
  16012. result = n;
  16013. }
  16014. return result.output();
  16015. }
  16016. emitStringLiteral(c) {
  16017. return torch._C.insertConstant(this.graph, c.value, c.range());
  16018. }
  16019. emitConst(c) {
  16020. if (c.type === 'int') {
  16021. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  16022. } else if (c.type === 'complex') {
  16023. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  16024. } else if (c.type === 'float') {
  16025. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  16026. }
  16027. throw new python.Error(`Unsupported constant type.`);
  16028. }
  16029. emitListLiteral(ll, type_hint) {
  16030. type_hint = type_hint || null;
  16031. const values = this.getValues(ll.elts, true);
  16032. if (values.length === 0 && type_hint === null) {
  16033. throw new python.Error('Not implemented.');
  16034. }
  16035. let inferred_elem_type = torch.TensorType.get();
  16036. const refined_type_hint = type_hint;
  16037. const annotated_union_type = refined_type_hint && refined_type_hint.isUnionType() ? refined_type_hint : null;
  16038. const all_candidates = [];
  16039. if (refined_type_hint) {
  16040. const do_if_type_match = () => {
  16041. inferred_elem_type = refined_type_hint.expect(torch.ListType).getElementType();
  16042. };
  16043. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  16044. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  16045. if (all_candidates.length > 0 && values.len === 0) {
  16046. throw new python.Error('Cannot assign an empty list.');
  16047. }
  16048. }
  16049. if (values.length !== 0) {
  16050. const types = values.map((v) => v.type());
  16051. const elem_type_hint = refined_type_hint && refined_type_hint.kind() === 'ListType' ? refined_type_hint.getElementType() : null;
  16052. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  16053. if (!refined_type_hint && unified_elem_type.kind() === 'UnionType') {
  16054. throw new python.Error('Not implemented.');
  16055. }
  16056. if (all_candidates.length === 0 && refined_type_hint && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  16057. throw new python.Error('Not implemented.');
  16058. }
  16059. if (all_candidates.length !== 0) {
  16060. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, unified_elem_type, ll);
  16061. inferred_elem_type = refined_type_hint.expect(torch.ListType).getElementType();
  16062. }
  16063. if (!refined_type_hint) {
  16064. inferred_elem_type = unified_elem_type;
  16065. }
  16066. }
  16067. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  16068. if (annotated_union_type) {
  16069. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  16070. n.output().setType(annotated_union_type);
  16071. result = n;
  16072. }
  16073. return result.output();
  16074. }
  16075. insertRefinements(loc, ref) {
  16076. for (const r of ref.activeRefinements()) {
  16077. const v = this.environment_stack.getVar(r.identifier(), loc);
  16078. const new_v = this.graph.insertUncheckedCast(v, r.type());
  16079. this.environment_stack.setVar(loc, r.identifier(), new_v);
  16080. }
  16081. }
  16082. shouldDeriveSetStateType(def, schema) {
  16083. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  16084. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  16085. if (!shouldInfer) {
  16086. return false;
  16087. }
  16088. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  16089. throw new python.Error(`Invalid '__setstate' method.`);
  16090. }
  16091. return true;
  16092. }
  16093. checkApplyNumInputs(apply, expected_inputs) {
  16094. if (apply.args.length !== expected_inputs) {
  16095. throw new python.Error('Invalid number of arguments.');
  16096. }
  16097. if (apply.keywords.length > 0) {
  16098. throw new python.Error('Invalid number of keyword arguments.');
  16099. }
  16100. }
  16101. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  16102. const position_arg_size = apply.args.length;
  16103. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  16104. throw new python.Error('Invalid number of arguments.');
  16105. }
  16106. if (apply.keywords.length > 0) {
  16107. throw new python.Error('Invalid number of keyword arguments.');
  16108. }
  16109. }
  16110. validateAssignLhsExpr(lhs /*, r */) {
  16111. let num_normal_assign = 0;
  16112. let num_starred = 0;
  16113. for (const assignee of lhs) {
  16114. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  16115. num_normal_assign++;
  16116. } else if (assignee instanceof ast.Starred) {
  16117. num_starred++;
  16118. } else {
  16119. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  16120. }
  16121. }
  16122. if (num_starred > 1) {
  16123. throw new python.Error('Only one starred expression is allowed.');
  16124. }
  16125. if (num_starred > 0 && num_normal_assign === 0) {
  16126. throw new python.Error('Invalid starred expression.');
  16127. }
  16128. return num_starred;
  16129. }
  16130. createTempName(prefix) {
  16131. return `${prefix}${this._temp_name_count++}`;
  16132. }
  16133. handleMaybeNoReturn(def, block) {
  16134. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16135. if (this.exit_blocks.size === 0) {
  16136. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  16137. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  16138. }
  16139. const b = new torch._C.WithInsertPoint(block.nodes()[-1]);
  16140. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  16141. b.dispose();
  16142. throw new Error();
  16143. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  16144. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  16145. }
  16146. }
  16147. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  16148. let adj_index = input_index;
  16149. const tuple_len = tuple_type.elements().length;
  16150. if (input_index < 0) {
  16151. adj_index = tuple_len + input_index;
  16152. }
  16153. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  16154. throw new python.Error(`Tuple index out of range at ${loc}.`);
  16155. }
  16156. return adj_index;
  16157. }
  16158. emitTupleIndex(loc, tuple_val, idx_val) {
  16159. const tuple_typ = tuple_val.type();
  16160. const elems = tuple_typ.elements();
  16161. let output_type = null;
  16162. if (idx_val.type() !== torch.IntType.get()) {
  16163. throw new python.Error('Tuple index must be an integer.');
  16164. }
  16165. const idx = torch._C.toIValue(idx_val);
  16166. if (idx) {
  16167. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  16168. output_type = elems[adj_index];
  16169. } else {
  16170. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  16171. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  16172. }
  16173. [output_type] = elems;
  16174. }
  16175. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  16176. }
  16177. getSliceInd(idx_val, loc) {
  16178. const ivalue = torch._C.toIValue(idx_val);
  16179. if (ivalue && ivalue.isInt()) {
  16180. return ivalue.toInt();
  16181. }
  16182. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  16183. }
  16184. emitTupleSlice(loc, tuple_val, tuple_args) {
  16185. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  16186. const tuple_len = tuple_type.elements().length;
  16187. const [beg_val, end_val, step] = tuple_args;
  16188. let step_size = 1;
  16189. if (step) {
  16190. const val = torch._C.toIValue(step.value(this.graph));
  16191. torch._C.TORCH_CHECK(val.isInt());
  16192. step_size = val.toInt();
  16193. }
  16194. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  16195. if (beg_val) {
  16196. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  16197. }
  16198. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  16199. if (end_val) {
  16200. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  16201. }
  16202. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  16203. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  16204. }
  16205. emitSliceOp(loc, sliceable, dim, start, end, step) {
  16206. const args = [];
  16207. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  16208. if (dim) {
  16209. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  16210. args.emplace_back(new torch._C.NamedValue(dim));
  16211. } else {
  16212. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  16213. }
  16214. if (sliceable.type() instanceof torch.TupleType) {
  16215. const tuple_args = [];
  16216. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  16217. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  16218. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  16219. return this.emitTupleSlice(loc, args[0], tuple_args);
  16220. }
  16221. if (!step) {
  16222. step = this.graph.insertConstant(1, loc);
  16223. }
  16224. args.push(new torch._C.NamedValue(loc, 'start', start));
  16225. args.push(new torch._C.NamedValue(loc, 'end', end));
  16226. args.push(new torch._C.NamedValue(loc, 'step', step));
  16227. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  16228. }
  16229. emitSlice(loc, input, dim, slice) {
  16230. let start = null;
  16231. let end = null;
  16232. let step = null;
  16233. if (slice.lower) {
  16234. start = this.emitExpr(slice.lower);
  16235. }
  16236. if (slice.upper) {
  16237. end = this.emitExpr(slice.upper);
  16238. }
  16239. if (slice.step) {
  16240. step = this.emitExpr(slice.step);
  16241. }
  16242. return this.emitSliceOp(loc, input, dim, start, end, step);
  16243. }
  16244. emitBasicSlice(loc, sliceable, subscript_exprs) {
  16245. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  16246. const slice_exp = subscript_exprs;
  16247. let maybe_dim = null;
  16248. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  16249. maybe_dim = this.graph.insertConstant(0, loc);
  16250. }
  16251. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  16252. }
  16253. emitSubscript(subscript, type_hint) {
  16254. type_hint = type_hint === undefined ? null : type_hint;
  16255. const sv = this.emitSugaredExpr(subscript.value, 1);
  16256. const subscript_exprs = subscript.slice;
  16257. const range = subscript.range();
  16258. const val_range = subscript.value;
  16259. if (subscript_exprs instanceof ast.Tuple) {
  16260. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  16261. }
  16262. if (subscript_exprs instanceof ast.Slice) {
  16263. if (sv.kind() === 'module') {
  16264. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  16265. const [slice] = subscript_exprs;
  16266. const tuple_args = [];
  16267. if (slice.start().present()) {
  16268. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  16269. tuple_args.push(begin);
  16270. } else {
  16271. tuple_args.push(null);
  16272. }
  16273. if (slice.end().present()) {
  16274. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  16275. tuple_args.push(end);
  16276. } else {
  16277. tuple_args.push(null);
  16278. }
  16279. if (slice.step().present()) {
  16280. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  16281. tuple_args.push(step);
  16282. } else {
  16283. tuple_args.push(null);
  16284. }
  16285. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  16286. return new torch._C.SimpleValue(tupleSliceValue);
  16287. }
  16288. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  16289. }
  16290. const sliceable = sv.asValue(val_range, this.method);
  16291. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  16292. if (subscript_sv instanceof torch._C.SliceValue) {
  16293. const slice_value = subscript_sv;
  16294. let dim = null;
  16295. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  16296. dim = this.method.graph().insertConstant(0, val_range);
  16297. }
  16298. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  16299. return new torch._C.SimpleValue(sliced);
  16300. }
  16301. const idx = subscript_sv.asValue(val_range, this.method);
  16302. if (sliceable.type() instanceof torch.TupleType) {
  16303. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  16304. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  16305. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  16306. }
  16307. return sv.getitem(range, this.method, idx, type_hint);
  16308. }
  16309. });
  16310. this.registerType('torch.jit.CompilationUnit', class {
  16311. constructor() {
  16312. this._functions = new Map();
  16313. this._classes = new Map();
  16314. }
  16315. register_type(namedType) {
  16316. this._classes.set(namedType.annotation_str, namedType);
  16317. }
  16318. register_function(fn) {
  16319. const name = fn.qualname().qualifiedName();
  16320. torch._C.TORCH_CHECK(!this._functions.has(name));
  16321. this._functions.set(name, fn);
  16322. return fn;
  16323. }
  16324. define(...args) {
  16325. if (Array.isArray(args[1])) {
  16326. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  16327. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  16328. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  16329. const functions = [];
  16330. const function_table = new Map();
  16331. const record_function = (fn) => {
  16332. function_table.set(fn.name(), fn);
  16333. functions.push(fn);
  16334. this.register_function(fn);
  16335. };
  16336. for (let i = 0; i < properties.length; i++) {
  16337. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  16338. const getter_fn = property_fns.getGetter();
  16339. const setter_fn = property_fns.getSetter();
  16340. record_function(getter_fn);
  16341. if (setter_fn) {
  16342. record_function(setter_fn);
  16343. }
  16344. }
  16345. for (let i = 0; i < definitions.length; i++) {
  16346. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  16347. record_function(fn);
  16348. }
  16349. for (const [name, fn] of function_table) {
  16350. if (name === '__init__') {
  16351. fn.ensure_defined();
  16352. }
  16353. }
  16354. for (const fn of functions) {
  16355. fn.ensure_defined();
  16356. }
  16357. return functions;
  16358. } else if (args[1] instanceof ast.FunctionDef) {
  16359. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  16360. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  16361. const creator = (method) => {
  16362. return new torch._C.to_ir(def, _resolver, self, method);
  16363. };
  16364. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  16365. if (shouldMangle && this.find_function(name)) {
  16366. name = this.mangle(name);
  16367. }
  16368. const graph = new torch.Graph();
  16369. graph.set_op_version(operator_set_version);
  16370. const fn = new torch._C.GraphFunction(name, graph, creator);
  16371. fn.__ast__ = def; // remove
  16372. if (self) {
  16373. if (type === 'hook') {
  16374. self.getClassType().addForwardHook(fn);
  16375. } else if (type === 'prehook') {
  16376. self.getClassType().addPreHook(fn);
  16377. } else {
  16378. self.getClassType().addMethod(fn);
  16379. }
  16380. }
  16381. return fn;
  16382. }
  16383. throw new python.Error('Invalid arguments.');
  16384. }
  16385. get_type(name) {
  16386. return this._classes.get(name.qualifiedName());
  16387. }
  16388. get_class(name) {
  16389. return this.get_type(name);
  16390. }
  16391. find_function(name) {
  16392. const key = name.qualifiedName();
  16393. return this._functions.get(key);
  16394. }
  16395. });
  16396. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  16397. const ctrl = new torch._C.ControlFlowLoadStores();
  16398. ctrl.run(graph);
  16399. const exit_vars = new torch._C.LoopContinuations();
  16400. exit_vars.run(graph);
  16401. torch._C.InlineLoopCondition(graph);
  16402. const erase_loads_stores = new torch._C.EraseLoadStores();
  16403. erase_loads_stores.run(graph);
  16404. torch._C.TransformExits(graph);
  16405. });
  16406. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  16407. /*
  16408. LoopView loop(n);
  16409. if (loop.loopType() != LoopView::ModifiedLoop) {
  16410. return;
  16411. }
  16412. const g = n.owningGraph();
  16413. WithInsertPoint node_insert(n);
  16414. const zero = g.insertConstant(0);
  16415. const one = g.insertConstant(1);
  16416. const max_trip_count = loop.maxTripCount();
  16417. const condition = g.insert(aten::gt, {max_trip_count, zero});
  16418. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  16419. const inp_condition = toIValue(loop.inputCond());
  16420. if (inp_condition == null || inp_condition.toBool() == false) {
  16421. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  16422. }
  16423. loop.replaceInputCondition(condition);
  16424. n.addOutput().setType(IntType::get());
  16425. WithInsertPoint loop_insert(loop.bodyBlock());
  16426. n.addInput(zero);
  16427. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  16428. // unset unique name for jitter, its replacement does not have a name
  16429. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  16430. const inc_iter = g.insert(aten::add, {new_iter, one});
  16431. loop.bodyBlock().registerOutput(inc_iter);
  16432. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  16433. const loop_continue = loop.nextCond();
  16434. const new_condition =
  16435. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  16436. loop.bodyBlock().eraseOutput(0);
  16437. loop.bodyBlock().insertOutput(0, new_condition);
  16438. */
  16439. });
  16440. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  16441. for (const n of block.nodes()) {
  16442. for (const b of n.blocks()) {
  16443. torch._C.canonicalizeModifiedLoops(b);
  16444. }
  16445. if (n.kind() === 'prim::Loop') {
  16446. torch._C.canonicalizeModifiedLoop(n);
  16447. }
  16448. }
  16449. });
  16450. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  16451. torch._C.canonicalizeModifiedLoops(graph.block());
  16452. });
  16453. this.registerType('torch._C.MiniEnvironment', class {
  16454. constructor(b, next) {
  16455. this.next = next || null;
  16456. this.table = new Map();
  16457. }
  16458. setVar(name, value) {
  16459. this.table.set(name, value);
  16460. }
  16461. definedVariables() {
  16462. const result = Array.from(this.table.keys());
  16463. return result.sort();
  16464. }
  16465. findInThisFrame(name) {
  16466. if (this.table.has(name)) {
  16467. return this.table.get(name);
  16468. }
  16469. return null;
  16470. }
  16471. findInAnyFrame(name) {
  16472. for (let runner = this; runner; runner = runner.next) {
  16473. const r = runner.findInThisFrame(name);
  16474. if (r) {
  16475. return r;
  16476. }
  16477. }
  16478. return null;
  16479. }
  16480. });
  16481. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  16482. });
  16483. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  16484. });
  16485. this.registerType('torch._C.ControlFlowLoadStores', class {
  16486. constructor() {
  16487. this.environment_stack = null;
  16488. }
  16489. pushFrame(b) {
  16490. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  16491. }
  16492. popFrame() {
  16493. const old_frame = this.environment_stack;
  16494. this.environment_stack = this.environment_stack.next;
  16495. return old_frame;
  16496. }
  16497. addBlockInput(b, type, name) {
  16498. const g = b.owningGraph();
  16499. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  16500. }
  16501. addBlockOutput(exit_block, type, name) {
  16502. const insert = new torch._C.WithInsertPoint(exit_block);
  16503. const g = exit_block.owningGraph();
  16504. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  16505. exit_block.registerOutput(block_exit);
  16506. insert.dispose();
  16507. }
  16508. addNodeOutput(n, type, name) {
  16509. const out = n.addOutput().setType(type);
  16510. if (torch._C.meaningfulName(name)) {
  16511. out.setDebugName(name);
  16512. }
  16513. const g = n.owningGraph();
  16514. g.createStore(name, out).insertAfter(n);
  16515. }
  16516. addNodeInput(n, type, name) {
  16517. const g = n.owningGraph();
  16518. const inp = g.createLoad(name, type).insertBefore(n).output();
  16519. n.addInput(inp);
  16520. }
  16521. addIfLoadStores(n) {
  16522. const [true_block, false_block] = n.blocks();
  16523. const true_vars = this.addControlFlowLoadStores(true_block);
  16524. const false_vars = this.addControlFlowLoadStores(false_block);
  16525. const mutated_variables = new Set();
  16526. for (const v of true_vars.definedVariables()) {
  16527. if (false_vars.findInAnyFrame(v)) {
  16528. mutated_variables.add(v);
  16529. }
  16530. }
  16531. for (const v of false_vars.definedVariables()) {
  16532. if (true_vars.findInAnyFrame(v)) {
  16533. mutated_variables.add(v);
  16534. }
  16535. }
  16536. for (const x of mutated_variables) {
  16537. const true_type = true_vars.findInAnyFrame(x);
  16538. const false_type = false_vars.findInAnyFrame(x);
  16539. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  16540. this.addBlockOutput(true_block, true_type, x);
  16541. this.addBlockOutput(false_block, false_type, x);
  16542. this.addNodeOutput(n, unified, x);
  16543. }
  16544. }
  16545. addLoopLoadStores(n) {
  16546. const [body_block] = n.blocks();
  16547. const loop_vars = this.addControlFlowLoadStores(body_block);
  16548. for (const name of loop_vars.definedVariables()) {
  16549. const parent_type = this.environment_stack.findInAnyFrame(name);
  16550. if (!parent_type) {
  16551. continue;
  16552. }
  16553. const block_type = loop_vars.findInThisFrame(name);
  16554. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  16555. this.addNodeInput(n, parent_type, name);
  16556. this.addBlockInput(body_block, unified_type, name);
  16557. this.addBlockOutput(body_block, block_type, name);
  16558. this.addNodeOutput(n, unified_type, name);
  16559. }
  16560. }
  16561. addControlFlowLoadStores(block) {
  16562. this.pushFrame(block);
  16563. for (const n of block.nodes()) {
  16564. switch (n.kind()) {
  16565. case 'prim::If': {
  16566. this.addIfLoadStores(n);
  16567. break;
  16568. }
  16569. case 'prim::Loop': {
  16570. this.addLoopLoadStores(n);
  16571. break;
  16572. }
  16573. case 'prim::Closure': {
  16574. for (const b of n.blocks()) {
  16575. this.addControlFlowLoadStores(b);
  16576. }
  16577. break;
  16578. }
  16579. case 'prim::Store': {
  16580. this.environment_stack.setVar(n.s('name'), n.input().type());
  16581. break;
  16582. }
  16583. case 'prim::ComprehensionScope': {
  16584. this.addControlFlowLoadStores(n.blocks()[0]);
  16585. break;
  16586. }
  16587. default: {
  16588. break;
  16589. }
  16590. }
  16591. }
  16592. return this.popFrame();
  16593. }
  16594. run(graph) {
  16595. this.addControlFlowLoadStores(graph.block());
  16596. }
  16597. });
  16598. this.registerType('torch._C.LoopContinuations', class {
  16599. constructor() {
  16600. this._graph = null;
  16601. this._false_val = null;
  16602. this._curr_loop = null;
  16603. }
  16604. assignExitContinuations(block) {
  16605. for (const n of block.nodes()) {
  16606. switch (n.kind()) {
  16607. case 'prim::If': {
  16608. this.assignExitContinuations(n.blocks()[0]);
  16609. this.assignExitContinuations(n.blocks()[1]);
  16610. break;
  16611. }
  16612. case 'prim::Closure': {
  16613. const closure_block = new torch._C.LoopContinuations();
  16614. closure_block.run(n.blocks()[0]);
  16615. break;
  16616. }
  16617. case 'prim::Loop': {
  16618. const prev_loop = this._curr_loop;
  16619. this._curr_loop = n;
  16620. this.assignExitContinuations(n.blocks()[0]);
  16621. this._curr_loop = prev_loop;
  16622. break;
  16623. }
  16624. case 'prim::ContinueStmt': {
  16625. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  16626. const header_block = loop_continuation.addBlock();
  16627. const [, pre_header] = this._curr_loop.blocks();
  16628. header_block.cloneFrom(pre_header, (v) => v);
  16629. this.InlineBlockBeforeNode(n, header_block);
  16630. loop_continuation.addInput(header_block.outputs()[0]);
  16631. loop_continuation.eraseBlock(0);
  16632. this.addLoopCarriedOutputs(loop_continuation);
  16633. n.destroy();
  16634. break;
  16635. }
  16636. case 'prim::BreakStmt': {
  16637. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  16638. loop_exit.addInput(this._false_val);
  16639. this.addLoopCarriedOutputs(loop_exit);
  16640. n.destroy();
  16641. break;
  16642. }
  16643. default: {
  16644. break;
  16645. }
  16646. }
  16647. }
  16648. }
  16649. run(...args) {
  16650. if (args.length === 1 && args[0] instanceof torch.Graph) {
  16651. const [graph] = args;
  16652. this.run(graph.block());
  16653. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  16654. const [b] = args;
  16655. {
  16656. this._graph = b.owningGraph();
  16657. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  16658. this._false_val = this._graph.insertConstant(false);
  16659. guard.dispose();
  16660. }
  16661. this.assignExitContinuations(b);
  16662. } else {
  16663. throw new python.Error('Not implemented.');
  16664. }
  16665. }
  16666. });
  16667. this.registerType('torch._C.LoopView', class {
  16668. constructor(node) {
  16669. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  16670. this._node = node;
  16671. }
  16672. bodyBlock() {
  16673. return this._node.blocks()[0];
  16674. }
  16675. nextCond() {
  16676. return this.bodyBlock().outputs()[0];
  16677. }
  16678. carriedOutputs() {
  16679. return this._node.outputs();
  16680. }
  16681. bodyCarriedInputs() {
  16682. return this.bodyBlock().inputs().slice(1);
  16683. }
  16684. bodyCarriedOutputs() {
  16685. return this.bodyBlock().outputs().slice(1);
  16686. }
  16687. });
  16688. this.registerType('torch._C.WithLoopStatus', class {
  16689. constructor(to_ir, new_status) {
  16690. this._to_ir = to_ir;
  16691. this._prev = this._to_ir._loop_status;
  16692. this._to_ir._loop_status = new_status;
  16693. }
  16694. dispose() {
  16695. this._to_ir._loop_status = this._prev;
  16696. }
  16697. });
  16698. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  16699. for (const block_node of block.nodes()) {
  16700. block_node.moveBefore(before_node);
  16701. }
  16702. });
  16703. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  16704. if (args.length === 1 && args[0] instanceof torch.Block) {
  16705. const [block] = args;
  16706. for (const n of block.nodes()) {
  16707. for (const b of n.blocks()) {
  16708. torch._C.inlineLoopCondition(b);
  16709. }
  16710. if (n.kind() === 'prim::Loop') {
  16711. torch._C.inlineLoopCondition(n);
  16712. }
  16713. }
  16714. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  16715. const [n] = args;
  16716. const [body_block, pre_header] = n.blocks();
  16717. const temp_block = n.addBlock();
  16718. temp_block.cloneFrom(pre_header, (v) => v);
  16719. torch._C.InlineBlockBeforeNode(n, temp_block);
  16720. n.insertInput(1, temp_block.outputs()[0]);
  16721. n.eraseBlock(2);
  16722. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  16723. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  16724. n.eraseBlock(1);
  16725. } else {
  16726. throw new python.Error('Not implemented.');
  16727. }
  16728. });
  16729. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  16730. torch._C.inlineLoopCondition(graph.block());
  16731. });
  16732. this.registerType('torch._C.EraseLoadStores', class {
  16733. pushFrame(b) {
  16734. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  16735. }
  16736. popFrame() {
  16737. const old_frame = this.environment_stack;
  16738. this.environment_stack = this.environment_stack.next;
  16739. return old_frame;
  16740. }
  16741. eraseBlockLoadStores(block) {
  16742. this.pushFrame(block);
  16743. for (const n of block.nodes()) {
  16744. switch (n.kind()) {
  16745. case 'prim::Store': {
  16746. this.environment_stack.setVar(n.s('name'), n.input());
  16747. n.destroy();
  16748. break;
  16749. }
  16750. case 'prim::Load': {
  16751. const name = n.s('name');
  16752. const value = this.environment_stack.findInAnyFrame(name);
  16753. torch._C.TORCH_INTERNAL_ASSERT(value);
  16754. n.output().replaceAllUsesWith(value);
  16755. n.destroy();
  16756. break;
  16757. }
  16758. case 'prim::ComprehensionScope': {
  16759. const [body] = n.blocks();
  16760. this.eraseBlockLoadStores(body);
  16761. for (const body_node of body.nodes()) {
  16762. body_node.moveBefore(n);
  16763. }
  16764. n.destroy();
  16765. break;
  16766. }
  16767. default: {
  16768. for (const b of n.blocks()) {
  16769. this.eraseBlockLoadStores(b);
  16770. }
  16771. break;
  16772. }
  16773. }
  16774. }
  16775. this.popFrame();
  16776. }
  16777. run(graph) {
  16778. this.eraseBlockLoadStores(graph.block());
  16779. }
  16780. });
  16781. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  16782. });
  16783. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  16784. });
  16785. this.registerType('torch._C.ExitPair', class {
  16786. constructor(exit_v, exit_val_ref) {
  16787. const exit_vals = [];
  16788. for (const v of exit_val_ref) {
  16789. exit_vals.push(v);
  16790. }
  16791. if (exit_v.type() !== torch.BoolType.get()) {
  16792. throw new python.Error('Invalid exit value type.');
  16793. }
  16794. this.first = exit_v;
  16795. this.second = exit_vals;
  16796. }
  16797. hasExited() {
  16798. return this.first;
  16799. }
  16800. exitValues() {
  16801. return this.second;
  16802. }
  16803. });
  16804. this.registerType('torch._C.ExitTransformer', class {
  16805. constructor(graph) {
  16806. this._graph = graph;
  16807. this._target_block = null;
  16808. this._unit_values = new Map();
  16809. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  16810. this._true_val = this._graph.insertConstant(true);
  16811. this._false_val = this._graph.insertConstant(false);
  16812. this._throws_val = this.getUnitValue(torch.BoolType.get());
  16813. guard.dispose();
  16814. }
  16815. getUnitValue(type) {
  16816. const maybe_val = this._unit_values.get(type);
  16817. if (maybe_val) {
  16818. return maybe_val;
  16819. }
  16820. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  16821. this._unit_values.set(type, unit);
  16822. return unit;
  16823. }
  16824. transformReturnStmts() {
  16825. this._current_exit_kind = 'prim::ReturnStmt';
  16826. this.transformExits(this._graph.block());
  16827. }
  16828. transformLoopContinuations() {
  16829. this._current_exit_kind = 'prim::LoopContinuation';
  16830. this.transformExits(this._graph.block());
  16831. }
  16832. destroyNodeAfterExit(n) {
  16833. for (const output of n.outputs()) {
  16834. if (output.uses().length > 0) {
  16835. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  16836. }
  16837. }
  16838. n.destroy();
  16839. }
  16840. deleteAfterExitNodes(block, iter) {
  16841. const nodes = block.nodes();
  16842. if (iter === nodes.end()) {
  16843. return;
  16844. }
  16845. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  16846. for (const it of Array.from(nodes).reverse()) {
  16847. if (it === iter) {
  16848. break;
  16849. }
  16850. if (it !== block.return_node()) {
  16851. this.destroyNodeAfterExit(it);
  16852. }
  16853. }
  16854. this.destroyNodeAfterExit(iter);
  16855. insert.dispose();
  16856. }
  16857. updateTargetBlock(block) {
  16858. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  16859. this._target_block = block;
  16860. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  16861. this._target_block = block;
  16862. }
  16863. }
  16864. transformLoop(node) {
  16865. const loop = new torch._C.LoopView(node);
  16866. const body = loop.bodyBlock();
  16867. const exit_pair = this.transformExits(body);
  16868. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  16869. return this.constructWontExitPair();
  16870. }
  16871. const insert = new torch._C.WithInsertPoint(body);
  16872. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  16873. new_if.addInput(exit_pair.hasExited());
  16874. new_if.addBlock().registerOutput(this._false_val);
  16875. new_if.addBlock().registerOutput(loop.nextCond());
  16876. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  16877. loop.bodyBlock().eraseOutput(0);
  16878. loop.bodyBlock().insertOutput(0, new_condition);
  16879. node.addInput(this._false_val);
  16880. body.addInput().setType(torch.BoolType.get());
  16881. body.registerOutput(exit_pair.hasExited());
  16882. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  16883. for (const exit_value of exit_pair.exitValues()) {
  16884. const typ = exit_value.type();
  16885. node.addInput(this.getUnitValue(typ));
  16886. node.addOutput().setType(typ);
  16887. body.addInput().setType(typ);
  16888. body.registerOutput(exit_value);
  16889. }
  16890. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  16891. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  16892. insert.dispose();
  16893. return result;
  16894. }
  16895. calcIfExitStatus(then_status, else_status) {
  16896. if (then_status === 'THROWS') {
  16897. return else_status;
  16898. } else if (else_status === 'THROWS') {
  16899. return then_status;
  16900. }
  16901. if (then_status === 'WONT' && else_status === 'WONT') {
  16902. return 'WONT';
  16903. }
  16904. if (then_status === 'WILL' && else_status === 'WILL') {
  16905. return 'WILL';
  16906. }
  16907. return 'MIGHT';
  16908. }
  16909. transformIf(node) {
  16910. const [then_block, else_block] = node.blocks();
  16911. let then_pair = this.transformExits(then_block);
  16912. let else_pair = this.transformExits(else_block);
  16913. const then_status = this.getExitStatus(then_pair);
  16914. const else_status = this.getExitStatus(else_pair);
  16915. const if_status = this.calcIfExitStatus(then_status, else_status);
  16916. if (if_status === 'THROWS') {
  16917. return this.constructThrowsExitPair();
  16918. }
  16919. if (if_status === 'WONT') {
  16920. return this.constructWontExitPair();
  16921. }
  16922. if (then_status === 'WONT' || then_status === 'THROWS') {
  16923. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  16924. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  16925. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  16926. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  16927. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  16928. }
  16929. let has_exited = null;
  16930. if (if_status === 'WILL') {
  16931. has_exited = this._true_val;
  16932. } else {
  16933. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  16934. has_exited = node.outputs().at(node.outputs().length - 1);
  16935. }
  16936. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  16937. const num_exit_vals = then_pair.exitValues().size();
  16938. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  16939. return new torch._C.ExitPair(has_exited, exit_vals);
  16940. }
  16941. transformExits(block) {
  16942. const prev_target_block = this._target_block;
  16943. this.updateTargetBlock(block);
  16944. let exit_pair = this.constructWontExitPair();
  16945. for (const node of block.nodes()) {
  16946. const it = node.next;
  16947. switch (node.kind()) {
  16948. case 'prim::RaiseException': {
  16949. exit_pair = this.constructThrowsExitPair();
  16950. break;
  16951. }
  16952. case 'prim::ReturnStmt':
  16953. case 'prim::LoopContinuation': {
  16954. if (node.kind() === this._current_exit_kind) {
  16955. exit_pair = this.constructWillExitPair(node.inputs());
  16956. node.destroy();
  16957. }
  16958. break;
  16959. }
  16960. case 'prim::If': {
  16961. exit_pair = this.transformIf(node);
  16962. break;
  16963. }
  16964. case 'prim::With': {
  16965. exit_pair = this.transformWith(node);
  16966. break;
  16967. }
  16968. case 'prim::Closure': {
  16969. this.transformExits(node.blocks()[0]);
  16970. break;
  16971. }
  16972. case 'prim::Loop': {
  16973. exit_pair = this.transformLoop(node);
  16974. break;
  16975. }
  16976. default: {
  16977. break;
  16978. }
  16979. }
  16980. const status = this.getExitStatus(exit_pair);
  16981. if (status === 'WILL' || status === 'THROWS') {
  16982. this.deleteAfterExitNodes(block, it);
  16983. break;
  16984. }
  16985. if (status === 'MIGHT') {
  16986. throw new python.Error('Not implemented.');
  16987. // const nodes = block.nodes();
  16988. // if (node === nodes[nodes.length - 1]) {
  16989. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  16990. // }
  16991. // break;
  16992. }
  16993. }
  16994. if (this._target_block === block) {
  16995. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  16996. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  16997. new_if.addBlock();
  16998. new_if.addBlock();
  16999. new_if.addInput(exit_pair.hasExited());
  17000. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  17001. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  17002. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  17003. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  17004. }
  17005. exit_pair = this.constructWontExitPair();
  17006. }
  17007. this._target_block = prev_target_block;
  17008. return exit_pair;
  17009. }
  17010. constructThrowsExitPair() {
  17011. return new torch._C.ExitPair(this._throws_val, []);
  17012. }
  17013. constructWontExitPair() {
  17014. return new torch._C.ExitPair(this._false_val, []);
  17015. }
  17016. constructWillExitPair(exit_val_ref) {
  17017. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  17018. }
  17019. getExitStatus(exit_pair) {
  17020. const exit_v = exit_pair.hasExited();
  17021. if (exit_v === this._true_val) {
  17022. return 'WILL';
  17023. } else if (exit_v === this._false_val) {
  17024. return 'WONT';
  17025. } else if (exit_v === this._throws_val) {
  17026. return 'THROWS';
  17027. }
  17028. return 'MIGHT';
  17029. }
  17030. static owningNodeKind(block) {
  17031. if (block.owningNode()) {
  17032. return block.owningNode().kind();
  17033. }
  17034. return null;
  17035. }
  17036. static isGraphOrClosureBlock(block) {
  17037. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  17038. }
  17039. static removeOutputs(b) {
  17040. while (b.outputs().length > 0) {
  17041. b.eraseOutput(0);
  17042. }
  17043. }
  17044. static registerBlockOutputs(b, outs) {
  17045. for (const out of outs) {
  17046. b.registerOutput(out);
  17047. }
  17048. }
  17049. static replaceBlockOutputs(b, outs) {
  17050. torch._C.ExitTransformer.removeOutputs(b);
  17051. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  17052. }
  17053. });
  17054. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  17055. });
  17056. this.registerFunction('torch._C.TransformExits', (graph) => {
  17057. torch._C.convertEnterExitNodesToWithBlocks(graph);
  17058. const e_loop = new torch._C.ExitTransformer(graph);
  17059. e_loop.transformLoopContinuations();
  17060. const e_ret = new torch._C.ExitTransformer(graph);
  17061. e_ret.transformReturnStmts();
  17062. torch._C.inlineConsecutiveIfs(graph.block());
  17063. torch._C.convertWithBlocksToEnterExitNodes(graph);
  17064. });
  17065. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  17066. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  17067. const args = iter.inputs();
  17068. const newSub = iter.replaceWithNewSymbol('aten::sub');
  17069. newSub.replaceInput(0, args[1]);
  17070. newSub.replaceInput(1, args[0]);
  17071. iter.destroyCurrent();
  17072. return true;
  17073. }
  17074. return false;
  17075. });
  17076. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  17077. });
  17078. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  17079. const args = iter.inputs();
  17080. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  17081. if (iter.kind() === 'aten::__is__') {
  17082. iter.replaceWithNewSymbol('aten::eq');
  17083. iter.destroyCurrent();
  17084. return true;
  17085. }
  17086. if (iter.kind() === 'aten::__isnot__') {
  17087. iter.replaceWithNewSymbol('aten::ne');
  17088. iter.destroyCurrent();
  17089. return true;
  17090. }
  17091. }
  17092. return false;
  17093. });
  17094. this.registerFunction('torch._C.NormalizeOps', (block) => {
  17095. for (const it of block.nodes()) {
  17096. for (const sub of it.blocks()) {
  17097. torch._C.NormalizeOps(sub);
  17098. }
  17099. if (torch._C.normalizeRSub(it)) {
  17100. continue;
  17101. }
  17102. if (torch._C.normalizeOpAliases(it)) {
  17103. continue;
  17104. }
  17105. if (torch._C.normalizeIsBool(it)) {
  17106. continue;
  17107. }
  17108. }
  17109. });
  17110. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  17111. return false;
  17112. });
  17113. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  17114. /*
  17115. torch._C.liftClosures(to_clean);
  17116. torch._C.inlineForkedClosures(to_clean);
  17117. */
  17118. if (torch._C.getInlineEverythingMode()) {
  17119. torch._C.Inline(to_clean);
  17120. }
  17121. /*
  17122. torch._C.eraseListLiterals(to_clean);
  17123. */
  17124. torch._C.LowerSimpleTuples(to_clean);
  17125. torch._C.ConstantPropagationImmutableTypes(to_clean);
  17126. torch._C.ConstantPooling(to_clean);
  17127. /*
  17128. torch._C.CanonicalizeOutputs(to_clean);
  17129. torch._C.AnnotateWarns(to_clean);
  17130. */
  17131. });
  17132. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  17133. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  17134. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  17135. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  17136. constructor(cpp_module) {
  17137. super();
  17138. this._initializing = true;
  17139. this._c = cpp_module;
  17140. }
  17141. static _construct(cpp_module, init_fn) {
  17142. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  17143. init_fn(script_module);
  17144. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  17145. return script_module;
  17146. }
  17147. static _finalize_scriptmodule(script_module) {
  17148. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  17149. script_module._buffers = new torch.BufferDict(script_module._c).items();
  17150. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  17151. script_module._initializing = false;
  17152. }
  17153. get graph() {
  17154. // return this._c._get_method('forward').graph;
  17155. return this._c.graph;
  17156. }
  17157. get code_with_constants() {
  17158. // return this.forward.code_with_constants;
  17159. return this._c.code_with_constants;
  17160. }
  17161. __setattr__(name, value) {
  17162. if (this._initializing) {
  17163. super.__setattr__(name, value);
  17164. } else if (this._modules.has(name)) {
  17165. this._modules.set(name, value);
  17166. } else if (this._c.hasattr(name)) {
  17167. this._c.setattr(name, value);
  17168. } else {
  17169. //
  17170. }
  17171. }
  17172. __getattr__(name) {
  17173. if (this._initializing) {
  17174. return super.__getattr__(name);
  17175. }
  17176. if (this._modules.has(name)) {
  17177. return this._modules.get(name);
  17178. }
  17179. if (this._c.hasattr(name)) {
  17180. return this._c.getattr(name);
  17181. }
  17182. if (this._c._has_method(name)) {
  17183. //
  17184. }
  17185. return super.__getattr__(name);
  17186. }
  17187. });
  17188. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  17189. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  17190. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  17191. torch.CompilationUnit = torch.jit.CompilationUnit;
  17192. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  17193. torch._C.ScriptModule = torch.ScriptModule;
  17194. torch._C.ClassType = torch.ClassType;
  17195. this.registerType('torch._C.FlatBuffersLoader', class {
  17196. constructor(cu) {
  17197. this._cu = cu;
  17198. const torch = cu.execution.__import__('torch');
  17199. this._torch = torch;
  17200. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  17201. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  17202. this._ivalue_parsers = new Map();
  17203. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  17204. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  17205. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  17206. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  17207. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  17208. }
  17209. parseModule(module) {
  17210. this._module = module;
  17211. this._all_functions = new Map();
  17212. this._all_ivalues = new Array(module.ivalues.length);
  17213. this._all_types = new Array(module.object_types.length);
  17214. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  17215. for (let i = 0; i < mobile_ivalue_size; i++) {
  17216. this.parseAndPopulate(i, module.ivalues[i]);
  17217. }
  17218. const m = this._all_ivalues[module.state_obj];
  17219. for (const [name, value] of this._all_functions) {
  17220. const class_index = module.ivalues[name].val.class_type;
  17221. const class_type = this._all_types[class_index];
  17222. if (value) {
  17223. class_type.addMethod(value);
  17224. }
  17225. }
  17226. m._min_operator_version = module.operator_version;
  17227. m._bytecode_version = module.bytecode_version;
  17228. return m;
  17229. }
  17230. parseAndPopulate(i, ivalue) {
  17231. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  17232. this._all_functions.set(i, this.parseFunction(ivalue.val));
  17233. } else {
  17234. this._all_ivalues[i] = this.parseIValue(ivalue);
  17235. }
  17236. }
  17237. parseFunction(/* val */) {
  17238. return null;
  17239. }
  17240. parseIValue(ivalue) {
  17241. if (ivalue.val) {
  17242. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  17243. return callback(ivalue);
  17244. }
  17245. return null;
  17246. }
  17247. parseTensor(ivalue) {
  17248. return this.parseTensorFromMetadata(ivalue.val);
  17249. }
  17250. parseTensorFromMetadata(metadata) {
  17251. if (metadata.quantized_schema) {
  17252. throw new torch.Error('Quantized schema not implemented.');
  17253. }
  17254. const index = metadata.storage_location_index;
  17255. const data = this._module.storage_data[index].data;
  17256. const dtype = this._dtypes.get(metadata.scalar_type);
  17257. const size = data.length / dtype.itemsize();
  17258. const storage = this._cu.execution.invoke('torch.storage.TypedStorage', [size, dtype]);
  17259. storage._set_cdata(data);
  17260. const tensor = this._cu.execution.invoke('torch.Tensor', []);
  17261. const shape = Array.from(metadata.sizes);
  17262. const stride = Array.from(metadata.strides);
  17263. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  17264. return tensor;
  17265. }
  17266. parseObject(ivalue) {
  17267. const object = ivalue.val;
  17268. const obj_type = this._module.object_types[object.type_index];
  17269. const cls = this.getOrCreateClassTypeForObject(object);
  17270. switch (obj_type.type) {
  17271. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  17272. const torch = this._torch;
  17273. const obj = torch.ScriptObject.create(cls);
  17274. for (let i = 0; i < object.attrs.length; i++) {
  17275. const attr_name = obj_type.attr_names[i];
  17276. const val = this._all_ivalues[object.attrs[i]];
  17277. obj.__setattr__(attr_name, val);
  17278. }
  17279. return obj;
  17280. }
  17281. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  17282. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  17283. default: {
  17284. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  17285. }
  17286. }
  17287. }
  17288. getOrCreateClassTypeForObject(object) {
  17289. let cls = this._all_types[object.type_index];
  17290. const obj_type = this._module.object_types[object.type_index];
  17291. if (!cls) {
  17292. const name = obj_type.type_name;
  17293. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  17294. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  17295. if (!cls) {
  17296. const torch = this._torch;
  17297. cls = torch.ClassType.create(name, this._cu, true);
  17298. this._cu.register_type(cls);
  17299. }
  17300. } else {
  17301. // cls = c10::parseType(qn_str).cast<ClassType>();
  17302. }
  17303. this._all_types[object.type_index] = cls;
  17304. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  17305. for (let i = 0; i < object.attrs.length; i++) {
  17306. // const val = this._all_ivalues[object.attrs[i]];
  17307. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  17308. }
  17309. }
  17310. }
  17311. return cls;
  17312. }
  17313. });
  17314. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  17315. constructor(export_module, flat_args_adapter) {
  17316. super();
  17317. const export_graph = copy.deepcopy(export_module.graph);
  17318. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  17319. this.graph = torch.fx.Graph();
  17320. this.graph.owning_module = this;
  17321. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  17322. this.flat_args_adapter = flat_args_adapter;
  17323. this.adapted = false;
  17324. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  17325. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  17326. }
  17327. });
  17328. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  17329. constructor(input_specs, output_specs) {
  17330. this.input_specs = input_specs;
  17331. this.output_specs = output_specs;
  17332. }
  17333. user_inputs() {
  17334. const user_inputs = [];
  17335. for (const s of this.input_specs) {
  17336. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  17337. continue;
  17338. }
  17339. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  17340. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  17341. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  17342. user_inputs.push(s.arg.name);
  17343. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  17344. user_inputs.push(s.arg.value);
  17345. } else {
  17346. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  17347. }
  17348. }
  17349. return user_inputs;
  17350. }
  17351. user_outputs() {
  17352. const user_outputs = [];
  17353. for (const s of this.output_specs) {
  17354. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  17355. continue;
  17356. }
  17357. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  17358. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  17359. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  17360. user_outputs.push(s.arg.name);
  17361. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  17362. user_outputs.push(s.arg.value);
  17363. } else {
  17364. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  17365. }
  17366. }
  17367. return user_outputs;
  17368. }
  17369. inputs_to_parameters() {
  17370. return new Map(this.input_specs
  17371. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  17372. .map((s) => [s.arg.name, s.target]));
  17373. }
  17374. inputs_to_buffers() {
  17375. return new Map(this.input_specs
  17376. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  17377. .map((s) => [s.arg.name, s.target]));
  17378. }
  17379. inputs_to_lifted_tensor_constants() {
  17380. return new Map(this.input_specs
  17381. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  17382. .map((s) => [s.arg.name, s.target]));
  17383. }
  17384. });
  17385. torch.export.graph_signature.InputKind = {
  17386. USER_INPUT: 0,
  17387. PARAMETER: 1,
  17388. BUFFER: 2,
  17389. CONSTANT_TENSOR: 3,
  17390. CUSTOM_OBJ: 4,
  17391. TOKEN: 5
  17392. };
  17393. this.registerType('torch.export.graph_signature.InputSpec', class {
  17394. constructor(kind, arg, target, persistent) {
  17395. this.kind = kind;
  17396. this.arg = arg;
  17397. this.target = target;
  17398. this.persistent = persistent || null;
  17399. }
  17400. });
  17401. torch.export.graph_signature.OutputKind = {
  17402. USER_OUTPUT: 0,
  17403. LOSS_OUTPUT: 1,
  17404. BUFFER_MUTATION: 2,
  17405. GRADIENT_TO_PARAMETER: 3,
  17406. GRADIENT_TO_USER_INPUT: 4,
  17407. USER_INPUT_MUTATION: 5,
  17408. TOKEN: 6
  17409. };
  17410. this.registerType('torch.export.graph_signature.OutputSpec', class {
  17411. constructor(kind, arg, target) {
  17412. this.kind = kind;
  17413. this.arg = arg;
  17414. this.target = target;
  17415. }
  17416. });
  17417. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  17418. constructor(name, value) {
  17419. this.name = name;
  17420. this.value = value; // Union[int, float, bool, str, None]
  17421. }
  17422. });
  17423. this.registerType('torch.export.graph_signature.TensorArgument', class {
  17424. constructor(name) {
  17425. this.name = name;
  17426. }
  17427. });
  17428. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  17429. constructor(name) {
  17430. this.name = name;
  17431. }
  17432. });
  17433. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  17434. constructor(name, class_fqn, fake_val) {
  17435. this.name = name;
  17436. this.class_fqn = class_fqn;
  17437. this.fake_val = fake_val;
  17438. }
  17439. });
  17440. this.registerType('torch.export.exported_program.ExportedProgram', class {
  17441. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  17442. // graph._codegen = torch.fx.graph.CodeGen()
  17443. this._graph_module = this._create_graph_module_for_export(root, graph);
  17444. if (root instanceof torch.fx.GraphModule) {
  17445. // this._graph_module.meta.update(root.meta);
  17446. }
  17447. this._graph_signature = graph_signature;
  17448. this._state_dict = state_dict;
  17449. this._range_constraints = range_constraints;
  17450. this._module_call_graph = module_call_graph;
  17451. this._example_inputs = example_inputs;
  17452. this._constants = tensor_constants || constants || {};
  17453. }
  17454. _create_graph_module_for_export(root, graph) {
  17455. let gm = null;
  17456. try {
  17457. gm = new torch.fx.GraphModule(root, graph);
  17458. } catch {
  17459. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  17460. gm._graph = graph;
  17461. }
  17462. return gm;
  17463. }
  17464. get graph_module() {
  17465. return this._graph_module;
  17466. }
  17467. get graph() {
  17468. return this._graph_module.graph;
  17469. }
  17470. get graph_signature() {
  17471. return this._graph_signature;
  17472. }
  17473. get state_dict() {
  17474. return this._state_dict;
  17475. }
  17476. get constants() {
  17477. return this._constants;
  17478. }
  17479. });
  17480. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  17481. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  17482. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  17483. module = torch.export._remove_effect_tokens(module);
  17484. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  17485. });
  17486. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  17487. return new torch.fx.graph_module.GraphModule(root, graph);
  17488. });
  17489. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  17490. constructor(exported_program, state_dict, constants, example_inputs) {
  17491. this.exported_program = exported_program;
  17492. this.state_dict = state_dict;
  17493. this.constants = constants;
  17494. this.example_inputs = example_inputs;
  17495. }
  17496. });
  17497. torch._export.serde.serialize._SYM_INT_OPS = new Set([
  17498. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod,
  17499. torch.sym_sqrt, torch.sym_int, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt
  17500. ]);
  17501. torch._export.serde.serialize._SYM_BOOL_OPS = new Set([
  17502. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  17503. torch.sym_not
  17504. ]);
  17505. this.registerType('torch._export.serde.union._Union', class {
  17506. constructor(obj) {
  17507. if (obj.$type) {
  17508. this.type = obj.$type;
  17509. this[obj.$type] = obj.$value;
  17510. delete obj.$type;
  17511. delete obj.$value;
  17512. } else {
  17513. let entries = Object.entries(obj);
  17514. if (entries.length > 1) {
  17515. entries = entries.filter(([, value]) => value !== null);
  17516. }
  17517. if (entries.length !== 1) {
  17518. throw new Error();
  17519. }
  17520. const [entry] = entries;
  17521. const [type, value] = entry;
  17522. this.type = type;
  17523. this[type] = value;
  17524. }
  17525. }
  17526. get value() {
  17527. return this[this.type];
  17528. }
  17529. });
  17530. this.registerType('torch._export.serde.schema.NamedArgument', class {
  17531. constructor(obj) {
  17532. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17533. this.name = obj.name;
  17534. }
  17535. });
  17536. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  17537. constructor(obj) {
  17538. super(obj);
  17539. if (this.type === 'as_int' || this.type === 'as_ints' ||
  17540. this.type === 'as_float' || this.type === 'as_floats' ||
  17541. this.type === 'as_bool' || this.type === 'as_bools' ||
  17542. this.type === 'as_string' || this.type === 'as_strings' ||
  17543. this.type === 'as_scalar_type' || this.type === 'as_device' ||
  17544. this.type === 'as_memory_format' || this.type === 'as_layout') {
  17545. // continue
  17546. } else if (this.type === 'as_none') {
  17547. this.as_none = null;
  17548. } else if (this.type === 'as_tensor') {
  17549. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  17550. } else if (this.type === 'as_tensors') {
  17551. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  17552. } else if (this.type === 'as_sym_int') {
  17553. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  17554. } else if (this.type === 'as_sym_ints') {
  17555. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  17556. } else if (this.type === 'as_optional_tensors') {
  17557. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  17558. } else {
  17559. throw new python.Error(`Unsupported argument '${this.type}'.`);
  17560. }
  17561. /*
  17562. as_tensors: List[TensorArgument]
  17563. as_string: str
  17564. as_strings: List[str]
  17565. as_sym_int: SymIntArgument
  17566. as_sym_ints: List[SymIntArgument]
  17567. as_scalar_type: ScalarType
  17568. as_memory_format: MemoryFormat
  17569. as_layout: Layout
  17570. as_bools: List[bool]
  17571. as_sym_bool: SymBoolArgument
  17572. as_sym_bools: List[SymBoolArgument]
  17573. as_graph: GraphArgument
  17574. as_optional_tensors: List[OptionalTensorArgument]
  17575. as_custom_obj: CustomObjArgument
  17576. */
  17577. }
  17578. });
  17579. this.registerType('torch._export.serde.schema.Node', class {
  17580. constructor(obj) {
  17581. this.target = obj.target;
  17582. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  17583. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  17584. this.metadata = new Map(Object.entries(obj.metadata));
  17585. }
  17586. });
  17587. torch._export.serde.schema.ScalarType = {
  17588. UNKNOWN: 0,
  17589. BYTE: 1,
  17590. CHAR: 2,
  17591. SHORT: 3,
  17592. INT: 4,
  17593. LONG: 5,
  17594. HALF: 6,
  17595. FLOAT: 7,
  17596. DOUBLE: 8,
  17597. COMPLEXHALF: 9,
  17598. COMPLEXFLOAT: 10,
  17599. COMPLEXDOUBLE: 11,
  17600. BOOL: 12,
  17601. BFLOAT16: 13
  17602. };
  17603. torch._export.serde.schema.Layout = {
  17604. Unknown: 0,
  17605. SparseCoo: 1,
  17606. SparseCsr: 2,
  17607. SparseCsc: 3,
  17608. SparseBsr: 4,
  17609. SparseBsc: 5,
  17610. _mkldnn: 6,
  17611. Strided: 7
  17612. };
  17613. torch._export.serde.schema.MemoryFormat = {
  17614. Unknown: 0,
  17615. ContiguousFormat: 1,
  17616. ChannelsLast: 2,
  17617. ChannelsLast3d: 3,
  17618. PreserveFormat: 4,
  17619. };
  17620. this.registerType('torch._export.serde.schema.Device', class {
  17621. constructor(obj) {
  17622. Object.assign(this, { ...obj });
  17623. }
  17624. });
  17625. this.registerType('torch._export.serde.schema.TensorMeta', class {
  17626. constructor(obj) {
  17627. obj = obj.meta || obj;
  17628. this.dtype = obj.dtype;
  17629. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  17630. this.requires_grad = obj.requires_grad;
  17631. this.device = obj.device;
  17632. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  17633. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  17634. this.layout = obj.layout;
  17635. }
  17636. });
  17637. this.registerType('torch._export.serde.schema.Graph', class {
  17638. constructor(obj) {
  17639. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  17640. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  17641. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  17642. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  17643. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  17644. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  17645. this.is_single_tensor_return = obj.is_single_tensor_return;
  17646. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  17647. if (obj.contants) {
  17648. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  17649. // graph_signature -> input_specs -> tensor_constant
  17650. }
  17651. }
  17652. });
  17653. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  17654. constructor(obj) {
  17655. Object.assign(this, { ...obj });
  17656. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  17657. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  17658. }
  17659. });
  17660. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  17661. constructor(obj) {
  17662. Object.assign(this, { ...obj });
  17663. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  17664. }
  17665. });
  17666. this.registerType('torch._export.serde.schema.GraphModule', class {
  17667. constructor(obj) {
  17668. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  17669. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  17670. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  17671. this.metadata = new Map(Object.entries(obj.metadata || {}));
  17672. }
  17673. });
  17674. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  17675. constructor(obj) {
  17676. Object.assign(this, { ...obj });
  17677. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  17678. }
  17679. });
  17680. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  17681. this.registerType('torch._export.serde.schema.SymExpr', class {
  17682. constructor(obj) {
  17683. this.expr_str = obj.expr_str;
  17684. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  17685. }
  17686. });
  17687. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  17688. constructor(obj) {
  17689. super(obj);
  17690. if (this.type === 'as_int') {
  17691. // continue
  17692. } else if (this.type === 'as_expr') {
  17693. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  17694. } else {
  17695. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  17696. }
  17697. }
  17698. });
  17699. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  17700. constructor(obj) {
  17701. super(obj);
  17702. Object.assign(this, { ...obj });
  17703. }
  17704. });
  17705. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  17706. constructor(obj) {
  17707. super(obj);
  17708. if (this.type === 'as_bool') {
  17709. // continue
  17710. } else if (this.type === 'as_expr') {
  17711. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  17712. } else {
  17713. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  17714. }
  17715. }
  17716. });
  17717. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  17718. constructor(obj) {
  17719. super(obj);
  17720. Object.assign(this, { ...obj });
  17721. }
  17722. });
  17723. this.registerType('torch._export.serde.schema.GraphSignature', class {
  17724. constructor(obj) {
  17725. this.input_specs = [];
  17726. if (Array.isArray(obj.input_specs)) {
  17727. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  17728. }
  17729. if (Array.isArray(obj.user_inputs)) {
  17730. for (const user_input of obj.user_inputs) {
  17731. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  17732. }
  17733. }
  17734. if (obj.inputs_to_parameters) {
  17735. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  17736. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  17737. }
  17738. }
  17739. this.output_specs = [];
  17740. if (Array.isArray(obj.output_specs)) {
  17741. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  17742. }
  17743. }
  17744. });
  17745. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  17746. constructor(obj) {
  17747. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17748. }
  17749. });
  17750. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  17751. constructor(obj) {
  17752. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17753. this.parameter_name = obj.parameter_name;
  17754. }
  17755. });
  17756. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  17757. constructor(obj) {
  17758. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17759. this.buffer_name = obj.buffer_name;
  17760. }
  17761. });
  17762. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  17763. constructor(obj) {
  17764. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17765. this.tensor_constant_name = obj.tensor_constant_name;
  17766. }
  17767. });
  17768. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  17769. constructor(obj) {
  17770. this.name = obj.name;
  17771. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  17772. }
  17773. });
  17774. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  17775. constructor(obj) {
  17776. super(obj);
  17777. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  17778. // continue
  17779. } else if (this.type === 'as_none') {
  17780. this.as_none = null;
  17781. } else {
  17782. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  17783. }
  17784. }
  17785. });
  17786. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  17787. constructor(obj) {
  17788. super(obj);
  17789. if (this.type === 'user_input') {
  17790. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  17791. } else if (this.type === 'parameter') {
  17792. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  17793. } else if (this.type === 'buffer') {
  17794. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  17795. } else if (this.type === 'tensor_constant') {
  17796. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  17797. } else if (this.type === 'constant_input') {
  17798. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  17799. } else {
  17800. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  17801. }
  17802. /*
  17803. custom_obj: InputToCustomObjSpec
  17804. token: InputTokenSpec
  17805. */
  17806. }
  17807. });
  17808. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  17809. constructor(obj) {
  17810. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17811. }
  17812. });
  17813. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  17814. constructor(obj) {
  17815. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17816. this.buffer_name = obj.buffer_name;
  17817. }
  17818. });
  17819. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  17820. constructor(obj) {
  17821. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17822. this.parameter_name = obj.parameter_name;
  17823. }
  17824. });
  17825. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  17826. constructor(obj) {
  17827. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17828. this.user_input_name = obj.user_input_name;
  17829. }
  17830. });
  17831. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  17832. constructor(obj) {
  17833. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17834. this.user_input_name = obj.user_input_name;
  17835. }
  17836. });
  17837. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  17838. constructor(obj) {
  17839. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  17840. }
  17841. });
  17842. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  17843. constructor(obj) {
  17844. super(obj);
  17845. if (this.type === 'user_output') {
  17846. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  17847. } else if (this.type === 'loss_output') {
  17848. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  17849. } else if (this.type === 'buffer_mutation') {
  17850. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  17851. } else if (this.type === 'gradient_to_parameter') {
  17852. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  17853. } else if (this.type === 'gradient_to_user_input') {
  17854. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  17855. } else if (this.type === 'user_input_mutation') {
  17856. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  17857. } else if (this.type === 'token') {
  17858. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  17859. }
  17860. }
  17861. });
  17862. this.registerType('torch._export.serde.schema.TensorArgument', class {
  17863. constructor(obj) {
  17864. this.name = obj.name;
  17865. }
  17866. });
  17867. this.registerType('torch._export.serde.schema.TokenArgument', class {
  17868. constructor(obj) {
  17869. this.name = obj.name;
  17870. }
  17871. });
  17872. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  17873. constructor(obj) {
  17874. super(obj);
  17875. if (this.type === 'as_tensor') {
  17876. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  17877. } else if (this.type === 'as_none') {
  17878. this.as_none = null;
  17879. } else {
  17880. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  17881. }
  17882. }
  17883. });
  17884. this.registerFunction('torch._export.load', (f, expected_opset_version) => {
  17885. const serialized_exported_program = f.get('serialized_exported_program.json');
  17886. const serialized_state_dict = f.get('serialized_state_dict.pt');
  17887. const serialized_constants = f.get('serialized_constants.pt');
  17888. const serialized_example_inputs = f.get('serialized_example_inputs.pt');
  17889. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  17890. return torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  17891. });
  17892. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  17893. if (data === null) {
  17894. return data;
  17895. }
  17896. if (cls) {
  17897. return new cls(data);
  17898. }
  17899. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  17900. });
  17901. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  17902. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  17903. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  17904. });
  17905. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  17906. constructor(expected_opset_version) {
  17907. this.expected_opset_version = expected_opset_version;
  17908. }
  17909. deserialize(exported_program, state_dict, constants, example_inputs) {
  17910. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  17911. /*
  17912. symbol_name_to_range = {
  17913. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  17914. for k, v in exported_program.range_constraints.items()
  17915. }
  17916. */
  17917. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  17918. const res = deserializer.deserialize(
  17919. exported_program.graph_module,
  17920. state_dict,
  17921. constants,
  17922. example_inputs,
  17923. symbol_name_to_range);
  17924. const range_constraints = null;
  17925. /*
  17926. range_constraints = self.deserialize_range_constraints(
  17927. symbol_name_to_range, res.names_to_symbols,
  17928. )
  17929. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  17930. self._validate_model_opset_version(model_opset_version)
  17931. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  17932. */
  17933. return new torch.export.exported_program.ExportedProgram(
  17934. res.graph_module, res.graph_module.graph, res.signature,
  17935. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  17936. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  17937. res.constants);
  17938. // return upgrader.upgrade(exported_program)
  17939. }
  17940. });
  17941. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  17942. if (!serialized) {
  17943. return new builtins.dict();
  17944. }
  17945. const artifact = torch.load(serialized);
  17946. return artifact;
  17947. });
  17948. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  17949. constructor() {
  17950. this.serialized_name_to_node = new Map();
  17951. this.serialized_name_to_meta = new Map();
  17952. this.graph = new torch.fx.Graph();
  17953. this.module = new torch.nn.Module();
  17954. }
  17955. deserialize_graph_output(output) {
  17956. if (output.type === 'as_tensor') {
  17957. return this.serialized_name_to_node.get(output.as_tensor.name);
  17958. } else if (output.type === 'as_sym_int') {
  17959. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  17960. } else if (output.type === 'as_sym_bool') {
  17961. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  17962. } else if (output.type === 'as_int') {
  17963. return this.serialized_name_to_node.get(output.as_int.as_name);
  17964. } else if (output.type === 'as_none') {
  17965. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  17966. }
  17967. throw new python.Error(`Unsupported graph node ${output.type}.`);
  17968. }
  17969. deserialize_graph(serialized_graph) {
  17970. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  17971. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  17972. this.serialized_name_to_meta.set(name, meta_val);
  17973. }
  17974. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  17975. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  17976. }
  17977. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  17978. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  17979. }
  17980. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  17981. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  17982. }
  17983. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  17984. const input = serialized_graph.inputs[i];
  17985. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  17986. const node_name = input.value.name;
  17987. const placeholder_node = this.graph.placeholder(node_name);
  17988. placeholder_node.name = node_name;
  17989. this.sync_fx_node(node_name, placeholder_node);
  17990. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  17991. const node_name = this.signature.input_specs[i].arg.name;
  17992. const placeholder_node = this.graph.placeholder(node_name);
  17993. placeholder_node.meta.set('val', this.deserialize_input(input));
  17994. } else {
  17995. throw new python.Error(`Invalid input ${input.type}.`);
  17996. }
  17997. }
  17998. for (const serialized_node of serialized_graph.nodes) {
  17999. const target = this.deserialize_operator(serialized_node.target);
  18000. this.deserialize_node(serialized_node, target);
  18001. }
  18002. let outputs = [];
  18003. for (const output of serialized_graph.outputs) {
  18004. outputs.push(this.deserialize_graph_output(output));
  18005. }
  18006. if (serialized_graph.is_single_tensor_return) {
  18007. [outputs] = outputs;
  18008. } else {
  18009. outputs = new builtins.tuple(outputs);
  18010. }
  18011. const output_node = this.graph.output(outputs);
  18012. if (serialized_graph.is_single_tensor_return) {
  18013. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  18014. } else {
  18015. /* output_node.meta['val'] = tuple(
  18016. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  18017. for arg in output_node.args[0]
  18018. ) */
  18019. }
  18020. return self.graph;
  18021. }
  18022. deserialize_operator(serialized_target) {
  18023. let module = null;
  18024. let serialized_target_names = null;
  18025. if (serialized_target.startsWith('_operator')) {
  18026. module = operator;
  18027. serialized_target_names = serialized_target.split('.').slice(1);
  18028. } else if (serialized_target.startsWith('torch')) {
  18029. module = torch;
  18030. serialized_target_names = serialized_target.split('.').slice(1);
  18031. } else if (serialized_target.startsWith('#')) {
  18032. return self.deserialize_extension_operator(serialized_target);
  18033. } else {
  18034. return serialized_target;
  18035. }
  18036. let target = module;
  18037. for (const name of serialized_target_names) {
  18038. target = builtins.getattr(target, name);
  18039. if (!target) {
  18040. return serialized_target;
  18041. }
  18042. }
  18043. return target;
  18044. }
  18045. deserialize_node(serialized_node, target) {
  18046. let fx_node = null;
  18047. if (torch._export.serde.serialize._SYM_BOOL_OPS.has(target) || torch._export.serde.serialize._SYM_INT_OPS.has(target)) {
  18048. const name = serialized_node.outputs[0].value.as_name;
  18049. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  18050. fx_node = this.graph.create_node('call_function', target, args, null, name);
  18051. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  18052. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  18053. // assert(len(serialized_node.outputs) === 1 && serialized_node.outputs[0].type in ('as_tensors', 'as_tensor')), 'Only single tensor output or list of tensor output is supported for higher order operators.')
  18054. const [output] = serialized_node.outputs;
  18055. const name = output.type === 'as_tensor' ? output.value.name : null;
  18056. const args = serialized_node.inputs.map((input) => this.deserialize_input(input.arg));
  18057. fx_node = this.graph.create_node('call_function', target, args, {}, name);
  18058. if (output.as_tensor !== null) {
  18059. this.sync_fx_node(name, fx_node);
  18060. }
  18061. if (output.as_tensors !== null) {
  18062. this.deserialize_multiple_outputs(serialized_node, fx_node);
  18063. }
  18064. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  18065. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  18066. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  18067. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  18068. this.deserialize_outputs(serialized_node, fx_node);
  18069. } else {
  18070. throw new python.Error(`Unsupported node target type '${target}'.`);
  18071. }
  18072. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  18073. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  18074. fx_node.meta.set('nn_module_stack', new builtins.dict());
  18075. }
  18076. }
  18077. deserialize_input_spec(i) {
  18078. if (i.type === 'user_input') {
  18079. return new torch.export.graph_signature.InputSpec(
  18080. torch.export.graph_signature.InputKind.USER_INPUT,
  18081. this.deserialize_argument_spec(i.user_input.arg),
  18082. null);
  18083. } else if (i.type === 'parameter') {
  18084. return new torch.export.graph_signature.InputSpec(
  18085. torch.export.graph_signature.InputKind.PARAMETER,
  18086. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  18087. i.parameter.parameter_name,
  18088. );
  18089. } else if (i.type === 'buffer') {
  18090. return new torch.export.graph_signature.InputSpec(
  18091. torch.export.graph_signature.InputKind.BUFFER,
  18092. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  18093. i.buffer.buffer_name,
  18094. i.buffer.persistent,
  18095. );
  18096. } else if (i.type === 'tensor_constant') {
  18097. return new torch.export.graph_signature.InputSpec(
  18098. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  18099. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  18100. i.tensor_constant.tensor_constant_name);
  18101. } else if (i.type === 'custom_obj') {
  18102. return new torch.export.graph_signature.InputSpec(
  18103. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  18104. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  18105. i.custom_obj.custom_obj_name);
  18106. } else if (i.type === 'token') {
  18107. return new torch.export.graph_signature.InputSpec(
  18108. torch.export.graph_signature.InputKind.TOKEN,
  18109. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  18110. null);
  18111. } else if (i.type === 'constant_input') {
  18112. return new torch.export.graph_signature.InputSpec(
  18113. torch.export.graph_signature.InputKind.USER_INPUT,
  18114. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  18115. null);
  18116. }
  18117. throw new python.Error(`Unknown input spec ${i}`);
  18118. }
  18119. deserialize_constant_input(inp) {
  18120. if (inp.type === 'as_int') {
  18121. return inp.as_int;
  18122. } else if (inp.type === 'as_float') {
  18123. return inp.as_float;
  18124. } else if (inp.type === 'as_string') {
  18125. return inp.as_string;
  18126. } else if (inp.type === 'as_bool') {
  18127. return inp.as_bool;
  18128. } else if (inp.type === 'as_none') {
  18129. return null;
  18130. }
  18131. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  18132. }
  18133. deserialize_output_spec(o) {
  18134. if (o.type === 'user_output') {
  18135. return new torch.export.graph_signature.OutputSpec(
  18136. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  18137. this.deserialize_argument_spec(o.user_output.arg),
  18138. null);
  18139. } else if (o.type === 'loss_output') {
  18140. return new torch.export.graph_signature.OutputSpec(
  18141. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  18142. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  18143. null);
  18144. } else if (o.type === 'buffer_mutation') {
  18145. return new torch.export.graph_signature.OutputSpec(
  18146. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  18147. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  18148. o.buffer_mutation.buffer_name);
  18149. } else if (o.type === 'gradient_to_parameter') {
  18150. return new torch.export.graph_signature.OutputSpec(
  18151. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  18152. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  18153. o.gradient_to_parameter.parameter_name);
  18154. } else if (o.type === 'gradient_to_user_input') {
  18155. return new torch.export.graph_signature.OutputSpec(
  18156. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  18157. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  18158. o.gradient_to_user_input.user_input_name);
  18159. } else if (o.type === 'user_input_mutation') {
  18160. return new torch.export.graph_signature.OutputSpec(
  18161. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  18162. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  18163. o.user_input_mutation.user_input_name);
  18164. } else if (o.type === 'token') {
  18165. return new torch.export.graph_signature.OutputSpec(
  18166. torch.export.graph_signature.OutputKind.TOKEN,
  18167. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  18168. null);
  18169. }
  18170. throw new python.Error(`Unknown output spec ${o}.`);
  18171. }
  18172. deserialize_signature(sig) {
  18173. return new torch.export.graph_signature.ExportGraphSignature(
  18174. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  18175. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  18176. }
  18177. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  18178. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  18179. /*
  18180. this.fake_tensor_mode = FakeTensorMode(
  18181. allow_fallback_kernels=False,
  18182. allow_non_fake_inputs=True,
  18183. shape_env=this.shape_env,
  18184. )
  18185. */
  18186. this.symbol_name_to_symbol = new Map();
  18187. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  18188. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  18189. this.symbol_name_to_range = symbol_name_to_range || new Map();
  18190. /*
  18191. if symbol_name_to_range:
  18192. for k, vr in symbol_name_to_range.items():
  18193. lower = int(vr.lower)
  18194. if vr.upper >= 2: # max is >= 2, not sym bool range
  18195. lower = max(2, lower)
  18196. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  18197. */
  18198. this.example_inputs = null;
  18199. if (example_inputs && example_inputs.length > 0) {
  18200. torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  18201. }
  18202. this.deserialize_graph(serialized_graph_module.graph);
  18203. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  18204. return {
  18205. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  18206. signature: this.signature,
  18207. module_call_graph,
  18208. names_to_symbols: this.symbol_name_to_symbol,
  18209. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  18210. constants: this.constants,
  18211. example_inputs: this.example_inputs,
  18212. };
  18213. }
  18214. sync_fx_node(name, fx_node) {
  18215. if (this.serialized_name_to_node.has(name)) {
  18216. throw new python.Error(`Node ${name} has already been deserialized before.`);
  18217. }
  18218. this.serialized_name_to_node.set(name, fx_node);
  18219. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  18220. }
  18221. deserialize_sym_op_inputs(inputs) {
  18222. return inputs.map((input) => this.deserialize_input(input.arg));
  18223. }
  18224. deserialize_inputs(target, serialized_node) {
  18225. const schema_args = this._get_schema_from_target(target).arguments;
  18226. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  18227. const args = new builtins.list();
  18228. const kwargs = new builtins.dict();
  18229. for (const schema_arg of schema_args) {
  18230. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  18231. if (is_positional) {
  18232. args.push(actual_args.get(schema_arg.name));
  18233. } else if (actual_args.has(schema_arg.name)) {
  18234. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  18235. }
  18236. }
  18237. return [args, kwargs];
  18238. }
  18239. deserialize_input(inp) {
  18240. const value = inp.value;
  18241. const typ_ = inp.type;
  18242. if (typ_ === 'as_none') {
  18243. return null;
  18244. } else if (typ_ === 'as_tensor') {
  18245. return this.serialized_name_to_node.get(inp.as_tensor.name);
  18246. } else if (typ_ === 'as_scalar_type') {
  18247. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[inp.as_scalar_type];
  18248. } else if (typ_ === 'as_memory_format') {
  18249. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  18250. } else if (typ_ === 'as_layout') {
  18251. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  18252. } else if (typ_ === 'as_graph') {
  18253. /* assert isinstance(value, GraphArgument)
  18254. with this.save_graph_module():
  18255. this.deserialize_graph(value.graph)
  18256. submodule = ep._create_graph_module_for_export(this.module, this.graph)
  18257. this.module.register_module(value.name, submodule)
  18258. return this.graph.create_node(
  18259. 'get_attr',
  18260. value.name,
  18261. name=value.name,
  18262. )*/
  18263. } else if (typ_ === 'as_device') {
  18264. return this.deserialize_device(inp.as_device);
  18265. } else if (typ_ === 'as_int') {
  18266. return inp.as_int;
  18267. } else if (typ_ === 'as_float') {
  18268. return inp.as_float;
  18269. } else if (typ_ === 'as_bool') {
  18270. return inp.as_bool;
  18271. } else if (typ_ === 'as_string') {
  18272. return inp.as_string;
  18273. } else if (typ_ === 'as_sym_int') {
  18274. return this.deserialize_sym_argument(inp.as_sym_int);
  18275. } else if (typ_ === 'as_sym_bool') {
  18276. return this.deserialize_sym_argument(inp.as_sym_bool);
  18277. } else if (Array.isArray(value)) {
  18278. if (value.length === 0) {
  18279. return [];
  18280. } else if (typ_ === 'as_tensors') {
  18281. const result = [];
  18282. for (const arg of value) {
  18283. result.push(this.serialized_name_to_node.get(arg.name));
  18284. }
  18285. return result;
  18286. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  18287. return Array.from(value);
  18288. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  18289. return value.map((arg) => this.deserialize_sym_argument(arg));
  18290. } else if (typ_ === 'as_optional_tensors') {
  18291. const deserialize_optional_tensor_args = (a) => {
  18292. if (a.type === 'as_none') {
  18293. return null;
  18294. } else if (a.type === 'as_tensor') {
  18295. return this.serialized_name_to_node.get(a.value.name);
  18296. }
  18297. throw new python.Error(`Unsupported argument '${typ_}'.`);
  18298. };
  18299. return value.map((item) => deserialize_optional_tensor_args(item));
  18300. }
  18301. throw new python.Error(`Unsupported argument '${typ_}'.`);
  18302. } else if (typ_ === 'as_custom_obj') {
  18303. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  18304. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  18305. }
  18306. return this.constants[inp.as_custom_obj.name];
  18307. } else if (typ_ === 'as_operator') {
  18308. return this.deserialize_operator(inp.as_operator);
  18309. }
  18310. throw new python.Error(`Unsupported argument '${typ_}'.`);
  18311. }
  18312. deserialize_sym_argument(sym_arg) {
  18313. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  18314. if (sym_arg.type === 'as_int') {
  18315. return sym_arg.as_int;
  18316. } else if (sym_arg.type === 'as_name') {
  18317. return this.serialized_name_to_node.get(sym_arg.as_name);
  18318. }
  18319. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  18320. if (sym_arg.type === 'as_bool') {
  18321. return sym_arg.as_bool;
  18322. } else if (sym_arg.type === 'as_name') {
  18323. return self.serialized_name_to_node.get(sym_arg.as_name);
  18324. }
  18325. }
  18326. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  18327. }
  18328. deserialize_sym_op_outputs(serialized_node, fx_node) {
  18329. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  18330. }
  18331. deserialize_outputs(serialized_node, fx_node) {
  18332. if (serialized_node.outputs.length === 0) {
  18333. return;
  18334. }
  18335. if (serialized_node.outputs.length === 1 &&
  18336. serialized_node.outputs[0].type === 'as_tensor') {
  18337. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  18338. return;
  18339. } else if (serialized_node.outputs.length === 1 &&
  18340. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  18341. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  18342. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  18343. return;
  18344. }
  18345. this.deserialize_multiple_outputs(serialized_node, fx_node);
  18346. }
  18347. deserialize_multiple_outputs(serialized_node, fx_node) {
  18348. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  18349. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  18350. let name = '';
  18351. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  18352. name = arg.name;
  18353. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  18354. name = arg.as_name;
  18355. } else {
  18356. throw new python.Error(`Unsupported argument type '${arg}'.`);
  18357. }
  18358. const individual_output = this.graph.create_node(
  18359. 'call_function',
  18360. operator.getitem,
  18361. new builtins.tuple([fx_node, idx]),
  18362. null,
  18363. name,
  18364. );
  18365. this.sync_fx_node(name, individual_output);
  18366. meta_val.push(this.serialized_name_to_meta.get(name));
  18367. individual_output.meta.update(deserialized_metadata);
  18368. };
  18369. const generate_getitems = (meta_val, fx_node, args) => {
  18370. for (let idx = 0; idx < args.length; idx++) {
  18371. let arg = args[idx];
  18372. if (arg instanceof torch._export.serde.schema.Argument) {
  18373. arg = arg.value;
  18374. }
  18375. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  18376. generate_getitem(meta_val, fx_node, arg, idx);
  18377. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  18378. const list_output = this.graph.create_node(
  18379. 'call_function',
  18380. operator.getitem,
  18381. (fx_node, idx),
  18382. );
  18383. meta_val.append([]);
  18384. generate_getitems(meta_val[-1], list_output, arg);
  18385. list_output.meta.update(deserialized_metadata);
  18386. list_output.meta.set('val', meta_val[-1]);
  18387. } else {
  18388. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  18389. }
  18390. }
  18391. };
  18392. const meta_val = [];
  18393. if (serialized_node.outputs.length === 1) {
  18394. // assert isinstance(serialized_node.outputs[0].value, list)
  18395. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  18396. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  18397. } else {
  18398. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  18399. }
  18400. fx_node.meta.set('val', new builtins.tuple(meta_val));
  18401. this.serialized_name_to_node.set(fx_node.name, fx_node);
  18402. }
  18403. deserialize_metadata(metadata) {
  18404. const ret = new builtins.dict();
  18405. const stack_trace = metadata.get('stack_trace');
  18406. if (stack_trace) {
  18407. ret.set('stack_trace', stack_trace);
  18408. }
  18409. const deserialize_meta_func = (serialized_target) => {
  18410. let module = null;
  18411. let serialized_target_names = [];
  18412. if (serialized_target.startsWith('torch.nn')) {
  18413. module = torch.nn;
  18414. serialized_target_names = serialized_target.split('.').slice(1);
  18415. } else if (serialized_target.startsWith('torch')) {
  18416. module = torch;
  18417. serialized_target_names = serialized_target.split('.').slice(1);
  18418. } else {
  18419. return this.deserialize_operator(serialized_target);
  18420. }
  18421. let target = module;
  18422. for (const name of serialized_target_names) {
  18423. if (!builtins.hasattr(target, name)) {
  18424. return serialized_target;
  18425. }
  18426. target = builtins.getattr(target, name);
  18427. }
  18428. return target;
  18429. };
  18430. const nn_module_stack_str = metadata.get('nn_module_stack');
  18431. if (nn_module_stack_str) {
  18432. const import_nn_module_stack = (key, path, ty) => {
  18433. return [key, [path, ty]];
  18434. };
  18435. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  18436. ret.set('nn_module_stack', nn_module_stack);
  18437. }
  18438. const source_fn_st_str = metadata.get('source_fn_stack');
  18439. if (source_fn_st_str) {
  18440. const source_fn_st = [];
  18441. for (const source_fn_str of source_fn_st_str.split(';')) {
  18442. const [name, target_str] = source_fn_str.split(',');
  18443. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  18444. }
  18445. ret.set('source_fn_stack', source_fn_st);
  18446. }
  18447. const torch_fn = metadata.get('torch_fn');
  18448. if (torch_fn) {
  18449. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  18450. }
  18451. const custom_str = metadata.get('custom');
  18452. if (custom_str) {
  18453. ret.set('custom', JSON.parse(custom_str));
  18454. }
  18455. return ret;
  18456. }
  18457. deserialize_argument_spec(x) {
  18458. if (x.type === 'as_tensor') {
  18459. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  18460. } else if (x.type === 'as_sym_int') {
  18461. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  18462. } else if (x.type === 'as_custom_obj') {
  18463. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  18464. }
  18465. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  18466. }
  18467. deserialize_tensor_meta(tensor_meta) {
  18468. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  18469. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  18470. const device = this.deserialize_device(tensor_meta.device);
  18471. const dtype = torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[tensor_meta.dtype];
  18472. return torch.empty_strided(sizes, strides, dtype, null, device);
  18473. }
  18474. deserialize_sym_int(s) {
  18475. if (s.as_expr !== undefined && s.as_expr !== null) {
  18476. let sym = {};
  18477. if (this.symbol_name_to_symbol.has(s.as_expr.expr_str)) {
  18478. sym = this.symbol_name_to_symbol.get(s.as_expr.expr_str);
  18479. } else {
  18480. sym = {};
  18481. /*
  18482. sym = sympy.sympify(val.expr_str, locals=this.symbol_name_to_symbol)
  18483. if isinstance(sym, sympy.Symbol) {
  18484. this.symbol_name_to_symbol[val.expr_str] = sym
  18485. if vr := this.symbol_name_to_range.get(val.expr_str):
  18486. symbolic_shapes._constrain_symbol_range(
  18487. this.shape_env,
  18488. sym,
  18489. compiler_min=vr.lower, # type: ignore[arg-type]
  18490. compiler_max=vr.upper, # type: ignore[arg-type]
  18491. runtime_min=vr.lower, # type: ignore[arg-type]
  18492. runtime_max=vr.upper # type: ignore[arg-type]
  18493. )
  18494. }
  18495. */
  18496. }
  18497. const hint = s.as_expr.hint || null;
  18498. if (hint && (hint.$type === 'as_int' || hint.as_int !== undefined)) {
  18499. return this.deserialize_sym_int(hint);
  18500. }
  18501. return this.shape_env.create_symintnode(sym, hint);
  18502. } else if (s.as_int !== undefined && s.as_int !== null) {
  18503. return s.as_int;
  18504. } else if (s.$type === 'as_int') {
  18505. return s.$value;
  18506. }
  18507. throw new python.Error('SymInt has invalid field type.');
  18508. }
  18509. deserialize_device(d) {
  18510. if (d.index === null) {
  18511. return new torch.device(d.type);
  18512. }
  18513. return new torch.device(d.type, d.index);
  18514. }
  18515. _get_schema_from_target(target) {
  18516. if (target instanceof torch._ops.OpOverload) {
  18517. return target._schema;
  18518. }
  18519. throw new python.Error(`Unsupported schema '${target.name}'.`);
  18520. }
  18521. _is_single_tensor_return(target) {
  18522. const schema = this._get_schema_from_target(target);
  18523. const returns = schema.returns;
  18524. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  18525. }
  18526. });
  18527. this.registerType('torch._export.verifier.Verifier', class {});
  18528. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  18529. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  18530. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  18531. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  18532. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {});
  18533. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  18534. this.registerType('torch._dynamo.hooks.Hooks', class {});
  18535. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  18536. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  18537. this.registerType('torch._TorchCompileInductorWrapper', class {});
  18538. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  18539. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  18540. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  18541. const module = new types.ModuleType(name);
  18542. execution.register('sys').modules.set(name, module);
  18543. const context = new python.Execution.Context(module, null);
  18544. execution.exec(meta.get('module_src'), context);
  18545. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  18546. const state = meta.get('state');
  18547. if (state) {
  18548. if (obj.__setstate__) {
  18549. obj.__setstate__(state);
  18550. } else {
  18551. for (const [key, value] of state) {
  18552. obj[key] = value;
  18553. }
  18554. }
  18555. }
  18556. return obj;
  18557. });
  18558. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  18559. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  18560. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  18561. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  18562. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  18563. this.registerType('torch.device', class {
  18564. constructor(type, index) {
  18565. this.type = type;
  18566. this.index = index ? index : null;
  18567. }
  18568. __str__() {
  18569. return this.index === null ? this.type : `${this.type}:${this.index}`;
  18570. }
  18571. toString() {
  18572. const index = this.index === null ? '' : `, index=${this.index}`;
  18573. return `device(type='${this.type}'${index})`;
  18574. }
  18575. });
  18576. this.registerType('torch.memory_format', class {
  18577. constructor(name) {
  18578. this.name = name;
  18579. }
  18580. __str__() {
  18581. return `torch.${this.name}`;
  18582. }
  18583. toString() {
  18584. return this.__str__();
  18585. }
  18586. });
  18587. this.registerType('torch.dtype', class {
  18588. constructor(scalar_type, name, itemsize) {
  18589. this._scalar_type = scalar_type;
  18590. this._name = name;
  18591. this._itemsize = itemsize;
  18592. }
  18593. scalar_type() {
  18594. return this._scalar_type;
  18595. }
  18596. itemsize() {
  18597. return this._itemsize;
  18598. }
  18599. __reduce__() {
  18600. return this._name;
  18601. }
  18602. __str__() {
  18603. return `torch.${this._name}`;
  18604. }
  18605. toString() {
  18606. return this.__str__();
  18607. }
  18608. });
  18609. this.registerType('torch.layout', class {
  18610. constructor(name) {
  18611. this._name = name;
  18612. }
  18613. __str__() {
  18614. return `torch.${this._name}`;
  18615. }
  18616. toString() {
  18617. return this.__str__();
  18618. }
  18619. });
  18620. this.registerType('torch.qscheme', class {
  18621. constructor(name) {
  18622. this._name = name;
  18623. }
  18624. __str__() {
  18625. return this._name;
  18626. }
  18627. toString() {
  18628. return this.__str__();
  18629. }
  18630. });
  18631. this.registerType('torch.utils.hooks.RemovableHandle', class {
  18632. __setstate__(state) {
  18633. [this.hooks_dict_ref, this.id] = state;
  18634. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  18635. }
  18636. });
  18637. this.registerType('torch.storage._StorageBase', class {
  18638. constructor(size, dtype) {
  18639. this._size = size;
  18640. this._dtype = dtype;
  18641. this._device = null;
  18642. }
  18643. get device() {
  18644. return this._device;
  18645. }
  18646. get dtype() {
  18647. return this._dtype;
  18648. }
  18649. element_size() {
  18650. return this._dtype.element_size;
  18651. }
  18652. size() {
  18653. return this._size;
  18654. }
  18655. get data() {
  18656. return this._cdata;
  18657. }
  18658. _set_cdata(data) {
  18659. const length = this.size() * this.dtype.itemsize();
  18660. if (length !== data.length) {
  18661. throw new python.Error('Storage data size mismatch.');
  18662. }
  18663. this._cdata = data;
  18664. }
  18665. _set_from_file(unpickler) {
  18666. const buffer = unpickler.read(8);
  18667. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  18668. if (size !== this.size()) {
  18669. throw new python.Error('Storage size mismatch.');
  18670. }
  18671. const itemsize = this.dtype.itemsize();
  18672. const data = unpickler.stream(itemsize * size);
  18673. this._set_cdata(data);
  18674. }
  18675. static _new_with_file(unpickler) {
  18676. const buffer = unpickler.read(8);
  18677. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  18678. const storage = new this(size);
  18679. const itemsize = storage.dtype.itemsize();
  18680. const data = unpickler.stream(itemsize * size);
  18681. storage._set_cdata(data);
  18682. return storage;
  18683. }
  18684. });
  18685. this.registerType('torch.storage.UntypedStorage', class extends torch.storage._StorageBase {
  18686. constructor() {
  18687. super();
  18688. throw new python.Error('UntypedStorage not implemented.');
  18689. }
  18690. });
  18691. this.registerType('torch.storage.TypedStorage', class {
  18692. constructor(...args) {
  18693. if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  18694. if (args[3] instanceof torch.device) {
  18695. [this._size, this._dtype, , this._device] = args;
  18696. } else {
  18697. [this._size, this._dtype] = args;
  18698. }
  18699. } else {
  18700. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  18701. }
  18702. }
  18703. get device() {
  18704. return this._device;
  18705. }
  18706. get dtype() {
  18707. return this._dtype;
  18708. }
  18709. element_size() {
  18710. return this._dtype.element_size;
  18711. }
  18712. size() {
  18713. return this._size;
  18714. }
  18715. get data() {
  18716. return this._cdata;
  18717. }
  18718. _set_cdata(data) {
  18719. const length = this.size() * this.dtype.itemsize();
  18720. if (length !== data.length) {
  18721. throw new python.Error('Storage data size mismatch.');
  18722. }
  18723. this._cdata = data;
  18724. }
  18725. _set_from_file(unpickler) {
  18726. const buffer = unpickler.read(8);
  18727. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  18728. if (size !== this.size()) {
  18729. throw new python.Error('Storage size mismatch.');
  18730. }
  18731. const itemsize = this.dtype.itemsize();
  18732. const data = unpickler.stream(itemsize * size);
  18733. this._set_cdata(data);
  18734. }
  18735. static _new_with_file(unpickler) {
  18736. const buffer = unpickler.read(8);
  18737. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  18738. const storage = new this(size);
  18739. const itemsize = storage.dtype.itemsize();
  18740. const data = unpickler.stream(itemsize * size);
  18741. storage._set_cdata(data);
  18742. return storage;
  18743. }
  18744. });
  18745. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  18746. constructor() {
  18747. super();
  18748. throw new python.Error('_LegacyStorage not implemented.');
  18749. }
  18750. });
  18751. this.registerType('torch.BoolStorage', class extends torch.storage._StorageBase {
  18752. constructor(size) {
  18753. super(size, torch.bool);
  18754. }
  18755. });
  18756. this.registerType('torch.ByteStorage', class extends torch.storage._StorageBase {
  18757. constructor(size) {
  18758. super(size, torch.uint8);
  18759. }
  18760. });
  18761. this.registerType('torch.CharStorage', class extends torch.storage._StorageBase {
  18762. constructor(size) {
  18763. super(size, torch.int8);
  18764. }
  18765. });
  18766. this.registerType('torch.ShortStorage', class extends torch.storage._StorageBase {
  18767. constructor(size) {
  18768. super(size, torch.int16);
  18769. }
  18770. });
  18771. this.registerType('torch.IntStorage', class extends torch.storage._StorageBase {
  18772. constructor(size) {
  18773. super(size, torch.int32);
  18774. }
  18775. });
  18776. this.registerType('torch.LongStorage', class extends torch.storage._StorageBase {
  18777. constructor(size) {
  18778. super(size, torch.int64);
  18779. }
  18780. });
  18781. this.registerType('torch.HalfStorage', class extends torch.storage._StorageBase {
  18782. constructor(size) {
  18783. super(size, torch.float16);
  18784. }
  18785. });
  18786. this.registerType('torch.FloatStorage', class extends torch.storage._StorageBase {
  18787. constructor(size) {
  18788. super(size, torch.float32);
  18789. }
  18790. });
  18791. this.registerType('torch.DoubleStorage', class extends torch.storage._StorageBase {
  18792. constructor(size) {
  18793. super(size, torch.float64);
  18794. }
  18795. });
  18796. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._StorageBase {
  18797. constructor(size) {
  18798. super(size, torch.complex32);
  18799. }
  18800. });
  18801. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._StorageBase {
  18802. constructor(size) {
  18803. super(size, torch.complex64);
  18804. }
  18805. });
  18806. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._StorageBase {
  18807. constructor(size) {
  18808. super(size, torch.complex128);
  18809. }
  18810. });
  18811. this.registerType('torch.QInt8Storage', class extends torch.storage._StorageBase {
  18812. constructor(size) {
  18813. super(size, torch.qint8);
  18814. }
  18815. });
  18816. this.registerType('torch.QUInt8Storage', class extends torch.storage._StorageBase {
  18817. constructor(size) {
  18818. super(size, torch.quint8);
  18819. }
  18820. });
  18821. this.registerType('torch.QInt32Storage', class extends torch.storage._StorageBase {
  18822. constructor(size) {
  18823. super(size, torch.qint32);
  18824. }
  18825. });
  18826. this.registerType('torch.BFloat16Storage', class extends torch.storage._StorageBase {
  18827. constructor(size) {
  18828. super(size, torch.bfloat16);
  18829. }
  18830. });
  18831. this.registerType('torch.Size', class extends Array {
  18832. constructor(size) {
  18833. super(size.length);
  18834. for (let i = 0; i < size.length; i++) {
  18835. this[i] = size[i];
  18836. }
  18837. }
  18838. __len__() {
  18839. return this.length;
  18840. }
  18841. });
  18842. this.registerType('torch.Tensor', class {
  18843. constructor() {
  18844. this._layout = torch.strided;
  18845. }
  18846. get device() {
  18847. return this.storage().device;
  18848. }
  18849. get dtype() {
  18850. if (this._layout === torch.sparse_coo) {
  18851. return this._values.dtype();
  18852. }
  18853. return this.storage().dtype;
  18854. }
  18855. get shape() {
  18856. return this._shape;
  18857. }
  18858. get layout() {
  18859. return this._layout;
  18860. }
  18861. get values() {
  18862. if (this._layout === torch.sparse_coo) {
  18863. return this._values;
  18864. }
  18865. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  18866. }
  18867. get indices() {
  18868. if (this._layout === torch.sparse_coo) {
  18869. return this._indices;
  18870. }
  18871. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  18872. }
  18873. get is_quantized() {
  18874. return this.__quantized__ === true;
  18875. }
  18876. get is_nested() {
  18877. return this.__nested__ === true;
  18878. }
  18879. get is_sparse() {
  18880. return this.layout !== torch.strided;
  18881. }
  18882. size() {
  18883. return this._shape;
  18884. }
  18885. storage() {
  18886. if (!this._storage) {
  18887. const name = this.__class__.__name__ === 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  18888. this._storage = self.invoke(`${this.__class__.__module__}.${name}`, []);
  18889. }
  18890. return this._storage;
  18891. }
  18892. storage_offset() {
  18893. return this._storage_offset;
  18894. }
  18895. stride() {
  18896. return this._stride;
  18897. }
  18898. resize_(shape) {
  18899. this._shape = shape;
  18900. }
  18901. __len__() {
  18902. return this._shape[0];
  18903. }
  18904. __setstate__(state) {
  18905. switch (state.length) {
  18906. case 3:
  18907. break;
  18908. case 4:
  18909. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  18910. break;
  18911. case 5:
  18912. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  18913. break;
  18914. default:
  18915. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  18916. }
  18917. }
  18918. __bool__() {
  18919. return true;
  18920. }
  18921. __int__() {
  18922. const storage = this.storage();
  18923. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  18924. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  18925. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  18926. return view.getBigInt64(0, true);
  18927. }
  18928. return NaN;
  18929. }
  18930. __float__() {
  18931. const storage = this.storage();
  18932. if (storage && storage.dtype.__reduce__() === 'float32') {
  18933. if (storage.size() !== undefined && storage.data.length === 4) {
  18934. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  18935. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  18936. return view.getFloat32(0, true);
  18937. }
  18938. }
  18939. return NaN;
  18940. }
  18941. __str__() {
  18942. return 'tensor(...)';
  18943. }
  18944. });
  18945. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  18946. constructor(data, requires_grad) {
  18947. super();
  18948. this.data = data || new torch.Tensor([]);
  18949. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  18950. }
  18951. });
  18952. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  18953. constructor(requires_grad /*, device, dtype */) {
  18954. super(undefined, requires_grad);
  18955. }
  18956. });
  18957. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  18958. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  18959. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  18960. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  18961. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  18962. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  18963. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  18964. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  18965. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  18966. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  18967. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {});
  18968. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {});
  18969. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  18970. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  18971. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  18972. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  18973. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  18974. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  18975. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  18976. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  18977. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  18978. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  18979. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  18980. this.registerType('torch.SymBool', class {
  18981. constructor(node) {
  18982. this.node = node;
  18983. }
  18984. });
  18985. this.registerType('torch.SymInt', class {
  18986. constructor(node) {
  18987. this.node = node;
  18988. }
  18989. });
  18990. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  18991. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  18992. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  18993. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  18994. /* eslint-disable no-multi-assign */
  18995. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  18996. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  18997. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  18998. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  18999. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  19000. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  19001. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  19002. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  19003. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  19004. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex32', 4);
  19005. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex64', 8);
  19006. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex128', 16);
  19007. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  19008. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  19009. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  19010. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  19011. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  19012. torch.quint4x2 = new torch.dtype(16, 'quint4x2');
  19013. torch.quint2x4 = new torch.dtype(17, 'quint2x4');
  19014. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  19015. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  19016. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  19017. torch.bits8 = new torch.dtype(21, 'bits8');
  19018. torch.bits16 = new torch.dtype(22, 'bits16');
  19019. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  19020. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  19021. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  19022. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  19023. torch.uint16 = new torch.dtype(27, 'uint16', 2);
  19024. torch.uint32 = new torch.dtype(28, 'uint32', 4);
  19025. torch.uint64 = new torch.dtype(29, 'uint64', 8);
  19026. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = Object.fromEntries([
  19027. ['uint8', 'BYTE'],
  19028. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  19029. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  19030. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  19031. ['bool', 'BOOL'],
  19032. ['bfloat16', 'BFLOAT16']
  19033. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  19034. torch.contiguous_format = new torch.memory_format('contiguous_format');
  19035. torch.channels_last = new torch.memory_format('channels_last');
  19036. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  19037. torch.preserve_format = new torch.memory_format('preserve_format');
  19038. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  19039. ['contiguous_format', 'ContiguousFormat'],
  19040. ['channels_last', 'ChannelsLast'],
  19041. ['channels_last_3d', 'ChannelsLast3d'],
  19042. ['preserve_format', 'PreserveFormat']
  19043. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  19044. /* eslint-enable no-multi-assign */
  19045. torch.strided = new torch.layout('strided');
  19046. torch.sparse_coo = new torch.layout('sparse_coo');
  19047. torch.sparse_csr = new torch.layout('sparse_csr');
  19048. torch.sparse_csc = new torch.layout('sparse_csc');
  19049. torch.sparse_bsr = new torch.layout('sparse_bsr');
  19050. torch.sparse_bsc = new torch.layout('sparse_bsc');
  19051. torch._mkldnn = new torch.layout('_mkldnn');
  19052. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  19053. ['sparse_coo', 'SparseCoo'],
  19054. ['sparse_csr', 'SparseCsr'],
  19055. ['sparse_csc', 'SparseCsc'],
  19056. ['sparse_bsr', 'SparseBsr'],
  19057. ['sparse_bsc', 'SparseBsc'],
  19058. ['_mkldnn', '_mkldnn'],
  19059. ['strided', 'Strided'],
  19060. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  19061. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  19062. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  19063. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  19064. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  19065. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  19066. torch.inf = this.register('math').inf;
  19067. this.registerFunction('fastcore.basics._using_attr');
  19068. this.registerFunction('fastcore.imports.noop');
  19069. this.registerType('fastcore.basics.fastuple', class {});
  19070. this.registerType('fastcore.basics.GetAttr', class {});
  19071. this.registerType('fastcore.dispatch._TypeDict', class {});
  19072. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  19073. this.registerType('fastcore.foundation.L', class {});
  19074. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  19075. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  19076. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  19077. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  19078. this.registerType('fastai.basic_train.Learner', class {});
  19079. this.registerType('fastai.basic_train.Recorder', class {});
  19080. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  19081. const tensor = torch._utils._rebuild_tensor_v2(...args);
  19082. return self.invoke(cls, tensor);
  19083. });
  19084. this.registerFunction('fastai.torch_core.trainable_params');
  19085. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  19086. const tensor = self.invoke(type, [func(...args)]);
  19087. Object.assign(tensor, dict);
  19088. return tensor;
  19089. });
  19090. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  19091. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  19092. constructor(x) {
  19093. super();
  19094. Object.assign(this, x);
  19095. }
  19096. });
  19097. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  19098. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  19099. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  19100. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  19101. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  19102. this.registerFunction('fastai.torch_core.uniform');
  19103. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  19104. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  19105. this.registerType('fastai.callback.fp16.AMPMode', class extends this._enum.Enum {});
  19106. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  19107. this.registerFunction('fastai.callback.hook._hook_inner');
  19108. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  19109. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  19110. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  19111. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  19112. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  19113. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  19114. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  19115. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  19116. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  19117. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  19118. this.registerType('fastai.data.core.Datasets', class {});
  19119. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  19120. this.registerType('fastai.data.core.FilteredBase', class {});
  19121. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  19122. this.registerType('fastai.data.core.TfmdLists', class {});
  19123. this.registerType('fastai.data.load._FakeLoader', class {});
  19124. this.registerFunction('fastai.data.load._wif');
  19125. this.registerType('fastai.data.transforms.Categorize', class {});
  19126. this.registerType('fastai.data.transforms.Category', class {});
  19127. this.registerType('fastai.data.transforms.CategoryMap', class {});
  19128. this.registerType('fastai.data.transforms.ColReader', class {});
  19129. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  19130. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  19131. this.registerType('fastai.data.transforms.Normalize', class {});
  19132. this.registerType('fastai.data.transforms.parent_label', class {});
  19133. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  19134. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  19135. this.registerType('fastai.data.transforms.ToTensor', class {});
  19136. this.registerType('fastai.data_block.CategoryList', class {});
  19137. this.registerType('fastai.data_block.CategoryProcessor', class {});
  19138. this.registerType('fastai.imports.noop', class {});
  19139. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  19140. this.registerType('fastai.layers.ConvLayer', class {});
  19141. this.registerType('fastai.layers.Embedding', class {});
  19142. this.registerType('fastai.layers.Flatten', class {});
  19143. this.registerType('fastai.layers.FlattenedLoss', class {});
  19144. this.registerType('fastai.layers.LinBnDrop', class {});
  19145. this.registerType('fastai.layers.MergeLayer', class {});
  19146. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  19147. this.registerType('fastai.layers.ResBlock', class {});
  19148. this.registerType('fastai.layers.SelfAttention', class {});
  19149. this.registerType('fastai.layers.SigmoidRange', class {});
  19150. this.registerType('fastai.layers.TimeDistributed', class {});
  19151. this.registerType('fastai.layers.ToTensorBase', class {});
  19152. this.registerType('fastai.learner._ConstantFunc', class {});
  19153. this.registerType('fastai.learner.Metric', class {});
  19154. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  19155. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  19156. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  19157. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  19158. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  19159. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  19160. this.registerType('fastai.learner.Recorder', class {});
  19161. this.registerType('fastai.losses.BaseLoss', class {});
  19162. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  19163. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  19164. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  19165. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  19166. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  19167. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  19168. this.registerType('fastai.metrics.Dice', class {});
  19169. this.registerType('fastai.metrics.JaccardCoeff', class {});
  19170. this.registerFunction('fastai.metrics._rmse');
  19171. this.registerFunction('fastai.metrics.accuracy');
  19172. this.registerFunction('fastai.metrics.accuracy_multi');
  19173. this.registerFunction('fastai.metrics.foreground_acc');
  19174. this.registerFunction('fastai.metrics.mse');
  19175. this.registerFunction('fastai.metrics.error_rate');
  19176. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  19177. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  19178. this.registerFunction('fastai.optimizer.Adam');
  19179. this.registerFunction('fastai.optimizer.adam_step');
  19180. this.registerFunction('fastai.optimizer.average_grad');
  19181. this.registerFunction('fastai.optimizer.average_sqr_grad');
  19182. this.registerFunction('fastai.optimizer.RAdam');
  19183. this.registerFunction('fastai.optimizer.step_stat');
  19184. this.registerFunction('fastai.optimizer.weight_decay');
  19185. this.registerType('fastai.tabular.core.Categorify', class {});
  19186. this.registerType('fastai.tabular.core.FillMissing', class {});
  19187. this.registerType('fastai.tabular.core.FillStrategy', class {});
  19188. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  19189. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  19190. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  19191. this.registerType('fastai.tabular.core.Tabular', class {});
  19192. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  19193. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  19194. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  19195. this.registerType('fastai.tabular.model.TabularModel', class {});
  19196. this.registerFunction('fastai.vision.augment.aug_transforms');
  19197. this.registerFunction('fastai.vision.augment.dihedral_mat');
  19198. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  19199. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  19200. this.registerType('fastai.vision.augment._WarpCoord', class {});
  19201. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  19202. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  19203. this.registerType('fastai.vision.augment.Brightness', class {});
  19204. this.registerType('fastai.vision.augment.flip_mat', class {});
  19205. this.registerType('fastai.vision.augment.Flip', class {});
  19206. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  19207. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  19208. this.registerType('fastai.vision.augment.Resize', class {});
  19209. this.registerType('fastai.vision.augment.rotate_mat', class {});
  19210. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  19211. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  19212. this.registerType('fastai.vision.augment.zoom_mat', class {});
  19213. this.registerType('fastai.vision.core.PILImage', class {});
  19214. this.registerType('fastai.vision.core.PILMask', class {});
  19215. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  19216. this.registerType('fastai.vision.data.ImageList', class {});
  19217. this.registerType('fastai.vision.data.ImageItemList', class {});
  19218. this.registerType('fastai.vision.image.Image', class {});
  19219. this.registerType('fastai.vision.image.RandTransform', class {});
  19220. this.registerType('fastai.vision.image.TfmCrop', class {});
  19221. this.registerFunction('fastai.vision.learner._resnet_split');
  19222. this.registerFunction('fastai.vision.learner.default_split');
  19223. this.registerFunction('fastai.vision.learner.default_split');
  19224. this.registerType('fastai.vision.learner.TimmBody', class {});
  19225. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  19226. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  19227. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  19228. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  19229. this.registerFunction('fastai.vision.transform._crop_pad');
  19230. }
  19231. exec(code , context) {
  19232. const ast = this.ast;
  19233. const program = ast.parse(code, '', null);
  19234. if (!program) {
  19235. throw new python.Error("Module '?' parse error.");
  19236. }
  19237. this.block(program.body, context);
  19238. }
  19239. debug(/* file */) {
  19240. }
  19241. source(file) {
  19242. if (this._sources.has(file)) {
  19243. return this._sources.get(file);
  19244. }
  19245. return null;
  19246. }
  19247. read(file) {
  19248. const buffer = this.source(file);
  19249. if (buffer) {
  19250. const debug = this.debug(file);
  19251. return this.parse(file, buffer, debug);
  19252. }
  19253. return null;
  19254. }
  19255. parse(filename, buffer, debug) {
  19256. const ast = this.ast;
  19257. const source = this._utf8Decoder.decode(buffer);
  19258. const program = ast.parse(source, filename, debug);
  19259. if (!program) {
  19260. throw new python.Error(`Module '${filename}' parse error.`);
  19261. }
  19262. return program;
  19263. }
  19264. import(name, current, level) {
  19265. if (level) {
  19266. let bits = current.split('.');
  19267. if (bits.length < level) {
  19268. throw new python.Error('Invalid relative import beyond top-level package.');
  19269. }
  19270. bits = bits.slice(0, bits.length - level);
  19271. const base = bits.join('.');
  19272. name = name ? [base, name].join('.') : base;
  19273. }
  19274. const index = name.lastIndexOf('.');
  19275. let parent = null;
  19276. let child = null;
  19277. if (index > 0) {
  19278. parent = name.substring(0, index);
  19279. child = name.substring(index + 1);
  19280. this.import(parent);
  19281. }
  19282. if (!this._modules.has(name)) {
  19283. const module = this._registry.get(name) || new this.builtins.module(name);
  19284. module.__package__ = name;
  19285. this._modules.set(name, module);
  19286. const path = name.split('.').join('/');
  19287. module.__path__ = [path];
  19288. const file = `${path}.py`;
  19289. const program = this.read(file);
  19290. if (program) {
  19291. module.__file__ = file;
  19292. for (const [name, value] of Object.entries(this.builtins)) {
  19293. switch (name) {
  19294. case '__class__':
  19295. case '__package__':
  19296. case '__module__':
  19297. case '__name__':
  19298. case '__path__':
  19299. case '__file__':
  19300. break;
  19301. default:
  19302. module[name] = value;
  19303. break;
  19304. }
  19305. }
  19306. const context = new python.Execution.Context(module, null);
  19307. if (name !== 'builtins') {
  19308. context.set('__builtins__', this._modules.get('builtins'));
  19309. }
  19310. this.block(program.body, context);
  19311. }
  19312. if (parent) {
  19313. const parent_module = this._modules.get(parent);
  19314. parent_module[child] = module;
  19315. }
  19316. }
  19317. return this._modules.get(name);
  19318. }
  19319. __import__(name, globals, locals, fromlist, level) {
  19320. let module = null;
  19321. level = level || 0;
  19322. if (level === 0) {
  19323. module = this.import(name);
  19324. } else {
  19325. globals = globals || {};
  19326. let current = globals.__package__;
  19327. if (!current) {
  19328. const spec = globals.__spec__;
  19329. if (spec) {
  19330. current = spec.parent;
  19331. } else {
  19332. const name = globals.__name__;
  19333. const bits = name.split('.');
  19334. bits.pop();
  19335. current = bits.join('.');
  19336. }
  19337. }
  19338. module = this.import(name, current, level);
  19339. }
  19340. if (!fromlist) {
  19341. if (level === 0) {
  19342. return this.import(name.split('.')[0]);
  19343. } else if (name) {
  19344. throw new python.Error(`Unsupported relative import '${name}'.`);
  19345. // cut_off = len(name) - len(name.partition('.')[0])
  19346. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  19347. }
  19348. } else if (module.__path__) {
  19349. const handle_fromlist = (module, fromlist, recursive) => {
  19350. for (const name of fromlist) {
  19351. if (name === '*') {
  19352. if (!recursive && module.__all__) {
  19353. handle_fromlist(module, module.__all__, true);
  19354. }
  19355. } else if (!module[name]) {
  19356. this.import(`${module.__name__}.${name}`);
  19357. }
  19358. }
  19359. return module;
  19360. };
  19361. handle_fromlist(module, fromlist);
  19362. }
  19363. return module;
  19364. }
  19365. module(name) {
  19366. return this._modules.get(name);
  19367. }
  19368. resolve(name) {
  19369. const index = name.lastIndexOf('.');
  19370. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  19371. const moduleName = index === -1 ? '' : name.substring(0, index);
  19372. const module = this.import(moduleName);
  19373. let type = module ? module[memberName] : null;
  19374. if (!type) {
  19375. if (!this._unresolved.has(name)) {
  19376. const moduleName = name.split('.').shift();
  19377. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  19378. this.emit('resolve', name);
  19379. }
  19380. const type = this._createType(name, class {});
  19381. this._unresolved.set(name, type);
  19382. }
  19383. type = this._unresolved.get(name);
  19384. }
  19385. return type;
  19386. }
  19387. invoke(target, args) {
  19388. const builtins = this.builtins;
  19389. if (typeof target === 'string') {
  19390. target = this.resolve(target);
  19391. }
  19392. if (target) {
  19393. if (target.__class__ === builtins.type) {
  19394. if (target.prototype && target.prototype.__class__ === target) {
  19395. return Reflect.construct(target, args);
  19396. }
  19397. const obj = Object.create(target);
  19398. if (obj.__init__ && typeof obj.__init__ === 'function') {
  19399. obj.__init__(...args);
  19400. }
  19401. return obj;
  19402. } else if (target.__class__ === builtins.function) {
  19403. if (target.__call__) {
  19404. return target.__call__(args);
  19405. }
  19406. return target(...args);
  19407. }
  19408. }
  19409. throw new python.Error('Unsupported invoke target.');
  19410. }
  19411. call(target, name, args, keywords, context) {
  19412. const builtins = this.builtins;
  19413. const callTarget = this.target(target, context);
  19414. const callArguments = args.map((arg) => this.expression(arg, context));
  19415. if (!callTarget || (name !== null && !callTarget[name])) {
  19416. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  19417. name = null;
  19418. callArguments.shift();
  19419. } else {
  19420. const targetName = `${this.identifier(target)}.${name}`;
  19421. throw new python.Error(`Unknown function '${targetName}'.`);
  19422. }
  19423. }
  19424. const func = name ? callTarget[name] : callTarget;
  19425. if (func.__class__ === builtins.type) {
  19426. if (func.prototype && func.prototype.__class__ === func) {
  19427. return Reflect.construct(func, callArguments);
  19428. }
  19429. const obj = Object.create(func);
  19430. obj.__class__ = func;
  19431. if (obj.__init__ && typeof obj.__init__ === 'function') {
  19432. obj.__init__(...args);
  19433. }
  19434. return obj;
  19435. }
  19436. if (func.__class__ === builtins.function) {
  19437. if (func.__call__) {
  19438. return func.__call__(callArguments);
  19439. }
  19440. }
  19441. if (func.__class__ === builtins.method) {
  19442. if (func.__call__) {
  19443. return func.__call__([callTarget].concat(callArguments));
  19444. }
  19445. }
  19446. if (typeof func === 'function') {
  19447. return func.apply(callTarget, callArguments);
  19448. }
  19449. throw new python.Error('Unsupported call expression.');
  19450. }
  19451. apply(method, args, context) {
  19452. const locals = Array.prototype.slice.call(args);
  19453. context = new python.Execution.Context(context.globals, {});
  19454. args = method.args.posonlyargs.concat(method.args.args);
  19455. const default_pos = args.length - method.args.defaults.length;
  19456. for (let i = 0; i < method.args.args.length; i++) {
  19457. const arg = method.args.args[i];
  19458. let value = null;
  19459. if (locals.length > 0) {
  19460. value = locals.shift();
  19461. } else if (i >= default_pos) {
  19462. value = this.expression(method.args.defaults[i - default_pos], context);
  19463. } else {
  19464. throw new python.Error('Missing required positional argument.');
  19465. }
  19466. context.set(arg.arg, value);
  19467. }
  19468. return this.block(method.body, context);
  19469. }
  19470. block(statements, context) {
  19471. statements = Array.prototype.slice.call(statements);
  19472. while (statements.length > 0) {
  19473. const stmt = statements.shift();
  19474. const value = this.statement(stmt, context);
  19475. if (value !== undefined) {
  19476. return value;
  19477. }
  19478. }
  19479. return undefined;
  19480. }
  19481. statement(stmt, context) {
  19482. const ast = this.ast;
  19483. const builtins = this.builtins;
  19484. if (stmt instanceof ast.Pass) {
  19485. // pass
  19486. } else if (stmt instanceof ast.Constant) {
  19487. // pass
  19488. } else if (stmt instanceof ast.Return) {
  19489. return this.expression(stmt.value, context);
  19490. } else if (stmt instanceof ast.FunctionDef) {
  19491. const module = context.get('__name__');
  19492. const self = this;
  19493. const parent = context.get('__class__');
  19494. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  19495. const func = {
  19496. __class__: type,
  19497. __globals__: context,
  19498. __module__: module,
  19499. __name__: stmt.name,
  19500. __code__: stmt,
  19501. __call__(args) {
  19502. return self.apply(this.__code__, args, this.__globals__);
  19503. }
  19504. };
  19505. context.set(stmt.name, func);
  19506. } else if (stmt instanceof ast.ClassDef) {
  19507. const bases = stmt.bases.map((base) => this.expression(base, context));
  19508. if (bases.length > 1) {
  19509. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  19510. }
  19511. const base = bases.length === 1 ? bases[0] : null;
  19512. const name = `${context.get('__name__')}.${stmt.name}`;
  19513. const value = this._createType(name, base ? class extends base {} : class {});
  19514. value.__bases__ = bases;
  19515. context.set(stmt.name, value);
  19516. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  19517. } else if (stmt instanceof ast.AnnAssign) {
  19518. const target = this.identifier(stmt.target, context);
  19519. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  19520. } else if (stmt instanceof ast.Assign) {
  19521. this.expression(stmt, context);
  19522. } else if (stmt instanceof ast.If) {
  19523. const test = this.expression(stmt.test, context);
  19524. if (test === true || test) {
  19525. const value = this.block(stmt.body, context);
  19526. if (value !== undefined) {
  19527. return value;
  19528. }
  19529. } else if (test === false) {
  19530. if (stmt.orelse) {
  19531. const value = this.block(stmt.orelse, context);
  19532. if (value !== undefined) {
  19533. return value;
  19534. }
  19535. }
  19536. } else {
  19537. throw new python.Error('Unsupported condition.');
  19538. }
  19539. } else if (stmt instanceof ast.For) {
  19540. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  19541. const range = this.expression(stmt.iter, context);
  19542. const variable = stmt.target;
  19543. for (const current of range) {
  19544. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  19545. const value = this.block(stmt.body.statements, context);
  19546. if (value !== undefined) {
  19547. return value;
  19548. }
  19549. }
  19550. } else {
  19551. throw new python.Error("Unsupported 'for' statement.");
  19552. }
  19553. } else if (stmt instanceof ast.While) {
  19554. const test = this.expression(stmt.test, context);
  19555. if (test) {
  19556. const value = this.block(stmt.body.statements, context);
  19557. if (value !== undefined) {
  19558. return value;
  19559. }
  19560. }
  19561. } else if (stmt instanceof ast.With) {
  19562. const items = [];
  19563. for (const item of stmt.items) {
  19564. items.push(this.expression(item.context_expr, context));
  19565. }
  19566. for (const item of items) {
  19567. if (item.__enter__ && item.__enter__.__call__) {
  19568. item.__enter__.__call__([item]);
  19569. }
  19570. }
  19571. const value = this.block(stmt.body, context);
  19572. for (const item of items) {
  19573. if (item.__exit__ && item.__exit__.__call__) {
  19574. item.__exit__.__call__([item]);
  19575. }
  19576. }
  19577. if (value !== undefined) {
  19578. return value;
  19579. }
  19580. } else if (stmt instanceof ast.Expr) {
  19581. this.expression(stmt.value, context);
  19582. } else if (stmt instanceof ast.Import) {
  19583. for (const alias of stmt.names) {
  19584. let module = this.__import__(alias.name, context);
  19585. if (alias.asname) {
  19586. const bits = alias.name.split('.').reverse();
  19587. bits.pop();
  19588. while (bits.length > 0) {
  19589. module = module[bits.pop()];
  19590. }
  19591. context.set(alias.asname, module);
  19592. } else {
  19593. context.set(alias.name.split('.')[0], module);
  19594. }
  19595. }
  19596. } else if (stmt instanceof ast.ImportFrom) {
  19597. const fromlist = stmt.names.map((name) => name.name);
  19598. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  19599. for (const entry of stmt.names) {
  19600. const name = entry.name;
  19601. const asname = entry.asname ? entry.asname : null;
  19602. if (!module[name]) {
  19603. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  19604. }
  19605. context.set(asname ? asname : name, module[name]);
  19606. }
  19607. } else {
  19608. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  19609. }
  19610. return undefined;
  19611. }
  19612. expression(expr, context) {
  19613. const ast = this.ast;
  19614. const builtins = this.builtins;
  19615. const typing = this.typing;
  19616. const self = context.get('self');
  19617. switch (expr.__class__.__name__) {
  19618. case 'Assign': {
  19619. const [target] = expr.targets;
  19620. if (target instanceof ast.Name) {
  19621. const value = this.expression(expr.value, context);
  19622. context.set(target.id, value);
  19623. return undefined;
  19624. } else if (target instanceof ast.Subscript) {
  19625. if (target.value instanceof ast.Name &&
  19626. target.slice instanceof ast.List &&
  19627. target.slice.elts.length === 1) {
  19628. const index = this.expression(target.slice.elts[0], context);
  19629. const id = target.value.id;
  19630. if (id === '__annotations__') {
  19631. context.set(id, context.get(id) || {});
  19632. }
  19633. const obj = context.get(id);
  19634. const value = this.expression(expr.value, context);
  19635. if (obj instanceof Map) {
  19636. obj.set(index, value);
  19637. } else {
  19638. obj[index] = value;
  19639. }
  19640. return undefined;
  19641. }
  19642. } else if (target instanceof ast.Attribute) {
  19643. const obj = this.expression(target.value, context);
  19644. const value = this.expression(expr.value, context);
  19645. obj[target.attr] = value;
  19646. return undefined;
  19647. } else if (target instanceof ast.Tuple) {
  19648. context.target.push(target.elts);
  19649. const value = this.expression(expr.value, context);
  19650. context.target.pop();
  19651. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  19652. if (target.elts.length < value.length) {
  19653. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  19654. }
  19655. if (target.elts.length > value.length) {
  19656. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  19657. }
  19658. for (let i = 0; i < value.length; i++) {
  19659. context.set(target.elts[i].id, value[i]);
  19660. }
  19661. return undefined;
  19662. }
  19663. }
  19664. break;
  19665. }
  19666. case 'List': {
  19667. return expr.elts.map((expr) => this.expression(expr, context));
  19668. }
  19669. case 'Constant': {
  19670. return expr.value;
  19671. }
  19672. case 'Subscript': {
  19673. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  19674. const id = expr.value.id;
  19675. if (context.get(id)) {
  19676. const index = this.expression(expr.slice, context);
  19677. const target = context.get(id);
  19678. if (target instanceof Map) {
  19679. return target.get(index);
  19680. }
  19681. return target[index < 0 ? target.length + index : index];
  19682. }
  19683. }
  19684. const value = this.expression(expr.value, context);
  19685. if (value && expr.slice instanceof ast.List &&
  19686. (value.__class__ === typing._TupleType ||
  19687. value.__class__ === typing._SpecialGenericAlias ||
  19688. value.__class__ === typing._SpecialForm)) {
  19689. const type = { ...value };
  19690. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  19691. return type;
  19692. }
  19693. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  19694. const index = this.expression(expr.slice.elts[0], context);
  19695. if (value instanceof Map) {
  19696. return value.get(index);
  19697. }
  19698. return value[index < 0 ? value.length + index : index];
  19699. }
  19700. break;
  19701. }
  19702. case 'Attribute': {
  19703. const value = this.target(expr.value, context);
  19704. return value[expr.attr];
  19705. }
  19706. case 'Call': {
  19707. const func = expr.func;
  19708. if (func instanceof ast.Attribute) {
  19709. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  19710. }
  19711. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  19712. }
  19713. case 'Name': {
  19714. const id = expr.id;
  19715. if (id === 'self') {
  19716. return self;
  19717. }
  19718. const type = (value) => {
  19719. return value &&
  19720. (value.__class__ === builtins.type ||
  19721. value.__class__ === typing._TupleType ||
  19722. value.__class__ === typing._SpecialGenericAlias ||
  19723. value.__class__ === typing._SpecialForm);
  19724. };
  19725. const builtin = builtins[id];
  19726. if (type(builtin)) {
  19727. return builtin;
  19728. }
  19729. const value = context.get(id);
  19730. if (value === undefined) {
  19731. const value = typing[id];
  19732. if (type(value)) {
  19733. return value;
  19734. }
  19735. }
  19736. return value;
  19737. }
  19738. case 'Tuple': {
  19739. return expr.elts.map((expr) => this.expression(expr, context));
  19740. }
  19741. case 'Dict': {
  19742. const dict = {};
  19743. for (let i = 0; i < expr.keys.length; i++) {
  19744. const key = this.expression(expr.keys[i], context);
  19745. const value = this.expression(expr.values[i], context);
  19746. dict[key] = value;
  19747. }
  19748. return dict;
  19749. }
  19750. case 'UnaryOp': {
  19751. if (expr.op instanceof ast.USub) {
  19752. return -this.expression(expr.operand, context);
  19753. }
  19754. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  19755. }
  19756. case 'binary': {
  19757. switch (expr.op) {
  19758. case '==': {
  19759. return this.expression(expr.left, context) === this.expression(expr.right, context);
  19760. }
  19761. default: {
  19762. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  19763. }
  19764. }
  19765. }
  19766. default: {
  19767. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  19768. }
  19769. }
  19770. return undefined;
  19771. }
  19772. identifier(expr) {
  19773. const ast = this.ast;
  19774. if (expr instanceof ast.Name) {
  19775. return expr.id;
  19776. }
  19777. if (expr instanceof ast.Attribute) {
  19778. return `${this.identifier(expr.value)}.${expr.attr}`;
  19779. }
  19780. return null;
  19781. }
  19782. target(expr, context) {
  19783. const ast = this.ast;
  19784. let current = expr;
  19785. let path = [];
  19786. for (;;) {
  19787. if (current instanceof ast.Attribute) {
  19788. path.push(current.attr);
  19789. current = current.value;
  19790. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  19791. path.push(current.id);
  19792. break;
  19793. } else {
  19794. path = null;
  19795. break;
  19796. }
  19797. }
  19798. if (path) {
  19799. let target = null;
  19800. for (let i = path.length - 1; i >= 0; i--) {
  19801. const name = path[i];
  19802. if (target) {
  19803. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  19804. } else {
  19805. target = context.get(name);
  19806. }
  19807. if (!target) {
  19808. break;
  19809. }
  19810. }
  19811. if (!target) {
  19812. path.reverse();
  19813. const name = path.join('.');
  19814. const file = `${path.join('/')}.py`;
  19815. if (this._sources.has(file)) {
  19816. target = this.import(name);
  19817. } else {
  19818. target = this.resolve(name);
  19819. }
  19820. }
  19821. return target;
  19822. }
  19823. return this.expression(expr, context);
  19824. }
  19825. add(name, source) {
  19826. this._sources.set(name, source);
  19827. }
  19828. on(event, listener) {
  19829. const value = this._events.get(event) || [];
  19830. value.push(listener);
  19831. this._events.set(event, value);
  19832. }
  19833. emit(event, ...args) {
  19834. if (this._events.has(event)) {
  19835. for (const callback of this._events.get(event)) {
  19836. callback(this, ...args);
  19837. }
  19838. }
  19839. }
  19840. register(name, value) {
  19841. if (!this._registry.has(name)) {
  19842. value = value || new (this._registry.get('builtins').module)(name);
  19843. this._registry.set(name, value);
  19844. let current = name;
  19845. for (;;) {
  19846. const index = current.lastIndexOf('.');
  19847. if (index === -1) {
  19848. break;
  19849. }
  19850. const child = current.substring(index + 1);
  19851. current = current.substring(0, index);
  19852. if (!value.__module__) {
  19853. value.__module__ = current;
  19854. }
  19855. const parent = this.register(current);
  19856. parent[child] = value;
  19857. value = parent;
  19858. }
  19859. }
  19860. return this._registry.get(name);
  19861. }
  19862. registerFunction(name, value) {
  19863. const builtins = this.builtins;
  19864. const index = name.lastIndexOf('.');
  19865. if (!value) {
  19866. value = () => {
  19867. throw new python.Error(`'${name}' is not implemented.`);
  19868. };
  19869. }
  19870. value.__class__ = builtins.function;
  19871. value.__name__ = index === -1 ? name : name.substring(index + 1);
  19872. value.__module__ = index === -1 ? '' : name.substring(0, index);
  19873. const module = this.register(value.__module__);
  19874. if (module[name]) {
  19875. throw new python.Error(`Function '${name}' is already registered.`);
  19876. }
  19877. module[value.__name__] = value;
  19878. return value;
  19879. }
  19880. _createType(name, value) {
  19881. const builtins = this.builtins;
  19882. const index = name.lastIndexOf('.');
  19883. value.__class__ = builtins.type;
  19884. value.__name__ = index === -1 ? name : name.substring(index + 1);
  19885. value.__module__ = index === -1 ? '' : name.substring(0, index);
  19886. value.prototype.__class__ = value;
  19887. return value;
  19888. }
  19889. registerType(name, value) {
  19890. value = this._createType(name, value);
  19891. const parts = name.split('.');
  19892. const memberName = parts.pop();
  19893. const moduleName = parts.join('.');
  19894. const module = this.register(moduleName);
  19895. if (module[memberName]) {
  19896. throw new python.Error(`Class '${memberName}' is already registered.`);
  19897. }
  19898. module[memberName] = value;
  19899. return value;
  19900. }
  19901. };
  19902. python.Execution.Context = class {
  19903. constructor(globals, locals) {
  19904. this.globals = globals;
  19905. this.locals = locals;
  19906. }
  19907. set(name, value) {
  19908. if (this.locals) {
  19909. this.locals[name] = value;
  19910. } else {
  19911. this.globals[name] = value;
  19912. }
  19913. }
  19914. get(name) {
  19915. if (this.locals && name in this.locals) {
  19916. return this.locals[name];
  19917. }
  19918. if (name in this.globals) {
  19919. return this.globals[name];
  19920. }
  19921. return undefined;
  19922. }
  19923. get target() {
  19924. this._target = this._target || [];
  19925. return this._target;
  19926. }
  19927. };
  19928. python.BinaryReader = class {
  19929. constructor(buffer) {
  19930. this._buffer = buffer;
  19931. this._length = buffer.length;
  19932. this._position = 0;
  19933. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  19934. this._utf8Decoder = new TextDecoder('utf-8');
  19935. this._asciiDecoder = new TextDecoder('ascii');
  19936. }
  19937. get position() {
  19938. return this._position;
  19939. }
  19940. get length() {
  19941. return this._length;
  19942. }
  19943. seek(position) {
  19944. this._position = position >= 0 ? position : this._length + position;
  19945. if (this._position > this._buffer.length) {
  19946. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  19947. }
  19948. }
  19949. skip(offset) {
  19950. this._position += offset;
  19951. if (this._position > this._buffer.length) {
  19952. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  19953. }
  19954. }
  19955. stream(length) {
  19956. const buffer = this.read(length);
  19957. return new python.BinaryReader(buffer);
  19958. }
  19959. peek(length) {
  19960. const position = this._position;
  19961. length = length === undefined ? this._length - this._position : length;
  19962. this.skip(length);
  19963. const end = this._position;
  19964. this.skip(-length);
  19965. if (position === 0 && length === this._length) {
  19966. return this._buffer;
  19967. }
  19968. return this._buffer.subarray(position, end);
  19969. }
  19970. read(length) {
  19971. const position = this._position;
  19972. length = length === undefined ? this._length - this._position : length;
  19973. this.skip(length);
  19974. if (position === 0 && length === this._length) {
  19975. return this._buffer;
  19976. }
  19977. return this._buffer.subarray(position, this._position);
  19978. }
  19979. byte() {
  19980. const position = this._position;
  19981. this.skip(1);
  19982. return this._view.getUint8(position);
  19983. }
  19984. uint16() {
  19985. const position = this._position;
  19986. this.skip(2);
  19987. return this._view.getUint16(position, true);
  19988. }
  19989. int32() {
  19990. const position = this._position;
  19991. this.skip(4);
  19992. return this._view.getInt32(position, true);
  19993. }
  19994. uint32() {
  19995. const position = this._position;
  19996. this.skip(4);
  19997. return this._view.getUint32(position, true);
  19998. }
  19999. int64() {
  20000. const position = this._position;
  20001. this.skip(8);
  20002. return this._view.getBigInt64(position, true);
  20003. }
  20004. float64() {
  20005. const position = this._position;
  20006. this.skip(8);
  20007. return this._view.getFloat64(position, false);
  20008. }
  20009. string(size, encoding) {
  20010. const data = this.read(size);
  20011. return (encoding === 'utf-8') ?
  20012. this._utf8Decoder.decode(data) :
  20013. this._asciiDecoder.decode(data);
  20014. }
  20015. line() {
  20016. const index = this._buffer.indexOf(0x0A, this._position);
  20017. if (index === -1) {
  20018. throw new python.Error('Could not find end of line.');
  20019. }
  20020. const size = index - this._position;
  20021. const text = this.string(size, 'ascii');
  20022. this.skip(1);
  20023. return text;
  20024. }
  20025. };
  20026. python.StreamReader = class {
  20027. constructor(stream) {
  20028. this._stream = stream;
  20029. this._length = stream.length;
  20030. this._position = 0;
  20031. this._utf8Decoder = new TextDecoder('utf-8');
  20032. this._asciiDecoder = new TextDecoder('ascii');
  20033. }
  20034. get position() {
  20035. return this._position;
  20036. }
  20037. get length() {
  20038. return this._length;
  20039. }
  20040. seek(position) {
  20041. this._stream.seek(position);
  20042. this._position = this._stream.position;
  20043. }
  20044. skip(offset) {
  20045. this._position += offset;
  20046. if (this._position > this._length) {
  20047. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  20048. }
  20049. }
  20050. stream(length) {
  20051. this._stream.seek(this._position);
  20052. this.skip(length);
  20053. return this._stream.stream(length);
  20054. }
  20055. peek(length) {
  20056. this._stream.seek(this._position);
  20057. return this._stream.peek(length);
  20058. }
  20059. read(length) {
  20060. this._stream.seek(this._position);
  20061. this.skip(length);
  20062. return this._stream.read(length);
  20063. }
  20064. byte() {
  20065. const position = this._fill(1);
  20066. return this._view.getUint8(position);
  20067. }
  20068. uint16() {
  20069. const position = this._fill(2);
  20070. return this._view.getUint16(position, true);
  20071. }
  20072. int32() {
  20073. const position = this._fill(4);
  20074. return this._view.getInt32(position, true);
  20075. }
  20076. uint32() {
  20077. const position = this._fill(4);
  20078. return this._view.getUint32(position, true);
  20079. }
  20080. int64() {
  20081. const position = this._fill(8);
  20082. return this._view.getBigInt64(position, true);
  20083. }
  20084. float64() {
  20085. const position = this._fill(8);
  20086. return this._view.getFloat64(position, false);
  20087. }
  20088. string(size, encoding) {
  20089. const data = this.read(size);
  20090. return (encoding === 'utf-8') ?
  20091. this._utf8Decoder.decode(data) :
  20092. this._asciiDecoder.decode(data);
  20093. }
  20094. line() {
  20095. let position = this._fill(0);
  20096. let index = this._buffer.indexOf(0x0A, position);
  20097. if (index === -1) {
  20098. const size = Math.min(0x20000000, this._stream.length - this._position);
  20099. this._fill(size);
  20100. this.skip(-size);
  20101. position = this._fill(0);
  20102. index = this._buffer.indexOf(0x0A, position);
  20103. if (index === -1) {
  20104. throw new python.Error('Could not find end of line.');
  20105. }
  20106. }
  20107. const size = index - position;
  20108. const text = this.string(size, 'ascii');
  20109. this.skip(1);
  20110. return text;
  20111. }
  20112. _fill(length) {
  20113. if (this._position + length > this._length) {
  20114. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  20115. }
  20116. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  20117. this._offset = this._position;
  20118. this._stream.seek(this._offset);
  20119. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  20120. this._buffer = this._stream.read(size);
  20121. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  20122. }
  20123. const position = this._position;
  20124. this._position += length;
  20125. return position - this._offset;
  20126. }
  20127. };
  20128. python.Error = class extends Error {
  20129. constructor(message) {
  20130. super(message);
  20131. this.name = 'Python Error';
  20132. }
  20133. };
  20134. export const Execution = python.Execution;