python.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Execution = class {
  4. constructor(sources) {
  5. /* eslint-disable consistent-this */
  6. const self = this;
  7. /* eslint-enable consistent-this */
  8. const execution = self;
  9. this._sources = sources || new Map();
  10. this._events = new Map();
  11. this._utf8Decoder = new TextDecoder('utf-8');
  12. this._unresolved = new Map();
  13. this._operators = new Map();
  14. const dict = class extends Map {
  15. constructor(items) {
  16. super();
  17. if (items) {
  18. if (items instanceof Map) {
  19. items = Array.from(items);
  20. } else if (!Array.isArray(items)) {
  21. items = Object.entries(items);
  22. }
  23. for (const [name, value] of items) {
  24. this.__setitem__(name, value);
  25. }
  26. }
  27. }
  28. __contains__(key) {
  29. return this.has(key);
  30. }
  31. __setitem__(key, value) {
  32. this.set(key, value);
  33. }
  34. __getitem__(key) {
  35. return this.get(key);
  36. }
  37. __delitem__(key) {
  38. this.delete(key);
  39. }
  40. get(key, defaultValue) {
  41. return super.has(key) ? super.get(key) : defaultValue;
  42. }
  43. setdefault(key, defaultValue) {
  44. if (this.has(key)) {
  45. return this.get(key);
  46. }
  47. const value = defaultValue || null;
  48. this.set(key, value);
  49. return value;
  50. }
  51. pop(key) {
  52. if (this.__contains__(key)) {
  53. const v = this.__getitem__(key);
  54. this.__delitem__(key);
  55. return v;
  56. }
  57. return null;
  58. }
  59. items() {
  60. return Array.from(this);
  61. }
  62. update(other) {
  63. for (const [key, value] of other) {
  64. this.set(key, value);
  65. }
  66. }
  67. };
  68. this._modules = new dict();
  69. this._registry = new Map();
  70. const module = class {
  71. constructor(name) {
  72. this.__name__ = name;
  73. }
  74. };
  75. const builtins = this.register('builtins', new module('builtins'));
  76. this.builtins = builtins;
  77. this._registry.set('__builtin__', builtins);
  78. this.registerType('builtins.type', class {
  79. constructor(...args) {
  80. if (args.length === 1) {
  81. const [obj] = args;
  82. if (obj === null) {
  83. /* eslint-disable no-constructor-return */
  84. return builtins.NoneType;
  85. /* eslint-enable no-constructor-return */
  86. }
  87. if (obj && obj.__class__) {
  88. /* eslint-disable no-constructor-return */
  89. return obj.__class__;
  90. /* eslint-enable no-constructor-return */
  91. }
  92. throw new python.Error(`Unknown type '${obj}'`);
  93. }
  94. if (args.length === 3) {
  95. const [name, bases, body] = args;
  96. const cls = bases.length > 0 ? class extends bases[0] {} : class {};
  97. execution.registerType(name, cls);
  98. for (const [key, value] of body) {
  99. cls[key] = value;
  100. }
  101. /* eslint-disable no-constructor-return */
  102. return cls;
  103. /* eslint-enable no-constructor-return */
  104. }
  105. throw new python.Error(`Invalid 'builtins.dict' argument count.`);
  106. }
  107. }).__class__ = builtins.type;
  108. this.registerType('builtins.module', module);
  109. this.registerType('builtins.method', class {});
  110. this.registerType('builtins.function', class {
  111. constructor(code, globals, name) {
  112. this.__code__ = code;
  113. this.__globals__ = globals;
  114. this.__name__ = name;
  115. }
  116. });
  117. this.registerType('builtins.classmethod', class {});
  118. this.registerType('builtins.code', class {});
  119. this.import('builtins');
  120. this.registerType('builtins.builtin_function_or_method', class {});
  121. const typing = this.register('typing');
  122. this.typing = typing;
  123. const operator = this.register('operator');
  124. this.register('_codecs');
  125. this.register('argparse');
  126. this.enum = this.register('enum');
  127. const collections = this.register('collections');
  128. const copy = this.register('copy');
  129. this.register('copy_reg');
  130. const ast = this.register('ast');
  131. this.ast = ast;
  132. this.register('cuml');
  133. const cloudpickle = this.register('cloudpickle');
  134. const datetime = this.register('datetime');
  135. this.register('gensim');
  136. const io = this.register('io');
  137. const joblib = this.register('joblib');
  138. const jax = this.register('jax');
  139. this.register('jax.numpy');
  140. this.register('jax._src.array');
  141. this.register('jax._src.device_array');
  142. const functools = this.register('functools');
  143. this.registerType('functools.partial', class {});
  144. const keras = this.register('keras');
  145. const catboost = this.register('catboost');
  146. this.register('lightgbm');
  147. this.register('nolearn');
  148. const fastcore = this.register('fastcore');
  149. const fastai = this.register('fastai');
  150. const math = this.register('math');
  151. math.inf = Infinity;
  152. const numpy = this.register('numpy');
  153. this.register('numpy.core.multiarray');
  154. this.register('numpy.core._multiarray_umath');
  155. this.register('numpy.matrixlib.defmatrix');
  156. const pandas = this.register('pandas');
  157. this.register('pandas.indexes.base');
  158. this.register('pandas.indexes.range');
  159. this.register('pandas._libs.tslib');
  160. this.register('pandas._libs.internals');
  161. const pickle = this.register('pickle');
  162. const shap = this.register('shap');
  163. this.register('shap.explainers.linear');
  164. const sklearn = this.register('sklearn');
  165. this.register('sklearn.externals.joblib.numpy_pickle');
  166. const torch = this.register('torch');
  167. this.torch = torch;
  168. const torchvision = this.register('torchvision');
  169. const torchao = this.register('torchao');
  170. const sympy = this.register('sympy');
  171. this.register('torch.storage');
  172. this.register('torch.nn.parameter');
  173. this.register('torch.ops');
  174. this.register('torch._ops');
  175. this.register('torch.ops.torchvision');
  176. this.register('torch.ops.torchaudio');
  177. this.register('torch.ops._caffe2');
  178. this.register('torchvision');
  179. this.register('__torch__');
  180. const sys = this.register('sys');
  181. sys.modules = this._modules;
  182. this.register('xgboost');
  183. this.registerType('ast.AST', class {});
  184. this.registerType('ast.mod', class extends ast.AST {});
  185. this.registerType('ast.expr', class extends ast.AST {});
  186. this.registerType('ast.unaryop', class extends ast.AST {});
  187. this.registerType('ast.binop', class extends ast.AST {});
  188. this.registerType('ast.operator', class extends ast.AST {});
  189. this.registerType('ast.boolop', class extends ast.AST {});
  190. this.registerType('ast.cmpop', class extends ast.AST {});
  191. this.registerType('ast.stmt', class extends ast.AST {});
  192. this.registerType('ast.excepthandler', class extends ast.AST {});
  193. this.registerType('ast.keyword', class extends ast.AST {
  194. constructor(arg, value) {
  195. super();
  196. this.arg = arg;
  197. this.value = value;
  198. }
  199. });
  200. this.registerType('ast.alias', class extends ast.AST {
  201. constructor(name, asname) {
  202. super();
  203. this.name = name;
  204. this.asname = asname;
  205. }
  206. });
  207. this.registerType('ast.Name', class extends ast.expr {
  208. constructor(id, ctx) {
  209. super();
  210. this.id = id;
  211. if (ctx) {
  212. this.ctx = ctx;
  213. }
  214. }
  215. });
  216. this.registerType('ast.Constant', class extends ast.expr {
  217. constructor(value, type) {
  218. super();
  219. this.value = value;
  220. this.type = type || null;
  221. }
  222. });
  223. this.registerType('ast.Ellipsis', class extends ast.Constant {
  224. constructor() {
  225. super(builtins.ellipsis);
  226. }
  227. });
  228. this.registerType('ast.Starred', class extends ast.expr {
  229. constructor(value, ctx) {
  230. super();
  231. this.value = value;
  232. if (ctx) {
  233. this.ctx = ctx;
  234. }
  235. }
  236. });
  237. this.registerType('ast.List', class extends ast.expr {
  238. constructor(elts, ctx) {
  239. super();
  240. this.elts = elts;
  241. if (ctx) {
  242. this.ctx = ctx;
  243. }
  244. }
  245. });
  246. this.registerType('ast.Set', class extends ast.expr {
  247. constructor(elts) {
  248. super();
  249. this.elts = elts;
  250. }
  251. });
  252. this.registerType('ast.Tuple', class extends ast.expr {
  253. constructor(elts, ctx) {
  254. super();
  255. this.elts = elts;
  256. if (ctx) {
  257. this.ctx = ctx;
  258. }
  259. }
  260. });
  261. this.registerType('ast.Dict', class extends ast.expr {
  262. constructor(keys, values) {
  263. super();
  264. this.keys = keys;
  265. this.values = values;
  266. }
  267. });
  268. this.registerType('ast.ListComp', class extends ast.expr {
  269. constructor(elt, generators) {
  270. super();
  271. this.elt = elt;
  272. this.generators = generators;
  273. }
  274. });
  275. this.registerType('ast.SetComp', class extends ast.expr {
  276. constructor(elt, generators) {
  277. super();
  278. this.elt = elt;
  279. this.generators = generators;
  280. }
  281. });
  282. this.registerType('ast.GeneratorExp', class extends ast.expr {
  283. constructor(elt, generators) {
  284. super();
  285. this.elt = elt;
  286. this.generators = generators;
  287. }
  288. });
  289. this.registerType('ast.DictComp', class extends ast.expr {
  290. constructor(key, value, generators) {
  291. super();
  292. this.key = key;
  293. this.value = value;
  294. this.generators = generators;
  295. }
  296. });
  297. this.registerType('ast.comprehension', class extends ast.AST {
  298. constructor(target, iter, ifs, is_async) {
  299. super();
  300. this.target = target;
  301. this.iter = iter;
  302. this.ifs = ifs;
  303. this.is_async = is_async;
  304. }
  305. });
  306. this.registerType('ast.Subscript', class extends ast.expr {
  307. constructor(value, slice, ctx) {
  308. super();
  309. this.value = value;
  310. this.slice = slice;
  311. if (ctx) {
  312. this.ctx = ctx;
  313. }
  314. }
  315. });
  316. this.registerType('ast.Slice', class extends ast.expr {
  317. constructor(lower, upper, step) {
  318. super();
  319. this.lower = lower;
  320. this.upper = upper;
  321. this.step = step;
  322. }
  323. });
  324. this.registerType('ast.UnaryOp', class extends ast.expr {
  325. constructor(op, operand) {
  326. super();
  327. this.op = op;
  328. this.operand = operand;
  329. }
  330. });
  331. this.registerType('ast.UAdd', class extends ast.unaryop {});
  332. this.registerType('ast.USub', class extends ast.unaryop {});
  333. this.registerType('ast.Not', class extends ast.unaryop {});
  334. this.registerType('ast.Invert', class extends ast.unaryop {});
  335. this.registerType('ast.BinOp', class extends ast.expr {
  336. constructor(left, op, right) {
  337. super();
  338. this.left = left;
  339. this.op = op;
  340. this.right = right;
  341. }
  342. });
  343. this.registerType('ast.Add', class extends ast.operator {});
  344. this.registerType('ast.Sub', class extends ast.operator {});
  345. this.registerType('ast.Mult', class extends ast.operator {});
  346. this.registerType('ast.Div', class extends ast.operator {});
  347. this.registerType('ast.FloorDiv', class extends ast.operator {});
  348. this.registerType('ast.Mod', class extends ast.operator {});
  349. this.registerType('ast.Pow', class extends ast.operator {});
  350. this.registerType('ast.LShift', class extends ast.operator {});
  351. this.registerType('ast.RShift', class extends ast.operator {});
  352. this.registerType('ast.BitOr', class extends ast.operator {});
  353. this.registerType('ast.BitXor', class extends ast.operator {});
  354. this.registerType('ast.BitAnd', class extends ast.operator {});
  355. this.registerType('ast.MatMult', class extends ast.operator {});
  356. this.registerType('ast.BoolOp', class extends ast.expr {
  357. constructor(op, values) {
  358. super();
  359. this.op = op;
  360. this.values = values;
  361. }
  362. });
  363. this.registerType('ast.And', class extends ast.boolop {});
  364. this.registerType('ast.Or', class extends ast.boolop {});
  365. this.registerType('ast.Compare', class extends ast.expr {
  366. constructor(left, ops, comparators) {
  367. super();
  368. this.left = left;
  369. this.ops = ops;
  370. this.comparators = comparators;
  371. }
  372. });
  373. this.registerType('ast.Eq', class extends ast.cmpop {});
  374. this.registerType('ast.NotEq', class extends ast.cmpop {});
  375. this.registerType('ast.Lt', class extends ast.cmpop {});
  376. this.registerType('ast.LtE', class extends ast.cmpop {});
  377. this.registerType('ast.Gt', class extends ast.cmpop {});
  378. this.registerType('ast.GtE', class extends ast.cmpop {});
  379. this.registerType('ast.Is', class extends ast.cmpop {});
  380. this.registerType('ast.IsNot', class extends ast.cmpop {});
  381. this.registerType('ast.In', class extends ast.cmpop {});
  382. this.registerType('ast.NotIn', class extends ast.cmpop {});
  383. this.registerType('ast.Call', class extends ast.expr {
  384. constructor(func, args, keywords) {
  385. super();
  386. this.func = func;
  387. this.args = args;
  388. this.keywords = keywords || [];
  389. }
  390. });
  391. this.registerType('ast.Attribute', class extends ast.expr {
  392. constructor(value, attr, ctx) {
  393. super();
  394. this.value = value;
  395. this.attr = attr;
  396. if (ctx) {
  397. this.ctx = ctx;
  398. }
  399. }
  400. });
  401. this.registerType('ast.Lambda', class extends ast.expr {
  402. constructor(args, body) {
  403. super();
  404. this.args = args;
  405. this.body = body;
  406. }
  407. });
  408. this.registerType('ast.IfExp', class extends ast.expr {
  409. constructor(test, body, orelse) {
  410. super();
  411. this.test = test;
  412. this.body = body;
  413. this.orelse = orelse;
  414. }
  415. });
  416. this.registerType('ast.NamedExpr', class extends ast.expr {
  417. constructor(target, value) {
  418. super();
  419. this.target = target;
  420. this.value = value;
  421. }
  422. });
  423. this.registerType('ast.Yield', class extends ast.expr {
  424. constructor(value) {
  425. super();
  426. this.value = value;
  427. }
  428. });
  429. this.registerType('ast.YieldFrom', class extends ast.expr {
  430. constructor(value) {
  431. super();
  432. this.value = value;
  433. }
  434. });
  435. this.registerType('ast.Expr', class extends ast.stmt {
  436. constructor(value) {
  437. super();
  438. this.value = value;
  439. }
  440. });
  441. this.registerType('ast.Assign', class extends ast.stmt {
  442. constructor(targets, value, ctx) {
  443. super();
  444. this.targets = targets;
  445. this.value = value;
  446. if (ctx) {
  447. this.ctx = ctx;
  448. }
  449. }
  450. });
  451. this.registerType('ast.AnnAssign', class extends ast.stmt {
  452. constructor(target, annotation, value, simple) {
  453. super();
  454. this.target = target;
  455. this.annotation = annotation;
  456. this.value = value;
  457. this.simple = simple;
  458. }
  459. });
  460. this.registerType('ast.AugAssign', class extends ast.stmt {
  461. constructor(target, op, value) {
  462. super();
  463. this.target = target;
  464. this.op = op;
  465. this.value = value;
  466. }
  467. });
  468. this.registerType('ast.If', class extends ast.stmt {
  469. constructor(test, body, orelse) {
  470. super();
  471. this.test = test;
  472. this.body = body;
  473. this.orelse = orelse;
  474. }
  475. });
  476. this.registerType('ast.For', class extends ast.stmt {
  477. constructor(target, iter, body, orelse /*, type_comment */) {
  478. super();
  479. this.target = target;
  480. this.iter = iter;
  481. this.body = body;
  482. this.orelse = orelse;
  483. }
  484. });
  485. this.registerType('ast.While', class extends ast.stmt {
  486. constructor(test, body, orelse /*, type_comment */) {
  487. super();
  488. this.test = test;
  489. this.body = body;
  490. this.orelse = orelse;
  491. }
  492. });
  493. this.registerType('ast.Del', class extends ast.stmt {
  494. constructor(targets) {
  495. super();
  496. this.targets = targets;
  497. }
  498. });
  499. this.registerType('ast.Return', class extends ast.stmt {
  500. constructor(value) {
  501. super();
  502. this.value = value;
  503. }
  504. });
  505. this.registerType('ast.Try', class extends ast.stmt {
  506. constructor(body, handlers, orelse, finalbody) {
  507. super();
  508. this.body = body;
  509. this.handlers = handlers;
  510. this.orelse = orelse;
  511. this.finalbody = finalbody;
  512. }
  513. });
  514. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  515. constructor(type, name, body) {
  516. super();
  517. this.type_ = type;
  518. this.name = name;
  519. this.body = body;
  520. }
  521. });
  522. this.registerType('ast.ClassDef', class extends ast.stmt {
  523. constructor(name, bases, keywords, body, decorator_list, type_params) {
  524. super();
  525. this.name = name;
  526. this.bases = bases;
  527. this.keywords = keywords;
  528. this.body = body;
  529. this.decorator_list = decorator_list;
  530. this.type_params = type_params;
  531. }
  532. });
  533. this.registerType('ast.FunctionDef', class extends ast.stmt {
  534. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  535. super();
  536. this.name = name;
  537. this.args = args;
  538. this.body = body;
  539. this.decorator_list = decorator_list;
  540. this.returns = returns;
  541. this.type_comment = type_comment;
  542. this.type_params = type_params;
  543. }
  544. });
  545. this.registerType('ast.arguments', class extends ast.AST {
  546. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  547. super();
  548. this.posonlyargs = posonlyargs;
  549. this.args = args;
  550. this.vararg = vararg;
  551. this.kwonlyargs = kwonlyargs;
  552. this.kw_defaults = kw_defaults;
  553. this.kwarg = kwarg;
  554. this.defaults = defaults;
  555. }
  556. });
  557. this.registerType('ast.arg', class extends ast.AST {
  558. constructor(arg, annotation, type_comment) {
  559. super();
  560. this.arg = arg;
  561. this.annotation = annotation;
  562. this.type_comment = type_comment;
  563. }
  564. });
  565. this.registerType('ast.Import', class extends ast.stmt {
  566. constructor(names) {
  567. super();
  568. this.names = names;
  569. }
  570. });
  571. this.registerType('ast.ImportFrom', class extends ast.stmt {
  572. constructor(module, names, level) {
  573. super();
  574. this.module = module;
  575. this.names = names;
  576. this.level = level;
  577. }
  578. });
  579. this.registerType('ast.Assert', class extends ast.stmt {
  580. constructor(test, msg) {
  581. super();
  582. this.test = test;
  583. this.msg = msg;
  584. }
  585. });
  586. this.registerType('ast.Raise', class extends ast.stmt {
  587. constructor(exc, cause) {
  588. super();
  589. this.exc = exc;
  590. this.cause = cause;
  591. }
  592. });
  593. this.registerType('ast.With', class extends ast.stmt {
  594. constructor(items, body, type_comment) {
  595. super();
  596. this.items = items;
  597. this.body = body;
  598. this.type_comment = type_comment;
  599. }
  600. });
  601. this.registerType('ast.withitem', class extends ast.AST {
  602. constructor(context_expr, optional_vars) {
  603. super();
  604. this.context_expr = context_expr;
  605. this.optional_vars = optional_vars;
  606. }
  607. });
  608. this.registerType('ast.Global', class extends ast.stmt {
  609. constructor(names) {
  610. super();
  611. this.names = names;
  612. }
  613. });
  614. this.registerType('ast.Nonlocal', class extends ast.stmt {
  615. constructor(names) {
  616. super();
  617. this.names = names;
  618. }
  619. });
  620. this.registerType('ast.Continue', class extends ast.stmt {});
  621. this.registerType('ast.Break', class extends ast.stmt {});
  622. this.registerType('ast.Pass', class extends ast.stmt {});
  623. this.registerType('ast.Await', class extends ast.stmt {
  624. constructor(value) {
  625. super();
  626. this.value = value;
  627. }
  628. });
  629. this.registerType('ast.Module', class extends ast.mod {
  630. constructor(body, type_ignores) {
  631. super();
  632. this.body = body;
  633. this.type_ignores = type_ignores;
  634. }
  635. });
  636. this.registerFunction('ast.parse', (source, filename, mode, debug) => {
  637. const parser = new ast._Parser();
  638. const module = parser.parse(source, filename, debug, mode);
  639. return module;
  640. });
  641. this.registerFunction('ast._convert_literal', (node) => {
  642. if (node instanceof ast.Constant) {
  643. return node.value;
  644. }
  645. if (node instanceof ast.Dict && node.keys.length === node.values.length) {
  646. const keys = node.keys.map((k) => ast._convert_literal(k));
  647. const values = node.values.map((v) => ast._convert_literal(v));
  648. return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  649. }
  650. if (node instanceof ast.Tuple) {
  651. return new builtins.tuple(node.elts.map((e) => ast._convert_literal(e)));
  652. }
  653. if (node instanceof ast.List) {
  654. return new builtins.list(node.elts.map((e) => ast._convert_literal(e)));
  655. }
  656. throw new python.Error(`'${node.__class__.__name__}' not implemented.`);
  657. });
  658. this.registerFunction('ast.literal_eval', (node_or_string) => {
  659. if (typeof node_or_string === 'string') {
  660. node_or_string = ast.parse(node_or_string, '', 'eval').body;
  661. } else {
  662. throw new python.Error(`'ast.literal_eval' node eval not implemented.`);
  663. }
  664. return ast._convert_literal(node_or_string);
  665. });
  666. this.registerType('ast._Parser', class {
  667. constructor() {
  668. ast._Parser._precedence = ast._Parser._precedence || {
  669. 'or': 2, 'and': 3, 'not' : 4,
  670. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  671. '|': 6, '^' : 7, '&' : 8,
  672. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  673. // '+': 12, '-': 12,
  674. '~': 13, '**': 14
  675. };
  676. }
  677. parse(text, file, debug, mode) {
  678. this._tokenizer = new ast._Tokenizer(text, file);
  679. this._debug = debug;
  680. const position = this._position();
  681. let body = [];
  682. while (!this._tokenizer.match('eof')) {
  683. const statement = this._parseStatement();
  684. if (statement) {
  685. body.push(statement);
  686. continue;
  687. }
  688. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type === 'eof') {
  689. continue;
  690. }
  691. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type === 'eof') {
  692. continue;
  693. }
  694. throw new python.Error(`Unsupported statement ${this._location()}`);
  695. }
  696. if (mode === 'eval') {
  697. if (body.length !== 1 || body[0] instanceof ast.Expr === false) {
  698. throw new python.Error('Expected expression.');
  699. }
  700. body = body[0].value;
  701. }
  702. const module = new ast.Module(body);
  703. this._mark(module, position);
  704. return module;
  705. }
  706. _parseSuite() {
  707. const body = [];
  708. let statement = null;
  709. if (this._tokenizer.eat('\n')) {
  710. if (this._tokenizer.eat('indent')) {
  711. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  712. if (this._tokenizer.eat(';')) {
  713. continue;
  714. }
  715. statement = this._parseStatement();
  716. if (statement) {
  717. body.push(statement);
  718. continue;
  719. }
  720. if (this._tokenizer.eat('\n')) {
  721. continue;
  722. }
  723. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  724. continue;
  725. }
  726. throw new python.Error(`Empty statement ${this._location()}`);
  727. }
  728. }
  729. } else if (!this._tokenizer.eat('eof')) {
  730. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  731. if (this._tokenizer.eat(';')) {
  732. continue;
  733. }
  734. statement = this._parseStatement();
  735. if (statement) {
  736. body.push(statement);
  737. continue;
  738. }
  739. throw new python.Error(`Empty statement ${this._location()}`);
  740. }
  741. this._tokenizer.eat('\n');
  742. }
  743. return body;
  744. }
  745. _parseStatement() {
  746. let node = null;
  747. let position = this._position();
  748. if (this._eat('id', 'break')) {
  749. const node = new ast.Break();
  750. return this._mark(node, position);
  751. }
  752. if (this._eat('id', 'continue')) {
  753. const node = new ast.Continue();
  754. return this._mark(node, position);
  755. }
  756. if (this._eat('id', 'return')) {
  757. const value = this._parseExpression(-1, [], true);
  758. const node = new ast.Return(value);
  759. return this._mark(node, position);
  760. }
  761. if (this._eat('id', 'raise')) {
  762. let exc = this._parseExpression(-1, ['from']);
  763. let cause = null;
  764. if (this._tokenizer.eat('id', 'from')) {
  765. cause = this._parseExpression();
  766. } else if (this._tokenizer.eat(',')) {
  767. exc = [exc];
  768. exc.push(this._parseExpression());
  769. if (this._tokenizer.eat(',')) {
  770. exc.push(this._parseExpression());
  771. }
  772. }
  773. node = new ast.Raise(exc, cause);
  774. return this._mark(node, position);
  775. }
  776. if (this._eat('id', 'assert')) {
  777. const test = this._parseExpression(-1, [',']);
  778. let msg = null;
  779. if (this._tokenizer.eat(',')) {
  780. msg = this._parseExpression();
  781. }
  782. node = new ast.Assert(test, msg);
  783. return this._mark(node, position);
  784. }
  785. if (this._eat('id', 'global')) {
  786. const names = [];
  787. do {
  788. const name = this._parseName(true);
  789. names.push(name.id);
  790. }
  791. while (this._tokenizer.eat(','));
  792. const node = new ast.Global(names);
  793. return this._mark(node, position);
  794. }
  795. if (this._eat('id', 'nonlocal')) {
  796. const names = [];
  797. do {
  798. const name = this._parseName(true);
  799. names.push(name.id);
  800. }
  801. while (this._tokenizer.eat(','));
  802. const node = new ast.Nonlocal(names);
  803. return this._mark(node, position);
  804. }
  805. if (this._eat('id', 'import')) {
  806. const names = [];
  807. do {
  808. const name = this._parseDottedName();
  809. let asname = null;
  810. if (this._tokenizer.eat('id', 'as')) {
  811. asname = this._parseName(true).id;
  812. }
  813. const node = new ast.alias(name, asname);
  814. names.push(node);
  815. }
  816. while (this._tokenizer.eat(','));
  817. const node = new ast.Import(names);
  818. return this._mark(node, position);
  819. }
  820. if (this._eat('id', 'from')) {
  821. let level = 0;
  822. const dots = this._tokenizer.peek();
  823. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  824. this._eat(dots.type);
  825. level = Array.from(dots.type).length;
  826. }
  827. const module = this._parseDottedName();
  828. this._tokenizer.expect('id', 'import');
  829. const names = [];
  830. const close = this._tokenizer.eat('(');
  831. do {
  832. const name = this._parseName(true).id;
  833. let asname = null;
  834. if (this._tokenizer.eat('id', 'as')) {
  835. asname = this._parseName(true).id;
  836. }
  837. const node = new ast.alias(name, asname);
  838. names.push(node);
  839. }
  840. while (this._tokenizer.eat(','));
  841. if (close) {
  842. this._tokenizer.expect(')');
  843. }
  844. const node = new ast.ImportFrom(module, names, level);
  845. return this._mark(node, position);
  846. }
  847. const decorator_list = this._decorator();
  848. position = this._position();
  849. if (this._eat('id', 'class')) {
  850. const name = this._parseName(true);
  851. const bases = [];
  852. if (this._tokenizer.eat('(')) {
  853. while (!this._tokenizer.eat(')')) {
  854. if (this._tokenizer.eat('\n')) {
  855. continue;
  856. }
  857. const expression = this._parseExpression(-1, [], false);
  858. if (expression === null) {
  859. throw new python.Error(`Expected expression ${this._location()}`);
  860. }
  861. bases.push(expression);
  862. if (!this._tokenizer.eat(',')) {
  863. this._tokenizer.eat('\n');
  864. this._tokenizer.expect(')');
  865. break;
  866. }
  867. }
  868. }
  869. this._tokenizer.expect(':');
  870. const body = this._parseSuite();
  871. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  872. return this._mark(node, position);
  873. }
  874. const async = this._eat('id', 'async') !== null;
  875. if (async &&
  876. !this._tokenizer.match('id', 'def') &&
  877. !this._tokenizer.match('id', 'with') &&
  878. !this._tokenizer.match('id', 'for')) {
  879. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  880. }
  881. if (this._eat('id', 'def')) {
  882. const name = this._parseName(true);
  883. this._tokenizer.expect('(');
  884. const args = this._parseArguments(')');
  885. let returns = null;
  886. if (this._tokenizer.eat('->')) {
  887. returns = this._parseType();
  888. }
  889. this._tokenizer.expect(':');
  890. const body = this._parseSuite();
  891. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  892. if (async) {
  893. node.async = async;
  894. }
  895. return this._mark(node, position);
  896. }
  897. if (decorator_list && decorator_list.length > 0) {
  898. throw new python.Error('Unexpected decorator.');
  899. }
  900. if (this._eat('id', 'del')) {
  901. const targets = this._parseExpression(-1, [], true);
  902. node = new ast.Del(targets);
  903. return this._mark(node, position);
  904. }
  905. if (this._eat('id', 'if')) {
  906. const test = this._parseExpression();
  907. this._tokenizer.expect(':');
  908. const body = this._parseSuite();
  909. const node = new ast.If(test, body);
  910. let current = node;
  911. this._tokenizer.eat('\n');
  912. while (this._tokenizer.eat('id', 'elif')) {
  913. const test = this._parseExpression();
  914. this._tokenizer.expect(':');
  915. const body = this._parseSuite();
  916. current.orelse = new ast.If(test, body);
  917. current = current.orelse;
  918. this._tokenizer.eat('\n');
  919. }
  920. if (this._tokenizer.eat('id', 'else')) {
  921. this._tokenizer.expect(':');
  922. current.orelse = this._parseSuite();
  923. }
  924. return this._mark(node, position);
  925. }
  926. if (this._eat('id', 'while')) {
  927. const test = this._parseExpression();
  928. this._tokenizer.expect(':');
  929. const body = this._parseSuite();
  930. let orelse = null;
  931. if (this._tokenizer.eat('id', 'else')) {
  932. this._tokenizer.expect(':');
  933. orelse = this._parseSuite();
  934. }
  935. const node = new ast.While(test, body, orelse);
  936. return this._mark(node, position);
  937. }
  938. if (this._eat('id', 'pass')) {
  939. const node = new ast.Pass();
  940. return this._mark(node, position);
  941. }
  942. if (this._eat('id', 'for')) {
  943. let target = this._parseExpression(-1, ['in']);
  944. while (this._tokenizer.eat(',')) {
  945. if (target instanceof ast.Tuple === false) {
  946. target = new ast.Tuple([target]);
  947. }
  948. if (this._tokenizer.match('id', 'in')) {
  949. target.elts.push({});
  950. break;
  951. }
  952. target.elts.push(this._parseExpression(-1, ['in']));
  953. }
  954. this._tokenizer.expect('id', 'in');
  955. let iter = this._parseExpression();
  956. while (this._tokenizer.eat(',')) {
  957. if (iter.type !== 'tuple') {
  958. iter = new ast.Tuple([iter]);
  959. }
  960. if (this._tokenizer.match(':')) {
  961. iter.elts.push({});
  962. break;
  963. }
  964. iter.elts.push(this._parseExpression(-1, ['in']));
  965. }
  966. this._tokenizer.expect(':');
  967. const body = this._parseSuite();
  968. let orelse = null;
  969. if (this._tokenizer.eat('id', 'else')) {
  970. this._tokenizer.expect(':');
  971. orelse = this._parseSuite();
  972. }
  973. const node = new ast.For(target, iter, body, orelse);
  974. return this._mark(node, position);
  975. }
  976. if (this._eat('id', 'with')) {
  977. const items = [];
  978. do {
  979. const context_expr = this._parseExpression();
  980. let optional_vars = null;
  981. if (this._tokenizer.eat('id', 'as')) {
  982. optional_vars = this._parseExpression();
  983. }
  984. const node = new ast.withitem(context_expr, optional_vars);
  985. items.push(node);
  986. }
  987. while (this._tokenizer.eat(','));
  988. this._tokenizer.expect(':');
  989. const body = this._parseSuite();
  990. const node = new ast.With(items, body, null);
  991. if (async) {
  992. node.async = async;
  993. }
  994. return this._mark(node, position);
  995. }
  996. if (this._eat('id', 'try')) {
  997. this._tokenizer.expect(':');
  998. const body = this._parseSuite();
  999. const handlers = [];
  1000. let orelse = null;
  1001. let finalbody = null;
  1002. while (this._tokenizer.match('id', 'except')) {
  1003. this._tokenizer.expect('id', 'except');
  1004. const type = this._parseExpression();
  1005. const name = this._tokenizer.eat('id', 'as') ? this._parseExpression() : null;
  1006. this._tokenizer.expect(':');
  1007. const body = this._parseSuite();
  1008. const except = new ast.ExceptHandler(type, name, body);
  1009. handlers.push(except);
  1010. }
  1011. if (this._tokenizer.match('id', 'else')) {
  1012. this._tokenizer.expect('id', 'else');
  1013. this._tokenizer.expect(':');
  1014. orelse = this._parseSuite();
  1015. }
  1016. if (this._tokenizer.match('id', 'finally')) {
  1017. this._tokenizer.expect('id', 'finally');
  1018. this._tokenizer.expect(':');
  1019. finalbody = this._parseSuite();
  1020. }
  1021. const node = new ast.Try(body, handlers, orelse, finalbody);
  1022. return this._mark(node, position);
  1023. }
  1024. const expr = this._parseExpression(-1, [], true);
  1025. if (expr) {
  1026. if (expr instanceof ast.Name && this._tokenizer.eat(':')) {
  1027. const position = this._position();
  1028. const annotation = this._parseExpression(-1, ['=']);
  1029. let value = null;
  1030. if (this._tokenizer.eat('=')) {
  1031. value = this._parseExpression();
  1032. }
  1033. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  1034. return this._mark(node, position);
  1035. }
  1036. if (expr instanceof ast.stmt) {
  1037. return expr;
  1038. }
  1039. switch (expr.__class__.__name__) {
  1040. case 'AnnAssign':
  1041. case 'Assert':
  1042. case 'Assign':
  1043. case 'Attribute':
  1044. case 'AugAssign':
  1045. case 'Await':
  1046. case 'BinOp':
  1047. case 'Call':
  1048. case 'Compare':
  1049. case 'Constant':
  1050. case 'Dict':
  1051. case 'Ellipsis':
  1052. case 'For':
  1053. case 'If':
  1054. case 'Lambda':
  1055. case 'List':
  1056. case 'Name':
  1057. case 'NamedExpr':
  1058. case 'Raise':
  1059. case 'Subscript':
  1060. case 'Tuple':
  1061. case 'Yield':
  1062. // return expr;
  1063. return new ast.Expr(expr);
  1064. default:
  1065. throw new python.Error(`Unhandled expression ${this._location()}`);
  1066. }
  1067. }
  1068. return null;
  1069. }
  1070. _parseExpression(minPrecedence, terminal, tuple) {
  1071. minPrecedence = minPrecedence || -1;
  1072. const terminalSet = new Set(terminal);
  1073. const stack = [];
  1074. for (;;) {
  1075. let position = this._position();
  1076. let node = null;
  1077. const token = this._tokenizer.peek();
  1078. if (stack.length === 1 && terminalSet.has(token.value)) {
  1079. break;
  1080. }
  1081. const precedence = ast._Parser._precedence[token.value];
  1082. if (precedence) {
  1083. if (precedence >= minPrecedence) {
  1084. this._tokenizer.read();
  1085. if (token.value === 'not' && this._tokenizer.eat('id', 'in')) {
  1086. token.value = 'not in';
  1087. } else if (token.value === 'is' && this._tokenizer.eat('id', 'not')) {
  1088. token.value = 'is not';
  1089. }
  1090. if (stack.length > 0) {
  1091. let op = null;
  1092. switch (token.value) {
  1093. case '+': op = new ast.Add(); break;
  1094. case '-': op = new ast.Sub(); break;
  1095. case '*': op = new ast.Mult(); break;
  1096. case '/': op = new ast.Div(); break;
  1097. case '//': op = new ast.FloorDiv(); break;
  1098. case '**': op = new ast.Pow(); break;
  1099. case '@': op = new ast.MatMult(); break;
  1100. case '&': op = new ast.BitAnd(); break;
  1101. case '^': op = new ast.BitXor(); break;
  1102. case '|': op = new ast.BitOr(); break;
  1103. case '%': op = new ast.Mod(); break;
  1104. case '>>': op = new ast.RShift(); break;
  1105. case '<<': op = new ast.LShift(); break;
  1106. default: break;
  1107. }
  1108. if (op) {
  1109. const left = stack.pop();
  1110. const right = this._parseExpression(precedence, terminal, tuple === true);
  1111. node = new ast.BinOp(left, op, right);
  1112. } else {
  1113. switch (token.value) {
  1114. case '==': op = new ast.Eq(); break;
  1115. case '!=': op = new ast.NotEq(); break;
  1116. case '>=': op = new ast.GtE(); break;
  1117. case '<=': op = new ast.LtE(); break;
  1118. case '<': op = new ast.Lt(); break;
  1119. case '>': op = new ast.Gt(); break;
  1120. case 'is': op = new ast.Is(); break;
  1121. case 'is not': op = new ast.IsNot(); break;
  1122. case 'in': op = new ast.In(); break;
  1123. case 'not in': op = new ast.NotIn(); break;
  1124. default: break;
  1125. }
  1126. const left = stack.pop();
  1127. const comparator = this._parseExpression(precedence, ['for', 'if'], tuple === true);
  1128. node = new ast.Compare(left, [op], [comparator]);
  1129. }
  1130. } else if (token.value === '*') {
  1131. const value = this._parseExpression(precedence, terminal, tuple === true);
  1132. node = new ast.Starred(value);
  1133. } else if (token.value === '**') {
  1134. const value = this._parseExpression(precedence, terminal, tuple === true);
  1135. node = new ast.keyword(null, value);
  1136. } else {
  1137. let op = null;
  1138. switch (token.value) {
  1139. case '-': op = new ast.USub(); break;
  1140. case '+': op = new ast.UAdd(); break;
  1141. case '~': op = new ast.Invert(); break;
  1142. case 'not': op = new ast.Not(); break;
  1143. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1144. }
  1145. const operand = this._parseExpression(precedence, terminal, tuple === true);
  1146. node = new ast.UnaryOp(op, operand);
  1147. node = this._mark(node, position);
  1148. }
  1149. stack.push(node);
  1150. continue;
  1151. }
  1152. }
  1153. if (this._tokenizer.eat(':=')) {
  1154. const target = stack.pop();
  1155. const value = this._parseExpression(-1, terminal, tuple !== false);
  1156. const node = new ast.NamedExpr(target, value);
  1157. this._mark(node, position);
  1158. stack.push(node);
  1159. continue;
  1160. }
  1161. if (this._tokenizer.eat('=')) {
  1162. const position = this._position();
  1163. const targets = stack.pop();
  1164. const value = this._parseExpression(-1, terminal, tuple !== false);
  1165. const node = new ast.Assign([targets], value);
  1166. this._mark(node, position);
  1167. stack.push(node);
  1168. continue;
  1169. }
  1170. let op = null;
  1171. switch (token.type) {
  1172. case '+=': op = new ast.Add(); break;
  1173. case '-=': op = new ast.Sub(); break;
  1174. case '**=': op = new ast.Pow(); break;
  1175. case '*=': op = new ast.Mult(); break;
  1176. case '//=': op = new ast.FloorDiv(); break;
  1177. case '/=': op = new ast.Div(); break;
  1178. case '&=': op = new ast.BitAnd(); break;
  1179. case '%=': op = new ast.Mod(); break;
  1180. case '^=': op = new ast.BitXor(); break;
  1181. case '<<=': op = new ast.LShift(); break;
  1182. case '>>=': op = new ast.RShift(); break;
  1183. case '|=': op = new ast.BitOr(); break;
  1184. case '@=': op = new ast.MatMul(); break;
  1185. default: break;
  1186. }
  1187. if (op) {
  1188. this._tokenizer.expect(token.type);
  1189. const target = stack.pop();
  1190. const value = this._parseExpression(-1, terminal, true);
  1191. const node = new ast.AugAssign(target, op, value);
  1192. stack.push(node);
  1193. continue;
  1194. }
  1195. position = this._position();
  1196. if (this._eat('id', 'if')) {
  1197. const body = stack.pop();
  1198. const test = this._parseExpression();
  1199. this._tokenizer.expect('id', 'else');
  1200. const orelse = this._parseExpression();
  1201. const node = new ast.IfExp(test, body, orelse);
  1202. this._mark(node, position);
  1203. stack.push(node);
  1204. continue;
  1205. }
  1206. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1207. const position = this._position();
  1208. const elt = stack.pop();
  1209. const generators = this._parseGenerators();
  1210. let node = null;
  1211. if (elt instanceof ast.Dict) {
  1212. if (elt.keys.length !== 1 || elt.values.length !== 1) {
  1213. throw new python.Error(`Invalid dict comprehension ${this._location()}`);
  1214. }
  1215. node = new ast.DictComp(elt.keys[0], elt.values[0], generators);
  1216. } else if (elt instanceof ast.Set) {
  1217. if (elt.elts.length !== 1) {
  1218. throw new python.Error(`Invalid set comprehension ${this._location()}`);
  1219. }
  1220. node = new ast.SetComp(elt.elts[0], generators);
  1221. } else {
  1222. node = new ast.GeneratorExp(elt, generators);
  1223. }
  1224. this._mark(node, position);
  1225. stack.push(node);
  1226. continue;
  1227. }
  1228. if (this._eat('id', 'lambda')) {
  1229. const args = this._parseArguments(':');
  1230. const body = this._parseExpression(-1, terminal, false);
  1231. const node = new ast.Lambda(args, body);
  1232. this._mark(node, position);
  1233. stack.push(node);
  1234. continue;
  1235. }
  1236. if (this._eat('id', 'yield')) {
  1237. if (this._tokenizer.eat('id', 'from')) {
  1238. const value = this._parseExpression(-1, [], true);
  1239. node = new ast.YieldFrom(value);
  1240. stack.push(node);
  1241. } else {
  1242. const value = [];
  1243. do {
  1244. value.push(this._parseExpression(-1, [], false));
  1245. }
  1246. while (this._tokenizer.eat(','));
  1247. node = new ast.Yield(value);
  1248. stack.push(node);
  1249. }
  1250. continue;
  1251. }
  1252. if (this._eat('id', 'await')) {
  1253. const value = this._parseExpression(minPrecedence, terminal, tuple);
  1254. const node = new ast.Await(value);
  1255. this._mark(node, position);
  1256. stack.push(node);
  1257. continue;
  1258. }
  1259. if (this._eat('.')) {
  1260. const value = stack.pop();
  1261. const attr = this._parseName().id;
  1262. const node = new ast.Attribute(value, attr);
  1263. this._mark(node, position);
  1264. stack.push(node);
  1265. continue;
  1266. }
  1267. if (this._tokenizer.peek().type === '(') {
  1268. const position = this._position();
  1269. const args = [];
  1270. const keywords = [];
  1271. this._tokenizer.expect('(');
  1272. let tuple = false;
  1273. while (!this._tokenizer.eat(')')) {
  1274. if (this._tokenizer.eat('\n')) {
  1275. continue;
  1276. }
  1277. const position = this._position();
  1278. const expr = this._parseExpression(-1, [], false);
  1279. if (expr === null) {
  1280. throw new python.Error(`Expected expression ${this._location()}`);
  1281. }
  1282. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1283. const [target] = expr.targets;
  1284. if (target instanceof ast.Name === false) {
  1285. throw new python.Error(`Expected name ${this._location()}`);
  1286. }
  1287. const node = new ast.keyword(target.id, expr.value);
  1288. this._mark(node, position);
  1289. keywords.push(node);
  1290. } else {
  1291. args.push(expr);
  1292. }
  1293. if (this._tokenizer.eat(',')) {
  1294. tuple = true;
  1295. } else {
  1296. this._tokenizer.eat('\n');
  1297. this._tokenizer.expect(')');
  1298. break;
  1299. }
  1300. }
  1301. if (stack.length === 0 && keywords.length === 0) {
  1302. node = args.length === 1 && !tuple ? args[0] : new ast.Tuple(args);
  1303. this._mark(node, position);
  1304. } else {
  1305. const func = stack.pop();
  1306. node = new ast.Call(func, args, keywords);
  1307. let start = func;
  1308. while (start instanceof ast.Attribute) {
  1309. start = start.value;
  1310. }
  1311. position.lineno = start.lineno;
  1312. position.col_offset = start.col_offset;
  1313. this._mark(node, position);
  1314. }
  1315. stack.push(node);
  1316. continue;
  1317. }
  1318. if (this._tokenizer.peek().type === '[') {
  1319. if (stack.length === 0) {
  1320. stack.push(this._parseList());
  1321. } else {
  1322. const value = stack.pop();
  1323. const position = this._position();
  1324. const slice = this._parseSlice();
  1325. node = new ast.Subscript(value, slice);
  1326. this._mark(node, position);
  1327. stack.push(node);
  1328. }
  1329. continue;
  1330. }
  1331. if (this._tokenizer.peek().type === '{') {
  1332. const elts = [];
  1333. const keys = [];
  1334. const values = [];
  1335. this._tokenizer.expect('{');
  1336. let dict = true;
  1337. while (!this._tokenizer.eat('}')) {
  1338. const item = this._parseExpression(-1, [], false);
  1339. if (item === null) {
  1340. throw new python.Error(`Expected expression ${this._location()}`);
  1341. }
  1342. if (!this._tokenizer.eat(':')) {
  1343. dict = false;
  1344. }
  1345. if (dict) {
  1346. const value = this._parseExpression(-1, ['for'], false);
  1347. if (value === null) {
  1348. throw new python.Error(`Expected expression ${this._location()}`);
  1349. }
  1350. if (this._eat('id', 'for')) {
  1351. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1352. throw new python.Error(`Invalid list expression ${this._location()}`);
  1353. }
  1354. const target = this._parseExpression(-1, ['in'], true);
  1355. this._tokenizer.expect('id', 'in');
  1356. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1357. const ifs = [];
  1358. while (this._tokenizer.eat('id', 'if')) {
  1359. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1360. }
  1361. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1362. const generators = [comprehension];
  1363. this._tokenizer.expect('}');
  1364. return new ast.DictComp(item, value, generators);
  1365. }
  1366. keys.push(item);
  1367. values.push(value);
  1368. } else {
  1369. elts.push(item);
  1370. }
  1371. this._tokenizer.eat(',');
  1372. this._tokenizer.eat('\n');
  1373. if (this._tokenizer.eat('}')) {
  1374. break;
  1375. }
  1376. }
  1377. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1378. throw new python.Error(`Invalid set expression ${this._location()}`);
  1379. }
  1380. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1381. stack.push(node);
  1382. continue;
  1383. }
  1384. const literal = this._parseLiteral();
  1385. if (literal) {
  1386. if (stack.length > 0 &&
  1387. (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') &&
  1388. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  1389. const op = literal.value < 0 ? new ast.Sub() : new ast.Add();
  1390. const left = stack.pop();
  1391. const right = new ast.Constant(Math.abs(literal.value));
  1392. node = new ast.BinOp(left, op, right);
  1393. stack.push(node);
  1394. } else if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1395. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1396. } else {
  1397. let value = literal.value;
  1398. if (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') {
  1399. switch (value) {
  1400. case 'inf': value = Infinity; break;
  1401. case '-inf': value = -Infinity; break;
  1402. default: value = Number(value); break;
  1403. }
  1404. } else if (literal.type === 'str') {
  1405. value = literal.value.substring(1, literal.value.length - 1);
  1406. } else {
  1407. throw new python.Error(`Invalid literal ${this._location()}`);
  1408. }
  1409. const node = new ast.Constant(value, literal.type);
  1410. this._mark(node, position);
  1411. stack.push(node);
  1412. }
  1413. continue;
  1414. }
  1415. if (this._eat('id', 'False')) {
  1416. const node = new ast.Constant(false, 'bool');
  1417. this._mark(node, position);
  1418. stack.push(node);
  1419. continue;
  1420. }
  1421. if (this._eat('id', 'True')) {
  1422. const node = new ast.Constant(true, 'bool');
  1423. this._mark(node, position);
  1424. stack.push(node);
  1425. continue;
  1426. }
  1427. if (this._eat('id', 'None')) {
  1428. const node = new ast.Constant(null);
  1429. this._mark(node, position);
  1430. stack.push(node);
  1431. continue;
  1432. }
  1433. if (this._tokenizer.peek().keyword) {
  1434. break;
  1435. }
  1436. if (this._eat('...')) {
  1437. const node = new ast.Ellipsis();
  1438. this._mark(node, position);
  1439. stack.push(node);
  1440. continue;
  1441. }
  1442. const name = this._parseName();
  1443. if (name) {
  1444. stack.push(name);
  1445. continue;
  1446. }
  1447. if (tuple === true && stack.length === 1 && this._tokenizer.eat(',')) {
  1448. if (stack[0] instanceof ast.Tuple) {
  1449. [node] = stack;
  1450. } else {
  1451. const position = this._position();
  1452. const elts = [stack.pop()];
  1453. node = new ast.Tuple(elts);
  1454. this._mark(node, position);
  1455. stack.push(node);
  1456. }
  1457. // for, bar, = <expr>
  1458. if (this._tokenizer.peek().type === '=') {
  1459. continue;
  1460. }
  1461. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1462. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1463. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1464. if (expression) {
  1465. node.elts.push(expression);
  1466. continue;
  1467. }
  1468. }
  1469. break;
  1470. }
  1471. break;
  1472. }
  1473. if (stack.length === 1) {
  1474. return stack.pop();
  1475. }
  1476. if (stack.length !== 0) {
  1477. throw new python.Error(`Unexpected expression ${this._location()}`);
  1478. }
  1479. return null;
  1480. }
  1481. _decorator() {
  1482. const list = [];
  1483. while (this._tokenizer.eat('@')) {
  1484. const value = this._parseExpression();
  1485. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1486. throw new python.Error(`Invalid decorator ${this._location()}`);
  1487. }
  1488. this._tokenizer.eat('\n');
  1489. list.push(value);
  1490. }
  1491. return list;
  1492. }
  1493. _parseGenerators() {
  1494. const generators = [];
  1495. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1496. const is_async = this._eat('id', 'async') ? 1 : 0;
  1497. this._tokenizer.expect('id', 'for');
  1498. const target = this._parseExpression(-1, ['in'], true);
  1499. this._tokenizer.expect('id', 'in');
  1500. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1501. const ifs = [];
  1502. while (this._tokenizer.eat('id', 'if')) {
  1503. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1504. }
  1505. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1506. generators.push(comprehension);
  1507. }
  1508. return generators;
  1509. }
  1510. _parseList() {
  1511. const elts = [];
  1512. this._tokenizer.expect('[');
  1513. if (!this._tokenizer.match(']')) {
  1514. const position = this._position();
  1515. const expr = this._parseExpression(-1, ['for']);
  1516. if (this._tokenizer.match('id', 'for')) {
  1517. const generators = this._parseGenerators();
  1518. this._tokenizer.expect(']');
  1519. const node = new ast.ListComp(expr, generators);
  1520. this._mark(node, position);
  1521. return node;
  1522. }
  1523. if (expr === null) {
  1524. throw new python.Error(`Expected expression ${this._location()}`);
  1525. }
  1526. elts.push(expr);
  1527. while (this._tokenizer.eat(',')) {
  1528. if (this._tokenizer.match(']')) {
  1529. break;
  1530. }
  1531. const expr = this._parseExpression(-1, ['for']);
  1532. if (!expr) {
  1533. throw new python.Error(`Expected expression ${this._location()}`);
  1534. }
  1535. elts.push(expr);
  1536. }
  1537. }
  1538. this._tokenizer.expect(']');
  1539. return new ast.List(elts);
  1540. }
  1541. _parseSlice() {
  1542. const elts = [];
  1543. let slice = [null, null, null];
  1544. let index = 0;
  1545. let valid = false;
  1546. this._tokenizer.expect('[');
  1547. while (true) {
  1548. if (this._tokenizer.eat(':')) {
  1549. index++;
  1550. valid = true;
  1551. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1552. if (!valid || index > 2) {
  1553. throw new python.Error(`Invalid slice at ${this._location()}`);
  1554. }
  1555. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1556. slice = [null, null, null];
  1557. index = 0;
  1558. if (this._tokenizer.eat(']')) {
  1559. break;
  1560. }
  1561. this._tokenizer.expect(',');
  1562. } else {
  1563. const expression = this._parseExpression();
  1564. if (expression === null) {
  1565. throw new python.Error(`Expected expression ${this._location()}`);
  1566. }
  1567. slice[index] = expression;
  1568. valid = true;
  1569. }
  1570. }
  1571. if (elts.length > 1) {
  1572. return new ast.Tuple(elts);
  1573. }
  1574. return elts[0];
  1575. }
  1576. _parseName(required) {
  1577. const token = this._tokenizer.peek();
  1578. if (token.type === 'id' && !token.keyword) {
  1579. const position = this._position();
  1580. this._tokenizer.read();
  1581. const node = new ast.Name(token.value);
  1582. return this._mark(node, position);
  1583. }
  1584. if (required) {
  1585. throw new python.Error(`Invalid syntax ${this._location()}`);
  1586. }
  1587. return null;
  1588. }
  1589. _parseDottedName() {
  1590. const list = [];
  1591. do {
  1592. const name = this._parseName(true);
  1593. list.push(name.id);
  1594. }
  1595. while (this._tokenizer.eat('.'));
  1596. return list.join('.');
  1597. }
  1598. _parseLiteral() {
  1599. const token = this._tokenizer.peek();
  1600. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1601. this._tokenizer.read();
  1602. return token;
  1603. }
  1604. return null;
  1605. }
  1606. _parseTypeArguments() {
  1607. const list = [];
  1608. this._tokenizer.expect('[');
  1609. while (!this._tokenizer.eat(']')) {
  1610. const type = this._parseType();
  1611. if (type === null) {
  1612. throw new python.Error(`Expected type ${this._location()}`);
  1613. }
  1614. list.push(type);
  1615. if (!this._tokenizer.eat(',')) {
  1616. this._tokenizer.expect(']');
  1617. break;
  1618. }
  1619. }
  1620. return list;
  1621. }
  1622. _parseType() {
  1623. const target = this._parseExpression(-1, ['[', '=']);
  1624. if (target) {
  1625. if (this._tokenizer.peek().value === '[') {
  1626. const list = this._parseList();
  1627. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1628. return new ast.Subscript(target, slice);
  1629. }
  1630. return target;
  1631. }
  1632. return null;
  1633. }
  1634. _parseArguments(terminal) {
  1635. let posonlyargs = [];
  1636. let args = [];
  1637. let vararg = null;
  1638. const kwonlyargs = [];
  1639. const kw_defaults = [];
  1640. let kwarg = null;
  1641. const defaults = [];
  1642. let is_slash = false;
  1643. let is_vararg = false; // '*'
  1644. let is_kwarg = false; // '**'
  1645. const read = (required) => {
  1646. const name = this._parseName(required);
  1647. if (name) {
  1648. const annotation = terminal !== ':' && this._tokenizer.eat(':') ? this._parseType() : null;
  1649. return new ast.arg(name.id, annotation, null);
  1650. }
  1651. return null;
  1652. };
  1653. while (!this._tokenizer.eat(terminal)) {
  1654. this._tokenizer.eat('\n');
  1655. if (this._tokenizer.eat('/')) {
  1656. if (is_slash || is_vararg || is_kwarg) {
  1657. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1658. }
  1659. is_slash = true;
  1660. } else if (this._tokenizer.eat('*')) {
  1661. if (is_vararg) {
  1662. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1663. }
  1664. is_vararg = true;
  1665. const arg = read(false);
  1666. vararg = arg ? arg : vararg;
  1667. } else if (this._tokenizer.eat('**')) {
  1668. if (is_kwarg) {
  1669. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1670. }
  1671. is_kwarg = true;
  1672. kwarg = read(true);
  1673. } else {
  1674. const arg = read(false);
  1675. if (!arg) {
  1676. this._tokenizer.expect(terminal);
  1677. break;
  1678. }
  1679. const default_value = this._tokenizer.eat('=') ? this._parseExpression() : null;
  1680. if (!is_vararg && !is_kwarg) {
  1681. if (is_slash) {
  1682. args.push(arg);
  1683. } else {
  1684. posonlyargs.push(arg);
  1685. }
  1686. if (default_value !== null) {
  1687. defaults.push(default_value);
  1688. }
  1689. } else if (is_vararg && !is_kwarg) {
  1690. kwonlyargs.push(arg);
  1691. kw_defaults.push(default_value);
  1692. } else {
  1693. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1694. }
  1695. }
  1696. this._tokenizer.eat('\n');
  1697. if (!this._tokenizer.eat(',')) {
  1698. this._tokenizer.expect(terminal);
  1699. break;
  1700. }
  1701. }
  1702. if (!is_slash) {
  1703. args = posonlyargs.concat(args);
  1704. posonlyargs = [];
  1705. }
  1706. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1707. }
  1708. _eat(type, value) {
  1709. if (this._tokenizer.match(type, value)) {
  1710. const position = this._position();
  1711. this._tokenizer.expect(type, value);
  1712. return position;
  1713. }
  1714. return null;
  1715. }
  1716. _mark(node, position) {
  1717. node.filename = position.filename;
  1718. node.lineno = position.lineno;
  1719. node.col_offset = position.col_offset;
  1720. node.end_lineno = this._tokenizer.lineno;
  1721. node.end_col_offset = this._tokenizer.col_offset;
  1722. return node;
  1723. }
  1724. _position() {
  1725. return {
  1726. filename: this._tokenizer.filename,
  1727. lineno: this._tokenizer.lineno,
  1728. col_offset: this._tokenizer.col_offset
  1729. };
  1730. }
  1731. _location() {
  1732. return this._tokenizer.location();
  1733. }
  1734. });
  1735. this.registerType('ast._Tokenizer', class {
  1736. constructor(text, file) {
  1737. this._text = text;
  1738. this.filename = file;
  1739. this.linepos = 0;
  1740. this.lineno = 1;
  1741. this._position = 0;
  1742. this._token = { type: '', value: '' };
  1743. this._brackets = 0;
  1744. this._indentation = [];
  1745. this._outdent = 0;
  1746. if (!ast._Tokenizer._whitespace) {
  1747. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1748. 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';
  1749. 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';
  1750. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1751. /* eslint-disable no-misleading-character-class */
  1752. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1753. /* eslint-enable no-misleading-character-class */
  1754. }
  1755. }
  1756. peek() {
  1757. if (!this._cache) {
  1758. this._tokenize();
  1759. this._cache = true;
  1760. }
  1761. return this._token;
  1762. }
  1763. read() {
  1764. if (!this._cache) {
  1765. this._tokenize();
  1766. }
  1767. const next = this._position + this._token.value.length;
  1768. while (this._position < next) {
  1769. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1770. this._position = this._newLine(this._position);
  1771. this.linepos = this._position;
  1772. this.lineno++;
  1773. } else {
  1774. this._position++;
  1775. }
  1776. }
  1777. this._cache = false;
  1778. return this._token;
  1779. }
  1780. match(type, value) {
  1781. const token = this.peek();
  1782. if (token.type === type && (!value || token.value === value)) {
  1783. return true;
  1784. }
  1785. return false;
  1786. }
  1787. eat(type, value) {
  1788. const token = this.peek();
  1789. if (token.type === type && (!value || token.value === value)) {
  1790. this.read();
  1791. return true;
  1792. }
  1793. return false;
  1794. }
  1795. expect(type, value) {
  1796. const token = this.peek();
  1797. if (token.type !== type) {
  1798. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1799. }
  1800. if (value && token.value !== value) {
  1801. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1802. }
  1803. this.read();
  1804. }
  1805. location() {
  1806. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1807. }
  1808. get col_offset() {
  1809. return this._position - this.linepos + 1;
  1810. }
  1811. static _isSpace(c) {
  1812. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1813. return true;
  1814. }
  1815. if (c.charCodeAt(0) >= 0x1680) {
  1816. return ast._Tokenizer._whitespace.test(c);
  1817. }
  1818. return false;
  1819. }
  1820. static _isNewline(c) {
  1821. switch (c) {
  1822. case '\n':
  1823. case '\r':
  1824. case '\u2028': // 8232
  1825. case '\u2029': // 8233
  1826. return true;
  1827. default:
  1828. return false;
  1829. }
  1830. }
  1831. static _isIdentifierStartChar(c) {
  1832. if (c < 'A') {
  1833. return c === '$';
  1834. }
  1835. if (c <= 'Z') {
  1836. return true;
  1837. }
  1838. if (c < 'a') {
  1839. return c === '_';
  1840. }
  1841. if (c <= 'z') {
  1842. return true;
  1843. }
  1844. const code = c.charCodeAt(0);
  1845. if (code >= 0xAA) {
  1846. return ast._Tokenizer._identifierStart.test(c);
  1847. }
  1848. return false;
  1849. }
  1850. static _isIdentifierChar(c) {
  1851. if (c < '0') {
  1852. return c === '$';
  1853. }
  1854. if (c <= '9') {
  1855. return true;
  1856. }
  1857. if (c < 'A') {
  1858. return false;
  1859. }
  1860. if (c <= 'Z') {
  1861. return true;
  1862. }
  1863. if (c < 'a') {
  1864. return c === '_';
  1865. }
  1866. if (c <= 'z') {
  1867. return true;
  1868. }
  1869. const code = c.charCodeAt(0);
  1870. if (code >= 0xAA) {
  1871. return ast._Tokenizer._identifierChar.test(c);
  1872. }
  1873. return false;
  1874. }
  1875. _get(position) {
  1876. return position >= this._text.length ? '\0' : this._text[position];
  1877. }
  1878. _skipLine() {
  1879. while (this._position < this._text.length) {
  1880. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1881. break;
  1882. }
  1883. this._position++;
  1884. }
  1885. }
  1886. _skipWhitespace() {
  1887. while (this._position < this._text.length) {
  1888. const c = this._text[this._position];
  1889. if (c === '#') {
  1890. this._skipLine();
  1891. } else if (ast._Tokenizer._isSpace(c)) {
  1892. this._position++;
  1893. } else if (c === '\\') {
  1894. // Explicit Line Continuation
  1895. this._position++;
  1896. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1897. this._position = this._newLine(this._position);
  1898. this.linepos = this._position;
  1899. this.lineno += 1;
  1900. } else {
  1901. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1902. }
  1903. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1904. // Implicit Line Continuation
  1905. this._position = this._newLine(this._position);
  1906. this.linepos = this._position;
  1907. this.lineno += 1;
  1908. } else {
  1909. break;
  1910. }
  1911. }
  1912. }
  1913. _newLine(position) {
  1914. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1915. return position + 2;
  1916. }
  1917. return position + 1;
  1918. }
  1919. _tokenize() {
  1920. if (this._token.type !== '\n') {
  1921. this._skipWhitespace();
  1922. }
  1923. if (this._token.type === 'dedent') {
  1924. this._indentation.pop();
  1925. this._outdent--;
  1926. if (this._outdent > 0) {
  1927. this._token = { type: 'dedent', value: '' };
  1928. return;
  1929. }
  1930. }
  1931. if (this._token.type === '\n') {
  1932. let indent = '';
  1933. let i = this._position;
  1934. while (i < this._text.length) {
  1935. const c = this._text[i];
  1936. if (ast._Tokenizer._isSpace(c)) {
  1937. indent += c;
  1938. i++;
  1939. } else if (ast._Tokenizer._isNewline(c)) {
  1940. indent = '';
  1941. i = this._newLine(i);
  1942. this._position = i;
  1943. this.linepos = i;
  1944. this.lineno += 1;
  1945. } else if (c === '#') {
  1946. indent = '';
  1947. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1948. i++;
  1949. }
  1950. continue;
  1951. } else {
  1952. break;
  1953. }
  1954. }
  1955. let type = null;
  1956. if (indent.length > 0) {
  1957. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1958. if (indent.length > current.length) {
  1959. type = 'indent';
  1960. this._indentation.push(indent);
  1961. } else if (indent.length > 0 && indent.length < current.length) {
  1962. type = 'dedent';
  1963. this._outdent = 0;
  1964. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1965. this._outdent++;
  1966. }
  1967. } else {
  1968. this._position += indent.length;
  1969. }
  1970. } else if (i >= this._text.length) {
  1971. this._token = { type: 'eof', value: '' };
  1972. return;
  1973. } else if (this._indentation.length > 0) {
  1974. type = 'dedent';
  1975. this._outdent = this._indentation.length;
  1976. }
  1977. if (type === 'indent' || type === 'dedent') {
  1978. this._token = { type, value: indent };
  1979. return;
  1980. }
  1981. }
  1982. if (this._position >= this._text.length) {
  1983. this._token = { type: 'eof', value: '' };
  1984. return;
  1985. }
  1986. const c = this._get(this._position);
  1987. const string = this._string();
  1988. if (string) {
  1989. this._token = string;
  1990. return;
  1991. }
  1992. switch (c) {
  1993. case '(':
  1994. case '[':
  1995. case '{':
  1996. this._brackets++;
  1997. this._token = { type: c, value: c };
  1998. return;
  1999. case ')':
  2000. case ']':
  2001. case '}':
  2002. if (this._brackets === 0) {
  2003. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  2004. }
  2005. this._brackets--;
  2006. this._token = { type: c, value: c };
  2007. return;
  2008. case ',':
  2009. case ';':
  2010. case '?':
  2011. this._token = { type: c, value: c };
  2012. return;
  2013. default: {
  2014. const number = this._number();
  2015. if (number) {
  2016. this._token = number;
  2017. return;
  2018. }
  2019. if (c === '.') {
  2020. let end = this._position + 1;
  2021. while (this._get(end) === '.') {
  2022. end++;
  2023. }
  2024. const text = this._text.substring(this._position, end);
  2025. this._token = { type: text, value: text };
  2026. return;
  2027. }
  2028. const identifier = this._identifier();
  2029. if (identifier) {
  2030. this._token = identifier;
  2031. return;
  2032. }
  2033. const operator = this._operator();
  2034. if (operator) {
  2035. this._token = operator;
  2036. return;
  2037. }
  2038. break;
  2039. }
  2040. }
  2041. if (c === '.') {
  2042. this._token = { type: c, value: c };
  2043. return;
  2044. }
  2045. if (c === '\\') {
  2046. this._token = { type: '\\', value: c };
  2047. return;
  2048. }
  2049. if (ast._Tokenizer._isNewline(c)) {
  2050. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2051. return;
  2052. }
  2053. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2054. }
  2055. _number() {
  2056. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2057. const binary = (c) => c === '0' || c === '1' || c === '_';
  2058. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2059. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2060. let c = this._get(this._position);
  2061. const sign = (c === '-' || c === '+') ? 1 : 0;
  2062. let i = this._position + sign;
  2063. c = this._get(i);
  2064. if (c === '0') {
  2065. let radix = 0;
  2066. const n = this._get(i + 1);
  2067. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2068. i += 2;
  2069. while (hex(this._get(i))) {
  2070. i += 1;
  2071. }
  2072. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2073. i += 1;
  2074. }
  2075. radix = 16;
  2076. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2077. i += 2;
  2078. while (binary(this._get(i))) {
  2079. i++;
  2080. }
  2081. radix = 2;
  2082. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2083. i += 2;
  2084. while (octal(this._get(i))) {
  2085. i++;
  2086. }
  2087. radix = 8;
  2088. } else if (n >= '0' && n <= '7') {
  2089. i++;
  2090. while (octal(this._get(i))) {
  2091. i += 1;
  2092. }
  2093. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2094. i += 1;
  2095. }
  2096. radix = 8;
  2097. }
  2098. if (radix > 0 && this._get(i) !== '.') {
  2099. const radixText = this._text.substring(this._position, i);
  2100. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2101. if (!isNaN(parseInt(radixParseText, radix))) {
  2102. return { type: 'int', value: radixText };
  2103. }
  2104. }
  2105. }
  2106. i = this._position + sign;
  2107. let isDecimal = false;
  2108. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2109. while (decimal(this._get(i))) {
  2110. i++;
  2111. }
  2112. c = this._get(i).toLowerCase();
  2113. isDecimal = c !== '.' && c !== 'e';
  2114. }
  2115. if (this._get(i) === '0') {
  2116. i++;
  2117. c = this._get(i).toLowerCase();
  2118. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2119. }
  2120. if (isDecimal) {
  2121. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2122. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2123. }
  2124. // if (this._get(i) === 'l' || this._get(i) === 'L') {
  2125. // Python 2 long integer
  2126. // }
  2127. const intText = this._text.substring(this._position, i);
  2128. if (!isNaN(parseInt(intText, 10))) {
  2129. return { type: 'int', value: intText };
  2130. }
  2131. }
  2132. i = this._position + sign;
  2133. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2134. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2135. while (decimal(this._get(i))) {
  2136. i++;
  2137. }
  2138. if (this._get(i) === '.') {
  2139. i++;
  2140. }
  2141. while (decimal(this._get(i))) {
  2142. i++;
  2143. }
  2144. if (i > (this._position + sign)) {
  2145. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2146. i++;
  2147. if (this._get(i) === '-' || this._get(i) === '+') {
  2148. i++;
  2149. }
  2150. if (decimal(this._get(i))) {
  2151. while (decimal(this._get(i))) {
  2152. i++;
  2153. }
  2154. } else {
  2155. i = this._position;
  2156. }
  2157. } else {
  2158. while (decimal(this._get(i))) {
  2159. i++;
  2160. }
  2161. }
  2162. }
  2163. if (i > (this._position + sign)) {
  2164. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2165. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2166. }
  2167. const floatText = this._text.substring(this._position, i);
  2168. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2169. if (!isNaN(parseFloat(floatParseText))) {
  2170. return { type: 'float', value: floatText };
  2171. }
  2172. }
  2173. }
  2174. return null;
  2175. }
  2176. _identifier() {
  2177. let i = this._position;
  2178. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2179. i++;
  2180. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2181. i++;
  2182. }
  2183. }
  2184. if (i > this._position) {
  2185. const text = this._text.substring(this._position, i);
  2186. let keyword = false;
  2187. switch (text) {
  2188. case 'and':
  2189. case 'as':
  2190. case 'else':
  2191. case 'For':
  2192. case 'If':
  2193. case 'Import':
  2194. case 'in':
  2195. case 'is':
  2196. case 'not':
  2197. case 'or':
  2198. keyword = true;
  2199. break;
  2200. default:
  2201. break;
  2202. }
  2203. return { type: 'id', value: text, keyword };
  2204. }
  2205. return null;
  2206. }
  2207. _operator() {
  2208. let length = 0;
  2209. const c0 = this._get(this._position);
  2210. const c1 = this._get(this._position + 1);
  2211. const c2 = this._get(this._position + 2);
  2212. switch (c0) {
  2213. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2214. length = c1 === '=' ? 2 : 1;
  2215. break;
  2216. case '-':
  2217. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2218. break;
  2219. case '*':
  2220. switch (c1) {
  2221. case '*': length = c2 === '=' ? 3 : 2; break;
  2222. case '=': length = 2; break;
  2223. default: length = 1; break;
  2224. }
  2225. break;
  2226. case '/':
  2227. switch (c1) {
  2228. case '/': length = c2 === '=' ? 3 : 2; break;
  2229. case '=': length = 2; break;
  2230. default: length = 1; break;
  2231. }
  2232. break;
  2233. case '<':
  2234. switch (c1) {
  2235. case '>': length = 2; break;
  2236. case '<': length = c2 === '=' ? 3 : 2; break;
  2237. case '=': length = 2; break;
  2238. default: length = 1; break;
  2239. }
  2240. break;
  2241. case '>':
  2242. switch (c1) {
  2243. case '>': length = c2 === '=' ? 3 : 2; break;
  2244. case '=': length = 2; break;
  2245. default: length = 1; break;
  2246. }
  2247. break;
  2248. case '@':
  2249. length = c1 === '=' ? 2 : 1;
  2250. break;
  2251. case ':':
  2252. length = c1 === '=' ? 2 : 1;
  2253. break;
  2254. default:
  2255. return null;
  2256. }
  2257. const text = this._text.substring(this._position, this._position + length);
  2258. return { type: text, value: text };
  2259. }
  2260. _string() {
  2261. let i = this._position;
  2262. let prefix = -1;
  2263. if (this._get(i) === "'" || this._get(i) === '"') {
  2264. prefix = '';
  2265. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2266. const c = this._get(i);
  2267. const cc = c.toLowerCase();
  2268. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2269. prefix = c;
  2270. }
  2271. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2272. const c = this._text.substring(this._position, this._position + 2);
  2273. const cc = c.toLowerCase();
  2274. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2275. prefix = c;
  2276. }
  2277. }
  2278. if (prefix.length >= 0) {
  2279. i += prefix.length;
  2280. let quote = '';
  2281. let count = 0;
  2282. const q0 = this._get(i);
  2283. const q1 = this._get(i + 1);
  2284. const q2 = this._get(i + 2);
  2285. switch (q0) {
  2286. case "'":
  2287. quote = q0;
  2288. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2289. break;
  2290. case '"':
  2291. quote = q0;
  2292. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2293. break;
  2294. default:
  2295. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2296. }
  2297. i += count;
  2298. if (count === 1) {
  2299. while (i < this._text.length) {
  2300. if (this._text[i] === quote) {
  2301. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2302. } else if (this._text[i] === '\\' &&
  2303. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2304. i += 2;
  2305. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2306. break;
  2307. } else {
  2308. i++;
  2309. }
  2310. }
  2311. } else if (count === 3) {
  2312. while (i < this._text.length) {
  2313. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2314. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2315. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2316. i += 2;
  2317. continue;
  2318. }
  2319. i++;
  2320. }
  2321. }
  2322. }
  2323. i = this._position;
  2324. if (this._get(i) === '`') {
  2325. i++;
  2326. while (i < this._text.length) {
  2327. if (this._text[i] === '`') {
  2328. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2329. }
  2330. i++;
  2331. }
  2332. }
  2333. return null;
  2334. }
  2335. });
  2336. this.registerType('builtins.dict', dict);
  2337. this.registerType('builtins.ellipsis', class {});
  2338. this.registerType('builtins.cell', class {});
  2339. this.registerType('builtins.list', class extends Array {
  2340. constructor(iterable) {
  2341. super();
  2342. if (Array.isArray(iterable)) {
  2343. this.push(...iterable);
  2344. }
  2345. }
  2346. });
  2347. this.registerType('builtins.number', class {});
  2348. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2349. return execution.__import__(name, globals, locals, fromlist, level);
  2350. });
  2351. this.registerType('builtins.bool', class extends Boolean {
  2352. constructor(value) {
  2353. if (value && value.__bool__) {
  2354. value = value.__bool__();
  2355. } else if (value && value.__len__) {
  2356. value = value.__len__() > 0;
  2357. } else {
  2358. value = value ? true : false;
  2359. }
  2360. super(value);
  2361. }
  2362. });
  2363. this.registerType('builtins.int', class extends Number {
  2364. constructor(value) {
  2365. if (value && value.__int__) {
  2366. value = value.__int__();
  2367. } else if (!Number.isInteger(value)) {
  2368. value = NaN;
  2369. }
  2370. super(value);
  2371. }
  2372. });
  2373. this.registerType('builtins.float', class extends Number {
  2374. constructor(value) {
  2375. if (value && value.__float__) {
  2376. value = value.__float__();
  2377. } else if (Number(value) !== value) {
  2378. value = NaN;
  2379. }
  2380. super(value);
  2381. }
  2382. });
  2383. this.registerType('builtins.long', class extends Number {
  2384. constructor(value) {
  2385. if (value && value.__int__) {
  2386. value = value.__int__();
  2387. } else if (!Number.isInteger(value)) {
  2388. value = NaN;
  2389. }
  2390. super(value);
  2391. }
  2392. });
  2393. this.registerType('builtins.str', class extends String {
  2394. constructor(value) {
  2395. if (value && value.__str__) {
  2396. value = value.__str__();
  2397. } else if (typeof value !== 'string') {
  2398. value = JSON.stringify(value);
  2399. }
  2400. super(value);
  2401. }
  2402. });
  2403. this.registerType('builtins.complex', class {
  2404. constructor(real, imaginary) {
  2405. this.real = real;
  2406. this.imag = imaginary;
  2407. }
  2408. });
  2409. this.registerType('builtins.NoneType', class {});
  2410. this.registerType('builtins.object', class {
  2411. static __new__(cls, ...args) {
  2412. return execution.invoke(cls, args);
  2413. }
  2414. static __setattr__(obj, name, value) {
  2415. builtins.setattr(obj, name, value);
  2416. }
  2417. });
  2418. this.registerType('builtins.tuple', class extends Array {
  2419. constructor(items) {
  2420. super(items ? items.length : 0);
  2421. if (items) {
  2422. for (let i = 0; i < items.length; i++) {
  2423. this[i] = items[i];
  2424. }
  2425. }
  2426. }
  2427. });
  2428. this.registerType('builtins.staticmethod', class {});
  2429. this.registerType('builtins.Warning', class {});
  2430. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2431. this.registerType('builtins.BaseException', class {});
  2432. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2433. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2434. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2435. this.registerFunction('builtins.print', () => {});
  2436. this.registerFunction('builtins.unicode');
  2437. builtins.Ellipsis = new builtins.ellipsis();
  2438. this.registerType('typing._Final', class {});
  2439. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2440. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2441. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2442. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2443. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2444. this.registerType('typing._CallableType', class {});
  2445. this.registerFunction('typing.cast');
  2446. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2447. typing.Callable = Reflect.construct(typing._CallableType, []);
  2448. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2449. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2450. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2451. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2452. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2453. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2454. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2455. this.registerType('enum.Enum', class {
  2456. // __reduce_ex__(proto) {
  2457. // return self.__class__, (self._value_, )
  2458. // }
  2459. });
  2460. this.registerFunction('operator.add');
  2461. this.registerFunction('operator.and_');
  2462. this.registerFunction('operator.and_');
  2463. this.registerFunction('operator.eq');
  2464. this.registerFunction('operator.floordiv');
  2465. this.registerFunction('operator.ge');
  2466. this.registerFunction('operator.getitem');
  2467. this.registerFunction('operator.gt');
  2468. this.registerFunction('operator.le');
  2469. this.registerFunction('operator.lt');
  2470. this.registerFunction('operator.mod');
  2471. this.registerFunction('operator.mul');
  2472. this.registerFunction('operator.ne');
  2473. this.registerFunction('operator.neg');
  2474. this.registerFunction('operator.or_');
  2475. this.registerFunction('operator.pos');
  2476. this.registerFunction('operator.pow');
  2477. this.registerFunction('operator.sub');
  2478. this.registerFunction('operator.truediv');
  2479. this.registerFunction('sys.path.append', () => {});
  2480. this.registerFunction('sys.path.insert', () => {});
  2481. this.registerType('argparse.Namespace', class {
  2482. constructor(args) {
  2483. this.args = args;
  2484. }
  2485. });
  2486. this.registerType('catboost._catboost._CatBoost', class {
  2487. _deserialize_model(/* serialized_model_str */) {
  2488. }
  2489. });
  2490. this.registerType('catboost.core._CatBoostBase', class {
  2491. constructor() {
  2492. this._object = new catboost._catboost._CatBoost();
  2493. }
  2494. __setstate__(state) {
  2495. for (const [key, value] of state) {
  2496. if (key === '__model') {
  2497. this._load_from_string(value);
  2498. continue;
  2499. }
  2500. this[key] = value;
  2501. }
  2502. }
  2503. _load_from_string(dump_model_str) {
  2504. this._deserialize_model(dump_model_str);
  2505. }
  2506. _deserialize_model(dump_model_str) {
  2507. this._object._deserialize_model(dump_model_str);
  2508. }
  2509. });
  2510. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2511. load_model(/* blob */) {
  2512. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2513. // this._load_from_string(blob);
  2514. }
  2515. });
  2516. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2517. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2518. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2519. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2520. catboost.CatBoost = catboost.core.CatBoost;
  2521. this.registerType('collections.deque', class extends Array {
  2522. constructor(iterable) {
  2523. super();
  2524. if (Array.isArray(iterable)) {
  2525. for (const value of iterable) {
  2526. this.push(value);
  2527. }
  2528. }
  2529. }
  2530. });
  2531. this.registerType('collections.OrderedDict', class extends dict {});
  2532. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2533. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2534. this.registerType('cuml.internals.array.CumlArray', class {});
  2535. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2536. this.registerType('cuml.raft.common.handle.Handle', class {
  2537. __setstate__(state) {
  2538. this._handle = state;
  2539. }
  2540. });
  2541. this.registerType('cuml.svm.svr.SVR', class {});
  2542. this.registerType('datetime.date', class {});
  2543. this.registerType('datetime.datetime', class extends datetime.date {});
  2544. this.registerType('datetime.timedelta', class {});
  2545. this.registerType('datetime.tzinfo', class {});
  2546. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2547. this.registerType('dnnlib.tflib.network.Network', class {});
  2548. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2549. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2550. constructor(dict) {
  2551. Object.assign(this, dict);
  2552. }
  2553. });
  2554. this.registerType('haiku._src.data_structures.frozendict', class {
  2555. constructor(obj) {
  2556. Object.assign(this, obj);
  2557. }
  2558. });
  2559. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2560. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2561. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2562. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2563. this.registerType('io.BytesIO', class {
  2564. constructor(buf, mode) {
  2565. this.mode = mode || 'r';
  2566. this._buf = this.mode === 'w' ? null : buf;
  2567. this._point = 0;
  2568. }
  2569. seek(offset) {
  2570. if (this._buf.seek) {
  2571. this._buf.seek(offset);
  2572. }
  2573. this._point = offset;
  2574. }
  2575. read(size, stream) {
  2576. if (this._buf.stream && stream) {
  2577. return this._buf.stream(size);
  2578. }
  2579. if (this._buf.peek) {
  2580. return this._buf.read(size);
  2581. }
  2582. if (this._buf instanceof Uint8Array) {
  2583. const start = this._point;
  2584. this._point = size === undefined ? this._buf.length : start + size;
  2585. return this._buf.subarray(start, this._point);
  2586. }
  2587. throw new python.Error('Unsupported buffer type.');
  2588. }
  2589. write(data) {
  2590. const src = this._buf || new Uint8Array();
  2591. const end = this._point + data.length;
  2592. const size = Math.max(src.length, end);
  2593. this._buf = new Uint8Array(size);
  2594. this._buf.set(src, 0);
  2595. this._buf.set(data, this._point);
  2596. this._point = end;
  2597. }
  2598. getbuffer() {
  2599. return new builtins.memoryview(this._buf);
  2600. }
  2601. });
  2602. this.registerType('io.StringIO', class {
  2603. constructor() {
  2604. this._buf = [];
  2605. }
  2606. write(text) {
  2607. this._buf.push(text);
  2608. }
  2609. toString() {
  2610. return this._buf.join('');
  2611. }
  2612. });
  2613. this.registerType('numpy.dtype', class {
  2614. constructor(obj, align, copy) {
  2615. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2616. this.kind = 'V';
  2617. this.byteorder = '|';
  2618. this.itemsize = obj.itemsize;
  2619. this.names = obj.names;
  2620. this.fields = new Map();
  2621. for (let i = 0; i < obj.names.length; i++) {
  2622. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2623. }
  2624. return;
  2625. }
  2626. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2627. this.byteorder = obj.substring(0, 1);
  2628. obj = obj.substring(1);
  2629. } else {
  2630. this.byteorder = '=';
  2631. }
  2632. switch (obj) {
  2633. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2634. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2635. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2636. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2637. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2638. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2639. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2640. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2641. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2642. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2643. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2644. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2645. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2646. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2647. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2648. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2649. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2650. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2651. default:
  2652. if (obj.startsWith('V')) {
  2653. this.itemsize = parseInt(obj.substring(1), 10);
  2654. this.kind = 'V';
  2655. } else if (obj.startsWith('O')) {
  2656. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2657. this.kind = 'O';
  2658. } else if (obj.startsWith('S')) {
  2659. this.itemsize = parseInt(obj.substring(1), 10);
  2660. this.kind = 'S';
  2661. } else if (obj.startsWith('U')) { // Unicode string
  2662. this.kind = 'U';
  2663. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2664. } else if (obj.startsWith('T')) {
  2665. this.kind = 'T';
  2666. this.itemsize = parseInt(obj.substring(1), 10);
  2667. } else {
  2668. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2669. }
  2670. break;
  2671. }
  2672. if (align) {
  2673. this.align = align;
  2674. }
  2675. if (copy) {
  2676. this.copy = copy;
  2677. }
  2678. }
  2679. get str() {
  2680. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2681. }
  2682. get name() {
  2683. switch (this.kind) {
  2684. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2685. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2686. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2687. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2688. case 'M': return 'datetime64';
  2689. case 'm': return 'timedelta64';
  2690. case 'b': return 'bool';
  2691. default: return this.__name__;
  2692. }
  2693. }
  2694. __setstate__(state) {
  2695. switch (state.length) {
  2696. case 8:
  2697. [
  2698. this.version, this.byteorder, this.subarray, this.names,
  2699. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2700. ] = state;
  2701. break;
  2702. case 9:
  2703. [
  2704. this.version, this.byteorder, this.subarray, this.names,
  2705. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2706. this.metadata
  2707. ] = state;
  2708. break;
  2709. default:
  2710. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2711. }
  2712. }
  2713. get __name__() {
  2714. switch (this.kind) {
  2715. case 'b':
  2716. switch (this.itemsize) {
  2717. case 1: return 'boolean';
  2718. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2719. }
  2720. case 'i':
  2721. switch (this.itemsize) {
  2722. case 1: return 'int8';
  2723. case 2: return 'int16';
  2724. case 4: return 'int32';
  2725. case 8: return 'int64';
  2726. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2727. }
  2728. case 'u':
  2729. switch (this.itemsize) {
  2730. case 1: return 'uint8';
  2731. case 2: return 'uint16';
  2732. case 4: return 'uint32';
  2733. case 8: return 'uint64';
  2734. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2735. }
  2736. case 'f':
  2737. switch (this.itemsize) {
  2738. case 1: return 'float8e5m2';
  2739. case 2: return 'float16';
  2740. case 4: return 'float32';
  2741. case 8: return 'float64';
  2742. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2743. }
  2744. case 'c':
  2745. switch (this.itemsize) {
  2746. case 8: return 'complex64';
  2747. case 16: return 'complex128';
  2748. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2749. }
  2750. case 'S':
  2751. case 'T':
  2752. return 'string';
  2753. case 'U':
  2754. return 'string';
  2755. case 'M':
  2756. return 'datetime';
  2757. case 'm':
  2758. return 'timedelta';
  2759. case 'O':
  2760. return 'object';
  2761. case 'V':
  2762. return 'void';
  2763. default:
  2764. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2765. }
  2766. }
  2767. });
  2768. this.registerType('numpy.generic', class {});
  2769. this.registerType('numpy.inexact', class {});
  2770. this.registerType('numpy.flexible', class extends numpy.generic {});
  2771. this.registerType('numpy.void', class extends numpy.flexible {});
  2772. this.registerType('numpy.bool_', class extends numpy.generic {});
  2773. this.registerType('numpy.number', class extends numpy.generic {});
  2774. this.registerType('numpy.integer', class extends numpy.number {});
  2775. this.registerType('numpy.floating', class extends numpy.inexact {});
  2776. this.registerType('numpy.float16', class extends numpy.floating {});
  2777. this.registerType('numpy.float32', class extends numpy.floating {});
  2778. this.registerType('numpy.float64', class extends numpy.floating {});
  2779. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2780. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2781. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2782. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2783. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2784. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2785. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2786. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2787. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2788. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2789. this.registerType('numpy.datetime64', class extends numpy.generic {
  2790. constructor(...args) {
  2791. super();
  2792. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2793. [this.buffer] = args;
  2794. }
  2795. }
  2796. toString() {
  2797. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2798. const value = view.getBigInt64(0, true);
  2799. if (value === -9223372036854775808n) {
  2800. return 'NaT';
  2801. }
  2802. const date = new Date(Number(value / 1000000n));
  2803. return date.toISOString().slice(0, -1);
  2804. }
  2805. });
  2806. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2807. constructor() {
  2808. super('|T16');
  2809. }
  2810. });
  2811. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2812. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2813. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2814. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2815. this.registerType('gensim.models.fasttext.FastText', class {});
  2816. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2817. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2818. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2819. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2820. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2821. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2822. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2823. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2824. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2825. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2826. this.registerFunction('gensim.models.phrases.original_scorer');
  2827. this.registerType('gensim.models.phrases.Phraser', class {});
  2828. this.registerType('gensim.models.phrases.Phrases', class {});
  2829. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2830. this.registerType('gensim.models.word2vec.Vocab', class {});
  2831. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2832. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2833. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2834. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2835. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2836. throw new builtins.AttributeError('This method should be called on a class object.');
  2837. });
  2838. this.registerFunction('gensim.utils.identity');
  2839. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2840. constructor(obj) {
  2841. Object.assign(this, obj);
  2842. }
  2843. });
  2844. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2845. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2846. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2847. __read__(unpickler) {
  2848. if (this.dtype.__name__ === 'object') {
  2849. return unpickler.load();
  2850. }
  2851. if (this.numpy_array_alignment_bytes) {
  2852. const [size] = unpickler.read(1);
  2853. unpickler.read(size);
  2854. }
  2855. if (this.order === 'F') {
  2856. throw new python.Error('Fortran order not implemented.');
  2857. }
  2858. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2859. this.data = unpickler.read(size);
  2860. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2861. }
  2862. });
  2863. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2864. __setstate__(state) {
  2865. this.subclass = state.get('subclass');
  2866. this.filename = state.get('state');
  2867. this.allow_mmap = state.get('allow_mmap');
  2868. }
  2869. __read__(/* unpickler */) {
  2870. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2871. }
  2872. });
  2873. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2874. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2875. this.registerType('keras.engine.sequential.Sequential', class {});
  2876. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2877. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2878. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2879. this.registerType('lasagne.layers.input.InputLayer', class {});
  2880. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2881. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2882. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2883. this.registerType('lightgbm.basic.Booster', class {
  2884. constructor() {
  2885. this.average_output = false;
  2886. this.models = [];
  2887. this.loaded_parameter = '';
  2888. }
  2889. __setstate__(state) {
  2890. const model_str = state.get('_handle', state.get('handle', null));
  2891. if (model_str) {
  2892. this.LoadModelFromString(model_str);
  2893. return;
  2894. }
  2895. for (const [key, value] of state) {
  2896. this[key] = value;
  2897. }
  2898. }
  2899. LoadModelFromString(model_str) {
  2900. const lines = model_str.split('\n');
  2901. const signature = lines.shift() || '?';
  2902. if (signature.trim() !== 'tree') {
  2903. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2904. }
  2905. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2906. const key_vals = new Map();
  2907. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2908. const cur_line = lines.shift().trim();
  2909. if (cur_line.length > 0) {
  2910. const strs = cur_line.split('=');
  2911. if (strs.length === 1) {
  2912. key_vals.set(strs[0], '');
  2913. } else if (strs.length === 2) {
  2914. key_vals.set(strs[0], strs[1]);
  2915. } else if (strs.length > 2) {
  2916. if (strs[0] === "feature_names") {
  2917. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2918. } else if (strs[0] === 'monotone_constraints') {
  2919. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2920. } else {
  2921. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2922. }
  2923. }
  2924. }
  2925. }
  2926. const atoi = (key, value) => {
  2927. if (key_vals.has(key)) {
  2928. return parseInt(key_vals.get(key), 10);
  2929. }
  2930. if (value !== undefined) {
  2931. return value;
  2932. }
  2933. throw new python.Error(`Model file does not specify ${key}.`);
  2934. };
  2935. const list = (key, size) => {
  2936. if (key_vals.has(key)) {
  2937. const value = key_vals.get(key).split(' ');
  2938. if (value.length !== size) {
  2939. throw new python.Error(`Wrong size of ${key}.`);
  2940. }
  2941. return value;
  2942. }
  2943. throw new python.Error(`Model file does not contain ${key}.`);
  2944. };
  2945. this.version = key_vals.get('version') || '';
  2946. this.num_class = atoi('num_class');
  2947. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2948. this.label_index = atoi('label_index');
  2949. this.max_feature_idx = atoi('max_feature_idx');
  2950. if (key_vals.has('average_output')) {
  2951. this.average_output = true;
  2952. }
  2953. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2954. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2955. if (key_vals.has('monotone_constraints')) {
  2956. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2957. }
  2958. if (key_vals.has('objective')) {
  2959. this.objective = key_vals.get('objective');
  2960. }
  2961. let tree = null;
  2962. while (lines.length > 0) {
  2963. const text = lines.shift();
  2964. const line = text.trim();
  2965. if (line.length === 0) {
  2966. continue;
  2967. }
  2968. if (line.startsWith('Tree=')) {
  2969. tree = { index: parseInt(line.split('=').pop(), 10) };
  2970. this.models.push(tree);
  2971. continue;
  2972. }
  2973. if (line === 'end of trees') {
  2974. break;
  2975. }
  2976. const param = line.split('=');
  2977. if (param.length !== 2) {
  2978. throw new python.Error(`Invalid property '${line}'.`);
  2979. }
  2980. const name = param[0].trim();
  2981. const value = param[1].trim();
  2982. tree[name] = value;
  2983. }
  2984. const ss = [];
  2985. let is_inparameter = false;
  2986. while (lines.length > 0) {
  2987. const text = lines.shift();
  2988. const line = text.trim();
  2989. if (line === 'parameters:') {
  2990. is_inparameter = true;
  2991. continue;
  2992. } else if (line === 'end of parameters') {
  2993. break;
  2994. } else if (is_inparameter) {
  2995. ss.push(line);
  2996. }
  2997. }
  2998. if (ss.length > 0) {
  2999. this.loaded_parameter = ss.join('\n');
  3000. }
  3001. }
  3002. });
  3003. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  3004. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  3005. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  3006. this.registerFunction('megengine.functional.nn.relu', () => {});
  3007. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3008. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3009. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3010. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3011. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3012. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3013. this.registerFunction('megengine.functional.tensor.full', () => {});
  3014. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3015. this.registerFunction('megengine.functional.tensor.split', () => {});
  3016. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3017. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3018. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3019. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3020. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3021. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3022. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3023. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3024. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3025. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3026. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3027. this.registerType('megengine.distributed.group.Group', class {});
  3028. this.registerType('megengine.module.activation.ReLU', class {});
  3029. this.registerType('megengine.module.activation.Softmax', class {});
  3030. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3031. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3032. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3033. this.registerType('megengine.module.conv.Conv2d', class {});
  3034. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3035. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3036. this.registerType('megengine.module.dropout.Dropout', class {});
  3037. this.registerType('megengine.module.identity.Identity', class {});
  3038. this.registerType('megengine.module.linear.Linear', class {});
  3039. this.registerType('megengine.module.module.Module', class {});
  3040. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3041. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3042. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3043. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3044. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3045. this.registerType('megengine.module.qat.concat.Concat', class {});
  3046. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3047. this.registerType('megengine.module.sequential.Sequential', class {});
  3048. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3049. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3050. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3051. this.registerType('megengine.quantization.utils.QParams', class {});
  3052. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3053. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3054. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3055. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3056. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3057. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3058. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3059. this.registerType('megengine.traced_module.expr.Apply', class {});
  3060. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3061. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3062. this.registerType('megengine.traced_module.expr.Constant', class {});
  3063. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3064. this.registerType('megengine.traced_module.expr.Input', class {});
  3065. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3066. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3067. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3068. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3069. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3070. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3071. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3072. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3073. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3074. this.registerType('megengine.tensor.Parameter', class {
  3075. constructor(data, dtype, device) {
  3076. this.data = data;
  3077. this.dtype = dtype;
  3078. this.device = device;
  3079. }
  3080. });
  3081. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3082. toString() {
  3083. let content = '';
  3084. for (const child of this.children_defs) {
  3085. content += `${child},`;
  3086. }
  3087. if (typeof this.type === "string") {
  3088. return `${this.type.split(".").slice(-1)}(${content})`;
  3089. }
  3090. return `${this.type.__name__}(${content})`;
  3091. }
  3092. });
  3093. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3094. toString() {
  3095. let content = '';
  3096. if (this.const_val === null) {
  3097. content += '[';
  3098. } else {
  3099. content += this.const_val;
  3100. }
  3101. for (const t of Object.values(this.type)) {
  3102. content += t.__name__;
  3103. }
  3104. content += ']';
  3105. return content;
  3106. }
  3107. });
  3108. this.registerType('megengine.tensor.Tensor', class {
  3109. constructor(data, dtype, device) {
  3110. this.data = data;
  3111. this.dtype = dtype;
  3112. this.device = device;
  3113. }
  3114. });
  3115. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3116. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3117. this.name = name;
  3118. this.cname = cname;
  3119. this.np_dtype = np_dtype;
  3120. this.qmin = qmin;
  3121. this.qmax = qmax;
  3122. this.is_signed = is_signed;
  3123. }
  3124. });
  3125. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3126. this.registerType('nolearn.lasagne.base.Layers', class {});
  3127. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3128. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3129. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3130. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3131. this.registerType('numpy.ndarray', class {
  3132. constructor(shape, dtype, buffer, offset, strides, order) {
  3133. this.shape = shape;
  3134. this.dtype = dtype;
  3135. this.data = buffer === undefined ? null : buffer;
  3136. this.offset = offset === undefined ? 0 : offset;
  3137. this._strides = strides === undefined ? null : strides;
  3138. this.order = order === undefined ? null : order;
  3139. this.flags = {};
  3140. this._read();
  3141. }
  3142. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3143. return new cls(shape, dtype, buffer, offset, strides, order);
  3144. }
  3145. __setstate__(state) {
  3146. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3147. this._read();
  3148. }
  3149. flatten() {
  3150. const size = this.shape.reduce((a, b) => a * b, 1);
  3151. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3152. value.flags = this.flags;
  3153. return value;
  3154. }
  3155. reshape(shape, order) {
  3156. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3157. }
  3158. tobytes() {
  3159. return this.data;
  3160. }
  3161. tolist() {
  3162. if (this.shape.length < 0 || this.shape.length > 1) {
  3163. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3164. }
  3165. const size = this.shape.reduce((a, b) => a * b, 1);
  3166. const list = new Array(size);
  3167. switch (this.dtype.kind) {
  3168. case 'U': {
  3169. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3170. const itemsize = this.dtype.itemsize >> 2;
  3171. let offset = 0;
  3172. for (let i = 0; i < size; i++) {
  3173. const buffer = data.subarray(offset, offset + itemsize);
  3174. const index = buffer.indexOf(0);
  3175. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3176. offset += itemsize;
  3177. }
  3178. return list;
  3179. }
  3180. case 'S': {
  3181. const data = this.data;
  3182. const itemsize = this.dtype.itemsize;
  3183. const decoder = new TextDecoder('utf-8');
  3184. let offset = 0;
  3185. for (let i = 0; i < size; i++) {
  3186. const buffer = data.subarray(offset, offset + itemsize);
  3187. const index = buffer.indexOf(0);
  3188. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3189. offset += itemsize;
  3190. }
  3191. return list;
  3192. }
  3193. case 'V': {
  3194. const itemsize = this.dtype.itemsize;
  3195. let offset = 0;
  3196. for (let i = 0; i < size; i++) {
  3197. list[i] = this.data.slice(offset, offset + itemsize);
  3198. offset += itemsize;
  3199. }
  3200. return list;
  3201. }
  3202. case 'M': {
  3203. const itemsize = this.dtype.itemsize;
  3204. let offset = 0;
  3205. for (let i = 0; i < size; i++) {
  3206. const buffer = this.data.slice(offset, offset + itemsize);
  3207. list[i] = new numpy.datetime64(buffer);
  3208. offset += itemsize;
  3209. }
  3210. return list;
  3211. }
  3212. case 'T': {
  3213. return this.data;
  3214. }
  3215. case 'O': {
  3216. return this.data;
  3217. }
  3218. default: {
  3219. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3220. }
  3221. }
  3222. }
  3223. get itemsize() {
  3224. return this.dtype.itemsize;
  3225. }
  3226. get size() {
  3227. return (this.shape || []).reduce((a, b) => a * b, 1);
  3228. }
  3229. get strides() {
  3230. if (!this._strides) {
  3231. const shape = this.shape;
  3232. const strides = new Array(shape.length);
  3233. let stride = this.itemsize;
  3234. for (let i = shape.length - 1; i >= 0; i--) {
  3235. strides[i] = stride;
  3236. stride *= shape[i];
  3237. }
  3238. return strides;
  3239. }
  3240. return this._strides;
  3241. }
  3242. _read() {
  3243. if (this.data) {
  3244. const length = this.dtype.itemsize * this.size;
  3245. if (typeof this.data === 'string') {
  3246. this.data = this._unescape(this.data, length);
  3247. if (this.data.length !== length) {
  3248. throw new python.Error('Invalid string array data size.');
  3249. }
  3250. } else if (this.data.length !== length) {
  3251. // throw new python.Error('Invalid array data size.');
  3252. }
  3253. }
  3254. }
  3255. _unescape(token, size) {
  3256. const length = token.length;
  3257. const a = new Uint8Array(length);
  3258. if (size && size === length) {
  3259. for (let p = 0; p < size; p++) {
  3260. a[p] = token.charCodeAt(p);
  3261. }
  3262. return a;
  3263. }
  3264. let i = 0;
  3265. let o = 0;
  3266. while (i < length) {
  3267. let c = token.charCodeAt(i++);
  3268. if (c !== 0x5C || i >= length) {
  3269. a[o++] = c;
  3270. } else {
  3271. c = token.charCodeAt(i++);
  3272. switch (c) {
  3273. case 0x27: a[o++] = 0x27; break; // '
  3274. case 0x5C: a[o++] = 0x5C; break; // \\
  3275. case 0x22: a[o++] = 0x22; break; // "
  3276. case 0x72: a[o++] = 0x0D; break; // \r
  3277. case 0x6E: a[o++] = 0x0A; break; // \n
  3278. case 0x74: a[o++] = 0x09; break; // \t
  3279. case 0x62: a[o++] = 0x08; break; // \b
  3280. case 0x58: // x
  3281. case 0x78: { // X
  3282. const xsi = i - 1;
  3283. const xso = o;
  3284. for (let xi = 0; xi < 2; xi++) {
  3285. if (i >= length) {
  3286. i = xsi;
  3287. o = xso;
  3288. a[o] = 0x5c;
  3289. break;
  3290. }
  3291. let c = token.charCodeAt(i++);
  3292. if (c >= 65 && c <= 70) {
  3293. c -= 55;
  3294. } else if (c >= 97 && c <= 102) {
  3295. c -= 87;
  3296. } else if (c >= 48 && c <= 57) {
  3297. c -= 48;
  3298. } else {
  3299. c = -1;
  3300. }
  3301. if (c === -1) {
  3302. i = xsi;
  3303. o = xso;
  3304. a[o] = 0x5c;
  3305. break;
  3306. }
  3307. a[o] = a[o] << 4 | c;
  3308. }
  3309. o++;
  3310. break;
  3311. }
  3312. default:
  3313. if (c < 48 || c > 57) { // 0-9
  3314. a[o++] = 0x5c;
  3315. a[o++] = c;
  3316. } else {
  3317. i--;
  3318. const osi = i;
  3319. const oso = o;
  3320. for (let oi = 0; oi < 3; oi++) {
  3321. if (i >= length) {
  3322. i = osi;
  3323. o = oso;
  3324. a[o] = 0x5c;
  3325. break;
  3326. }
  3327. const od = token.charCodeAt(i++);
  3328. if (od < 48 || od > 57) {
  3329. i = osi;
  3330. o = oso;
  3331. a[o] = 0x5c;
  3332. break;
  3333. }
  3334. a[o] = a[o] << 3 | od - 48;
  3335. }
  3336. o++;
  3337. }
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. return a.slice(0, o);
  3343. }
  3344. });
  3345. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3346. static __new__(/* subtype, data, dtype, copy */) {
  3347. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3348. }
  3349. });
  3350. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3351. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3352. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3353. super(data.shape, data.dtype, data.data);
  3354. }
  3355. });
  3356. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3357. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3358. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3359. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3360. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3361. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3362. __setstate__(state) {
  3363. [this._dtype, this._ndarray] = state;
  3364. Object.assign(this, Object.fromEntries(state[2]));
  3365. }
  3366. });
  3367. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3368. __setstate__(state) {
  3369. [this._dtype, this._ndarray] = state;
  3370. Object.assign(this, Object.fromEntries(state[2]));
  3371. }
  3372. });
  3373. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3374. __setstate__(state) {
  3375. [this._dtype, this._ndarray] = state;
  3376. Object.assign(this, Object.fromEntries(state[2]));
  3377. }
  3378. });
  3379. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3380. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3381. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3382. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3383. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3384. this.registerType('pandas.core.generic.Flags', class {});
  3385. this.registerType('pandas.core.generic.NDFrame', class {
  3386. constructor(data) {
  3387. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3388. this._metadata = [];
  3389. builtins.object.__setattr__(self, "_mgr", data);
  3390. builtins.object.__setattr__(self, "_attrs", {});
  3391. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3392. }
  3393. __setstate__(state) {
  3394. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3395. this._mgr = state;
  3396. } else if (state instanceof builtins.dict) {
  3397. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3398. state.__setitem__('_mgr', state.pop('_data'));
  3399. }
  3400. const typ = state.get('_typ');
  3401. if (typ) {
  3402. let attrs = state.get('_attrs', new builtins.dict());
  3403. if (!attrs) {
  3404. attrs = new builtins.dict();
  3405. }
  3406. builtins.object.__setattr__(this, '_attrs', attrs);
  3407. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3408. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3409. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3410. for (const k of meta) {
  3411. if (state.__contains__(k) && k !== '_flags') {
  3412. const v = state.__getitem__(k);
  3413. builtins.object.__setattr__(this, k, v);
  3414. }
  3415. }
  3416. for (const [k, v] of state) {
  3417. if (!meta.has(k)) {
  3418. builtins.object.__setattr__(this, k, v);
  3419. }
  3420. }
  3421. } else {
  3422. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3423. }
  3424. } else if (state.size === 2) {
  3425. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3426. }
  3427. }
  3428. });
  3429. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3430. });
  3431. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3432. return new cls(d);
  3433. });
  3434. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3435. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3436. this.registerType('pandas.core.indexes.base.Index', class {});
  3437. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3438. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3439. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3440. this.registerType('pandas.core.index.Int64Index', class {});
  3441. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3442. });
  3443. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3444. });
  3445. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3446. return pandas.core.internals.blocks.NumpyBlock;
  3447. });
  3448. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3449. return values;
  3450. });
  3451. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3452. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3453. return new klass(values, ndim, placement, refs);
  3454. });
  3455. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3456. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3457. this.registerType('pandas.core.series.Series', class {});
  3458. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3459. const obj = new cls();
  3460. if (state && obj.__setstate__) {
  3461. obj.__setstate__(state);
  3462. }
  3463. return obj;
  3464. });
  3465. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3466. const obj = new cls();
  3467. if (state && obj.__setstate__) {
  3468. obj.__setstate__(state);
  3469. }
  3470. return obj;
  3471. });
  3472. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3473. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3474. // if not isinstance(placement, BlockPlacement):
  3475. // placement = BlockPlacement(placement)
  3476. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3477. });
  3478. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3479. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3480. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3481. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3482. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3483. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3484. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3485. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3486. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3487. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3488. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3489. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3490. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3491. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3492. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3493. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3494. this.registerType('pathlib.Path', class {});
  3495. this.registerType('pathlib._local.PosixPath', class {});
  3496. this.registerType('pathlib._local.WindowsPath', class {});
  3497. const pathlib = this.register('pathlib');
  3498. pathlib.PosixPath = pathlib._local.PosixPath;
  3499. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3500. this.registerType('shap._serializable.Serializable', class {});
  3501. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3502. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3503. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3504. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3505. this.registerType('sklearn._loss.link.BaseLink', class {});
  3506. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3507. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3508. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3509. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3510. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3511. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3512. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3513. this.registerType('sklearn._loss.link.Interval', class {});
  3514. this.registerType('sklearn._loss.link.LogitLink', class {});
  3515. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3516. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3517. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3518. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3519. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3520. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3521. this.registerType('sklearn.base.BaseEstimator', class {});
  3522. this.registerType('sklearn.base.TransformerMixin', class {});
  3523. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3524. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3525. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3526. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3527. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3528. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3529. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3530. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3531. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3532. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3533. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3534. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3535. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3536. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3537. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3538. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3539. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3540. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3541. this.registerType('sklearn.decomposition.PCA', class {});
  3542. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3543. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3544. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3545. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3546. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3547. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3548. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3549. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3550. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3551. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3552. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3553. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3554. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3555. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3556. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3557. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3558. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3559. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3560. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3561. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3562. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3563. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3564. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3565. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3566. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3567. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3568. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3569. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3570. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3571. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3572. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3573. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3574. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3575. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3576. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3577. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3578. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3579. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3580. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3581. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3582. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3583. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3584. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3585. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3586. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3587. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3588. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3589. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3590. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3591. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3592. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3593. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3594. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3595. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3596. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3597. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3598. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3599. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3600. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3601. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3602. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3603. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3604. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3605. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3606. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3607. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3608. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3609. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3610. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3611. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3612. this.registerType('sklearn.impute.SimpleImputer', class {});
  3613. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3614. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3615. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3616. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3617. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3618. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3619. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3620. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3621. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3622. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3623. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3624. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3625. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3626. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3627. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3628. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3629. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3630. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3631. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3632. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3633. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3634. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3635. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3636. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3637. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3638. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3639. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3640. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3641. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3642. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3643. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3644. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3645. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3646. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3647. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3648. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3649. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3650. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3651. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3652. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3653. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3654. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3655. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3656. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3657. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3658. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3659. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3660. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3661. this.registerType('sklearn.model_selection._split.KFold', class {});
  3662. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3663. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3664. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3665. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3666. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3667. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3668. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3669. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3670. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3671. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3672. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3673. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3674. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3675. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3676. return obj.__new__(obj);
  3677. });
  3678. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3679. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3680. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3681. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3682. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3683. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3684. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3685. return obj.__new__(obj);
  3686. });
  3687. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3688. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3689. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3690. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3691. return obj.__new__(obj);
  3692. });
  3693. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3694. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3695. return obj.__new__(obj);
  3696. });
  3697. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3698. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3699. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3700. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3701. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3702. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3703. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3704. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3705. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3706. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3707. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3708. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3709. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3710. this.registerType('sklearn.pipeline.Pipeline', class {});
  3711. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3712. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3713. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3714. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3715. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3716. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3717. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3718. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3719. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3720. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3721. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3722. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3723. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3724. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3725. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3726. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3727. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3728. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3729. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3730. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3731. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3732. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3733. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3734. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3735. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3736. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3737. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3738. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3739. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3740. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3741. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3742. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3743. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3744. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3745. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3746. this.registerType('sklearn.svm._classes.SVC', class {});
  3747. this.registerType('sklearn.svm._classes.SVR', class {});
  3748. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3749. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3750. this.registerType('sklearn.svm.classes.SVC', class {});
  3751. this.registerType('sklearn.svm.classes.SVR', class {});
  3752. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3753. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3754. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3755. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3756. this.registerType('sklearn.tree._tree.Tree', class {
  3757. constructor(n_features, n_classes, n_outputs) {
  3758. this.n_features = n_features;
  3759. this.n_classes = n_classes;
  3760. this.n_outputs = n_outputs;
  3761. }
  3762. __setstate__(state) {
  3763. this.max_depth = state.get('max_depth');
  3764. this.node_count = state.get('node_count');
  3765. this.nodes = state.get('nodes');
  3766. this.values = state.get('values');
  3767. }
  3768. });
  3769. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3770. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3771. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3772. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3773. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3774. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3775. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3776. this.registerType('pickle.Unpickler', class {
  3777. constructor(data) {
  3778. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3779. this.persistent_load = () => {
  3780. throw new python.Error('Unsupported persistent id.');
  3781. };
  3782. }
  3783. load() {
  3784. const reader = this._reader;
  3785. const marker = [];
  3786. let stack = [];
  3787. const memo = {};
  3788. let size = 0;
  3789. while (reader.position < reader.length) {
  3790. const opcode = reader.byte();
  3791. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3792. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3793. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3794. switch (opcode) {
  3795. case 128: { // PROTO
  3796. const version = reader.byte();
  3797. if (version > 5) {
  3798. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3799. }
  3800. break;
  3801. }
  3802. case 99: { // GLOBAL 'c'
  3803. const module = reader.line();
  3804. const name = reader.line();
  3805. stack.push(this.find_class(module, name));
  3806. break;
  3807. }
  3808. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3809. const name = stack.pop();
  3810. const module = stack.pop();
  3811. stack.push(this.find_class(module, name));
  3812. break;
  3813. }
  3814. case 111: { // OBJ 'o'
  3815. const args = stack;
  3816. const cls = args.pop();
  3817. stack = marker.pop();
  3818. const obj = this._instantiate(cls, args);
  3819. stack.push(obj);
  3820. break;
  3821. }
  3822. case 112 : { // PUT 'p'
  3823. const index = parseInt(reader.line(), 10);
  3824. if (stack.length === 0) {
  3825. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3826. }
  3827. memo[index] = stack[stack.length - 1];
  3828. size++;
  3829. break;
  3830. }
  3831. case 103: { // GET 'g'
  3832. const index = parseInt(reader.line(), 10);
  3833. stack.push(memo[index]);
  3834. break;
  3835. }
  3836. case 48: // POP '0'
  3837. stack.pop();
  3838. break;
  3839. case 49: // POP_MARK '1'
  3840. stack = marker.pop();
  3841. break;
  3842. case 50: // DUP '2'
  3843. if (stack.length === 0) {
  3844. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3845. }
  3846. stack.push(stack[stack.length - 1]);
  3847. break;
  3848. case 80: // PERSID 'P'
  3849. stack.push(this.persistent_load(reader.line()));
  3850. break;
  3851. case 81: // BINPERSID 'Q'
  3852. stack.push(this.persistent_load(stack.pop()));
  3853. break;
  3854. case 82: { // REDUCE 'R'
  3855. const args = stack.pop();
  3856. const func = stack.pop();
  3857. stack.push(this._reduce(func, args));
  3858. break;
  3859. }
  3860. case 129: { // NEWOBJ
  3861. const args = stack.pop();
  3862. const cls = stack.pop();
  3863. const obj = this._newobj(cls, args);
  3864. stack.push(obj);
  3865. break;
  3866. }
  3867. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3868. const kwargs = stack.pop();
  3869. const args = stack.pop();
  3870. const cls = stack.pop();
  3871. if (Object.entries(kwargs).length > 0) {
  3872. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3873. }
  3874. const obj = this._newobj(cls, args);
  3875. stack.push(obj);
  3876. break;
  3877. }
  3878. case 104: // BINGET 'h'
  3879. stack.push(memo[reader.byte()]);
  3880. break;
  3881. case 105: { // INST 'i'
  3882. const module = reader.line();
  3883. const name = reader.line();
  3884. const args = stack;
  3885. const cls = `${module}.${name}`;
  3886. stack = marker.pop();
  3887. // cls = this.find_class(module, name)
  3888. const obj = this._instantiate(cls, args);
  3889. stack.push(obj);
  3890. break;
  3891. }
  3892. case 106: // LONG_BINGET 'j'
  3893. stack.push(memo[reader.uint32()]);
  3894. break;
  3895. case 113: // BINPUT 'q'
  3896. if (stack.length === 0) {
  3897. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3898. }
  3899. memo[reader.byte()] = stack[stack.length - 1];
  3900. size++;
  3901. break;
  3902. case 114: // LONG_BINPUT 'r'
  3903. if (stack.length === 0) {
  3904. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3905. }
  3906. memo[reader.uint32()] = stack[stack.length - 1];
  3907. size++;
  3908. break;
  3909. case 74: // BININT 'J'
  3910. stack.push(reader.int32());
  3911. break;
  3912. case 75: // BININT1 'K'
  3913. stack.push(reader.byte());
  3914. break;
  3915. case 76: // LONG 'L'
  3916. stack.push(parseInt(reader.line(), 10));
  3917. break;
  3918. case 77: // BININT2 'M'
  3919. stack.push(reader.uint16());
  3920. break;
  3921. case 66: // BINBYTES 'B' (Protocol 3)
  3922. stack.push(reader.read(reader.int32()));
  3923. break;
  3924. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3925. stack.push(reader.read(reader.byte()));
  3926. break;
  3927. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3928. stack.push(reader.read(reader.int64().toNumber()));
  3929. break;
  3930. case 70: // FLOAT 'F'
  3931. stack.push(parseFloat(reader.line()));
  3932. break;
  3933. case 71: // BINFLOAT 'G'
  3934. stack.push(reader.float64());
  3935. break;
  3936. case 73: { // INT 'I'
  3937. const value = reader.line();
  3938. if (value === '01') {
  3939. stack.push(true);
  3940. } else if (value === '00') {
  3941. stack.push(false);
  3942. } else {
  3943. stack.push(parseInt(value, 10));
  3944. }
  3945. break;
  3946. }
  3947. case 93: // EMPTY_LIST ']'
  3948. stack.push(new builtins.list());
  3949. break;
  3950. case 41: // EMPTY_TUPLE ')'
  3951. stack.push([]);
  3952. break;
  3953. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3954. stack.push([]);
  3955. break;
  3956. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3957. const items = stack;
  3958. stack = marker.pop();
  3959. const obj = stack[stack.length - 1];
  3960. for (let i = 0; i < items.length; i++) {
  3961. obj.push(items[i]);
  3962. }
  3963. break;
  3964. }
  3965. case 145: { // FROZENSET '\x91' (Protocol 4)
  3966. const items = stack;
  3967. stack = marker.pop();
  3968. stack.push(items);
  3969. break;
  3970. }
  3971. case 100: { // DICT 'd'
  3972. const items = stack;
  3973. stack = marker.pop();
  3974. const dict = new builtins.dict();
  3975. for (let i = 0; i < items.length; i += 2) {
  3976. dict.__setitem__(items[i], items[i + 1]);
  3977. }
  3978. stack.push(dict);
  3979. break;
  3980. }
  3981. case 108: { // LIST 'l'
  3982. const items = stack;
  3983. stack = marker.pop();
  3984. stack.push(items);
  3985. break;
  3986. }
  3987. case 116: { // TUPLE 't'
  3988. const items = stack;
  3989. stack = marker.pop();
  3990. stack.push(items);
  3991. break;
  3992. }
  3993. case 133: { // TUPLE1 // '\x85'
  3994. stack.push([stack.pop()]);
  3995. break;
  3996. }
  3997. case 134: { // TUPLE2 '\x86'
  3998. const b = stack.pop();
  3999. const a = stack.pop();
  4000. stack.push([a, b]);
  4001. break;
  4002. }
  4003. case 135: { // TUPLE3 '\x87'
  4004. const c = stack.pop();
  4005. const b = stack.pop();
  4006. const a = stack.pop();
  4007. stack.push([a, b, c]);
  4008. break;
  4009. }
  4010. case 115: { // SETITEM 's'
  4011. const value = stack.pop();
  4012. const key = stack.pop();
  4013. const obj = stack[stack.length - 1];
  4014. if (obj.__setitem__) {
  4015. obj.__setitem__(key, value);
  4016. } else {
  4017. obj[key] = value;
  4018. }
  4019. break;
  4020. }
  4021. case 117: { // SETITEMS 'u'
  4022. const items = stack;
  4023. stack = marker.pop();
  4024. const obj = stack[stack.length - 1];
  4025. if (obj.__setitem__) {
  4026. for (let i = 0; i < items.length; i += 2) {
  4027. obj.__setitem__(items[i], items[i + 1]);
  4028. }
  4029. } else {
  4030. for (let i = 0; i < items.length; i += 2) {
  4031. obj[items[i]] = items[i + 1];
  4032. }
  4033. }
  4034. break;
  4035. }
  4036. case 125: // EMPTY_DICT '}'
  4037. stack.push(new builtins.dict());
  4038. break;
  4039. case 97: { // APPEND 'a'
  4040. const append = stack.pop();
  4041. stack[stack.length - 1].push(append);
  4042. break;
  4043. }
  4044. case 101: { // APPENDS 'e'
  4045. const appends = stack;
  4046. stack = marker.pop();
  4047. const list = stack[stack.length - 1];
  4048. list.push(...appends);
  4049. break;
  4050. }
  4051. case 83: { // STRING 'S'
  4052. const str = reader.line();
  4053. stack.push(str.substring(1, str.length - 1));
  4054. break;
  4055. }
  4056. case 84: // BINSTRING 'T'
  4057. stack.push(reader.string(reader.uint32()));
  4058. break;
  4059. case 85 : // SHORT_BINSTRING 'U'
  4060. stack.push(reader.string(reader.byte()));
  4061. break;
  4062. case 86: // UNICODE 'V'
  4063. stack.push(reader.line());
  4064. break;
  4065. case 88: // BINUNICODE 'X
  4066. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4067. break;
  4068. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4069. stack.push(reader.string(reader.byte(), 'utf-8'));
  4070. break;
  4071. case 98: { // BUILD 'b'
  4072. const state = stack.pop();
  4073. let obj = stack.pop();
  4074. if (obj.__setstate__) {
  4075. if (obj.__setstate__.__call__) {
  4076. obj.__setstate__.__call__([obj, state]);
  4077. } else {
  4078. obj.__setstate__(state);
  4079. }
  4080. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4081. obj.__state__ = state;
  4082. } else if (obj instanceof Map && state instanceof Map) {
  4083. for (const [key, value] of state) {
  4084. obj.set(key, value);
  4085. }
  4086. } else if (obj instanceof Map) {
  4087. /* eslint-disable guard-for-in */
  4088. for (const key in state) {
  4089. obj.set(key, state[key]);
  4090. }
  4091. /* eslint-enable guard-for-in */
  4092. } else if (state instanceof Map) {
  4093. for (const [key, value] of state) {
  4094. obj[key] = value;
  4095. }
  4096. } else {
  4097. Object.assign(obj, state);
  4098. }
  4099. if (obj.__read__) {
  4100. obj = obj.__read__(this);
  4101. }
  4102. stack.push(obj);
  4103. break;
  4104. }
  4105. case 40: // MARK '('
  4106. marker.push(stack);
  4107. stack = [];
  4108. break;
  4109. case 136: // NEWTRUE '\x88'
  4110. stack.push(true);
  4111. break;
  4112. case 137: // NEWFALSE '\x89'
  4113. stack.push(false);
  4114. break;
  4115. case 138: { // LONG1 '\x8a'
  4116. const data = reader.read(reader.byte());
  4117. let number = 0;
  4118. switch (data.length) {
  4119. case 0: number = 0; break;
  4120. case 1: [number] = data; break;
  4121. case 2: number = data[1] << 8 | data[0]; break;
  4122. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4123. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  4124. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4125. default: number = Array.prototype.slice.call(data, 0); break;
  4126. }
  4127. stack.push(number);
  4128. break;
  4129. }
  4130. case 139: // LONG4 '\x8b'
  4131. // decode LONG4
  4132. stack.push(reader.read(reader.uint32()));
  4133. break;
  4134. case 148: // MEMOIZE '\x94' (Protocol 4)
  4135. memo[size++] = stack[stack.length - 1];
  4136. break;
  4137. case 149: // FRAME '\x95' (Protocol 4)
  4138. reader.read(8);
  4139. break;
  4140. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4141. stack.push(reader.read(reader.int64().toNumber()));
  4142. break;
  4143. }
  4144. case 78: // NONE 'N'
  4145. stack.push(null);
  4146. break;
  4147. case 46: // STOP '.'
  4148. return stack.pop();
  4149. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4150. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4151. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4152. default:
  4153. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4154. }
  4155. }
  4156. throw new python.Error('Unexpected end of file.');
  4157. }
  4158. find_class(module, name) {
  4159. execution.__import__(module);
  4160. return execution.resolve(`${module}.${name}`);
  4161. }
  4162. _instantiate(cls, args) {
  4163. return execution.invoke(cls, args);
  4164. }
  4165. _newobj(cls, args) {
  4166. // cls.__new__(cls, args)
  4167. return execution.invoke(cls, args);
  4168. }
  4169. _reduce(func, args) {
  4170. return execution.invoke(func, args);
  4171. }
  4172. read(size) {
  4173. return this._reader.read(size);
  4174. }
  4175. stream(size) {
  4176. return this._reader.stream(size);
  4177. }
  4178. });
  4179. this.registerType('random.Random', class {});
  4180. this.registerType('re.Pattern', class {
  4181. constructor(pattern, flags) {
  4182. this.pattern = pattern;
  4183. this.flags = flags;
  4184. }
  4185. });
  4186. this.registerType('spacy._ml.PrecomputableAffine', class {
  4187. __setstate__(state) {
  4188. Object.assign(this, new pickle.Unpickler(state).load());
  4189. }
  4190. });
  4191. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4192. __setstate__(state) {
  4193. Object.assign(this, new pickle.Unpickler(state).load());
  4194. }
  4195. });
  4196. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4197. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4198. this.registerType('theano.compile.function_module.Function', class {});
  4199. this.registerType('theano.compile.function_module.Supervisor', class {});
  4200. this.registerType('theano.compile.io.In', class {});
  4201. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4202. this.registerType('theano.compile.mode.Mode', class {});
  4203. this.registerType('theano.compile.ops.OutputGuard', class {});
  4204. this.registerType('theano.compile.ops.Shape', class {});
  4205. this.registerType('theano.compile.ops.Shape_i', class {});
  4206. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4207. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4208. this.registerType('theano.gof.graph.Apply', class {});
  4209. this.registerType('theano.gof.link.Container', class {});
  4210. this.registerType('theano.gof.opt._metadict', class {});
  4211. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4212. this.registerType('theano.gof.opt.MergeFeature', class {});
  4213. this.registerType('theano.gof.optdb.Query', class {});
  4214. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4215. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4216. this.registerType('theano.gof.utils.scratchpad', class {});
  4217. this.registerType('theano.misc.ordered_set.Link', class {});
  4218. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4219. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4220. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4221. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4222. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4223. this.registerType('theano.scalar.basic.Abs', class {});
  4224. this.registerType('theano.scalar.basic.Add', class {});
  4225. this.registerType('theano.scalar.basic.Cast', class {});
  4226. this.registerType('theano.scalar.basic.Composite', class {});
  4227. this.registerType('theano.scalar.basic.EQ', class {});
  4228. this.registerType('theano.scalar.basic.GE', class {});
  4229. this.registerType('theano.scalar.basic.Identity', class {});
  4230. this.registerType('theano.scalar.basic.IntDiv', class {});
  4231. this.registerType('theano.scalar.basic.Inv', class {});
  4232. this.registerType('theano.scalar.basic.LE', class {});
  4233. this.registerType('theano.scalar.basic.LT', class {});
  4234. this.registerType('theano.scalar.basic.Mul', class {});
  4235. this.registerType('theano.scalar.basic.Neg', class {});
  4236. this.registerType('theano.scalar.basic.Pow', class {});
  4237. this.registerType('theano.scalar.basic.Scalar', class {});
  4238. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4239. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4240. this.registerType('theano.scalar.basic.Second', class {});
  4241. this.registerType('theano.scalar.basic.Sgn', class {});
  4242. this.registerType('theano.scalar.basic.specific_out', class {});
  4243. this.registerType('theano.scalar.basic.Sub', class {});
  4244. this.registerType('theano.scalar.basic.Switch', class {});
  4245. this.registerType('theano.scalar.basic.Tanh', class {});
  4246. this.registerType('theano.scalar.basic.transfer_type', class {});
  4247. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4248. this.registerType('theano.tensor.basic.Alloc', class {});
  4249. this.registerType('theano.tensor.basic.Dot', class {});
  4250. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4251. this.registerType('theano.tensor.basic.Reshape', class {});
  4252. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4253. this.registerType('theano.tensor.blas.Dot22', class {});
  4254. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4255. this.registerType('theano.tensor.blas.Gemm', class {});
  4256. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4257. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4258. this.registerType('theano.tensor.elemwise.Sum', class {});
  4259. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4260. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4261. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4262. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4263. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4264. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4265. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4266. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4267. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4268. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4269. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4270. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4271. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4272. this.registerType('theano.tensor.opt.MakeVector', class {});
  4273. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4274. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4275. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4276. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4277. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4278. this.registerType('theano.tensor.type.TensorType', class {});
  4279. this.registerType('theano.tensor.var.TensorConstant', class {});
  4280. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4281. this.registerType('theano.tensor.var.TensorVariable', class {});
  4282. this.registerType('thinc.describe.Biases', class {});
  4283. this.registerType('thinc.describe.Dimension', class {});
  4284. this.registerType('thinc.describe.Gradient', class {});
  4285. this.registerType('thinc.describe.Weights', class {});
  4286. this.registerType('thinc.describe.Synapses', class {});
  4287. this.registerType('thinc.neural._classes.affine.Affine', class {
  4288. __setstate__(state) {
  4289. Object.assign(this, new pickle.Unpickler(state).load());
  4290. }
  4291. });
  4292. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4293. __setstate__(state) {
  4294. Object.assign(this, new pickle.Unpickler(state).load());
  4295. }
  4296. });
  4297. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4298. __setstate__(state) {
  4299. Object.assign(this, new pickle.Unpickler(state).load());
  4300. }
  4301. });
  4302. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4303. __setstate__(state) {
  4304. Object.assign(this, new pickle.Unpickler(state).load());
  4305. }
  4306. });
  4307. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4308. __setstate__(state) {
  4309. Object.assign(this, new pickle.Unpickler(state).load());
  4310. }
  4311. });
  4312. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4313. __setstate__(state) {
  4314. Object.assign(this, new pickle.Unpickler(state).load());
  4315. }
  4316. });
  4317. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4318. __setstate__(state) {
  4319. Object.assign(this, new pickle.Unpickler(state).load());
  4320. }
  4321. });
  4322. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4323. __setstate__(state) {
  4324. Object.assign(this, new pickle.Unpickler(state).load());
  4325. }
  4326. });
  4327. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4328. __setstate__(state) {
  4329. Object.assign(this, new pickle.Unpickler(state).load());
  4330. }
  4331. });
  4332. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4333. __setstate__(state) {
  4334. Object.assign(this, new pickle.Unpickler(state).load());
  4335. }
  4336. });
  4337. this.registerType('thinc.neural.mem.Memory', class {
  4338. });
  4339. this.registerType('thinc.neural.ops.NumpyOps', class {
  4340. });
  4341. this.registerType('__main__.BYOLState', class {
  4342. constructor(dict) {
  4343. Object.assign(this, dict);
  4344. }
  4345. });
  4346. const types = this.register('types');
  4347. this.registerType('types.GenericAlias', class {});
  4348. this.registerType('types.SimpleNamespace', class {});
  4349. this.registerType('types.BuiltinFunctionType', class {});
  4350. this.registerType('types.BuiltinMethodType', class {});
  4351. this.registerFunction('types.resolve_bases', (bases) => {
  4352. return bases;
  4353. });
  4354. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4355. if (kwds) {
  4356. kwds = new builtins.dict(kwds);
  4357. } else {
  4358. kwds = new builtins.dict();
  4359. }
  4360. let meta = null;
  4361. if (kwds.__contains__('metaclass')) {
  4362. meta = kwds.pop('metaclass');
  4363. } else if (bases && bases.length > 0) {
  4364. meta = builtins.type(bases[0]);
  4365. } else {
  4366. meta = builtins.type;
  4367. }
  4368. if (meta instanceof builtins.type) {
  4369. meta = types._calculate_meta(meta, bases);
  4370. }
  4371. let ns = null;
  4372. if (builtins.hasattr(meta, '__prepare__')) {
  4373. // ns = meta.__prepare__(name, bases, **kwds)
  4374. } else {
  4375. ns = new builtins.dict();
  4376. }
  4377. return [meta, ns, kwds];
  4378. });
  4379. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4380. const winner = meta;
  4381. return winner;
  4382. });
  4383. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4384. const resolved_bases = types.resolve_bases(bases);
  4385. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4386. if (exec_body) {
  4387. exec_body(ns);
  4388. }
  4389. return new meta(name, resolved_bases, ns);
  4390. });
  4391. types.ObjectType = builtins.object;
  4392. types.ModuleType = builtins.module;
  4393. types.MethodType = builtins.method;
  4394. types.FunctionType = builtins.function;
  4395. types.TypeType = builtins.type;
  4396. types.CodeType = builtins.code;
  4397. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4398. this.registerType('xgboost.core.Booster', class {
  4399. load_model(fname) {
  4400. if (fname instanceof Uint8Array) {
  4401. // XGBoosterLoadModel()
  4402. } else {
  4403. // XGBoosterUnserializeFromBuffer(handle) {
  4404. }
  4405. }
  4406. __setstate__(state) {
  4407. const handle = state.get('handle');
  4408. if (handle) {
  4409. this.handle = handle;
  4410. // XGBoosterLoadModelFromBuffer()
  4411. }
  4412. }
  4413. });
  4414. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4415. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4416. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4417. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4418. return new builtins.bytearray(obj, encoding);
  4419. });
  4420. this.registerType('builtins.bytearray', class extends Uint8Array {
  4421. constructor(source, encoding /*, errors */) {
  4422. source = builtins.bytes.__encode__(source, encoding);
  4423. super(Number.isInteger(source) ? source : source.length);
  4424. if (Array.isArray(source)) {
  4425. for (let i = 0; i < source.length; i++) {
  4426. this[i] = source;
  4427. }
  4428. } else if (source instanceof Uint8Array) {
  4429. this.set(source, 0);
  4430. } else if (typeof source === 'string') {
  4431. for (let i = 0; i < source.length; i++) {
  4432. this[i] = source.charCodeAt(i);
  4433. }
  4434. }
  4435. }
  4436. static __encode__(source, encoding) {
  4437. if (source === undefined) {
  4438. return 0;
  4439. }
  4440. if (Number.isInteger(source)) {
  4441. return source;
  4442. }
  4443. if (Array.isArray(source) || source instanceof Uint8Array) {
  4444. return source;
  4445. }
  4446. if (typeof source === 'string') {
  4447. switch (encoding) {
  4448. case 'latin1':
  4449. case 'latin-1':
  4450. return source;
  4451. case 'utf8':
  4452. case 'utf-8':
  4453. return new TextEncoder('utf-8').encode(source);
  4454. case undefined:
  4455. throw new python.Error('Unsupported string argument without an encoding.');
  4456. default:
  4457. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4458. }
  4459. }
  4460. throw new python.Error('Unsupported source.');
  4461. }
  4462. });
  4463. this.registerType('builtins.bytes', class extends Uint8Array {
  4464. constructor(source, encoding /*, errors */) {
  4465. source = builtins.bytes.__encode__(source, encoding);
  4466. super(Number.isInteger(source) ? source : source.length);
  4467. if (Array.isArray(source)) {
  4468. for (let i = 0; i < source.length; i++) {
  4469. this[i] = source;
  4470. }
  4471. } else if (source instanceof Uint8Array) {
  4472. this.set(source, 0);
  4473. } else if (typeof source === 'string') {
  4474. for (let i = 0; i < source.length; i++) {
  4475. this[i] = source.charCodeAt(i);
  4476. }
  4477. }
  4478. }
  4479. static __encode__(source, encoding) {
  4480. if (source === undefined) {
  4481. return 0;
  4482. }
  4483. if (Number.isInteger(source)) {
  4484. return source;
  4485. }
  4486. if (Array.isArray(source) || source instanceof Uint8Array) {
  4487. return source;
  4488. }
  4489. if (typeof source === 'string') {
  4490. switch (encoding) {
  4491. case 'latin1':
  4492. case 'latin-1':
  4493. return source;
  4494. case 'utf8':
  4495. case 'utf-8':
  4496. return new TextEncoder('utf-8').encode(source);
  4497. case undefined:
  4498. throw new python.Error('Unsupported string argument without an encoding.');
  4499. default:
  4500. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4501. }
  4502. }
  4503. throw new python.Error('Unsupported source.');
  4504. }
  4505. });
  4506. this.registerType('builtins.memoryview', class {
  4507. constructor(buf) {
  4508. this._buf = buf;
  4509. }
  4510. get nbytes() {
  4511. return this._buf.length;
  4512. }
  4513. });
  4514. this.registerType('builtins.frozenset', class extends Set {
  4515. constructor(iterable) {
  4516. super();
  4517. if (iterable) {
  4518. for (const item of iterable) {
  4519. this.add(item);
  4520. }
  4521. }
  4522. }
  4523. });
  4524. this.registerFunction('builtins.exec');
  4525. this.registerFunction('builtins.issubclass', (obj, type) => {
  4526. const name = `${type.__module__}.${type.__name__}`;
  4527. if (obj.__module__ && obj.__name__) {
  4528. if (name === `${obj.__module__}.${obj.__name__}`) {
  4529. return true;
  4530. }
  4531. }
  4532. if (obj.__bases__) {
  4533. for (const base of obj.__bases__) {
  4534. if (builtins.issubclass(base, type)) {
  4535. return true;
  4536. }
  4537. }
  4538. }
  4539. return false;
  4540. });
  4541. this.registerFunction('builtins.isinstance', (obj, type) => {
  4542. return obj.__class__ ? builtins.issubclass(obj.__class__, type) : false;
  4543. });
  4544. this.registerFunction('builtins.hasattr', (obj, name) => {
  4545. if (obj instanceof Map && obj.__contains__) {
  4546. return obj.__contains__(name);
  4547. }
  4548. return Object.prototype.hasOwnProperty.call(obj, name);
  4549. });
  4550. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4551. if (obj && obj.__getattr__) {
  4552. return obj.__getattr__(name);
  4553. }
  4554. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4555. return obj[name];
  4556. }
  4557. return defaultValue;
  4558. });
  4559. this.registerFunction('builtins.len', (obj) => {
  4560. return obj.length;
  4561. });
  4562. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4563. obj[name] = value;
  4564. });
  4565. this.registerType('builtins.set', class extends Set {
  4566. __contains__(item) {
  4567. return this.has(item);
  4568. }
  4569. update(iterable) {
  4570. for (const item of iterable) {
  4571. this.add(item);
  4572. }
  4573. }
  4574. });
  4575. this.registerType('builtins.slice', class {
  4576. constructor(start, stop, step) {
  4577. this.start = start;
  4578. this.stop = stop;
  4579. this.step = step;
  4580. }
  4581. });
  4582. this.registerFunction('builtins.hash');
  4583. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4584. return name;
  4585. });
  4586. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4587. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4588. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4589. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4590. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4591. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4592. cell.cell_contents = value;
  4593. }
  4594. return cell;
  4595. });
  4596. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4597. // globals["__builtins__"] = __builtins__
  4598. return new types.FunctionType(code, globals, name, argdefs, closure);
  4599. });
  4600. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4601. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4602. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4603. if (class_tracker_id) {
  4604. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4605. }
  4606. return class_def;
  4607. });
  4608. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4609. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4610. const kwds = { 'metaclass': type_constructor };
  4611. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4612. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4613. });
  4614. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4615. return new builtins.cell();
  4616. });
  4617. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4618. [state] = state;
  4619. let registry = null;
  4620. for (const [attrname, attr] of state.items()) {
  4621. if (attrname === '_abc_impl') {
  4622. registry = attr;
  4623. } else {
  4624. builtins.setattr(obj, attrname, attr);
  4625. }
  4626. }
  4627. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4628. obj.__firstlineno__ = state.get('__firstlineno__');
  4629. }
  4630. if (registry) {
  4631. for (const subclass of registry) {
  4632. obj.register(subclass);
  4633. }
  4634. }
  4635. return obj;
  4636. });
  4637. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4638. const [, slotstate] = state;
  4639. [state] = state;
  4640. // obj.__dict__.update(state)
  4641. /* const obj_globals = */ slotstate.pop('__globals__');
  4642. const obj_closure = slotstate.pop('__closure__');
  4643. slotstate.pop('_cloudpickle_submodules');
  4644. if (obj.__globals__) {
  4645. // obj.__globals__.update(obj_globals);
  4646. // obj.__globals__.__builtins__ = __builtins__;
  4647. }
  4648. if (obj_closure) {
  4649. // let value = null;
  4650. for (let i = 0; i < obj_closure.length; i++) {
  4651. // const cell = obj_closure[i];
  4652. try {
  4653. // value = cell.cell_contents;
  4654. } catch {
  4655. // cell is empty
  4656. }
  4657. // obj.__closure__[i].cell_contents = value;
  4658. }
  4659. }
  4660. for (const [k, v] of slotstate.items()) {
  4661. builtins.setattr(obj, k, v);
  4662. }
  4663. });
  4664. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4665. execution.__import__(name);
  4666. return sys.modules.get(name);
  4667. });
  4668. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4669. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4670. const ray = this.register('ray');
  4671. this.register('ray.cloudpickle.cloudpickle');
  4672. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4673. this.registerType('collections.Counter', class {});
  4674. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4675. return {};
  4676. });
  4677. this.registerFunction('copy.deepcopy');
  4678. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4679. // copyreg._reconstructor in Python 3
  4680. if (base === '__builtin__.object' || base === builtins.object) {
  4681. return self.invoke(cls, []);
  4682. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4683. const obj = self.invoke(cls, []);
  4684. for (let i = 0; i < state.length; i++) {
  4685. obj[i] = state[i];
  4686. }
  4687. return obj;
  4688. }
  4689. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4690. });
  4691. this.registerFunction('copy.deepcopy', (/* x */) => {
  4692. throw new python.Error('Unsupported copy.deepcopy().');
  4693. });
  4694. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4695. const array = f(...args);
  4696. if (array.__setstate__) {
  4697. array.__setstate__(state);
  4698. }
  4699. if (npdict) {
  4700. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4701. }
  4702. return array;
  4703. });
  4704. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4705. return function() {
  4706. };
  4707. });
  4708. this.registerFunction('dill._dill._create_code', (args) => {
  4709. return self.invoke('types.CodeType', [args]);
  4710. });
  4711. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4712. return function() {
  4713. };
  4714. });
  4715. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4716. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4717. if (obj) {
  4718. return obj;
  4719. }
  4720. return undefined;
  4721. });
  4722. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4723. const [name, bases, dict] = args;
  4724. const type = class extends bases[0] {};
  4725. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4726. return self.registerType(identifier, Object.assign(type, dict));
  4727. });
  4728. this.registerFunction('dill._dill._eval_repr');
  4729. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4730. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4731. return self[name];
  4732. }
  4733. return undefined;
  4734. });
  4735. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4736. try {
  4737. if (import_name.startsWith('__runtime__.')) {
  4738. return execution.module(import_name);
  4739. } else if (import_name.indexOf('.') === -1) {
  4740. return execution.__import__(import_name);
  4741. }
  4742. return execution.resolve(import_name);
  4743. } catch (error) {
  4744. if (safe) {
  4745. return null;
  4746. }
  4747. throw error;
  4748. }
  4749. });
  4750. this.registerFunction('dill._dill._load_type', (name) => {
  4751. const _dill = self.register('dill._dill');
  4752. if (!_dill._reverse_typemap) {
  4753. _dill._reverse_typemap = new Map();
  4754. for (const name of ['__builtin__', 'types']) {
  4755. const module = self.register(name);
  4756. for (const [name, obj] of Object.entries(module)) {
  4757. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4758. _dill._reverse_typemap.set(name, obj);
  4759. }
  4760. }
  4761. }
  4762. _dill._reverse_typemap.set('PartialType', functools.partial);
  4763. _dill._reverse_typemap.set('CellType', builtins.cell);
  4764. }
  4765. if (!_dill._reverse_typemap.has(name)) {
  4766. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4767. }
  4768. return _dill._reverse_typemap.get(name);
  4769. });
  4770. this.registerFunction('dill._dill.loads');
  4771. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4772. const np_value = fun(...args);
  4773. np_value.__setstate__(arr_state);
  4774. const jnp_value = jax.device_put(np_value);
  4775. jnp_value.aval = jnp_value.aval.update(aval_state);
  4776. return jnp_value;
  4777. });
  4778. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4779. this.registerFunction('jax.device_put', (x) => {
  4780. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4781. return new jax.Array(aval, x.data);
  4782. });
  4783. this.registerType('jax._src.core.AbstractValue', class {});
  4784. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4785. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4786. constructor(shape, dtype, weak_type) {
  4787. super();
  4788. this.shape = shape;
  4789. this.dtype = dtype;
  4790. this.weak_type = weak_type || false;
  4791. }
  4792. update(dict) {
  4793. const shape = dict.get('shape') || this.shape;
  4794. const dtype = dict.get('dtype') || this.dtype;
  4795. const weak_type = dict.get('weak_type') || this.weak_type;
  4796. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4797. }
  4798. });
  4799. this.registerType('jax.Array', class {
  4800. constructor(aval, data) {
  4801. this.aval = aval;
  4802. this.data = data;
  4803. }
  4804. get dtype() {
  4805. return this.aval.dtype;
  4806. }
  4807. get shape() {
  4808. return this.aval.shape;
  4809. }
  4810. tobytes() {
  4811. return this.data;
  4812. }
  4813. });
  4814. jax.numpy.ndarray = jax.Array;
  4815. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4816. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4817. });
  4818. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4819. this.registerFunction('lasagne.nonlinearities.rectify');
  4820. this.registerFunction('lasagne.nonlinearities.softmax');
  4821. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4822. this.registerFunction('lasagne.updates.nesterov_momentum');
  4823. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4824. const BinaryReader = class {
  4825. constructor(buffer, ext_hook) {
  4826. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4827. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4828. this._buffer = buffer;
  4829. this._position = 0;
  4830. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4831. this._ext_hook = ext_hook;
  4832. }
  4833. value() {
  4834. const c = this._view.getUint8(this.skip(1));
  4835. if (c >= 0xe0) {
  4836. return c - 0x100;
  4837. }
  4838. if (c < 0xC0) {
  4839. if (c < 0x80) {
  4840. return c;
  4841. }
  4842. if (c < 0x90) {
  4843. return this.map(c - 0x80);
  4844. }
  4845. if (c < 0xa0) {
  4846. return this.array(c - 0x90);
  4847. }
  4848. return this.string(c - 0xa0);
  4849. }
  4850. switch (c) {
  4851. case 0xC0: return null;
  4852. case 0xC2: return false;
  4853. case 0xC3: return true;
  4854. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4855. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4856. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4857. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4858. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4859. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4860. case 0xCA: return this._view.getFloat32(this.skip(4));
  4861. case 0xCB: return this._view.getFloat64(this.skip(8));
  4862. case 0xCC: return this._view.getUint8(this.skip(1));
  4863. case 0xCD: return this._view.getUint16(this.skip(2));
  4864. case 0xCE: return this._view.getUint32(this.skip(4));
  4865. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4866. case 0xD0: return this._view.getInt8(this.skip(1));
  4867. case 0xD1: return this._view.getInt16(this.skip(2));
  4868. case 0xD2: return this._view.getInt32(this.skip(4));
  4869. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4870. case 0xD4: return this.extension(1);
  4871. case 0xD5: return this.extension(2);
  4872. case 0xD6: return this.extension(4);
  4873. case 0xD7: return this.extension(8);
  4874. case 0xD8: return this.extension(16);
  4875. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4876. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4877. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4878. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4879. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4880. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4881. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4882. default: throw new python.Error(`Invalid code '${c}'.`);
  4883. }
  4884. }
  4885. map(size) {
  4886. const map = {};
  4887. for (let i = 0; i < size; i++) {
  4888. const key = this.value();
  4889. const value = this.value();
  4890. map[key] = value;
  4891. }
  4892. return map;
  4893. }
  4894. array(size) {
  4895. const array = new Array(size);
  4896. for (let i = 0; i < size; i++) {
  4897. array[i] = this.value();
  4898. }
  4899. return array;
  4900. }
  4901. extension(size) {
  4902. const code = this._view.getUint8(this.skip(1));
  4903. const data = this.read(size);
  4904. return this._ext_hook(code, data);
  4905. }
  4906. skip(offset) {
  4907. const position = this._position;
  4908. this._position += offset;
  4909. if (this._position > this._buffer.length) {
  4910. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4911. }
  4912. return position;
  4913. }
  4914. read(size) {
  4915. const data = this._buffer.subarray(this._position, this._position + size);
  4916. this._position += size;
  4917. return data;
  4918. }
  4919. string(size) {
  4920. const buffer = this.read(size);
  4921. this._decoder = this._decoder || new TextDecoder('utf8');
  4922. return this._decoder.decode(buffer);
  4923. }
  4924. };
  4925. return new BinaryReader(packed, ext_hook).value();
  4926. });
  4927. this.registerFunction('nolearn.lasagne.base.objective');
  4928. this.registerFunction('numpy.core._DType_reconstruct');
  4929. this.registerFunction('numpy.core._ufunc_reconstruct');
  4930. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4931. return numpy.ndarray.__new__(subtype, shape, dtype);
  4932. });
  4933. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4934. const shape = [buf.length / dtype.itemsize];
  4935. return new numpy.ndarray(shape, dtype, buf);
  4936. });
  4937. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  4938. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  4939. });
  4940. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4941. return new numpy.dtypes.StringDType();
  4942. });
  4943. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4944. let data = rawData;
  4945. if (typeof rawData === 'string' || rawData instanceof String) {
  4946. data = new Uint8Array(rawData.length);
  4947. for (let i = 0; i < rawData.length; i++) {
  4948. data[i] = rawData.charCodeAt(i);
  4949. }
  4950. }
  4951. switch (dtype.kind) {
  4952. case 'b': {
  4953. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4954. switch (dtype.itemsize) {
  4955. case 1: return view.getInt8(0) ? true : false;
  4956. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  4957. }
  4958. }
  4959. case 'f': {
  4960. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4961. switch (dtype.itemsize) {
  4962. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  4963. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  4964. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  4965. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  4966. }
  4967. }
  4968. case 'i': {
  4969. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4970. switch (dtype.itemsize) {
  4971. case 1: return view.getInt8(0);
  4972. case 2: return view.getInt16(0, dtype.byteorder === '<');
  4973. case 4: return view.getInt32(0, dtype.byteorder === '<');
  4974. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  4975. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  4976. }
  4977. }
  4978. case 'u': {
  4979. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4980. switch (dtype.itemsize) {
  4981. case 1: return view.getUint8(0);
  4982. case 2: return view.getUint16(0, dtype.byteorder === '<');
  4983. case 4: return view.getUint32(0, dtype.byteorder === '<');
  4984. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  4985. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  4986. }
  4987. }
  4988. case 'U': {
  4989. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4990. const list = [];
  4991. for (let i = 0; i < dtype.itemsize; i += 4) {
  4992. list.push(String.fromCodePoint(view.getUint32(i, true)));
  4993. }
  4994. return list.join('');
  4995. }
  4996. default: {
  4997. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  4998. }
  4999. }
  5000. });
  5001. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5002. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5003. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5004. this.registerFunction('numpy.core._multiarray_umath.greater');
  5005. this.registerFunction('numpy.core._multiarray_umath.less');
  5006. this.registerFunction('numpy.core._multiarray_umath.log');
  5007. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5008. let data = rawData;
  5009. if (typeof rawData === 'string') {
  5010. data = new Uint8Array(rawData.length);
  5011. for (let i = 0; i < rawData.length; i++) {
  5012. data[i] = rawData.charCodeAt(i);
  5013. }
  5014. }
  5015. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5016. switch (dtype.__name__) {
  5017. case 'uint8':
  5018. return dataView.getUint8(0);
  5019. case 'float32':
  5020. return dataView.getFloat32(0, true);
  5021. case 'float64':
  5022. return dataView.getFloat64(0, true);
  5023. case 'int8':
  5024. return dataView.getInt8(0, true);
  5025. case 'int16':
  5026. return dataView.getInt16(0, true);
  5027. case 'int32':
  5028. return dataView.getInt32(0, true);
  5029. case 'int64':
  5030. return dataView.getBigInt64(0, true);
  5031. default:
  5032. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5033. }
  5034. });
  5035. this.registerFunction('numpy.core._multiarray_umath.sin');
  5036. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5037. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5038. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5039. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5040. this.register('numpy.core.numeric', numpy._core.numeric);
  5041. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5042. this.registerFunction('numpy.load', (file) => {
  5043. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5044. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5045. if (!file.read(6).every((v, i) => v === signature[i])) {
  5046. throw new python.Error('Invalid signature.');
  5047. }
  5048. const version = file.read(2);
  5049. const [major, minor] = version;
  5050. if (major > 3) {
  5051. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5052. }
  5053. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5054. let data = null;
  5055. switch (dtype.byteorder) {
  5056. case '|': {
  5057. data = file.read();
  5058. if (dtype.kind === 'O') {
  5059. const unpickler = new pickle.Unpickler(data);
  5060. return unpickler.load();
  5061. }
  5062. break;
  5063. }
  5064. case '>':
  5065. case '<': {
  5066. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5067. const stream = file.getbuffer().nbytes > 0x1000000;
  5068. data = file.read(dtype.itemsize * count, stream);
  5069. break;
  5070. }
  5071. default: {
  5072. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5073. }
  5074. }
  5075. if (fortran_order) {
  5076. data = null;
  5077. }
  5078. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5079. });
  5080. this.registerFunction('numpy.save', (file, arr) => {
  5081. const descr = arr.dtype.str;
  5082. if (descr[0] !== '<' && descr[0] !== '>') {
  5083. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5084. }
  5085. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5086. throw new python.Error(`Unsupported data type '${descr}'.`);
  5087. }
  5088. let shape = '';
  5089. switch (arr.shape.length) {
  5090. case 0: shape = '()'; break;
  5091. case 1: shape = `(${arr.shape[0]},)`; break;
  5092. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5093. }
  5094. const properties = [
  5095. `'descr': '${descr}'`,
  5096. "'fortran_order': False",
  5097. `'shape': ${shape}`
  5098. ];
  5099. let header = `{ ${properties.join(', ')} }`;
  5100. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5101. const encoder = new TextEncoder('ascii');
  5102. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5103. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5104. file.write(encoder.encode(header));
  5105. file.write(arr.tobytes());
  5106. });
  5107. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5108. const buffer = new Uint8Array([0, 0, 0, 0]);
  5109. const [major] = version;
  5110. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5111. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5112. let header = file.read(header_length);
  5113. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5114. header = decoder.decode(header).trim();
  5115. try {
  5116. header = ast.literal_eval(header);
  5117. } catch {
  5118. if (major <= 2) {
  5119. header = numpy.lib._format_impl._filter_header(header);
  5120. header = ast.literal_eval(header);
  5121. }
  5122. }
  5123. if (header.descr === undefined) {
  5124. throw new python.Error("Invalid 'descr'.");
  5125. }
  5126. if (!Array.isArray(header.shape)) {
  5127. throw new python.Error("Invalid 'shape'.");
  5128. }
  5129. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5130. return [header.shape, header.fortran_order, dtype];
  5131. });
  5132. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5133. if (typeof descr === 'string') {
  5134. return new numpy.dtype(descr);
  5135. } else if (descr instanceof builtins.tuple) {
  5136. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5137. return new numpy.dtype([dt, descr[1]]);
  5138. }
  5139. const titles = [];
  5140. const names = [];
  5141. const formats = [];
  5142. const offsets = [];
  5143. let offset = 0;
  5144. for (const field of descr) {
  5145. let name = null;
  5146. let dt = null;
  5147. let descr_str = null;
  5148. let shape = null;
  5149. let title = null;
  5150. if (field.length === 2) {
  5151. [name, descr_str] = field;
  5152. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5153. } else {
  5154. [name, descr_str, shape] = field;
  5155. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5156. }
  5157. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5158. if (!is_pad) {
  5159. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5160. titles.push(title);
  5161. names.push(name);
  5162. formats.push(dt);
  5163. offsets.push(offset);
  5164. }
  5165. offset += dt.itemsize;
  5166. }
  5167. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5168. });
  5169. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5170. const tokens = [];
  5171. const tokenizer = new ast._Tokenizer(s, '');
  5172. while (!tokenizer.match('eof')) {
  5173. const token = tokenizer.read();
  5174. if (token.type === 'int') {
  5175. const next = tokenizer.peek();
  5176. if (next.type === 'id' && next.value === 'L') {
  5177. tokenizer.read();
  5178. }
  5179. }
  5180. tokens.push(token.value);
  5181. }
  5182. return tokens.join('');
  5183. });
  5184. this.registerFunction('numpy.amin');
  5185. this.registerFunction('numpy.amax');
  5186. this.registerFunction('numpy.std');
  5187. this.registerFunction('numpy.asarray', (a, dtype) => {
  5188. const encode = (context, data, dim) => {
  5189. const size = context.shape[dim];
  5190. const littleendian = context.littleendian;
  5191. if (dim === context.shape.length - 1) {
  5192. for (let i = 0; i < size; i++) {
  5193. switch (context.dtype) {
  5194. case 'f2':
  5195. context.view.setFloat16(context.position, data[i], littleendian);
  5196. break;
  5197. case 'f4':
  5198. context.view.setFloat32(context.position, data[i], littleendian);
  5199. break;
  5200. case 'f8':
  5201. context.view.setFloat64(context.position, data[i], littleendian);
  5202. break;
  5203. case 'i1':
  5204. context.view.setInt8(context.position, data[i], littleendian);
  5205. break;
  5206. case 'i2':
  5207. context.view.setInt16(context.position, data[i], littleendian);
  5208. break;
  5209. case 'i4':
  5210. context.view.setInt32(context.position, data[i], littleendian);
  5211. break;
  5212. case 'i8':
  5213. context.view.setBigInt64(context.position, data[i], littleendian);
  5214. break;
  5215. case 'u1':
  5216. context.view.setUint8(context.position, data[i], littleendian);
  5217. break;
  5218. case 'u2':
  5219. context.view.setUint16(context.position, data[i], littleendian);
  5220. break;
  5221. case 'u4':
  5222. context.view.setUint32(context.position, data[i], littleendian);
  5223. break;
  5224. case 'u8':
  5225. context.view.setBigUint64(context.position, data[i], littleendian);
  5226. break;
  5227. case 'c8':
  5228. context.view.setComplex64(context.position, data[i], littleendian);
  5229. break;
  5230. case 'c16':
  5231. context.view.setComplex128(context.position, data[i], littleendian);
  5232. break;
  5233. case 'b1':
  5234. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5235. break;
  5236. default:
  5237. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5238. }
  5239. context.position += context.itemsize;
  5240. }
  5241. } else {
  5242. for (let j = 0; j < size; j++) {
  5243. encode(context, data[j], dim + 1);
  5244. }
  5245. }
  5246. };
  5247. const array_size = (value) => {
  5248. if (value.every((item) => Array.isArray(item))) {
  5249. const dims = value.map((item) => array_size(item));
  5250. const [dim] = dims;
  5251. for (let i = 1; i < dims.length; i++) {
  5252. if (dim.length === dims[i].length) {
  5253. if (!dims[i].every((value, i) => value === dim[i])) {
  5254. throw new python.Error('Invalid array shape.');
  5255. }
  5256. }
  5257. }
  5258. return [value.length].concat(dim);
  5259. }
  5260. return [value.length];
  5261. };
  5262. const shape = Array.isArray(a) ? array_size(a) : [];
  5263. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5264. const context = {
  5265. position: 0,
  5266. itemsize: dtype.itemsize,
  5267. dtype: dtype.str.substring(1),
  5268. littleendian: dtype.str[0],
  5269. shape,
  5270. data: new Uint8Array(size)
  5271. };
  5272. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5273. encode(context, a, 0);
  5274. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5275. });
  5276. this.registerFunction('numpy.max');
  5277. this.registerFunction('numpy.mean');
  5278. this.registerFunction('numpy.min');
  5279. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5280. const data = self.invoke(baseclass, [baseshape, basetype]);
  5281. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5282. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5283. return self.invoke(subtype, [data, mask, basetype]);
  5284. });
  5285. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5286. return {};
  5287. });
  5288. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5289. return {};
  5290. });
  5291. this.registerType('numpy.random.bit_generator.BitGenerator', class {});
  5292. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5293. __setstate__(/* state */) {
  5294. }
  5295. });
  5296. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5297. const obj = new cls();
  5298. if (state) {
  5299. obj.__setstate__(state);
  5300. }
  5301. return obj;
  5302. });
  5303. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5304. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5305. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5306. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5307. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5308. numpy.random._pickle.BitGenerators = {
  5309. 'MT19937': numpy.random._mt19937.MT19937,
  5310. 'PCG64': numpy.random._pcg64.PCG64,
  5311. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5312. 'Philox': numpy.random._philox.Philox,
  5313. 'SFC64': numpy.random._sfc64.SFC64,
  5314. };
  5315. this.registerType('numpy.random._generator.Generator', class {
  5316. constructor(bit_generator) {
  5317. this.bit_generator = bit_generator;
  5318. }
  5319. });
  5320. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5321. bit_generator = bit_generator || 'MT19937';
  5322. let bit_gen_class = null;
  5323. if (builtins.isinstance(bit_generator, builtins.type)) {
  5324. bit_gen_class = bit_generator;
  5325. } else {
  5326. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5327. }
  5328. if (bit_gen_class) {
  5329. return new bit_gen_class();
  5330. }
  5331. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5332. });
  5333. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5334. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5335. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5336. });
  5337. this.registerFunction('numpy.reshape');
  5338. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5339. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5340. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5341. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5342. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5343. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5344. this.registerFunction('sklearn.metrics._classification.f1_score');
  5345. this.registerFunction('sklearn.metrics._classification.log_loss');
  5346. this.registerFunction('sklearn.metrics._classification.precision_score');
  5347. this.registerFunction('sklearn.metrics._classification.recall_score');
  5348. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5349. return obj.__new__(obj);
  5350. });
  5351. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5352. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5353. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5354. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5355. this.registerFunction('sklearn.metrics._regression.r2_score');
  5356. sklearn.metrics.regression = sklearn.metrics._regression;
  5357. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5358. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5359. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5360. this.registerFunction('re._compile', (pattern, flags) => {
  5361. return self.invoke('re.Pattern', [pattern, flags]);
  5362. });
  5363. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5364. return function() {
  5365. return self.invoke(`types.${args[0]}`, args);
  5366. };
  5367. });
  5368. this.registerFunction('theano.scalar.basic.same_out');
  5369. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5370. this.registerFunction('theano.scalar.basic.upcast_out');
  5371. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5372. this.registerFunction('theano.tensor.nnet.conv2d');
  5373. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5374. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5375. this.registerType('torch.nn.modules.module.Module', class {
  5376. constructor() {
  5377. this._modules = new collections.OrderedDict();
  5378. this._parameters = new collections.OrderedDict();
  5379. this._buffers = new collections.OrderedDict();
  5380. }
  5381. __setattr__(name, value) {
  5382. if (value instanceof torch.nn.modules.module.Module) {
  5383. this._modules.set(name, value);
  5384. } else {
  5385. this[name] = value;
  5386. }
  5387. }
  5388. __getattr__(name) {
  5389. if (this._modules.has(name)) {
  5390. return this._modules.get(name);
  5391. }
  5392. return this[name];
  5393. }
  5394. __delattr__(name) {
  5395. if (this._modules.has(name)) {
  5396. this._modules.delete(name);
  5397. }
  5398. }
  5399. children() {
  5400. return this._modules.values();
  5401. }
  5402. named_modules(memo, prefix, remove_duplicate) {
  5403. memo = memo || new Set();
  5404. prefix = prefix || '';
  5405. const modules = new builtins.dict();
  5406. if (!memo.has(this)) {
  5407. if (remove_duplicate) {
  5408. memo.add(this);
  5409. }
  5410. modules.set(prefix, this);
  5411. for (const [name, module] of this._modules.items()) {
  5412. if (module && module.named_modules) {
  5413. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5414. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5415. modules.set(k, v);
  5416. }
  5417. }
  5418. }
  5419. }
  5420. return modules;
  5421. }
  5422. named_children() {
  5423. return this._modules;
  5424. }
  5425. parameters() {
  5426. return this._parameters.values();
  5427. }
  5428. named_parameters(recurse) {
  5429. if (recurse) {
  5430. throw new python.Error('Named parameters with recurse not implemented.');
  5431. }
  5432. return this._parameters;
  5433. }
  5434. buffers() {
  5435. return this._buffers.values();
  5436. }
  5437. named_buffers(recurse) {
  5438. if (recurse) {
  5439. throw new python.Error('Named parameters with recurse not implemented.');
  5440. }
  5441. return this._buffers;
  5442. }
  5443. _get_name() {
  5444. return this.__class__.__name__;
  5445. }
  5446. });
  5447. torch.nn.Module = torch.nn.modules.module.Module;
  5448. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5449. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5450. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5451. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5452. this.registerType('torch._C.OperatorRegistry', class {
  5453. constructor() {
  5454. this.to_register = [];
  5455. this.operators = new Map();
  5456. }
  5457. registerPendingOperators() {
  5458. for (const op of this.to_register) {
  5459. const sym = op.schema().name;
  5460. if (!this.operators.has(sym)) {
  5461. this.operators.set(sym, []);
  5462. }
  5463. this.operators.get(sym).push(op);
  5464. }
  5465. this.to_register = [];
  5466. }
  5467. registerOperator(op) {
  5468. this.to_register.push(op);
  5469. }
  5470. getOperators(name) {
  5471. this.registerPendingOperators();
  5472. if (this.operators.has(name)) {
  5473. return this.operators.get(name);
  5474. }
  5475. return [];
  5476. }
  5477. });
  5478. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  5479. return torch._C.getRegistry().getOperators(name);
  5480. });
  5481. this.registerType('torch._C.Operator', class {
  5482. constructor(schema) {
  5483. this._schema = schema;
  5484. }
  5485. schema() {
  5486. return this._schema;
  5487. }
  5488. getOperation(/* node */) {
  5489. return null;
  5490. }
  5491. aliasAnalysisKind() {
  5492. const schemaRef = this.schema();
  5493. const alias_analysis = schemaRef.aliasAnalysis();
  5494. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  5495. return alias_analysis;
  5496. }
  5497. });
  5498. this.registerFunction('torch._C.getRegistry', () => {
  5499. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  5500. return torch._C.r;
  5501. });
  5502. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  5503. const operations = torch._C.getAllOperatorsFor(op_name);
  5504. for (const op of operations) {
  5505. if (op.schema().overload_name === overload_name) {
  5506. return op.schema();
  5507. }
  5508. }
  5509. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  5510. });
  5511. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  5512. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  5513. });
  5514. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  5515. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  5516. if (sortedOps.length === 0) {
  5517. return [null, null];
  5518. }
  5519. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  5520. return [{}, overload_names];
  5521. });
  5522. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  5523. const operations = torch._C.getAllOperatorsFor(op_name);
  5524. for (const op of operations) {
  5525. if (op.schema().overload_name === overload_name) {
  5526. return [{}, {}, null];
  5527. }
  5528. }
  5529. return null;
  5530. });
  5531. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  5532. return null;
  5533. });
  5534. this.registerFunction('torch._C._set_dispatch_mode', () => {
  5535. });
  5536. this.registerType('torch._C.MatchedSchema', class {
  5537. constructor(inputs, return_types, return_field_names, schema_name) {
  5538. this.inputs = inputs;
  5539. this.return_types = return_types;
  5540. this.register_field_names = return_field_names;
  5541. this.schema_name = schema_name;
  5542. }
  5543. });
  5544. this.registerType('torch._C.Self', class {
  5545. });
  5546. this.registerFunction('torch._C.toValues', (g, nvs) => {
  5547. return nvs.map((v) => v.value(g));
  5548. });
  5549. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  5550. constructor(classType) {
  5551. super();
  5552. this._classType = classType;
  5553. }
  5554. makeSugared(v) {
  5555. v.setType(this._classType);
  5556. return new torch._C.SimpleValue(v);
  5557. }
  5558. getClassType() {
  5559. return this._classType;
  5560. }
  5561. });
  5562. this.registerType('torch._C.Function', class {
  5563. isGraphFunction() {
  5564. return false;
  5565. }
  5566. name() {
  5567. return this.qualname().name();
  5568. }
  5569. });
  5570. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  5571. constructor(qualname, schema) {
  5572. super();
  5573. this._name = qualname;
  5574. this._schema = schema;
  5575. }
  5576. qualname() {
  5577. return this._name;
  5578. }
  5579. getSchema() {
  5580. return this._schema;
  5581. }
  5582. ensure_defined() {
  5583. }
  5584. });
  5585. this.registerType('torch._C.DeadCodeEliminator', class {
  5586. constructor(...args) {
  5587. this._aliasDb = null;
  5588. this._useAliasDb = false;
  5589. this._memo = new Map();
  5590. this._marked = new Set();
  5591. this._liveValues = new Set();
  5592. this._deleteCallback = () => {};
  5593. if (args.length > 0 && args[0] instanceof torch.Graph) {
  5594. [this._graph, this._sideEffectPolicy] = args;
  5595. this._useAliasDb = true;
  5596. } else {
  5597. [this._sideEffectPolicy] = args;
  5598. }
  5599. }
  5600. run(block, recurse) {
  5601. this.eliminateDeadForkInputs(block, recurse);
  5602. this.mark(block.return_node());
  5603. this.mark(block);
  5604. this._deleteCallback(this._liveValues);
  5605. this.sweep(block, recurse);
  5606. }
  5607. setDeleteCallback(deleteCallback) {
  5608. this._deleteCallback = deleteCallback;
  5609. }
  5610. eliminateDeadForkInputs(block, recurse) {
  5611. for (const node of block.nodes()) {
  5612. if (recurse) {
  5613. for (const sb of node.blocks()) {
  5614. this.eliminateDeadForkInputs(sb, recurse);
  5615. }
  5616. }
  5617. if (node.kind() !== 'prim::fork') {
  5618. continue;
  5619. }
  5620. const g = node.g("Subgraph");
  5621. for (let i = 0; i < g.inputs().length; i++) {
  5622. if (!g.inputs()[i].hasUses()) {
  5623. g.eraseInput(i);
  5624. node.removeInput(i);
  5625. }
  5626. }
  5627. }
  5628. }
  5629. markReturnNode(node) {
  5630. if (this._marked.has(node)) {
  5631. return false;
  5632. }
  5633. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  5634. const outerNode = node.owningBlock().owningNode();
  5635. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  5636. return this.mark(node);
  5637. }
  5638. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  5639. const loop = new torch._C.LoopView(outerNode);
  5640. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  5641. if (outerNode.kind() === 'onnx::Loop') {
  5642. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  5643. continue;
  5644. }
  5645. const innerInput = loop.bodyCarriedInputs()[i];
  5646. const innerOutput = loop.bodyCarriedOutputs()[i];
  5647. const outerOutput = loop.carriedOutputs()[i];
  5648. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  5649. this._liveValues.add(innerOutput);
  5650. }
  5651. }
  5652. this._liveValues.add(loop.nextCond());
  5653. } else {
  5654. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  5655. for (let i = 0; i < outerNode.outputs().length; i++) {
  5656. const innerOutput = node.inputs()[i];
  5657. const outerOutput = outerNode.outputs()[i];
  5658. if (!this._liveValues.has(outerOutput)) {
  5659. this._liveValues.add(innerOutput);
  5660. }
  5661. }
  5662. }
  5663. this._marked.add(node);
  5664. return true;
  5665. }
  5666. markLoop(node) {
  5667. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  5668. let marked = false;
  5669. let anyMarked = false;
  5670. do {
  5671. marked = this.mark(node.blocks()[0]);
  5672. anyMarked = anyMarked || marked;
  5673. } while (marked);
  5674. return anyMarked;
  5675. }
  5676. mark(...args) {
  5677. if (args.length === 1 && args[0] instanceof torch.Block) {
  5678. const [block] = args;
  5679. let anyMarked = false;
  5680. for (const node of block.nodes()) {
  5681. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  5682. const marked = this.mark(node);
  5683. anyMarked = anyMarked || marked;
  5684. }
  5685. }
  5686. const marked = this.markReturnNode(block.return_node());
  5687. anyMarked = anyMarked || marked;
  5688. for (const node of block.nodes()) {
  5689. if (node.kind() === 'prim::Loop') {
  5690. const marked = this.markLoop(node);
  5691. anyMarked = anyMarked || marked;
  5692. } else {
  5693. for (const subBlock of node.blocks()) {
  5694. const marked = this.mark(subBlock);
  5695. anyMarked = anyMarked || marked;
  5696. }
  5697. }
  5698. const marked = this.markIfLive(node);
  5699. anyMarked = anyMarked || marked;
  5700. }
  5701. return anyMarked;
  5702. }
  5703. if (args.length === 1 && args[0] instanceof torch.Node) {
  5704. const [node] = args;
  5705. if (this._marked.has(node)) {
  5706. return false;
  5707. }
  5708. this._marked.add(node);
  5709. let curNode = node;
  5710. while (curNode && curNode.owningBlock()) {
  5711. this.mark(curNode);
  5712. curNode = curNode.owningBlock().owningNode();
  5713. }
  5714. for (const input of node.inputs()) {
  5715. if (!this._liveValues.has(input)) {
  5716. this._liveValues.add(input);
  5717. }
  5718. }
  5719. return true;
  5720. }
  5721. throw new python.Error('Not implemented.');
  5722. }
  5723. markIfLive(node) {
  5724. for (const output of node.outputs()) {
  5725. if (this._liveValues.has(output)) {
  5726. return this.mark(node);
  5727. }
  5728. }
  5729. if (this._useAliasDb) {
  5730. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  5731. return this.mark(node);
  5732. }
  5733. }
  5734. return false;
  5735. }
  5736. sweep(block, recurse) {
  5737. const nodes = Array.from(block.nodes()).reverse();
  5738. for (const node of nodes) {
  5739. this.removeDeadBlockOutputs(node);
  5740. this.removeDeadLoopOutputs(node);
  5741. if (recurse) {
  5742. for (const block of node.blocks()) {
  5743. this.sweep(block, true);
  5744. }
  5745. }
  5746. if (!this._marked.has(node) && !node.hasUses()) {
  5747. node.destroy();
  5748. }
  5749. }
  5750. }
  5751. hasUntrackedMutation(node) {
  5752. if (!this._useAliasDb) {
  5753. if (node.kind() === 'prim::SetAttr') {
  5754. return true;
  5755. }
  5756. const schema = node.maybeSchema();
  5757. return schema && schema.is_mutable();
  5758. }
  5759. return this.getOrCreateAliasDb().writesToWildcard(node);
  5760. }
  5761. hasSideEffects(node) {
  5762. const it = this._memo.get(node);
  5763. if (it) {
  5764. return it;
  5765. }
  5766. const has_side_effects = node.hasSideEffects() ||
  5767. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  5768. this.hasUntrackedMutation(node);
  5769. this._memo.set(node, has_side_effects);
  5770. return has_side_effects;
  5771. }
  5772. removeDeadBlockOutputs(node) {
  5773. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  5774. return;
  5775. }
  5776. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  5777. const i = i_1 - 1;
  5778. if (!node.outputs()[i].hasUses()) {
  5779. node.eraseOutput(i);
  5780. for (const b of node.blocks()) {
  5781. b.eraseOutput(i);
  5782. }
  5783. }
  5784. }
  5785. }
  5786. removeDeadLoopOutputs() {
  5787. }
  5788. getOrCreateAliasDb() {
  5789. if (!this._aliasDb) {
  5790. this._aliasDb = new torch._C.AliasDb(this._graph);
  5791. }
  5792. return this._aliasDb;
  5793. }
  5794. });
  5795. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  5796. if (args.length === 1 && args[0] instanceof torch.Graph) {
  5797. const [graph] = args;
  5798. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  5799. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  5800. worker.run(graph.block(), /*recurse=*/true);
  5801. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  5802. const [block] = args;
  5803. const recurse = false;
  5804. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  5805. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  5806. worker.run(block, recurse);
  5807. } else {
  5808. throw new python.Error('Not implemented.');
  5809. }
  5810. });
  5811. this.registerFunction('torch._C.removeTupleNodes', () => {
  5812. });
  5813. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  5814. if (args.length === 1 && args[0] instanceof torch.Graph) {
  5815. const [graph] = args;
  5816. torch._C.LowerSimpleTuples(graph.block());
  5817. torch._C.EliminateDeadCode(graph);
  5818. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  5819. const [block] = args;
  5820. for (const n of block.nodes()) {
  5821. torch._C.removeTupleNodes(n, false);
  5822. for (const b of n.blocks()) {
  5823. torch._C.LowerSimpleTuples(b);
  5824. }
  5825. }
  5826. } else {
  5827. throw new python.Error('Not implemented.');
  5828. }
  5829. });
  5830. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  5831. torch._C.AT_ASSERT(lhs !== null);
  5832. torch._C.AT_ASSERT(rhs !== null);
  5833. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  5834. return false;
  5835. }
  5836. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  5837. return true;
  5838. }
  5839. const lnames = lhs.attributeNames();
  5840. const rnames = rhs.attributeNames();
  5841. lnames.sort();
  5842. rnames.sort();
  5843. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  5844. return false;
  5845. }
  5846. for (const name of lnames) {
  5847. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  5848. return false;
  5849. }
  5850. const kind = lhs.kindOf(name);
  5851. switch (kind) {
  5852. case 'i':
  5853. case 'f':
  5854. case 's':
  5855. case 't': {
  5856. if (lhs[kind](name) !== rhs[kind](name)) {
  5857. return false;
  5858. }
  5859. break;
  5860. }
  5861. case 'ival': {
  5862. if (lhs[kind](name) !== rhs[kind](name)) {
  5863. return false;
  5864. }
  5865. break;
  5866. }
  5867. default: {
  5868. throw new python.Error('Not implemented.');
  5869. }
  5870. }
  5871. }
  5872. return true;
  5873. });
  5874. this.registerFunction('torch._C.get_hash', (...args) => {
  5875. let hash = 0;
  5876. for (const value of args) {
  5877. if (typeof value === 'number') {
  5878. hash += (value | 0);
  5879. } else if (typeof value === 'string') {
  5880. hash += (value.length | 0);
  5881. } else if (Array.isArray(value)) {
  5882. for (const item of value) {
  5883. hash += torch._C.get_hash(item);
  5884. }
  5885. }
  5886. }
  5887. return hash;
  5888. });
  5889. this.registerFunction('torch._C.HashNode', (k) => {
  5890. torch._C.AT_ASSERT(k !== null);
  5891. let constant_hash = 0;
  5892. if (k.kind() === 'prim::Constant') {
  5893. const type = k.output().type();
  5894. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  5895. constant_hash = k.i('value');
  5896. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  5897. constant_hash = k.f('value');
  5898. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  5899. constant_hash = k.c('value');
  5900. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  5901. constant_hash = k.i('value');
  5902. }
  5903. }
  5904. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  5905. });
  5906. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  5907. if (lhs === null && rhs === null) {
  5908. return true;
  5909. }
  5910. if (lhs === null || rhs === null) {
  5911. return false;
  5912. }
  5913. if (lhs.kind() !== rhs.kind()) {
  5914. return false;
  5915. }
  5916. const lhs_outputs = lhs.outputs();
  5917. const rhs_outputs = rhs.outputs();
  5918. if (lhs_outputs.length !== rhs_outputs.length) {
  5919. return false;
  5920. }
  5921. for (let i = 0; i < lhs_outputs.length; i++) {
  5922. const lt = lhs_outputs[i].type();
  5923. const rt = rhs_outputs[i].type();
  5924. if (!lt.equals(rt)) {
  5925. return false;
  5926. }
  5927. }
  5928. const lhs_inputs = lhs.inputs();
  5929. const rhs_inputs = rhs.inputs();
  5930. if (lhs_inputs.length !== rhs_inputs.length) {
  5931. return false;
  5932. }
  5933. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  5934. return false;
  5935. }
  5936. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  5937. return false;
  5938. }
  5939. if (lhs.blocks().length !== rhs.blocks().length) {
  5940. return false;
  5941. }
  5942. for (let i = 0; i < lhs.blocks().length; i++) {
  5943. if (lhs.blocks()[i] !== rhs.blocks()[i]) {
  5944. return false;
  5945. }
  5946. }
  5947. return true;
  5948. });
  5949. this.registerType('torch._C.NodeSet', class {
  5950. constructor() {
  5951. this._nodes = new Map();
  5952. }
  5953. insert(n) {
  5954. const key = torch._C.HashNode(n);
  5955. if (this._nodes.has(key)) {
  5956. this._nodes.get(key).push(n);
  5957. } else {
  5958. this._nodes.set(key, [n]);
  5959. }
  5960. }
  5961. get(n) {
  5962. const key = torch._C.HashNode(n);
  5963. if (this._nodes.has(key)) {
  5964. const nodes = this._nodes.get(key);
  5965. for (const node of nodes) {
  5966. if (torch._C.EqualNode(node, n)) {
  5967. return node;
  5968. }
  5969. }
  5970. }
  5971. return null;
  5972. }
  5973. has(n) {
  5974. return this.get(n) !== null;
  5975. }
  5976. });
  5977. this.registerFunction('torch._C.isinstance', (stack, types) => {
  5978. const ty = stack.pop().type();
  5979. for (const candidate of types) {
  5980. if (ty.isSubtypeOf(candidate)) {
  5981. stack.push(new torch._C.IValue(true, 'Bool'));
  5982. stack.push(true);
  5983. return;
  5984. }
  5985. }
  5986. stack.push(new torch._C.IValue(false, 'Bool'));
  5987. });
  5988. this.registerType('torch._C.Tuple', class {
  5989. constructor(elements) {
  5990. this._elements = elements;
  5991. }
  5992. static create(elements) {
  5993. return new torch._C.Tuple(elements);
  5994. }
  5995. elements() {
  5996. return this._elements;
  5997. }
  5998. });
  5999. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6000. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6001. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6002. const tuple = torch._C.Tuple.create(elems.reverse());
  6003. stack.push(new torch._C.IValue(tuple));
  6004. });
  6005. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6006. let stack = [];
  6007. for (const input of n.inputs()) {
  6008. const ival = torch._C.toIValue(input);
  6009. if (ival) {
  6010. stack.push(ival);
  6011. } else {
  6012. return null;
  6013. }
  6014. }
  6015. switch (n.kind()) {
  6016. case 'prim::ListUnpack': {
  6017. if (stack.back().toList().size() !== n.outputs().length) {
  6018. return null;
  6019. }
  6020. torch._C.listUnpack(stack, n.outputs().length);
  6021. break;
  6022. }
  6023. case 'prim::TupleConstruct': {
  6024. const tt = n.output().type().expect(torch.TupleType);
  6025. if (tt.name()) {
  6026. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6027. } else {
  6028. torch._C.tupleConstruct(stack, n.inputs().length);
  6029. }
  6030. break;
  6031. }
  6032. case 'prim::ListConstruct': {
  6033. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6034. break;
  6035. }
  6036. case 'prim::DictConstruct': {
  6037. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6038. break;
  6039. }
  6040. case 'prim::CreateObject': {
  6041. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6042. break;
  6043. }
  6044. case 'prim::GetAttr': {
  6045. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6046. torch._C.push(stack, attr);
  6047. break;
  6048. }
  6049. case 'prim::isinstance': {
  6050. torch._C.isinstance(stack, n.tys('types'));
  6051. break;
  6052. }
  6053. default: {
  6054. const maybe_schema = n.maybeSchema();
  6055. if (maybe_schema && maybe_schema.is_vararg) {
  6056. return null;
  6057. }
  6058. // try
  6059. // {
  6060. // const op = n.getOperation();
  6061. // op(stack);
  6062. const [module, name] = n.kind().split('::');
  6063. const obj = torch.ops[module];
  6064. if (!obj) {
  6065. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6066. }
  6067. const fn = torch.ops[module].__getattr__(name);
  6068. if (!fn || !fn.__call__) {
  6069. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6070. }
  6071. const args = stack.map((v) => v.value);
  6072. const result = fn.__call__(...args);
  6073. if (result === undefined) {
  6074. stack = [];
  6075. } else if (result instanceof torch._C.IValue) {
  6076. stack = [result];
  6077. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6078. stack = result;
  6079. } else {
  6080. stack = [new torch._C.IValue(result)];
  6081. }
  6082. // } catch {
  6083. // stack = [];
  6084. // return null;
  6085. // }
  6086. break;
  6087. }
  6088. }
  6089. for (const v of stack) {
  6090. if (v.isTensor()) {
  6091. const t = v.toTensor();
  6092. if (t.defined() && t.requires_grad()) {
  6093. return null;
  6094. }
  6095. }
  6096. if (ignore_custom_classes) {
  6097. if (v.isCustomClass()) {
  6098. return null;
  6099. }
  6100. }
  6101. if (v.isCustomClass()) {
  6102. if (v.toObject().is_weak_compilation_ref()) {
  6103. continue;
  6104. }
  6105. if (!db) {
  6106. continue;
  6107. }
  6108. const n_non_const = n;
  6109. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6110. continue;
  6111. }
  6112. const obj = v.toObject();
  6113. obj.unsafe_make_weak_compilation_ref();
  6114. }
  6115. if (v.isObject()) {
  6116. if (!v.toObject().is_weak_compilation_ref()) {
  6117. return null;
  6118. }
  6119. }
  6120. }
  6121. return stack;
  6122. });
  6123. this.registerType('torch._C.ConstantPropagator', class {
  6124. constructor(graph, aliasing_types, ignore_custom_classes) {
  6125. this._made_change = false;
  6126. this._graph = graph;
  6127. this._aliasing_types = aliasing_types;
  6128. this._ignore_custom_classes = ignore_custom_classes;
  6129. }
  6130. static NoAliasDb(graph) {
  6131. return new torch._C.ConstantPropagator(graph, false, false);
  6132. }
  6133. run() {
  6134. this.ConstantPropagation(this._graph.block());
  6135. return this._made_change;
  6136. }
  6137. propagateNode(n) {
  6138. let outputs = [];
  6139. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6140. if (outputs_opt) {
  6141. outputs = outputs_opt;
  6142. const graph = n.owningGraph();
  6143. const guard = new torch._C.WithInsertPoint(n);
  6144. for (let i = 0; i < outputs.length; i++) {
  6145. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6146. if (new_output) {
  6147. this._made_change = true;
  6148. if (outputs[i].isNone()) {
  6149. new_output.setType(n.outputs()[i].type());
  6150. }
  6151. n.outputs()[i].replaceAllUsesWith(new_output);
  6152. }
  6153. }
  6154. guard.dispose();
  6155. }
  6156. }
  6157. removeLoopNode(n) {
  6158. const loop_input_offset = 2;
  6159. for (let i = 0; i < n.outputs().length; i++) {
  6160. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6161. }
  6162. this._made_change = true;
  6163. n.destroy();
  6164. }
  6165. loopWillNotRun(node) {
  6166. const [trip_count, start_cond] = node.inputs();
  6167. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6168. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6169. const loop_might_run = cond_val && iter_len > 0;
  6170. return !loop_might_run;
  6171. }
  6172. inlineIfBody(body) {
  6173. const n = body.owningNode();
  6174. for (const body_node of body.nodes()) {
  6175. body_node.moveBefore(n);
  6176. }
  6177. for (let i = 0; i < n.outputs().length; i++) {
  6178. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6179. }
  6180. n.destroy();
  6181. }
  6182. inlineIf(n) {
  6183. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6184. torch._C.AT_ASSERT(input_bool !== null);
  6185. const block_index = input_bool ? 0 : 1;
  6186. this.ConstantPropagation(n.blocks()[block_index]);
  6187. this.inlineIfBody(n.blocks()[block_index]);
  6188. this._made_change = true;
  6189. }
  6190. replaceAndRemoveIfOutput(n, i, replacement) {
  6191. n.outputs()[i].replaceAllUsesWith(replacement);
  6192. n.eraseOutput(i);
  6193. n.blocks()[0].eraseOutput(i);
  6194. n.blocks()[1].eraseOutput(i);
  6195. }
  6196. removeExtraIfOutputs(n) {
  6197. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6198. const [true_block, false_block] = n.blocks();
  6199. const graph = n.owningGraph();
  6200. const initial_outputs = true_block.outputs().length;
  6201. const guard = new torch._C.WithInsertPoint(n);
  6202. for (let i = 0; i < true_block.outputs().length;) {
  6203. const t_out = true_block.outputs()[i];
  6204. const f_out = false_block.outputs()[i];
  6205. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6206. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6207. continue;
  6208. }
  6209. const maybe_const = torch._C.toIValue(t_out);
  6210. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6211. const new_const = graph.insertConstant(maybe_const);
  6212. this.replaceAndRemoveIfOutput(n, i, new_const);
  6213. continue;
  6214. }
  6215. i++;
  6216. }
  6217. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6218. guard.dispose();
  6219. }
  6220. removeExtraLoopOutputs(node) {
  6221. const initial_outputs = node.outputs().length;
  6222. const [loop_body] = node.blocks();
  6223. const loop_input_offset = 2;
  6224. const loop_body_offset = 1;
  6225. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6226. const i = i_1 - 1;
  6227. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6228. const node_input = node.inputs()[loop_input_offset + i];
  6229. node.outputs().at(i).replaceAllUsesWith(node_input);
  6230. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6231. node.eraseOutput(i);
  6232. node.removeInput(loop_input_offset + i);
  6233. loop_body.eraseInput(loop_body_offset + i);
  6234. loop_body.eraseOutput(loop_body_offset + i);
  6235. }
  6236. }
  6237. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6238. }
  6239. noMutableValues(values) {
  6240. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6241. }
  6242. getOrCreateAliasDb() {
  6243. if (!this._aliasDb) {
  6244. this._aliasDb = new torch._C.AliasDb(this._graph);
  6245. }
  6246. return this._aliasDb;
  6247. }
  6248. supportedNode(n) {
  6249. torch._C.skip_list = torch._C.skip_list || new Set([
  6250. 'prim::If',
  6251. 'prim::Loop',
  6252. 'prim::Closure',
  6253. 'prim::Constant',
  6254. 'prim::AutogradZero',
  6255. 'prim::Uninitialized',
  6256. 'prim::Guard',
  6257. 'prim::profile',
  6258. 'prim::profile_ivalue',
  6259. 'prim::unchecked_unwrap_optional',
  6260. 'prim::awaitable',
  6261. 'aten::dequantize'
  6262. ]);
  6263. let no_mutation = false;
  6264. if (this._aliasing_types) {
  6265. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  6266. } else {
  6267. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  6268. }
  6269. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  6270. }
  6271. ConstantPropagation(...args) {
  6272. if (args[0] instanceof torch.Graph) {
  6273. throw new python.Error('Not implemented.');
  6274. } else if (args[0] instanceof torch.Block) {
  6275. const [block] = args;
  6276. for (const n of block.nodes()) {
  6277. this.ConstantPropagation(n);
  6278. }
  6279. } else if (args[0] instanceof torch.Node) {
  6280. const [n] = args;
  6281. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  6282. if (n.kind() === 'prim::If') {
  6283. if (constant_inputs) {
  6284. this.inlineIf(n);
  6285. } else {
  6286. this.ConstantPropagation(n.blocks());
  6287. this.removeExtraIfOutputs(n);
  6288. }
  6289. } else if (n.kind() === 'prim::Loop') {
  6290. if (this.loopWillNotRun(n)) {
  6291. this.removeLoopNode(n);
  6292. } else {
  6293. this.ConstantPropagation(n.blocks());
  6294. this.removeExtraLoopOutputs(n);
  6295. }
  6296. } else if (constant_inputs && this.supportedNode(n)) {
  6297. this.propagateNode(n);
  6298. } else {
  6299. this.ConstantPropagation(n.blocks()); // not implemented
  6300. }
  6301. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  6302. const [blocks] = args;
  6303. for (const block of blocks) {
  6304. this.ConstantPropagation(block);
  6305. }
  6306. } else {
  6307. throw new python.Error('Not implemented.');
  6308. }
  6309. }
  6310. });
  6311. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  6312. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  6313. const made_change = cp.run();
  6314. if (made_change) {
  6315. torch._C.EliminateDeadCode(graph);
  6316. }
  6317. return made_change;
  6318. });
  6319. this.registerType('torch._C.MutableTypePtrHelper', class {
  6320. constructor(mutable_type_cache) {
  6321. this._mutable_type_cache = mutable_type_cache;
  6322. }
  6323. mapTypeToAliasTypeSet(type) {
  6324. if (this._mutable_type_cache) {
  6325. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  6326. if (result) {
  6327. return result;
  6328. }
  6329. }
  6330. return this.mapTypeToAliasTypeSetImpl(type);
  6331. }
  6332. mapTypeToAliasTypeSetImpl(type) {
  6333. if (type instanceof torch.ListType ||
  6334. type instanceof torch.DictType ||
  6335. type instanceof torch.ClassType ||
  6336. type instanceof torch.TensorType) {
  6337. return [torch._C.unshapedType(type)];
  6338. }
  6339. if (type instanceof torch.UnionType) {
  6340. const mutable_types = [];
  6341. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  6342. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  6343. if (maybe_inner_types) {
  6344. mutable_types.push(...maybe_inner_types);
  6345. }
  6346. }
  6347. if (mutable_types.length === 0) {
  6348. return null;
  6349. }
  6350. return mutable_types;
  6351. }
  6352. if (type instanceof torch.OptionalType) {
  6353. const inner = type.getElementType();
  6354. return this.mapTypeToAliasTypeSet(inner);
  6355. }
  6356. if (type instanceof torch.AnyType) {
  6357. return [torch._C.AliasTypeSet([type])];
  6358. }
  6359. if (type instanceof torch.FutureType) {
  6360. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  6361. if (maybe_mut_types) {
  6362. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  6363. }
  6364. return null;
  6365. }
  6366. if (type instanceof torch.AwaitType) {
  6367. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  6368. if (maybe_mut_types) {
  6369. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  6370. }
  6371. return null;
  6372. }
  6373. if (type instanceof torch.TupleType) {
  6374. const mutable_types = [];
  6375. for (const inner of type.elements()) {
  6376. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  6377. if (maybe_inner_types) {
  6378. mutable_types.push(...maybe_inner_types);
  6379. }
  6380. }
  6381. if (mutable_types.length === 0) {
  6382. return null;
  6383. }
  6384. return [[torch.TupleType.create(mutable_types)]];
  6385. }
  6386. return null;
  6387. }
  6388. });
  6389. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  6390. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  6391. type instanceof torch.ClassType || type instanceof torch.DictType) {
  6392. return true;
  6393. }
  6394. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  6395. if (mutable_type_cache) {
  6396. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  6397. }
  6398. return helper.mapTypeToAliasTypeSet(type) !== null;
  6399. });
  6400. this.registerType('torch._C.AliasDb', class {
  6401. constructor() {
  6402. this._writeIndex = new Map();
  6403. }
  6404. static isMutableType(...args) {
  6405. if (args[0] instanceof torch.Type) {
  6406. const [type] = args;
  6407. return torch._C.isMutableTypeImpl(type, null);
  6408. }
  6409. if (args[0] instanceof torch.Value) {
  6410. const [value] = args;
  6411. return torch._C.AliasDb.isMutableType(value.type());
  6412. }
  6413. throw new python.Error('Not implemented.');
  6414. }
  6415. writesToAlias(/* n, vs */) {
  6416. /*
  6417. const writtenTo = this.getWrites(n);
  6418. if (writtenTo.length === 0) {
  6419. return false;
  6420. }
  6421. MemoryLocations locs;
  6422. for (const v of vs) {
  6423. const it = elementMap_.find(v);
  6424. if (it != elementMap_.end()) {
  6425. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  6426. if (writtenTo.intersects(vlocs)) {
  6427. return true;
  6428. }
  6429. }
  6430. }
  6431. */
  6432. return false;
  6433. }
  6434. writesToWildcard(n) {
  6435. if (!this._writeIndex.has(n)) {
  6436. return false;
  6437. }
  6438. const writes = this._writeIndex.get(n);
  6439. for (const pr of this._wildcardIndex) {
  6440. const [, wildcardElement] = pr;
  6441. if (writes.test(wildcardElement.index)) {
  6442. return true;
  6443. }
  6444. }
  6445. return false;
  6446. }
  6447. safeToChangeAliasingRelationship(a, b) {
  6448. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  6449. return false;
  6450. }
  6451. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  6452. }
  6453. });
  6454. this.registerFunction('torch._C.hasWriters', () => {
  6455. });
  6456. this.registerFunction('torch._C.escapesScope', () => {
  6457. });
  6458. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  6459. constructor(graph) {
  6460. this._current = graph.block().nodes().front();
  6461. }
  6462. next() {
  6463. return null;
  6464. }
  6465. });
  6466. this.registerType('torch._C.ConcatCombiner', class {
  6467. constructor(graph) {
  6468. this._graph = graph;
  6469. this._aliasDb = new torch._C.AliasDb(graph);
  6470. this._combinable_concats = [];
  6471. }
  6472. collectOptimizableConcats() {
  6473. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  6474. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  6475. if (node.kind() === 'aten::cat') {
  6476. this.handleConcat(node);
  6477. }
  6478. }
  6479. }
  6480. combineConcats() {
  6481. if (this._combinable_concats.length === 0) {
  6482. return false;
  6483. }
  6484. const list_construct_inputs = this.getListConstructInputs();
  6485. for (const node_and_new_list of list_construct_inputs) {
  6486. const [node, inputs] = node_and_new_list;
  6487. const new_list_construct = this.createListConstruct(inputs);
  6488. const old_list_construct = node.input(0).node();
  6489. new_list_construct.output().setType(old_list_construct.output().type());
  6490. new_list_construct.insertBefore(node);
  6491. old_list_construct.replaceAllUsesWith(new_list_construct);
  6492. }
  6493. return true;
  6494. }
  6495. run() {
  6496. this.collectOptimizableConcats();
  6497. const changed = this.combineConcats();
  6498. if (changed) {
  6499. torch._C.EliminateDeadCode(this._graph);
  6500. }
  6501. return changed;
  6502. }
  6503. });
  6504. this.registerFunction('torch._C.CombineConcats', (graph) => {
  6505. const changed = new torch._C.ConcatCombiner(graph).run();
  6506. return changed;
  6507. });
  6508. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  6509. constructor(graph, disable_shape_peepholes) {
  6510. this._graph = graph;
  6511. this._shape_peepholes = !disable_shape_peepholes;
  6512. }
  6513. run() {
  6514. let changed = this.optimizeBlock(this._graph.block());
  6515. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  6516. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  6517. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  6518. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  6519. changed = changed || torch._C.CombineConcats(this._graph);
  6520. return changed;
  6521. }
  6522. optimizeBlock(block) {
  6523. let changed = false;
  6524. for (const node of block.nodes()) {
  6525. for (const sub_block of node.blocks()) {
  6526. changed = changed || this.optimizeBlock(sub_block);
  6527. }
  6528. if (node.kind() !== 'prim::Constant') {
  6529. const guard = new torch._C.WithInsertPoint(node);
  6530. for (const output of node.outputs()) {
  6531. if (output.type() instanceof torch.NoneType) {
  6532. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  6533. changed = true;
  6534. }
  6535. }
  6536. guard.dispose();
  6537. }
  6538. if (node.kind() === 'prim::If') {
  6539. // throw new python.Error('Not implemented.');
  6540. /*
  6541. const n = new torch._C.IfView(node);
  6542. // this handles redundant short circuits like "x and True" or "x or
  6543. // False"
  6544. for (const auto i : c10::irange(n.outputs().length)) {
  6545. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  6546. continue;
  6547. }
  6548. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  6549. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  6550. if (true_val && !false_val) {
  6551. n.outputs().at(i).replaceAllUsesWith(n.cond());
  6552. changed = true;
  6553. }
  6554. }
  6555. for (let i = 0; i < n.outputs().length; ++i) {
  6556. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  6557. const output_optional = n.outputs()[i].type();
  6558. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  6559. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  6560. if (unif) {
  6561. n.outputs()[i].setType(unif);
  6562. changed = true;
  6563. }
  6564. }
  6565. }
  6566. */
  6567. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  6568. torch._C.AT_ASSERT(node.inputs().length === 2);
  6569. for (const check_none_index of [0, 1]) {
  6570. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  6571. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  6572. if (input_must_be_none && other_must_not_be_none) {
  6573. const guard = new torch._C.WithInsertPoint(node);
  6574. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  6575. node.output().replaceAllUsesWith(output);
  6576. changed = true;
  6577. guard.dispose();
  6578. }
  6579. }
  6580. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  6581. throw new python.Error('Not implemented.');
  6582. /*
  6583. // we are unwrapping an input that can't be None, remove the unwrap
  6584. const input = node.input();
  6585. if (input.mustNotBeNone()) {
  6586. node.output().replaceAllUsesWith(node.input());
  6587. changed = true;
  6588. }
  6589. */
  6590. } else if (node.kind() === 'prim::unchecked_cast') {
  6591. const input_type = torch._C.unshapedType(node.input().type());
  6592. const output_type = torch._C.unshapedType(node.output().type());
  6593. if (input_type.isSubtypeOf(output_type)) {
  6594. node.output().replaceAllUsesWith(node.input());
  6595. changed = true;
  6596. }
  6597. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  6598. node.output().replaceAllUsesWith(node.input());
  6599. changed = true;
  6600. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  6601. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  6602. continue;
  6603. }
  6604. const inp_type = node.inputs()[0].type();
  6605. const immut_type = (type) => {
  6606. const kind = type.kind();
  6607. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  6608. return handled_immutable_types.has(kind);
  6609. };
  6610. let non_throwing_type = false;
  6611. if (inp_type instanceof torch.ListType) {
  6612. non_throwing_type = immut_type(inp_type.getElementType());
  6613. } else if (inp_type instanceof torch.DictType) {
  6614. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  6615. } else {
  6616. non_throwing_type = immut_type(inp_type);
  6617. }
  6618. if (non_throwing_type) {
  6619. const guard = new torch._C.WithInsertPoint(node);
  6620. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  6621. changed = true;
  6622. guard.dispose();
  6623. }
  6624. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  6625. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  6626. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  6627. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  6628. }
  6629. }
  6630. return changed;
  6631. }
  6632. });
  6633. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  6634. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  6635. const changed = peephole.run();
  6636. if (changed) {
  6637. torch._C.EliminateDeadCode(graph.block());
  6638. }
  6639. return changed;
  6640. });
  6641. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  6642. if (!cond) {
  6643. throw new python.Error('Assertion failed.');
  6644. }
  6645. });
  6646. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  6647. if (!cond) {
  6648. throw new python.Error('Assertion failed.');
  6649. }
  6650. });
  6651. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  6652. if (!cond) {
  6653. throw new python.Error('Assertion failed.');
  6654. }
  6655. });
  6656. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  6657. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  6658. for (let next_node = it.next(); next_node !== null;) {
  6659. const node = next_node;
  6660. next_node = it.next();
  6661. if (node.kind() === 'prim::EmptyListLiteral') {
  6662. if (node.hasUses()) {
  6663. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  6664. }
  6665. const li = graph.createList(torch.TensorType.get(), []);
  6666. li.insertBefore(node);
  6667. node.replaceAllUsesWith(li);
  6668. }
  6669. node.destroy();
  6670. }
  6671. });
  6672. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  6673. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6674. const [graph] = args;
  6675. const aliasDb = new torch._C.AliasDb(graph);
  6676. const constants = new torch._C.NodeSet();
  6677. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  6678. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  6679. const [block, constants, aliasDb] = args;
  6680. for (const node of block.nodes()) {
  6681. if (node.blocks().length > 0) {
  6682. for (const block of node.blocks()) {
  6683. torch._C.ConstantPooling(block, constants, aliasDb);
  6684. }
  6685. continue;
  6686. }
  6687. if (node.kind() !== 'prim::Constant') {
  6688. continue;
  6689. }
  6690. if (constants.has(node)) {
  6691. const existing = constants.get(node);
  6692. const old_ivalue = torch._C.toIValue(existing.output());
  6693. const new_ivalue = torch._C.toIValue(node.output());
  6694. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  6695. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  6696. continue;
  6697. }
  6698. node.replaceAllUsesWith(existing);
  6699. node.destroy();
  6700. continue;
  6701. } else {
  6702. constants.insert(node);
  6703. }
  6704. const [first_node] = node.owningGraph().block().nodes();
  6705. if (node !== first_node) {
  6706. node.moveBefore(first_node);
  6707. }
  6708. }
  6709. } else {
  6710. throw new python.Error('Not implemented.');
  6711. }
  6712. });
  6713. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  6714. /*
  6715. const autocast_stack = [];
  6716. let incompatible_amp = null;
  6717. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  6718. for (const node of block.nodes()) {
  6719. switch (node.kind()) {
  6720. case 'prim::CallFunction':
  6721. if (current_state() === initial_state) {
  6722. if (current_state()) {
  6723. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6724. }
  6725. break;
  6726. }
  6727. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  6728. incompatible_amp = true;
  6729. break;
  6730. case 'prim::CallMethod':
  6731. if (current_state() === initial_state) {
  6732. if (current_state()) {
  6733. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6734. }
  6735. break;
  6736. }
  6737. if (node.input(0).type() instanceof torch.ClassType) {
  6738. const class_type = node.input(0).type();
  6739. const name = node.s('name');
  6740. const fn = class_type.getMethod(name);
  6741. if (!fn.isGraphFunction()) {
  6742. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  6743. incompatible_amp = true;
  6744. }
  6745. } else {
  6746. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  6747. incompatible_amp = true;
  6748. }
  6749. break;
  6750. case 'prim::Enter': {
  6751. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  6752. if (autocast_scope) {
  6753. if (node.hasUses()) {
  6754. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  6755. }
  6756. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  6757. incompatible_amp = false;
  6758. autocast_stack.push(autocast_scope);
  6759. }
  6760. break;
  6761. }
  6762. case 'prim::Exit': {
  6763. if (torch._C.isAutocastNode(node.input(0))) {
  6764. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  6765. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  6766. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  6767. incompatible_amp = false;
  6768. autocast_stack.pop();
  6769. }
  6770. break;
  6771. }
  6772. case 'aten::is_autocast_enabled': {
  6773. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  6774. break;
  6775. }
  6776. case 'aten::is_autocast_cpu_enabled': {
  6777. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  6778. break;
  6779. }
  6780. case 'aten::_convolution':
  6781. case 'aten::conv1d':
  6782. case 'aten::conv2d':
  6783. case 'aten::conv3d':
  6784. case 'aten::conv_tbc':
  6785. case 'aten::conv_transpose1d':
  6786. case 'aten::convolution':
  6787. case 'aten::cudnn_convolution':
  6788. case 'aten::cudnn_convolution_transpose':
  6789. case 'aten::prelu':
  6790. case 'aten::addmm':
  6791. case 'aten::addmv':
  6792. case 'aten::addr':
  6793. case 'aten::matmul':
  6794. case 'aten::mm':
  6795. case 'aten::mv':
  6796. case 'aten::linear':
  6797. case 'aten::addbmm':
  6798. case 'aten::baddbmm':
  6799. case 'aten::bmm':
  6800. case 'aten::chain_matmul':
  6801. case 'aten::_thnn_fused_lstm_cell':
  6802. case 'aten::_thnn_fused_gru_cell':
  6803. case 'aten::lstm_cell':
  6804. case 'aten::gru_cell':
  6805. case 'aten::rnn_tanh_cell':
  6806. case 'aten::rnn_relu_cell': {
  6807. if (!node.schema().is_mutable()) {
  6808. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  6809. }
  6810. break;
  6811. }
  6812. case 'aten::native_layer_norm':
  6813. case 'aten::acos':
  6814. case 'aten::asin':
  6815. case 'aten::cosh':
  6816. case 'aten::erfinv':
  6817. case 'aten::exp':
  6818. case 'aten::expm1':
  6819. case 'aten::log':
  6820. case 'aten::log10':
  6821. case 'aten::log2':
  6822. case 'aten::log1p':
  6823. case 'aten::reciprocal':
  6824. case 'aten::rsqrt':
  6825. case 'aten::sinh':
  6826. case 'aten::tan':
  6827. case 'aten::pow':
  6828. case 'aten::softplus':
  6829. case 'aten::gelu':
  6830. case 'aten::layer_norm':
  6831. case 'aten::group_norm':
  6832. case 'aten::frobenius_norm':
  6833. case 'aten::nuclear_norm':
  6834. case 'aten::cosine_similarity':
  6835. case 'aten::cosine_embedding_loss':
  6836. case 'aten::nll_loss':
  6837. case 'aten::nll_loss2d':
  6838. case 'aten::hinge_embedding_loss':
  6839. case 'aten::kl_div':
  6840. case 'aten::l1_loss':
  6841. case 'aten::smooth_l1_loss':
  6842. case 'aten::mse_loss':
  6843. case 'aten::margin_ranking_loss':
  6844. case 'aten::multilabel_margin_loss':
  6845. case 'aten::soft_margin_loss':
  6846. case 'aten::triplet_margin_loss':
  6847. case 'aten::multi_margin_loss':
  6848. case 'aten::binary_cross_entropy_with_logits':
  6849. case 'aten::dist':
  6850. case 'aten::pdist':
  6851. case 'aten::cdist':
  6852. case 'aten::renorm':
  6853. case 'aten::logsumexp': {
  6854. if (!node.schema().is_mutable()) {
  6855. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6856. }
  6857. break;
  6858. }
  6859. case 'aten::prod':
  6860. case 'aten::log_softmax':
  6861. case 'aten::cumprod':
  6862. case 'aten::cumsum':
  6863. case 'aten::sum': {
  6864. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  6865. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  6866. }
  6867. break;
  6868. }
  6869. case 'aten::softmax': {
  6870. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  6871. const context = current_state();
  6872. context.cpu_enabled = false;
  6873. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  6874. }
  6875. break;
  6876. }
  6877. case 'aten::addcdiv':
  6878. case 'aten::addcmul':
  6879. case 'aten::atan2':
  6880. case 'aten::bilinear':
  6881. case 'aten::cat':
  6882. case 'aten::cross':
  6883. case 'aten::dot':
  6884. case 'aten::equal':
  6885. case 'aten::index_put':
  6886. case 'aten::stack':
  6887. case 'aten::tensordot':
  6888. case 'aten::add':
  6889. case 'aten::sub':
  6890. case 'aten::mul':
  6891. case 'aten::div': {
  6892. if (!node.schema().is_mutable()) {
  6893. torch._C.castInputsToWidestType(node, current_state());
  6894. }
  6895. break;
  6896. }
  6897. case 'aten::binary_cross_entropy': {
  6898. if (current_state()) {
  6899. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  6900. }
  6901. break;
  6902. }
  6903. default: {
  6904. break;
  6905. }
  6906. }
  6907. for (const sub_block of node.blocks()) {
  6908. torch._C.handleBlock(sub_block, current_state());
  6909. }
  6910. }
  6911. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  6912. */
  6913. });
  6914. this.registerFunction('torch._C.autocastEnabled', () => {
  6915. return true;
  6916. });
  6917. this.registerFunction('torch._C.Autocast', (graph) => {
  6918. if (torch._C.autocastEnabled()) {
  6919. const init = null;
  6920. /* AutocastContext init = {
  6921. at::autocast::is_autocast_enabled(at::kCUDA),
  6922. at::autocast::is_autocast_enabled(at::kCPU),
  6923. at::autocast::get_autocast_dtype(at::kCUDA),
  6924. at::autocast::get_autocast_dtype(at::kCPU)}; */
  6925. torch._C.handleBlock(graph.block(), init);
  6926. }
  6927. });
  6928. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  6929. disable_autocast = disable_autocast || false;
  6930. torch._C.Inline(graph);
  6931. torch._C.PeepholeOptimize(graph, true);
  6932. torch._C.ConstantPropagationImmutableTypes(graph);
  6933. if (!disable_autocast) {
  6934. torch._C.Autocast(graph);
  6935. }
  6936. torch._C.ConstantPooling(graph);
  6937. });
  6938. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  6939. constructor(name, graph, function_creator, executor_execution_mode) {
  6940. super();
  6941. this._name = name;
  6942. this._graph = graph;
  6943. this._executor_execution_mode = executor_execution_mode || null;
  6944. this._function_creator = function_creator;
  6945. this._force_no_amp = false;
  6946. }
  6947. isGraphFunction() {
  6948. return true;
  6949. }
  6950. qualname() {
  6951. return this._name;
  6952. }
  6953. graph() {
  6954. return this._graph;
  6955. }
  6956. optimized_graph() {
  6957. const graph_ref = this._graph.copy();
  6958. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  6959. return graph_ref;
  6960. }
  6961. ensure_defined() {
  6962. if (this._function_creator) {
  6963. const creator = this._function_creator;
  6964. this._function_creator = () => {
  6965. throw new python.Error('Recursive method call.');
  6966. };
  6967. creator(this);
  6968. this._function_creator = null;
  6969. }
  6970. this.check_single_output();
  6971. }
  6972. check_single_output() {
  6973. if (this.graph().outputs().length !== 1) {
  6974. throw new python.Error('Graph must have a single output.');
  6975. }
  6976. }
  6977. getSchema() {
  6978. this._schema = this._schema || this.defaultSchemaFor(this);
  6979. return this._schema;
  6980. }
  6981. setSchema(schema) {
  6982. this._schema = schema;
  6983. }
  6984. num_inputs() {
  6985. return this.graph().inputs().length;
  6986. }
  6987. unshapedType(type) {
  6988. if (type.isSubtypeOf(torch.TensorType.get())) {
  6989. return torch.TensorType.get();
  6990. }
  6991. const contained = type.containedTypes();
  6992. if (contained.length === 0) {
  6993. return type;
  6994. }
  6995. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  6996. }
  6997. defaultSchemaFor(fn) {
  6998. const args = [];
  6999. const returns = [];
  7000. const g = fn.graph();
  7001. const num_inputs = fn.num_inputs();
  7002. for (let i = 0; i < num_inputs; i++) {
  7003. const v = g.inputs()[i];
  7004. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7005. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7006. args.push(argument);
  7007. }
  7008. const num_outputs = g.outputs().length;
  7009. for (let i = 0; i < num_outputs; i++) {
  7010. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7011. returns.push(argument);
  7012. }
  7013. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7014. }
  7015. });
  7016. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7017. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7018. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7019. this.registerType('torch.utils._sympy.functions.FloorDiv', class {});
  7020. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7021. this.registerType('torch.utils._sympy.functions.Where', class {});
  7022. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7023. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7024. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7025. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7026. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7027. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7028. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7029. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7030. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7031. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7032. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7033. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7034. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7035. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7036. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7037. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7038. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7039. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7040. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7041. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7042. static extract() {
  7043. }
  7044. });
  7045. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7046. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7047. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7048. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7049. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7050. this.registerType('torch.utils.data.dataset.Subset', class {});
  7051. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7052. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7053. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7054. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7055. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7056. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7057. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7058. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7059. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7060. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7061. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7062. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7063. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7064. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7065. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7066. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7067. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7068. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7069. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7070. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7071. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7072. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7073. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7074. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7075. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7076. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7077. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7078. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7079. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7080. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7081. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7082. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7083. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7084. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7085. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7086. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7087. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7088. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7089. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7090. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7091. this.registerType('torch._C._LegacyVariableBase', class {});
  7092. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7093. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7094. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7095. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7096. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7097. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7098. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7099. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7100. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7101. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7102. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7103. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7104. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7105. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7106. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7107. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7108. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7109. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7110. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7111. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7112. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7113. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7114. this.registerType('torch.distributions.beta.Beta', class {});
  7115. this.registerType('torch.distributions.binomial.Binomial', class {});
  7116. this.registerType('torch.distributions.categorical.Categorical', class {});
  7117. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7118. this.registerType('torch.distributions.constraints._Interval', class {});
  7119. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7120. this.registerType('torch.distributions.constraints._Real', class {});
  7121. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7122. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7123. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7124. this.registerType('torch.distributions.normal.Normal', class {});
  7125. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7126. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7127. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7128. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7129. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7130. this.registerType('torch.distributions.uniform.Uniform', class {});
  7131. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7132. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7133. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7134. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7135. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7136. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7137. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7138. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7139. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7140. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7141. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7142. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7143. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7144. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7145. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7146. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7147. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7148. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7149. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7150. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7151. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7152. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7153. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7154. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7155. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7156. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7157. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7158. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7159. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7160. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7161. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7162. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7163. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7164. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7165. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7166. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7167. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7168. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7169. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7170. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7171. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7172. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7173. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7174. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7175. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7176. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7177. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7178. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7179. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7180. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7181. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7182. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7183. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7184. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7185. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7186. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7187. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7188. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7189. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7190. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7191. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7192. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7193. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7194. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7195. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7196. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7197. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7198. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7199. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7200. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7201. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7202. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7203. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7204. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7205. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7206. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7207. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7208. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7209. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7210. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7211. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7212. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7213. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7214. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7215. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7216. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7217. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7218. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7219. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7220. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7221. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7222. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7223. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7224. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7225. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7226. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7227. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7228. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7229. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7230. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7231. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7232. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7233. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7234. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7235. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7236. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7237. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7238. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7239. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7240. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7241. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7242. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  7243. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7244. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  7245. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  7246. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  7247. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  7248. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  7249. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  7250. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  7251. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  7252. this.registerType('torch.nn.modules.module.PatchForward', class {});
  7253. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  7254. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  7255. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  7256. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  7257. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  7258. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  7259. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7260. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7261. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7262. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  7263. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7264. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7265. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7266. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  7267. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  7268. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  7269. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  7270. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  7271. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  7272. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  7273. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  7274. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  7275. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  7276. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7277. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7278. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7279. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  7280. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  7281. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  7282. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  7283. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  7284. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  7285. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  7286. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  7287. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  7288. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  7289. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  7290. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  7291. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7292. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7293. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7294. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  7295. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7296. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7297. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7298. this.registerType('torch.nn.modules.rnn.GRU', class {});
  7299. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  7300. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  7301. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  7302. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  7303. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  7304. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  7305. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  7306. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  7307. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  7308. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  7309. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  7310. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  7311. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  7312. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  7313. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  7314. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  7315. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  7316. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  7317. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  7318. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  7319. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  7320. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  7321. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  7322. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  7323. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  7324. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  7325. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  7326. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  7327. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  7328. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  7329. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  7330. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  7331. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  7332. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  7333. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  7334. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  7335. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  7336. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  7337. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  7338. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  7339. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  7340. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  7341. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  7342. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  7343. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  7344. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  7345. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  7346. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  7347. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  7348. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  7349. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  7350. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  7351. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  7352. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  7353. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  7354. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7355. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  7356. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  7357. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  7358. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7359. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  7360. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  7361. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  7362. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  7363. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  7364. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  7365. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  7366. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  7367. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  7368. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  7369. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  7370. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  7371. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  7372. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  7373. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  7374. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  7375. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  7376. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  7377. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  7378. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  7379. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  7380. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  7381. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  7382. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  7383. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  7384. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  7385. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  7386. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  7387. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  7388. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  7389. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  7390. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  7391. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  7392. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  7393. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  7394. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  7395. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  7396. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7397. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7398. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7399. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7400. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  7401. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7402. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  7403. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  7404. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  7405. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  7406. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  7407. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  7408. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  7409. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  7410. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  7411. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  7412. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  7413. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  7414. this.registerType('torch.optim.optimizer.Optimizer', class {});
  7415. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  7416. this.registerType('torch.optim.adamw.AdamW', class {});
  7417. this.registerType('torch.optim.adagrad.Adagrad', class {});
  7418. this.registerType('torch.optim.adadelta.Adadelta', class {});
  7419. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  7420. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  7421. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  7422. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  7423. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  7424. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  7425. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  7426. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  7427. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  7428. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  7429. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  7430. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  7431. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  7432. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  7433. this.registerType('torch.optim.sgd.SGD', class {});
  7434. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  7435. this.registerType('torch.optim.swa_utils.SWALR', class {});
  7436. torch.optim.RAdam = torch.optim.radam.RAdam;
  7437. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  7438. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  7439. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  7440. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  7441. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  7442. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  7443. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7444. this.registerFunction('torch.quantization.observer._with_args');
  7445. this.registerType('torch.quantization.qconfig.QConfig', class {});
  7446. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  7447. this.registerType('torch.quantization.stubs.QuantStub', class {});
  7448. this.registerType('torch.utils._pytree.LeafSpec', class {});
  7449. this.registerType('torch.utils._pytree.TreeSpec', class {});
  7450. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  7451. __enter__() {
  7452. return this;
  7453. }
  7454. __exit__(/* exc_type, exc_value, traceback */) {
  7455. }
  7456. });
  7457. this.registerFunction('torch.utils._pytree.tree_map');
  7458. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  7459. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  7460. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  7461. this._expr = expr;
  7462. this.shape_env = shape_env;
  7463. this.pytype = pytype;
  7464. this._optimized_summation = optimized_summation;
  7465. this._hint = hint;
  7466. this.constant = constant;
  7467. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  7468. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  7469. }
  7470. __str__() {
  7471. return this._expr.__str__();
  7472. }
  7473. });
  7474. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  7475. constructor() {
  7476. this.var_to_val = new Map();
  7477. this.var_to_stack = new Map();
  7478. }
  7479. add_var_to_val(expr, val) {
  7480. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  7481. }
  7482. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  7483. }
  7484. create_symintnode(sym, hint, source) {
  7485. let out = null;
  7486. let fx_node = null;
  7487. if (this._translation_validation_enabled && source !== null) {
  7488. throw new python.Error('Not implemented.');
  7489. } else {
  7490. fx_node = null;
  7491. }
  7492. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  7493. out = builtins.int(sym);
  7494. if (hint !== null && out !== hint) {
  7495. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  7496. }
  7497. } else {
  7498. // if free_unbacked_symbols(sym):
  7499. // hint = None
  7500. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  7501. }
  7502. return out;
  7503. }
  7504. create_symboolnode(sym) {
  7505. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  7506. }
  7507. });
  7508. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  7509. /*
  7510. assert isinstance(sym, sympy.Symbol)
  7511. const name_str = sym.name.toLowerCase();
  7512. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  7513. return name_str.startsWith(prefix_str[prefix])
  7514. }
  7515. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  7516. */
  7517. return false;
  7518. });
  7519. this.registerType('sympy.printing.defaults.Printable', class {});
  7520. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  7521. constructor(...args) {
  7522. super();
  7523. this._args = args;
  7524. }
  7525. get args() {
  7526. return this._args;
  7527. }
  7528. });
  7529. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  7530. });
  7531. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  7532. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  7533. __str__() {
  7534. return this._args.map((a) => a.__str__()).join('**');
  7535. }
  7536. });
  7537. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  7538. __str__() {
  7539. return this._args.map((a) => a.__str__()).join(' + ');
  7540. }
  7541. });
  7542. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  7543. __str__() {
  7544. return this._args.map((a) => a.__str__()).join('*');
  7545. }
  7546. });
  7547. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  7548. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  7549. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  7550. constructor(value) {
  7551. super();
  7552. this.value = value;
  7553. this.is_Integer = true;
  7554. }
  7555. __int__() {
  7556. return this.value;
  7557. }
  7558. __str__() {
  7559. return this.value.toString();
  7560. }
  7561. });
  7562. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  7563. constructor(name) {
  7564. super();
  7565. this.name = name;
  7566. }
  7567. __int__() {
  7568. throw new python.Error('Cannot convert symbols to int.');
  7569. }
  7570. __str__() {
  7571. return this.name;
  7572. }
  7573. });
  7574. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  7575. constructor(lhs, rhs, op) {
  7576. super();
  7577. this._args = [lhs, rhs];
  7578. this._op = op;
  7579. }
  7580. __str__() {
  7581. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  7582. }
  7583. });
  7584. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  7585. });
  7586. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  7587. });
  7588. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  7589. constructor(lhs, rhs) {
  7590. super(lhs, rhs, '>');
  7591. }
  7592. });
  7593. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  7594. });
  7595. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  7596. constructor(lhs, rhs) {
  7597. super(lhs, rhs, '<');
  7598. }
  7599. });
  7600. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  7601. constructor(lhs, rhs) {
  7602. super(lhs, rhs, '==');
  7603. }
  7604. });
  7605. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  7606. });
  7607. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  7608. __str__() {
  7609. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  7610. }
  7611. });
  7612. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  7613. if (a instanceof sympy.core.expr.Expr) {
  7614. return a;
  7615. }
  7616. const p = ast.parse(a);
  7617. const sympify = (node) => {
  7618. if (node instanceof ast.Call) {
  7619. switch (node.func.id) {
  7620. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  7621. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  7622. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  7623. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  7624. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  7625. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  7626. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  7627. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  7628. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  7629. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  7630. }
  7631. }
  7632. if (node instanceof ast.Name) {
  7633. return new sympy.core.symbol.Symbol(node.id);
  7634. }
  7635. if (node instanceof ast.Constant) {
  7636. if (node.type === 'int') {
  7637. return new sympy.core.numbers.Integer(node.value);
  7638. }
  7639. }
  7640. if (node instanceof ast.BinOp) {
  7641. if (node.op instanceof ast.Mult) {
  7642. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  7643. }
  7644. if (node.op instanceof ast.Pow) {
  7645. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  7646. }
  7647. }
  7648. if (node instanceof ast.Compare) {
  7649. const left = sympify(node.left);
  7650. const right = sympify(node.comparators[0]);
  7651. const [op] = node.ops;
  7652. if (op instanceof ast.Gt) {
  7653. return new sympy.core.relational.GreaterThan(left, right);
  7654. }
  7655. if (op instanceof ast.Lt) {
  7656. return new sympy.core.relational.LessThan(left, right);
  7657. }
  7658. if (op instanceof ast.Eq) {
  7659. return new sympy.core.relational.Equality(left, right);
  7660. }
  7661. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  7662. }
  7663. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  7664. };
  7665. return sympify(p.body[0].value);
  7666. });
  7667. this.registerType('torch.fx.proxy.TracerBase', class {
  7668. constructor() {
  7669. this.traced_func_name = 'forward';
  7670. }
  7671. });
  7672. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  7673. trace(root /*, concrete_args */) {
  7674. let fn = null;
  7675. if (root instanceof torch.nn.Module) {
  7676. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  7677. this.root = root;
  7678. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  7679. this.root_module_name = root._get_name();
  7680. this.submodule_paths = new builtins.dict(root.named_modules());
  7681. } else {
  7682. this.root = new torch.nn.Module();
  7683. fn = root;
  7684. }
  7685. const tracer_cls = builtins.getattr(this, '__class__', null);
  7686. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  7687. if (builtins.hasattr(this, '__code__')) {
  7688. const code = fn.__code__;
  7689. this.graph._co_fields = {
  7690. co_name: code.co_name,
  7691. co_filename: code.co_filename,
  7692. co_firstlineno: code.co_firstlineno,
  7693. };
  7694. }
  7695. return this.graph;
  7696. }
  7697. is_leaf_module(m /*, module_qualified_name */) {
  7698. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  7699. }
  7700. });
  7701. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  7702. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  7703. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  7704. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  7705. return new graph_module_cls(...args);
  7706. });
  7707. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  7708. let tracer_cls = body.get('_tracer_cls');
  7709. if (!tracer_cls) {
  7710. tracer_cls = torch.fx._symbolic_trace.Tracer;
  7711. }
  7712. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  7713. const cls_tracer = tracer_cls;
  7714. const KeepModules = class extends cls_tracer {
  7715. is_leaf_module() {
  7716. return true;
  7717. }
  7718. };
  7719. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  7720. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  7721. const graph = new KeepModules().trace(com, tracer_extras);
  7722. graph._tracer_cls = tracer_cls;
  7723. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  7724. for (const [k, v] of body.items()) {
  7725. if (!builtins.hasattr(gm, k)) {
  7726. builtins.setattr(gm, k, v);
  7727. }
  7728. }
  7729. return gm;
  7730. });
  7731. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  7732. globals = { ...globals };
  7733. const context = new python.Execution.Context(globals, null);
  7734. execution.exec(src, context);
  7735. const forward_fn = globals.forward;
  7736. delete globals.forward;
  7737. return forward_fn;
  7738. });
  7739. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  7740. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  7741. let fn_src = null;
  7742. if (body.has('_code')) {
  7743. fn_src = body.get('_code');
  7744. } else if (body.has('code')) {
  7745. fn_src = body.get('code');
  7746. } else {
  7747. fn_src = body._code || body.code;
  7748. }
  7749. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  7750. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  7751. });
  7752. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  7753. const forward = importer.import_module(generated_module_name).forward;
  7754. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  7755. });
  7756. this.registerType('torch.fx.graph.CodeGen', class {});
  7757. this.registerType('torch.fx.graph._Namespace', class {
  7758. constructor() {
  7759. this._obj_to_name = new Map();
  7760. this._unassociated_names = new Set();
  7761. this._used_names = new Set();
  7762. this._base_count = {};
  7763. }
  7764. create_name(candidate, obj) {
  7765. if (obj && this._obj_to_name.has(obj)) {
  7766. return self._obj_to_name.get(obj);
  7767. }
  7768. candidate = candidate || '_unnamed';
  7769. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  7770. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  7771. const match = candidate.match(/(.*)_(\d+)$"/);
  7772. let base = candidate;
  7773. let num = null;
  7774. if (match) {
  7775. [, base] = match;
  7776. num = parseInt(match[2], 10);
  7777. }
  7778. candidate = num ? `${base}_${num}` : base;
  7779. if (!num) {
  7780. num = this._base_count[base] || 0;
  7781. }
  7782. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  7783. num += 1;
  7784. candidate = `${base}_${num}`;
  7785. }
  7786. this._used_names.add(candidate);
  7787. this._base_count[base] = num;
  7788. if (obj) {
  7789. this._obj_to_name[obj] = candidate;
  7790. } else {
  7791. this._unassociated_names.add(candidate);
  7792. }
  7793. return candidate;
  7794. }
  7795. _is_illegal_name(/* name, obj */) {
  7796. /*
  7797. if name in keyword.kwlist:
  7798. return True
  7799. if name in builtins.__dict__:
  7800. return obj is not builtins.__dict__[name]
  7801. if name in _custom_builtins:
  7802. return obj is not _custom_builtins[name].obj
  7803. */
  7804. return false;
  7805. }
  7806. associate_name_with_obj() {
  7807. }
  7808. });
  7809. this.registerType('torch.fx.node.Node', class {
  7810. constructor(graph, name, op, target, args, kwargs, return_type) {
  7811. this.graph = graph;
  7812. this.name = name;
  7813. this.op = op;
  7814. this.target = target;
  7815. this._input_nodes = new builtins.dict();
  7816. this.__update_args_kwargs(args, kwargs);
  7817. this.users = new builtins.dict();
  7818. this.type = return_type;
  7819. this._prev = this;
  7820. this._next = this;
  7821. this._erased = false;
  7822. this._repr_fn = null;
  7823. this.meta = new builtins.dict();
  7824. }
  7825. get args() {
  7826. return this._args;
  7827. }
  7828. get kwargs() {
  7829. return this._kwargs;
  7830. }
  7831. get next() {
  7832. return this._next;
  7833. }
  7834. prepend(x) {
  7835. x._remove_from_list();
  7836. const p = this._prev;
  7837. [p._next, x._prev] = [x, p];
  7838. [x._next, this._prev] = [this, x];
  7839. }
  7840. _remove_from_list() {
  7841. const [p, n] = [this._prev, this._next];
  7842. [p._next, n._prev] = [n, p];
  7843. }
  7844. __update_args_kwargs(new_args, new_kwargs) {
  7845. const update_users_and_input_nodes = (n) => {
  7846. if (n instanceof torch.fx.node.Node) {
  7847. this._input_nodes.setdefault(n);
  7848. n.users.setdefault(this);
  7849. }
  7850. return n;
  7851. };
  7852. const map_aggregate = (a, fn) => {
  7853. if (a instanceof builtins.tuple) {
  7854. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  7855. if (!builtins.hasattr(a, '_fields')) {
  7856. return t;
  7857. }
  7858. throw new python.Error('Not implemented.');
  7859. // return type(a)(*t);
  7860. } else if (Array.isArray(a)) {
  7861. return a.map((elem) => map_aggregate(elem, fn));
  7862. } else if (a instanceof builtins.dict) {
  7863. const rv = new builtins.dict();
  7864. for (const [k, v] of a) {
  7865. rv.__setitem__(k, map_aggregate(v, fn));
  7866. }
  7867. return rv;
  7868. } else if (a instanceof builtins.slice) {
  7869. throw new python.Error('Not implemented.');
  7870. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  7871. }
  7872. return fn(a);
  7873. };
  7874. for (const old_use of this._input_nodes.keys()) {
  7875. old_use.users.pop(this);
  7876. }
  7877. // object.__setattr__(self, "_input_nodes", {})
  7878. this._input_nodes = new builtins.dict();
  7879. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  7880. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  7881. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  7882. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  7883. }
  7884. });
  7885. torch.fx.Node = torch.fx.node.Node;
  7886. torch.fx.graph.Node = torch.fx.node.Node;
  7887. this.registerType('torch.fx.graph.Graph', class {
  7888. constructor(owning_module, tracer_cls, tracer_extras) {
  7889. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  7890. this._used_names = new Map();
  7891. this._len = 0;
  7892. this._graph_namespace = new torch.fx.graph._Namespace();
  7893. this._owning_module = owning_module;
  7894. this._tracer_cls = tracer_cls;
  7895. this._tracer_extras = tracer_extras;
  7896. // this._codegen = CodeGen()
  7897. // this._co_fields = {}
  7898. }
  7899. get nodes() {
  7900. const array = new Array(this._len);
  7901. let node = this._root.next;
  7902. for (let i = 0; node !== this._root; i++) {
  7903. array[i] = node;
  7904. node = node.next;
  7905. }
  7906. return array;
  7907. }
  7908. placeholder(name, type_expr /*, default_value */) {
  7909. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  7910. const kwargs = new builtins.dict();
  7911. return this.create_node('placeholder', name, args, kwargs, type_expr);
  7912. }
  7913. create_node(op, target, args, kwargs, name, type_expr) {
  7914. args = args || new builtins.tuple();
  7915. kwargs = kwargs || new builtins.dict();
  7916. const candidate = name || this._target_to_str(target);
  7917. name = this._graph_namespace.create_name(candidate, null);
  7918. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  7919. this._graph_namespace.associate_name_with_obj(name, n);
  7920. this._insert(n);
  7921. this._len += 1;
  7922. return n;
  7923. }
  7924. _insert(n) {
  7925. this._root.prepend(n);
  7926. }
  7927. output(result, type_expr) {
  7928. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  7929. }
  7930. _target_to_str(target) {
  7931. if (typeof target === 'string') {
  7932. if (target.startsWith('__') && target.endsWith('__')) {
  7933. target = target.substring(2, target.length - 2);
  7934. }
  7935. } else {
  7936. target = target.__name__;
  7937. }
  7938. return this._snake_case(target);
  7939. }
  7940. _snake_case(s) {
  7941. const chars = [];
  7942. let prev_lower = false;
  7943. for (const c of s) {
  7944. const x = c.toLowerCase();
  7945. if (prev_lower && x !== c) {
  7946. chars.push('_');
  7947. } else {
  7948. prev_lower = true;
  7949. }
  7950. chars.push(x);
  7951. }
  7952. return chars.join('');
  7953. }
  7954. });
  7955. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  7956. constructor(body) {
  7957. super();
  7958. for (const [k, v] of body.items()) {
  7959. builtins.setattr(this, k, v);
  7960. }
  7961. }
  7962. });
  7963. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  7964. constructor(root, graph, class_name) {
  7965. super();
  7966. this.__class__.__name__ = class_name || 'GraphModule';
  7967. this.graph = graph;
  7968. }
  7969. });
  7970. torch.fx.Graph = torch.fx.graph.Graph;
  7971. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  7972. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  7973. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  7974. return fn_or_name;
  7975. });
  7976. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  7977. this.registerFunction('torchvision.datasets.folder.default_loader');
  7978. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  7979. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  7980. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  7981. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  7982. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  7983. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  7984. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  7985. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  7986. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  7987. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  7988. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  7989. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  7990. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  7991. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  7992. this.registerType('torchvision.ops.misc.Permute', class {});
  7993. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  7994. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  7995. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  7996. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  7997. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  7998. this.registerType('torchvision.models._api.Weights', class {});
  7999. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8000. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8001. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8002. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8003. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8004. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8005. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8006. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8007. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8008. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8009. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8010. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8011. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8012. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8013. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8014. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8015. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8016. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8017. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8018. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8019. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8020. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8021. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8022. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8023. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8024. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8025. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8026. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8027. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8028. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8029. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8030. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8031. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8032. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8033. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8034. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8035. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8036. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8037. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8038. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8039. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8040. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8041. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8042. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8043. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8044. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8045. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8046. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8047. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8048. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8049. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8050. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8051. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8052. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8053. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8054. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8055. this.registerType('torchvision.models.googlenet.Inception', class {});
  8056. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8057. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8058. this.registerType('torchvision.models.inception.Inception3', class {});
  8059. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8060. this.registerType('torchvision.models.inception.InceptionA', class {});
  8061. this.registerType('torchvision.models.inception.InceptionB', class {});
  8062. this.registerType('torchvision.models.inception.InceptionC', class {});
  8063. this.registerType('torchvision.models.inception.InceptionD', class {});
  8064. this.registerType('torchvision.models.inception.InceptionE', class {});
  8065. this.registerFunction('torchvision.models.inception.inception_v3');
  8066. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8067. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8068. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8069. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8070. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8071. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8072. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8073. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8074. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8075. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8076. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8077. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8078. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8079. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8080. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8081. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8082. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8083. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8084. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8085. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8086. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8087. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8088. this.registerType('torchvision.models.regnet.RegNet', class {});
  8089. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8090. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8091. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8092. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8093. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8094. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8095. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8096. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8097. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8098. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8099. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8100. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8101. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8102. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8103. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8104. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8105. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8106. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8107. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8108. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8109. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8110. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8111. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8112. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8113. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8114. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8115. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8116. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8117. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8118. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8119. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8120. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8121. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8122. this.registerType('torchvision.models.resnet.ResNet', class {});
  8123. this.registerType('torchvision.models.vgg.VGG', class {});
  8124. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8125. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8126. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8127. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8128. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8129. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8130. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8131. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8132. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8133. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8134. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8135. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8136. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8137. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8138. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8139. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8140. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8141. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8142. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8143. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8144. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8145. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8146. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8147. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8148. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8149. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8150. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8151. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8152. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8153. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8154. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8155. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8156. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8157. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8158. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8159. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8160. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8161. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8162. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8163. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8164. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8165. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8166. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8167. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8168. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8169. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8170. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8171. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8172. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8173. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8174. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8175. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8176. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8177. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8178. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8179. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8180. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8181. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8182. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8183. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8184. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8185. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8186. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8187. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8188. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8189. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8190. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8191. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8192. this.registerFunction('torchvision.ops.boxes.box_iou');
  8193. this.registerFunction('builtins.annotate', (type, value) => {
  8194. if (type === builtins.int) {
  8195. return Number.isInteger(value) ? value : NaN;
  8196. }
  8197. if (type === builtins.float) {
  8198. return typeof value === 'number' ? value : NaN;
  8199. }
  8200. if (type === builtins.number) {
  8201. // if (pytorch.Utility.isTensor(value)) {
  8202. // value.resize_([]);
  8203. // }
  8204. }
  8205. return value;
  8206. });
  8207. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8208. return undefined;
  8209. });
  8210. this.registerFunction('builtins.range', (start, stop, step) => {
  8211. if (stop === undefined && step === undefined) {
  8212. if (Number.isInteger(start)) {
  8213. return Array(start).keys();
  8214. }
  8215. if (isNaN(start)) {
  8216. return [];
  8217. }
  8218. }
  8219. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8220. });
  8221. this.registerFunction('math.trunc');
  8222. builtins.xrange = builtins.range;
  8223. this.registerFunction('torch._C._nn.gelu');
  8224. this.registerFunction('torch._C._nn.avg_pool2d');
  8225. this.registerFunction('torch._C._nn.avg_pool3d');
  8226. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8227. this.registerFunction('torch._C._nn.softplus');
  8228. this.registerFunction('torch._native_multi_head_attention');
  8229. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8230. if (layout === torch.sparse_coo) {
  8231. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8232. }
  8233. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8234. });
  8235. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8236. return device;
  8237. });
  8238. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8239. device = torch._utils._get_restore_location(device);
  8240. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8241. });
  8242. this.registerFunction('torch.from_numpy', (obj) => {
  8243. const dtypes = new Map([
  8244. ['<f2', torch.float16],
  8245. ['<f4', torch.float32],
  8246. ['<f8', torch.float64],
  8247. ['<i2', torch.int16],
  8248. ['<i4', torch.int32],
  8249. ['<i8', torch.int64],
  8250. ]);
  8251. if (!dtypes.has(obj.dtype.str)) {
  8252. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8253. }
  8254. const dtype = dtypes.get(obj.dtype.str);
  8255. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8256. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8257. storage._set_cdata(obj.data);
  8258. const tensor = new torch.Tensor();
  8259. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8260. return tensor;
  8261. });
  8262. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8263. const tensor = torch.from_numpy(data);
  8264. // tensor = tensor.to(dtype, device)
  8265. tensor.requires_grad = requires_grad;
  8266. return tensor;
  8267. });
  8268. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  8269. const tensor = self.invoke('torch.Tensor', []);
  8270. tensor._layout = torch.sparse_coo;
  8271. tensor._indices = indices;
  8272. tensor._values = values;
  8273. tensor._shape = size;
  8274. return tensor;
  8275. });
  8276. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  8277. torch._C._set_tensor_metadata(tensor, metadata);
  8278. });
  8279. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  8280. return tensor;
  8281. });
  8282. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  8283. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  8284. });
  8285. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  8286. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  8287. const [, storage_type, , ,size] = storage;
  8288. storage = new storage_type(size);
  8289. }
  8290. const tensor = new torch.Tensor();
  8291. tensor.__setstate__([storage, storage_offset, size, stride]);
  8292. return tensor;
  8293. });
  8294. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  8295. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  8296. tensor.requires_grad = requires_grad;
  8297. if (metadata) {
  8298. torch._utils.set_tensor_metadata(tensor, metadata);
  8299. }
  8300. tensor.backward_hooks = backward_hooks;
  8301. return tensor;
  8302. });
  8303. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  8304. const t = new torch.Tensor(null, null, dtype);
  8305. t.set_(storage, storage_offset, size, stride);
  8306. if (metadata) {
  8307. torch._utils.set_tensor_metadata(t, metadata);
  8308. }
  8309. t._backward_hooks = backward_hooks;
  8310. return torch._utils._restore_device_fake_mode(t);
  8311. });
  8312. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  8313. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8314. param.backward_hooks = backward_hooks;
  8315. return param;
  8316. });
  8317. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  8318. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8319. param.backward_hooks = backward_hooks;
  8320. torch._utils._set_obj_state(param, state);
  8321. return param;
  8322. });
  8323. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  8324. const _set_obj_state = (obj, state) => {
  8325. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  8326. if (dict_state) {
  8327. for (const [k, v] of Object.entries(dict_state)) {
  8328. builtins.setattr(obj, k, v);
  8329. }
  8330. }
  8331. if (slots_state) {
  8332. for (const [k, v] of Object.entries(slots_state)) {
  8333. builtins.setattr(obj, k, v);
  8334. }
  8335. }
  8336. };
  8337. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8338. param._backward_hooks = backward_hooks;
  8339. _set_obj_state(param, state);
  8340. return param;
  8341. });
  8342. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  8343. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  8344. tensor.quantizer_params = quantizer_params;
  8345. return tensor;
  8346. });
  8347. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  8348. let dict_state = state;
  8349. let slots_state = null;
  8350. if (state instanceof self.builtins.tuple) {
  8351. if (state.length !== 2) {
  8352. throw new python.Error(`Invalid serialized state: '${state}'.`);
  8353. }
  8354. [dict_state, slots_state] = state;
  8355. }
  8356. if (dict_state) {
  8357. for (const [name, value] of Object.entries(dict_state)) {
  8358. builtins.setattr(obj, name, value);
  8359. }
  8360. }
  8361. if (slots_state) {
  8362. for (const [name, value] of Object.entries(slots_state)) {
  8363. builtins.setattr(obj, name, value);
  8364. }
  8365. }
  8366. return obj;
  8367. });
  8368. this.registerFunction('torch._set_item', (dict, key, value) => {
  8369. dict[key] = value;
  8370. });
  8371. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  8372. let ret = func(...args);
  8373. if (ret.__class__ !== new_type) {
  8374. // ret = ret.as_subclass(new_type);
  8375. }
  8376. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  8377. if (setstate === torch.Tensor.__setstate__) {
  8378. ret = torch._utils._set_obj_state(ret, state);
  8379. } else {
  8380. ret.__setstate__(state);
  8381. }
  8382. return ret;
  8383. });
  8384. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  8385. if (step === 0) {
  8386. throw new python.Error('range() arg 3 must not be zero');
  8387. }
  8388. if (step > 0 && lo < hi) {
  8389. return 1 + (hi - 1 - lo) / step;
  8390. } else if (step < 0 && lo > hi) {
  8391. return 1 + (lo - 1 - hi) / (0 - step);
  8392. }
  8393. return 0;
  8394. });
  8395. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  8396. this.registerOperator('aten::_unwrap_optional', (value) => {
  8397. return value;
  8398. });
  8399. this.registerFunction('torch.get_default_dtype', () => {
  8400. torch._default_type = torch._default_type || torch.float32;
  8401. return torch._default_type;
  8402. });
  8403. this.registerFunction('torch.set_default_dtype', (value) => {
  8404. torch._default_type = value;
  8405. });
  8406. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  8407. return value || torch.get_default_dtype();
  8408. });
  8409. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  8410. const shape = size;
  8411. dtype = torch._prims_common.dtype_or_default(dtype);
  8412. let storage = null;
  8413. if (size.every((d) => d instanceof torch.SymInt === false)) {
  8414. const size = shape.reduce((a, b) => a * b, 1);
  8415. storage = new torch.storage.TypedStorage(size, dtype);
  8416. }
  8417. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  8418. tensor.__setstate__([storage, 0, shape, stride]);
  8419. return tensor;
  8420. });
  8421. this.registerFunction('torch.all', (input) => {
  8422. if (Array.isArray(input) && input.length === 0) {
  8423. return true;
  8424. }
  8425. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  8426. });
  8427. this.registerFunction('torch.append', (list, value) => {
  8428. list.push(value);
  8429. return value;
  8430. });
  8431. this.registerFunction('torch.clear', (value) => {
  8432. if (value instanceof torch.Value) {
  8433. throw new python.Error('Invalid value.');
  8434. }
  8435. if (Object(value) === value) {
  8436. for (const key of Object.keys(value)) {
  8437. delete value[key];
  8438. }
  8439. }
  8440. });
  8441. this.registerFunction('torch.dict', (args) => {
  8442. const obj = {};
  8443. if (args) {
  8444. if (Array.isArray(args)) {
  8445. for (const [key, value] of args) {
  8446. obj[key] = value;
  8447. }
  8448. } else {
  8449. throw new python.Error("'torch.dict' arguments not supported.");
  8450. }
  8451. }
  8452. return obj;
  8453. });
  8454. this.registerOperator('aten::cosine_similarity', () => {
  8455. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  8456. });
  8457. this.registerOperator('aten::extend', (list, value) => {
  8458. list.push(...value);
  8459. });
  8460. this.registerOperator('aten::insert', (list, index, value) => {
  8461. list.splice(index, 0, value);
  8462. return value;
  8463. });
  8464. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  8465. return value.replace(oldvalue, newvalue);
  8466. });
  8467. this.registerOperator('aten::add', (left, right) => {
  8468. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8469. return left + right;
  8470. }
  8471. if (Array.isArray(left) && Array.isArray(right)) {
  8472. return left.concat(right);
  8473. }
  8474. if (typeof left === 'string' && typeof right === 'string') {
  8475. return left + right;
  8476. }
  8477. throw new python.Error('Unsupported aten::add expression type.');
  8478. });
  8479. this.registerOperator('aten::log', (x) => {
  8480. if (typeof x === 'number' || x instanceof Number) {
  8481. return Math.log(x);
  8482. }
  8483. throw new python.Error('Unsupported aten::log expression type.');
  8484. });
  8485. this.registerOperator('aten::dim', (tensor) => {
  8486. if (tensor && tensor.size) {
  8487. const size = tensor.size();
  8488. if (size) {
  8489. return size.length;
  8490. }
  8491. }
  8492. return NaN;
  8493. });
  8494. this.registerOperator('aten::numel', (tensor) => {
  8495. if (tensor && tensor.size) {
  8496. const size = tensor.size();
  8497. if (size) {
  8498. return size.reduce((a, b) => a * b, 1);
  8499. }
  8500. }
  8501. return NaN;
  8502. });
  8503. this.registerOperator('aten::eq', (left, right) => {
  8504. if (typeof left === 'string' && typeof right === 'string') {
  8505. return left === right;
  8506. }
  8507. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8508. if (isNaN(left) && isNaN(right)) {
  8509. return true;
  8510. }
  8511. return left === right;
  8512. }
  8513. if (left === undefined || right === undefined) {
  8514. return true;
  8515. }
  8516. if (Array.isArray(left) && Array.isArray(right)) {
  8517. return left.length === right.length && left.every((item, index) => item === right[index]);
  8518. }
  8519. throw new python.Error("Unsupported 'torch.eq' expression type.");
  8520. });
  8521. this.registerOperator('aten::floor', (value) => {
  8522. return Math.floor(value);
  8523. });
  8524. this.registerOperator('aten::ceil', (value) => {
  8525. return Math.ceil(value);
  8526. });
  8527. this.registerOperator('aten::floordiv', (left, right) => {
  8528. return Math.floor(left / right);
  8529. });
  8530. this.registerOperator('aten::format', (...args) => {
  8531. const list = args.shift().split(/({}D?)/);
  8532. return list.map((text) => {
  8533. if (text === '{}' || text === '{}D') {
  8534. const arg = args.shift();
  8535. if (Array.isArray(arg)) {
  8536. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  8537. }
  8538. return arg ? arg.toString() : '?';
  8539. }
  8540. return text;
  8541. }).join('');
  8542. });
  8543. this.registerOperator('aten::strip', (self, chars) => {
  8544. chars = chars || '\\n\\t\\f\\v';
  8545. const regex = new RegExp(`[${chars}]`, 'g');
  8546. return self.replace(regex, '');
  8547. });
  8548. this.registerOperator('aten::gt', (left, right) => {
  8549. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8550. if (!isNaN(left) && !isNaN(right)) {
  8551. return left > right;
  8552. }
  8553. }
  8554. if (isNaN(left) && !isNaN(right)) {
  8555. return true;
  8556. }
  8557. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  8558. });
  8559. this.registerOperator('aten::ge', (left, right) => {
  8560. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8561. if (!isNaN(left) && !isNaN(right)) {
  8562. return left > right;
  8563. }
  8564. }
  8565. if (isNaN(left) && !isNaN(right)) {
  8566. return true;
  8567. }
  8568. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  8569. });
  8570. this.registerOperator('aten::is_floating_point', (tensor) => {
  8571. const type = tensor.dtype.scalar_type();
  8572. return (type === 5 || type === 6 || type === 7);
  8573. });
  8574. this.registerOperator('aten::is_grad_enabled', () => {
  8575. return false;
  8576. });
  8577. this.registerOperator('aten::is_autocast_enabled', () => {
  8578. return false;
  8579. });
  8580. this.registerOperator('aten::isfinite');
  8581. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  8582. });
  8583. this.registerFunction('torch.serialization._get_layout', (name) => {
  8584. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  8585. return value instanceof torch.layout ? value : null;
  8586. });
  8587. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  8588. return torch.load(b);
  8589. });
  8590. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  8591. return data;
  8592. });
  8593. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  8594. return data;
  8595. });
  8596. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  8597. return data;
  8598. });
  8599. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  8600. return data;
  8601. });
  8602. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  8603. return self.builtins.CONSTANTS[`c${data}`];
  8604. });
  8605. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  8606. return value;
  8607. });
  8608. this.registerOperator('aten::keys', (dict) => {
  8609. return Object.keys(dict);
  8610. });
  8611. this.registerOperator('aten::len', (value) => {
  8612. if (Array.isArray(value)) {
  8613. return value.length;
  8614. }
  8615. if (value && value.shape && value.__len__) {
  8616. return value.__len__();
  8617. }
  8618. return NaN;
  8619. });
  8620. this.registerOperator('aten::le', (left, right) => {
  8621. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8622. if (isNaN(left) || isNaN(right)) {
  8623. return false;
  8624. }
  8625. return left <= right;
  8626. }
  8627. if (left === undefined || right === undefined) {
  8628. return true;
  8629. }
  8630. throw new python.Error("Unsupported 'torch.le' expression type.");
  8631. });
  8632. this.registerOperator('aten::list', (args) => {
  8633. return args;
  8634. });
  8635. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  8636. return size;
  8637. });
  8638. this.registerType('torch.PyTorchFileReader', class {
  8639. constructor(entries) {
  8640. let prefix = 0;
  8641. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  8642. for (let set = new Set(); set && paths.length > 0;) {
  8643. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  8644. set = set.size > 1 || set.keys().next().value === null ? null : set;
  8645. prefix += set ? set.keys().next().value.length + 1 : 0;
  8646. }
  8647. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  8648. this._version = 0;
  8649. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  8650. if (stream) {
  8651. const decoder = new TextDecoder('utf-8');
  8652. const buffer = stream.peek();
  8653. const text = decoder.decode(buffer);
  8654. this._version = Number(text.split('\n').shift().trim());
  8655. }
  8656. }
  8657. has_record(name) {
  8658. return this._records.has(name);
  8659. }
  8660. get_record(name) {
  8661. return this._records.get(name);
  8662. }
  8663. get_all_records() {
  8664. return Array.from(this._records.keys());
  8665. }
  8666. version() {
  8667. return this._version;
  8668. }
  8669. });
  8670. this.registerFunction('torch.load', (f) => {
  8671. const legacy_load = (entries) => {
  8672. const deserialized_objects = {};
  8673. if (entries.has('storages')) {
  8674. const data = entries.get('storages');
  8675. const unpickler = new pickle.Unpickler(data);
  8676. const num_storages = unpickler.load();
  8677. for (let i = 0; i < num_storages; i++) {
  8678. const args = unpickler.load();
  8679. const [key, , storage_type] = args;
  8680. const obj = storage_type._new_with_file(unpickler);
  8681. deserialized_objects[key] = obj;
  8682. }
  8683. /*
  8684. let storage_views = unpickler.load();
  8685. for target_cdata, root_cdata, offset, size in storage_views:
  8686. root = deserialized_objects[root_cdata]
  8687. deserialized_objects[target_cdata] = root[offset:offset + size]
  8688. */
  8689. }
  8690. if (entries.has('tensors')) {
  8691. const data = entries.get('tensors');
  8692. const unpickler = new pickle.Unpickler(data);
  8693. const num_tensors = unpickler.load();
  8694. const int32 = (unpickler) => {
  8695. const buffer = unpickler.read(4);
  8696. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  8697. };
  8698. const int64 = (unpickler) => {
  8699. const buffer = unpickler.read(8);
  8700. if (buffer[6] !== 0 && buffer[7] !== 0) {
  8701. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  8702. }
  8703. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  8704. };
  8705. for (let i = 0; i < num_tensors; i++) {
  8706. const args = unpickler.load();
  8707. const [key, storage_id] = args;
  8708. const storage = deserialized_objects[storage_id];
  8709. const ndim = int32(unpickler);
  8710. unpickler.read(4);
  8711. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  8712. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  8713. const storage_offset = int64(unpickler);
  8714. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  8715. deserialized_objects[key] = tensor;
  8716. }
  8717. }
  8718. const data = entries.get('pickle');
  8719. const unpickler = new pickle.Unpickler(data);
  8720. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  8721. return unpickler.load();
  8722. };
  8723. const _legacy_load = () => {
  8724. const unpickler = new pickle.Unpickler(f);
  8725. unpickler.load(); // magic_number
  8726. const protocol_version = unpickler.load();
  8727. if (protocol_version !== 1001) {
  8728. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  8729. }
  8730. const sys_info = unpickler.load();
  8731. if (sys_info.get('protocol_version') !== 1001) {
  8732. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  8733. }
  8734. if (sys_info.get('little_endian') === false) {
  8735. throw new python.Error("Unsupported big-endian storage data.");
  8736. }
  8737. const module_source_map = new Map();
  8738. const deserialized_objects = new Map();
  8739. unpickler.persistent_load = (saved_id) => {
  8740. switch (saved_id[0]) {
  8741. case 'module': {
  8742. const [, module, ,source] = saved_id;
  8743. module_source_map.set(module, source);
  8744. return saved_id[1];
  8745. }
  8746. case 'storage': {
  8747. const [, storage_type, key, , size, view_metadata] = saved_id;
  8748. if (!deserialized_objects.has(key)) {
  8749. const obj = new storage_type(size);
  8750. deserialized_objects.set(key, obj);
  8751. }
  8752. if (view_metadata) {
  8753. const view_key = view_metadata.shift();
  8754. view_metadata.shift(); // view_offset
  8755. view_metadata.shift(); // view_size
  8756. if (!deserialized_objects.has(view_key)) {
  8757. const view = null; // storage.slice(view_offset, view_offset + view_size);
  8758. deserialized_objects.set(view_key, view);
  8759. }
  8760. return deserialized_objects.get(view_key);
  8761. }
  8762. return deserialized_objects.get(key);
  8763. }
  8764. default: {
  8765. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  8766. }
  8767. }
  8768. };
  8769. const obj = unpickler.load();
  8770. const deserialized_storage_keys = unpickler.load();
  8771. for (const deserialized_storage_key of deserialized_storage_keys) {
  8772. const storage = deserialized_objects.get(deserialized_storage_key);
  8773. storage._set_from_file(unpickler);
  8774. }
  8775. if (!obj) {
  8776. throw new python.Error('File format is not PyTorch.');
  8777. }
  8778. if (obj === 'None') {
  8779. throw new python.Error("File contains 'None' root object.");
  8780. }
  8781. return obj;
  8782. };
  8783. const _load = (entries) => {
  8784. if (f.has('constant.pkl')) {
  8785. throw python.Error("TorchScript 'torch.load' not supported.");
  8786. }
  8787. const loaded_storages = new Map();
  8788. const persistent_load = (saved_id) => {
  8789. switch (saved_id[0]) {
  8790. case 'storage': {
  8791. const [, storage_type, key, , numel] = saved_id;
  8792. if (!loaded_storages.has(key)) {
  8793. const storage = new storage_type(numel);
  8794. const name = `data/${key}`;
  8795. const stream = entries.get(name);
  8796. storage._set_cdata(stream);
  8797. loaded_storages.set(key, storage);
  8798. }
  8799. return loaded_storages.get(key);
  8800. }
  8801. default: {
  8802. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  8803. }
  8804. }
  8805. };
  8806. const data_file = entries.get('data.pkl');
  8807. const unpickler = new pickle.Unpickler(data_file);
  8808. unpickler.persistent_load = persistent_load;
  8809. const result = unpickler.load();
  8810. return result;
  8811. };
  8812. if (f instanceof Map) {
  8813. const reader = new torch.PyTorchFileReader(f);
  8814. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  8815. f = new Map(records);
  8816. if (f.has('pickle')) {
  8817. return legacy_load(f);
  8818. }
  8819. if (f.has('data.pkl')) {
  8820. return _load(f);
  8821. }
  8822. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  8823. }
  8824. return _legacy_load(f);
  8825. });
  8826. this.registerOperator('prim::unchecked_cast', (type, value) => {
  8827. return value;
  8828. });
  8829. this.registerOperator('prim::data', (tensor) => {
  8830. return tensor;
  8831. });
  8832. this.registerOperator('prim::device', (tensor) => {
  8833. return tensor.device;
  8834. });
  8835. this.registerOperator('prim::dtype', (tensor) => {
  8836. return tensor.dtype.scalar_type();
  8837. });
  8838. this.registerOperator('prim::is_quantized', (tensor) => {
  8839. return tensor.is_quantized;
  8840. });
  8841. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  8842. return false;
  8843. });
  8844. this.registerOperator('prim::is_nested', (tensor) => {
  8845. return tensor.is_nested;
  8846. });
  8847. this.registerOperator('prim::is_sparse', (tensor) => {
  8848. return tensor.is_sparse;
  8849. });
  8850. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  8851. return value;
  8852. });
  8853. this.registerOperator('prim::NumToTensor', (value) => {
  8854. const tensor = self.invoke('torch.Tensor', []);
  8855. tensor.value = value;
  8856. return tensor;
  8857. });
  8858. this.registerOperator('prim::min', (...args) => {
  8859. if (Array.isArray(args[0])) {
  8860. return Math.min.apply(null, args[0]);
  8861. }
  8862. return Math.min.apply(null, args);
  8863. });
  8864. this.registerOperator('prim::max', (...args) => {
  8865. if (Array.isArray(args[0])) {
  8866. return Math.max.apply(null, args[0]);
  8867. }
  8868. return Math.max.apply(null, args);
  8869. });
  8870. this.registerOperator('prim::shape', (tensor) => {
  8871. return tensor && tensor.size ? tensor.size() : undefined;
  8872. });
  8873. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  8874. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  8875. params.weight = weight;
  8876. params.bias = bias;
  8877. params.stride = stride;
  8878. params.padding = padding;
  8879. params.dilation = dilation;
  8880. params.groups = groups;
  8881. return params;
  8882. });
  8883. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  8884. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  8885. params.weight = weight;
  8886. params.bias = bias;
  8887. params.stride = stride;
  8888. params.padding = padding;
  8889. params.dilation = dilation;
  8890. params.groups = groups;
  8891. return params;
  8892. });
  8893. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  8894. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  8895. params.weight = weight;
  8896. params.bias = bias;
  8897. params.stride = stride;
  8898. params.padding = padding;
  8899. params.dilation = dilation;
  8900. params.groups = groups;
  8901. return params;
  8902. });
  8903. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  8904. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  8905. params.weight = weight;
  8906. params.bias = bias;
  8907. params.stride = stride;
  8908. params.padding = padding;
  8909. params.dilation = dilation;
  8910. params.groups = groups;
  8911. return params;
  8912. });
  8913. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  8914. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  8915. params.weight = weight;
  8916. params.bias = bias;
  8917. params.stride = stride;
  8918. params.padding = padding;
  8919. params.output_padding = output_padding;
  8920. params.dilation = dilation;
  8921. params.groups = groups;
  8922. return params;
  8923. });
  8924. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  8925. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  8926. params.weight = weight;
  8927. params.bias = bias;
  8928. params.stride = stride;
  8929. params.padding = padding;
  8930. params.output_padding = output_padding;
  8931. params.dilation = dilation;
  8932. params.groups = groups;
  8933. return params;
  8934. });
  8935. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  8936. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  8937. params.weight = weight;
  8938. params.bias = bias;
  8939. return params;
  8940. });
  8941. this.registerOperator('prim::RaiseException', (message) => {
  8942. throw new python.Error(message);
  8943. });
  8944. this.registerOperator('prim::TupleIndex', (t, i) => {
  8945. return t.elements()[i];
  8946. });
  8947. this.registerOperator('prim::TupleUnpack', (t) => {
  8948. return t.elements();
  8949. });
  8950. this.registerOperator('aten::is_scripting', () => {
  8951. return true;
  8952. });
  8953. this.registerOperator('aten::__and__', (left, right) => {
  8954. return left && right;
  8955. });
  8956. this.registerOperator('aten::__contains__', (dict, key) => {
  8957. return builtins.hasattr(dict, key);
  8958. });
  8959. this.registerFunction('torch.__derive_index', (index, start, step) => {
  8960. return start + index * step;
  8961. });
  8962. this.registerOperator('aten::__is__', (left, right) => {
  8963. return left === right;
  8964. });
  8965. this.registerOperator('aten::__isnot__', (left, right) => {
  8966. return left !== right;
  8967. });
  8968. this.registerOperator('aten::__not__', (value) => {
  8969. if (Number.isInteger(value)) {
  8970. value = Boolean(value);
  8971. }
  8972. if (typeof value === 'boolean') {
  8973. return !value;
  8974. }
  8975. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  8976. });
  8977. this.registerOperator('aten::log10', (value) => {
  8978. return Math.log10(value);
  8979. });
  8980. this.registerOperator('aten::device', (type, index) => {
  8981. return new torch.device(type, index);
  8982. });
  8983. this.registerOperator('aten::lt', (left, right) => {
  8984. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8985. return left < right;
  8986. }
  8987. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  8988. });
  8989. this.registerOperator('aten::mul', (left, right) => {
  8990. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8991. return left * right;
  8992. }
  8993. if (isNaN(left) || isNaN(right)) {
  8994. return NaN;
  8995. }
  8996. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8997. return left.map((value) => value * right);
  8998. }
  8999. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9000. });
  9001. this.registerOperator('aten::div', (left, right) => {
  9002. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9003. return left / right;
  9004. }
  9005. if (isNaN(left) || isNaN(right)) {
  9006. return NaN;
  9007. }
  9008. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9009. });
  9010. this.registerFunction('torch.round', (value) => {
  9011. if (typeof value === 'number' || value instanceof Number) {
  9012. return Math.round(value);
  9013. }
  9014. if (isNaN(value)) {
  9015. return value;
  9016. }
  9017. throw new python.Error("Unsupported 'torch.round' expression type.");
  9018. });
  9019. this.registerOperator('aten::remainder', (left, right) => {
  9020. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9021. return left % right;
  9022. }
  9023. if (isNaN(left) || isNaN(right)) {
  9024. return NaN;
  9025. }
  9026. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9027. });
  9028. this.registerOperator('aten::ne', (left, right) => {
  9029. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9030. return left !== right;
  9031. }
  9032. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9033. if (isNaN(left) || isNaN(right)) {
  9034. return false;
  9035. }
  9036. return left !== right;
  9037. }
  9038. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9039. return false;
  9040. }
  9041. if (typeof left === 'string' && typeof right === 'string') {
  9042. return left !== right;
  9043. }
  9044. if (left === undefined || right === undefined) {
  9045. return true;
  9046. }
  9047. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9048. });
  9049. this.registerOperator('aten::neg', (value) => {
  9050. if (typeof value === 'number') {
  9051. return -value;
  9052. }
  9053. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9054. });
  9055. this.registerOperator('aten::pow', (left, right) => {
  9056. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9057. return Math.pow(left, right);
  9058. }
  9059. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9060. });
  9061. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9062. return -1;
  9063. });
  9064. this.registerFunction('torch.t', (tensor) => {
  9065. return tensor;
  9066. });
  9067. this.registerOperator('aten::size', (tensor, dim) => {
  9068. if (tensor && tensor.size) {
  9069. const size = tensor.size();
  9070. if (Array.isArray(size)) {
  9071. if (dim === undefined) {
  9072. return size;
  9073. }
  9074. if (Number.isInteger(dim)) {
  9075. if (dim >= 0 && dim < size.length) {
  9076. return size[dim];
  9077. }
  9078. if (dim < 0 && -dim < size.length) {
  9079. return size[size.length + dim];
  9080. }
  9081. }
  9082. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9083. }
  9084. }
  9085. if (Number.isInteger(dim)) {
  9086. return NaN;
  9087. }
  9088. return [];
  9089. });
  9090. this.registerFunction('aten::sqrt', (x) => {
  9091. return Math.sqrt(x);
  9092. });
  9093. this.registerOperator('aten::slice', (l, start, end, step) => {
  9094. if (!Array.isArray(l)) {
  9095. throw new python.Error('Slicing expected array');
  9096. }
  9097. step = step || 1;
  9098. if (step !== 1) {
  9099. throw new python.Error('Slicing only supports step=1');
  9100. }
  9101. start = Math.max(0, start >= 0 ? start : l.length + start);
  9102. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9103. return l.slice(start, end);
  9104. });
  9105. this.registerOperator('aten::sub', (left, right) => {
  9106. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9107. return left - right;
  9108. }
  9109. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9110. });
  9111. this.registerFunction('torch.sym_int');
  9112. this.registerFunction('torch.sym_float');
  9113. this.registerFunction('torch.sym_ite');
  9114. this.registerFunction('torch.sym_max');
  9115. this.registerFunction('torch.sym_min');
  9116. this.registerFunction('torch.sym_not');
  9117. this.registerFunction('torch.sym_sqrt');
  9118. this.registerFunction('torch.sym_sqrt');
  9119. this.registerFunction('torch.functional.einsum');
  9120. this.registerFunction('torch.functional.norm');
  9121. this.registerFunction('torch.functional.split');
  9122. this.registerFunction('torch.nn.init.constant_');
  9123. this.registerFunction('torch.nn.init.normal_');
  9124. this.registerFunction('torch.nn.init.xavier_uniform_');
  9125. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9126. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9127. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9128. this.registerFunction('torch.nn.functional.cross_entropy');
  9129. this.registerFunction('torch.nn.functional.elu');
  9130. this.registerFunction('torch.nn.functional.gelu');
  9131. this.registerFunction('torch.nn.functional.hardsigmoid');
  9132. this.registerFunction('torch.nn.functional.hardswish');
  9133. this.registerFunction('torch.nn.functional.hardtanh');
  9134. this.registerFunction('torch.nn.functional.interpolate');
  9135. this.registerFunction('torch.nn.functional.leaky_relu');
  9136. this.registerFunction('torch.nn.functional.l1_loss');
  9137. this.registerFunction('torch.nn.functional.linear');
  9138. this.registerFunction('torch.nn.functional.log_softmax');
  9139. this.registerFunction('torch.nn.functional._max_pool2d');
  9140. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9141. this.registerFunction('torch.nn.functional.mse_loss');
  9142. this.registerFunction('torch.nn.functional.pad');
  9143. this.registerFunction('torch.nn.functional.relu');
  9144. this.registerFunction('torch.nn.functional.relu6');
  9145. this.registerFunction('torch.nn.functional.sigmoid');
  9146. this.registerFunction('torch.nn.functional.silu');
  9147. this.registerFunction('torch.nn.functional.softmax');
  9148. this.registerFunction('torch.nn.functional.tanh');
  9149. this.registerFunction('torch.values', (dict) => {
  9150. return Object.values(dict);
  9151. });
  9152. this.registerFunction('torch.warn', () => {
  9153. });
  9154. this.registerType('torch._ops.OperatorBase', class {
  9155. constructor() {
  9156. this.functorch_table = {};
  9157. }
  9158. });
  9159. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9160. constructor(name, cacheable) {
  9161. super();
  9162. this._name = name;
  9163. this.__name__ = name;
  9164. // _higher_order_ops[name] = this;
  9165. this._ns = 'higher_order';
  9166. this.__module__ = 'torch.ops.higher_order';
  9167. this._cacheable = cacheable;
  9168. }
  9169. });
  9170. this.registerType('torch.Type', class {
  9171. constructor(kind, annotation_str) {
  9172. this._kind = kind;
  9173. if (annotation_str) {
  9174. this._annotation_str = annotation_str;
  9175. }
  9176. }
  9177. static get(kind, annotation_str) {
  9178. torch.Type.cache = torch.Type.cache || new Map();
  9179. if (!annotation_str) {
  9180. if (!torch.Type.cache.has(kind)) {
  9181. torch.Type.cache.set(kind, new torch.Type(kind));
  9182. }
  9183. return torch.Type.cache.get(kind);
  9184. }
  9185. return new torch.Type(kind, annotation_str);
  9186. }
  9187. kind() {
  9188. return this._kind;
  9189. }
  9190. get annotation_str() {
  9191. return this._annotation_str;
  9192. }
  9193. equals(rhs) {
  9194. return this.kind() === rhs.kind();
  9195. }
  9196. isSubtypeOf(rhs) {
  9197. if (rhs.kind() === 'AnyType' || this === rhs) {
  9198. return true;
  9199. }
  9200. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  9201. return this.isSubtypeOf(rhs.getElementType());
  9202. }
  9203. if (rhs instanceof torch.UnionType) {
  9204. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  9205. }
  9206. if (rhs instanceof torch._C.DynamicType) {
  9207. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  9208. }
  9209. return this.equals(rhs);
  9210. }
  9211. containedTypes() {
  9212. return [];
  9213. }
  9214. containedType(i) {
  9215. return this.containedTypes()[i];
  9216. }
  9217. withContained(contained_types) {
  9218. const current_contained = this.containedTypes();
  9219. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  9220. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  9221. return this;
  9222. }
  9223. return this.createWithContained(contained_types);
  9224. }
  9225. createWithContained(/* createWithContained */) {
  9226. throw new python.Error('Not implemented.');
  9227. }
  9228. isUnionType() {
  9229. return false;
  9230. }
  9231. hasFreeVariables() {
  9232. return false;
  9233. }
  9234. is_module() {
  9235. return false;
  9236. }
  9237. expect(type) {
  9238. torch._C.AT_ASSERT(this instanceof type);
  9239. return this;
  9240. }
  9241. str() {
  9242. if (this instanceof torch._C.VarType && this._annotation_str) {
  9243. return this._annotation_str;
  9244. } else if (this._kind === 'ScalarTypeType') {
  9245. return 'ScalarType';
  9246. } else if (this._kind === 'QSchemeType') {
  9247. return 'QScheme';
  9248. } else if (this._kind) {
  9249. return this._kind;
  9250. }
  9251. throw new python.Error(`Not implemented '${this.kind()}'.`);
  9252. }
  9253. __str__() {
  9254. return this.str();
  9255. }
  9256. toString() {
  9257. return this.__str__();
  9258. }
  9259. });
  9260. this.registerType('torch.ClassType', class extends torch.Type {
  9261. constructor(qualified_name, cu, is_module) {
  9262. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  9263. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  9264. this._is_module = is_module;
  9265. this._attributes = [];
  9266. this._attributeTypes = [];
  9267. this._methods = [];
  9268. this._staticmethods = new Map();
  9269. this._forward_hooks = [];
  9270. this._forward_pre_hooks = [];
  9271. this._properties = [];
  9272. this._constants = new Map();
  9273. }
  9274. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  9275. return new torch.ClassType(qualifiedName, cu, is_module);
  9276. }
  9277. qualified_name() {
  9278. return this.annotation_str;
  9279. }
  9280. name() {
  9281. return this._name;
  9282. }
  9283. is_module() {
  9284. return this._is_module;
  9285. }
  9286. is_parameter(slot) {
  9287. return this._attributes[slot].is_parameter === true;
  9288. }
  9289. is_buffer(slot) {
  9290. return this._attributes[slot].is_buffer === true;
  9291. }
  9292. addMethod(method) {
  9293. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  9294. this._methods.push(method);
  9295. }
  9296. findMethod(name) {
  9297. for (const method of this._methods) {
  9298. if (name === method.name()) {
  9299. return method;
  9300. }
  9301. }
  9302. return null;
  9303. }
  9304. getMethod(name) {
  9305. const method = this.findMethod(name);
  9306. if (!method) {
  9307. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  9308. }
  9309. return method;
  9310. }
  9311. methods() {
  9312. return this._methods;
  9313. }
  9314. addStaticMethod(func) {
  9315. this._staticmethods.set(func.name, func);
  9316. }
  9317. findStaticMethod(name) {
  9318. return this._staticmethods.get(name);
  9319. }
  9320. findHook(name) {
  9321. let hook = this.findForwardHook(name);
  9322. if (hook === null) {
  9323. hook = this.findForwardPreHook(name);
  9324. }
  9325. return hook;
  9326. }
  9327. findForwardHook(name) {
  9328. for (const hook of this._forward_hooks) {
  9329. if (name === hook.name()) {
  9330. return hook;
  9331. }
  9332. }
  9333. return null;
  9334. }
  9335. findForwardPreHook(name) {
  9336. for (const pre_hook of this._forward_pre_hooks) {
  9337. if (name === pre_hook.name()) {
  9338. return pre_hook;
  9339. }
  9340. }
  9341. return null;
  9342. }
  9343. numAttributes() {
  9344. return this._attributes.length;
  9345. }
  9346. addAttribute(name, type, is_parameter, is_buffer) {
  9347. is_parameter = is_parameter || false;
  9348. is_buffer = is_buffer || false;
  9349. const slot = this._attributes.length;
  9350. this._attributes.push({ name, type, is_parameter, is_buffer });
  9351. this._attributeTypes.push(type);
  9352. return slot;
  9353. }
  9354. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  9355. is_parameter = is_parameter || false;
  9356. is_buffer = is_buffer || false;
  9357. const slot_idx = this.findAttributeSlot(name);
  9358. if (slot_idx === null) {
  9359. return this.addAttribute(name, ty, is_parameter, is_buffer);
  9360. }
  9361. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  9362. // const TypePtr& atype = getAttribute(*slot_idx);
  9363. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  9364. return slot_idx;
  9365. }
  9366. findAttributeSlot(name) {
  9367. for (let pos = 0; pos < this._attributes.length; pos++) {
  9368. if (name === this._attributes[pos].name) {
  9369. return pos;
  9370. }
  9371. }
  9372. return null;
  9373. }
  9374. findAttribute(name) {
  9375. const slot = this.findAttributeSlot(name);
  9376. if (slot !== null) {
  9377. return this._attributes[slot].type;
  9378. }
  9379. return null;
  9380. }
  9381. hasAttribute(name) {
  9382. return this._attributes.find((attr) => attr.name === name);
  9383. }
  9384. getAttribute(arg) {
  9385. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  9386. return this._attributes[slot].type;
  9387. }
  9388. getAttributeName(slot) {
  9389. return this._attributes[slot].name;
  9390. }
  9391. addConstant(name, value) {
  9392. this._constants.set(name, value);
  9393. }
  9394. hasConstant(name) {
  9395. return this._constants.has(name);
  9396. }
  9397. getProperty(name) {
  9398. for (const prop of this._properties) {
  9399. if (name === prop.name) {
  9400. return prop;
  9401. }
  9402. }
  9403. return null;
  9404. }
  9405. containedTypes() {
  9406. return this._attributeTypes;
  9407. }
  9408. createWithContained(contained_types) {
  9409. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  9410. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  9411. for (let i = 0; i < this._attributes.length; i++) {
  9412. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  9413. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  9414. }
  9415. for (const method of this.methods()) {
  9416. ptr.addMethod(method);
  9417. }
  9418. return ptr;
  9419. }
  9420. str() {
  9421. return this.qualified_name();
  9422. }
  9423. });
  9424. this.registerType('torch.EnumType', class extends torch.Type {
  9425. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  9426. super('EnumType', qualified_class_name);
  9427. this._name = qualified_class_name;
  9428. this._value_type = value_type;
  9429. this._enum_names_values = enum_names_values;
  9430. this._cu = cu;
  9431. }
  9432. static create(qualified_class_name, value, enum_names_values, cu) {
  9433. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  9434. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  9435. }
  9436. torch._C.TORCH_CHECK(false);
  9437. return null;
  9438. }
  9439. name() {
  9440. return this._name;
  9441. }
  9442. get annotation_str() {
  9443. return this._name.qualifiedName();
  9444. }
  9445. enumNamesValues() {
  9446. return this._enum_names_values;
  9447. }
  9448. compilation_unit() {
  9449. return this._cu;
  9450. }
  9451. getValueType() {
  9452. return this._value_type;
  9453. }
  9454. equals(rhs) {
  9455. if (rhs instanceof torch.EnumType) {
  9456. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  9457. }
  9458. return false;
  9459. }
  9460. isSubtypeOf(rhs) {
  9461. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  9462. return true;
  9463. }
  9464. return super.isSubtypeOf(rhs);
  9465. }
  9466. });
  9467. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  9468. if (args.length === 1) {
  9469. const [to_flatten] = args;
  9470. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  9471. const to_fill = [];
  9472. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  9473. to_flatten.splice(0, to_flatten.length);
  9474. to_flatten.push(...to_fill);
  9475. } else if (args.length === 2) {
  9476. const [reference, to_fill] = args;
  9477. for (const type of reference) {
  9478. torch._C.flattenUnion(type, to_fill);
  9479. }
  9480. torch._C.filterDuplicateSubtypes(to_fill);
  9481. torch._C.sortUnion(to_fill);
  9482. } else {
  9483. throw new python.Error('Not implemented.');
  9484. }
  9485. });
  9486. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  9487. if (type instanceof torch.UnionType) {
  9488. for (const inner of type.containedTypes()) {
  9489. torch._C.flattenUnion(inner, to_fill);
  9490. }
  9491. } else if (type instanceof torch.OptionalType) {
  9492. const inner = type.getElementType();
  9493. torch._C.flattenUnion(inner, to_fill);
  9494. to_fill.push(torch.NoneType.get());
  9495. } else if (type instanceof torch.NumberType) {
  9496. to_fill.push(torch.IntType.get());
  9497. to_fill.push(torch.FloatType.get());
  9498. to_fill.push(torch.ComplexType.get());
  9499. } else {
  9500. to_fill.push(type);
  9501. }
  9502. });
  9503. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  9504. if (types.length === 0) {
  9505. // return;
  9506. }
  9507. /*
  9508. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  9509. // We don't want nested Optionals. Also, prematurely unifying to
  9510. // `Optional` could prevent us from coalescing other types
  9511. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  9512. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  9513. return null;
  9514. } else {
  9515. return unifyTypes(t1, t2, default_to_union=false);
  9516. }
  9517. };
  9518. size_t end_idx = types->size()-1;
  9519. for (size_t i = types->size()-1; i > 0; --i) {
  9520. for (size_t j = std::min(i-1, end_idx); ; --j) {
  9521. std::optional<TypePtr> unified;
  9522. unified = get_supertype((*types)[i], (*types)[j]);
  9523. if (unified) {
  9524. (*types)[j] = *unified;
  9525. (*types)[i] = (*types)[end_idx];
  9526. --end_idx;
  9527. break;
  9528. }
  9529. if (j == 0) {
  9530. break;
  9531. }
  9532. }
  9533. }
  9534. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  9535. */
  9536. });
  9537. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  9538. /*
  9539. std::sort(types->begin(), types->end(),
  9540. [](const TypePtr& a, const TypePtr& b) -> bool {
  9541. if (a->kind() != b->kind()) {
  9542. return a->kind() < b->kind();
  9543. }
  9544. return a->str() < b->str();
  9545. });
  9546. */
  9547. });
  9548. this.registerType('torch.UnionType', class extends torch.Type {
  9549. constructor(reference, kind) {
  9550. super(kind || 'UnionType');
  9551. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  9552. this._types = [];
  9553. torch._C.standardizeVectorForUnion(reference, this._types);
  9554. if (this._types.length === 1) {
  9555. throw new python.Error('Invalid union type reference.');
  9556. }
  9557. this._can_hold_none = false;
  9558. this._has_free_variables = false;
  9559. for (const type of this._types) {
  9560. if (type instanceof torch.NoneType) {
  9561. this._can_hold_none = true;
  9562. }
  9563. if (type.hasFreeVariables()) {
  9564. this._has_free_variables = true;
  9565. }
  9566. }
  9567. }
  9568. static create(reference) {
  9569. const union_type = new torch.UnionType(reference);
  9570. /*
  9571. bool int_found = false;
  9572. bool float_found = false;
  9573. bool complex_found = false;
  9574. bool nonetype_found = false;
  9575. const update_is_opt_flags = [&](const TypePtr& t) {
  9576. if (t == IntType::get()) {
  9577. int_found = true;
  9578. } else if (t == FloatType::get()) {
  9579. float_found = true;
  9580. } else if (t == ComplexType::get()) {
  9581. complex_found = true;
  9582. } else if (t == NoneType::get()) {
  9583. nonetype_found = true;
  9584. }
  9585. };
  9586. for (const auto& t : union_type->containedTypes()) {
  9587. update_is_opt_flags(t);
  9588. }
  9589. bool numbertype_found = int_found && float_found && complex_found;
  9590. if (nonetype_found) {
  9591. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  9592. return OptionalType::create(NumberType::get());
  9593. }
  9594. if (union_type->containedTypes().size() == 2) {
  9595. const not_none = union_type->containedTypes()[0] != NoneType::get()
  9596. ? union_type->containedTypes()[0]
  9597. : union_type->containedTypes()[1];
  9598. return OptionalType::create(not_none);
  9599. }
  9600. }
  9601. */
  9602. return union_type;
  9603. }
  9604. containedTypes() {
  9605. return this._types;
  9606. }
  9607. isUnionType() {
  9608. return true;
  9609. }
  9610. hasFreeVariables() {
  9611. return this._has_free_variables;
  9612. }
  9613. equals(rhs) {
  9614. if (rhs instanceof torch.UnionType) {
  9615. if (rhs.containedTypes().length !== this.containedTypes().length) {
  9616. return false;
  9617. }
  9618. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  9619. } else if (rhs instanceof torch.OptionalType) {
  9620. if (rhs.getElementType() === torch.NumberType.get()) {
  9621. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  9622. }
  9623. const optional_lhs = this.toOptional();
  9624. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  9625. } else if (rhs instanceof torch.NumberType) {
  9626. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  9627. }
  9628. return false;
  9629. }
  9630. isSubtypeOf(rhs) {
  9631. const rhs_types = [];
  9632. if (rhs instanceof torch.UnionType) {
  9633. if (this.containedTypes() === rhs.containedTypes()) {
  9634. return true;
  9635. }
  9636. for (const typePtr of rhs.containedTypes()) {
  9637. rhs_types.push(typePtr);
  9638. }
  9639. } else if (rhs instanceof torch.OptionalType) {
  9640. rhs_types.push(torch.NoneType.get());
  9641. if (rhs.getElementType() === torch.NumberType.get()) {
  9642. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  9643. rhs_types.push(...number_types);
  9644. } else {
  9645. rhs_types.push(rhs.getElementType());
  9646. }
  9647. } else if (rhs instanceof torch.NumberType) {
  9648. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  9649. rhs_types.push(...number_types);
  9650. } else {
  9651. rhs_types.push(rhs);
  9652. }
  9653. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  9654. }
  9655. });
  9656. this.registerType('torch.OptionalType', class extends torch.UnionType {
  9657. constructor(contained) {
  9658. super([contained, torch.NoneType.get()], 'OptionalType');
  9659. let is_numbertype = false;
  9660. if (contained instanceof torch.UnionType) {
  9661. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  9662. }
  9663. if (super.containedTypes().length === 2) {
  9664. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  9665. } else if (contained === torch.NumberType.get() || is_numbertype) {
  9666. this._contained = torch.NumberType.get();
  9667. this._types.splice(0, this._types.length);
  9668. this._types.push(torch.NumberType.get());
  9669. this._types.push(torch.NoneType.get());
  9670. } else {
  9671. const to_subtract = [torch.NoneType.get()];
  9672. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  9673. this._contained = torch.UnionType.create([without_none]);
  9674. }
  9675. this._has_free_variables = contained.hasFreeVariables();
  9676. }
  9677. static create(elem) {
  9678. return new torch.OptionalType(elem);
  9679. }
  9680. getElementType() {
  9681. return this._contained;
  9682. }
  9683. equals(rhs) {
  9684. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  9685. }
  9686. isSubtypeOf(rhs) {
  9687. if (rhs instanceof torch.OptionalType) {
  9688. return this.getElementType().isSubtypeOf(rhs.getElementType());
  9689. } else if (rhs instanceof torch.UnionType) {
  9690. throw new python.Error('Not implemented.');
  9691. }
  9692. // return super.isSubtypeOf(rhs);
  9693. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  9694. }
  9695. containedTypes() {
  9696. return [this._contained];
  9697. }
  9698. createWithContained(contained_types) {
  9699. torch._C.AT_ASSERT(contained_types.length === 1);
  9700. return torch.OptionalType.create(contained_types[0]);
  9701. }
  9702. subtractTypeSetFrom(to_subtract, from) {
  9703. const types = [];
  9704. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  9705. for (const t of from) {
  9706. if (!should_subtract(t)) {
  9707. types.push(t);
  9708. }
  9709. }
  9710. if (types.length === 0) {
  9711. return null;
  9712. } else if (types.length === 1) {
  9713. return types[0];
  9714. }
  9715. return torch.UnionType.create(types);
  9716. }
  9717. str() {
  9718. return `${this.getElementType().str()}?`;
  9719. }
  9720. __str__() {
  9721. return `Optional[${this.getElementType().__str__()}]`;
  9722. }
  9723. });
  9724. this.registerType('torch.ListType', class extends torch.Type {
  9725. constructor(elem) {
  9726. super('ListType');
  9727. this._elem = elem;
  9728. }
  9729. static create(elem) {
  9730. return new torch.ListType(elem);
  9731. }
  9732. getElementType() {
  9733. return this._elem;
  9734. }
  9735. equals(rhs) {
  9736. if (rhs instanceof torch.ListType) {
  9737. return this.getElementType().equals(rhs.getElementType());
  9738. }
  9739. return false;
  9740. }
  9741. isSubtypeOf(rhs) {
  9742. if (super.isSubtypeOf(rhs)) {
  9743. return true;
  9744. }
  9745. if (rhs.kind() === 'AnyListType') {
  9746. return true;
  9747. }
  9748. return false;
  9749. }
  9750. containedTypes() {
  9751. return [this._elem];
  9752. }
  9753. createWithContained(contained_types) {
  9754. return new torch.ListType(contained_types[0]);
  9755. }
  9756. hasFreeVariables() {
  9757. return this.getElementType().hasFreeVariables();
  9758. }
  9759. str() {
  9760. return `${this.getElementType().str()}[]`;
  9761. }
  9762. __str__() {
  9763. return `List[${this.getElementType().__str__()}]`;
  9764. }
  9765. });
  9766. this.registerType('torch.FutureType', class extends torch.Type {
  9767. constructor(elem) {
  9768. super('FutureType');
  9769. this._elem = elem;
  9770. }
  9771. static create(elem) {
  9772. return new torch.FutureType(elem);
  9773. }
  9774. getElementType() {
  9775. return this._elem;
  9776. }
  9777. containedTypes() {
  9778. throw new python.Error('Not implemented.');
  9779. }
  9780. str() {
  9781. return `Future(${this.getElementType().str()})`;
  9782. }
  9783. __str__() {
  9784. return `Future[${this.getElementType().__str__()}]`;
  9785. }
  9786. });
  9787. this.registerType('torch.RRefType', class extends torch.Type {
  9788. constructor(elem) {
  9789. super('RRefType');
  9790. this._elem = elem;
  9791. }
  9792. static create(elem) {
  9793. return new torch.RRefType(elem);
  9794. }
  9795. getElementType() {
  9796. return this._elem;
  9797. }
  9798. containedTypes() {
  9799. throw new python.Error('Not implemented.');
  9800. }
  9801. str() {
  9802. return `RRef(${this.getElementType().str()})`;
  9803. }
  9804. __str__() {
  9805. return `RRef[${this.getElementType().__str__()}]`;
  9806. }
  9807. });
  9808. this.registerType('torch.AwaitType', class extends torch.Type {
  9809. constructor(elem) {
  9810. super('AwaitType');
  9811. this._elem = elem;
  9812. }
  9813. static get(elem) {
  9814. return new torch.AwaitType(elem);
  9815. }
  9816. getElementType() {
  9817. return this._elem;
  9818. }
  9819. containedTypes() {
  9820. throw new python.Error('Not implemented.');
  9821. }
  9822. str() {
  9823. return `Await(${this.getElementType().str()})`;
  9824. }
  9825. __str__() {
  9826. return `Await[${this.getElementType().__str__()}]`;
  9827. }
  9828. });
  9829. this.registerType('torch.TupleType', class extends torch.Type {
  9830. constructor(elements, annotation_str, schema) {
  9831. super('TupleType', annotation_str);
  9832. this._elements = elements;
  9833. this._has_free_variables = elements.some((v) => {
  9834. if (!v) {
  9835. throw new python.Error('Can not create tuple with None type');
  9836. }
  9837. return v.hasFreeVariables();
  9838. });
  9839. this._schema = schema;
  9840. }
  9841. static create(elements) {
  9842. return new torch.TupleType(elements, null, null);
  9843. }
  9844. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  9845. const args = [];
  9846. for (let i = 0; i < field_names.length; i++) {
  9847. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  9848. args.push(arg);
  9849. }
  9850. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  9851. return new torch.TupleType(field_types, qualified_name, schema);
  9852. }
  9853. elements() {
  9854. return this._elements;
  9855. }
  9856. name() {
  9857. return this.annotation_str;
  9858. }
  9859. containedTypes() {
  9860. return this._elements;
  9861. }
  9862. createWithContained(createWithContained) {
  9863. return new torch.TupleType(createWithContained, this.name(), this.schema());
  9864. }
  9865. hasFreeVariables() {
  9866. return this._has_free_variables;
  9867. }
  9868. schema() {
  9869. return this._schema;
  9870. }
  9871. str() {
  9872. if (this._schema) {
  9873. return `NamedTuple(...)`;
  9874. }
  9875. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  9876. }
  9877. __str__() {
  9878. if (this.annotation_str) {
  9879. return this.annotation_str;
  9880. }
  9881. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  9882. }
  9883. });
  9884. this.registerType('torch.AnyType', class extends torch.Type {
  9885. constructor() {
  9886. super('AnyType');
  9887. }
  9888. static get() {
  9889. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  9890. return torch.AnyType.value;
  9891. }
  9892. str() {
  9893. return 'Any';
  9894. }
  9895. __str__() {
  9896. return 'Any';
  9897. }
  9898. });
  9899. this.registerType('torch.NoneType', class extends torch.Type {
  9900. constructor() {
  9901. super('NoneType');
  9902. }
  9903. static get() {
  9904. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  9905. return torch.NoneType.value;
  9906. }
  9907. equals(rhs) {
  9908. return this.kind() === rhs.kind();
  9909. }
  9910. isSubtypeOf(rhs) {
  9911. if (rhs.kind() === 'OptionalType') {
  9912. return true;
  9913. }
  9914. return super.isSubtypeOf(rhs);
  9915. }
  9916. str() {
  9917. return 'NoneType';
  9918. }
  9919. __str__() {
  9920. return 'NoneType';
  9921. }
  9922. });
  9923. this.registerType('torch.TensorType', class extends torch.Type {
  9924. constructor() {
  9925. super('TensorType');
  9926. this._is_inferred = false;
  9927. }
  9928. static get() {
  9929. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  9930. return torch.TensorType.value;
  9931. }
  9932. equals(rhs) {
  9933. return this.kind() === rhs.kind();
  9934. }
  9935. isInferredType() {
  9936. return this._is_inferred;
  9937. }
  9938. str() {
  9939. return 'Tensor';
  9940. }
  9941. __str__() {
  9942. return 'Tensor';
  9943. }
  9944. });
  9945. this.registerType('torch.NumberType', class extends torch.Type {
  9946. constructor() {
  9947. super('NumberType');
  9948. }
  9949. static get() {
  9950. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  9951. return torch.NumberType.value;
  9952. }
  9953. str() {
  9954. return 'Scalar';
  9955. }
  9956. __str__() {
  9957. return 'number';
  9958. }
  9959. });
  9960. this.registerType('torch.BoolType', class extends torch.Type {
  9961. constructor() {
  9962. super('BoolType');
  9963. }
  9964. static get() {
  9965. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  9966. return torch.BoolType.value;
  9967. }
  9968. equals(rhs) {
  9969. return this.kind() === rhs.kind();
  9970. }
  9971. str() {
  9972. return 'bool';
  9973. }
  9974. __str__() {
  9975. return 'bool';
  9976. }
  9977. });
  9978. this.registerType('torch.IntType', class extends torch.Type {
  9979. constructor() {
  9980. super('IntType');
  9981. }
  9982. static get() {
  9983. torch.IntType.value = torch.IntType.value || new torch.IntType();
  9984. return torch.IntType.value;
  9985. }
  9986. equals(rhs) {
  9987. return this.kind() === rhs.kind();
  9988. }
  9989. isSubtypeOf(rhs) {
  9990. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  9991. }
  9992. str() {
  9993. return 'int';
  9994. }
  9995. __str__() {
  9996. return 'int';
  9997. }
  9998. });
  9999. this.registerType('torch.SymIntType', class extends torch.Type {
  10000. constructor() {
  10001. super('SymIntType');
  10002. }
  10003. static get() {
  10004. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10005. return torch.SymIntType.value;
  10006. }
  10007. equals(rhs) {
  10008. return this.kind() === rhs.kind();
  10009. }
  10010. str() {
  10011. return 'SymInt';
  10012. }
  10013. __str__() {
  10014. return 'int';
  10015. }
  10016. });
  10017. this.registerType('torch.FloatType', class extends torch.Type {
  10018. constructor() {
  10019. super('FloatType');
  10020. }
  10021. static get() {
  10022. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10023. return torch.FloatType.value;
  10024. }
  10025. equals(rhs) {
  10026. return this.kind() === rhs.kind();
  10027. }
  10028. isSubtypeOf(rhs) {
  10029. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10030. }
  10031. str() {
  10032. return 'float';
  10033. }
  10034. __str__() {
  10035. return 'float';
  10036. }
  10037. });
  10038. this.registerType('torch.StringType', class extends torch.Type {
  10039. constructor() {
  10040. super('StringType');
  10041. }
  10042. static get() {
  10043. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10044. return torch.StringType.value;
  10045. }
  10046. equals(rhs) {
  10047. return this.kind() === rhs.kind();
  10048. }
  10049. str() {
  10050. return 'str';
  10051. }
  10052. __str__() {
  10053. return 'str';
  10054. }
  10055. });
  10056. this.registerType('torch.ComplexType', class extends torch.Type {
  10057. constructor() {
  10058. super('ComplexType');
  10059. }
  10060. static get() {
  10061. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10062. return torch.ComplexType.value;
  10063. }
  10064. equals(rhs) {
  10065. return this.kind() === rhs.kind();
  10066. }
  10067. isSubtypeOf(rhs) {
  10068. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10069. }
  10070. str() {
  10071. return 'complex';
  10072. }
  10073. __str__() {
  10074. return 'complex';
  10075. }
  10076. });
  10077. this.registerType('torch.DictType', class extends torch.Type {
  10078. constructor(key, value) {
  10079. super('DictType');
  10080. this.types = [key, value];
  10081. }
  10082. static create(key, value) {
  10083. let kind = key.kind();
  10084. if (key instanceof torch._C.DynamicType) {
  10085. kind = key.dynamicKind();
  10086. }
  10087. switch (kind) {
  10088. case 'AnyType':
  10089. case 'IntType':
  10090. case 'BoolType':
  10091. case 'FloatType':
  10092. case 'ComplexType':
  10093. case 'StringType':
  10094. case 'TensorType':
  10095. case 'DeviceObjType':
  10096. return new torch.DictType(key, value);
  10097. default:
  10098. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10099. }
  10100. }
  10101. createWithContained(contained_types) {
  10102. if (contained_types.length !== 2) {
  10103. throw new python.Error('Expected 2 contained types.');
  10104. }
  10105. return torch.DictType.create(contained_types[0], contained_types[1]);
  10106. }
  10107. getKeyType() {
  10108. return this.types[0];
  10109. }
  10110. getValueType() {
  10111. return this.types[1];
  10112. }
  10113. hasFreeVariables() {
  10114. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10115. }
  10116. containedTypes() {
  10117. return this.types;
  10118. }
  10119. equals(rhs) {
  10120. if (rhs instanceof torch.DictType) {
  10121. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10122. }
  10123. return false;
  10124. }
  10125. str() {
  10126. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10127. }
  10128. __str__() {
  10129. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10130. }
  10131. });
  10132. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10133. constructor() {
  10134. super('DeviceObjType');
  10135. }
  10136. static get() {
  10137. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10138. return torch.DeviceObjType.value;
  10139. }
  10140. str() {
  10141. return 'Device';
  10142. }
  10143. __str__() {
  10144. return 'Device';
  10145. }
  10146. });
  10147. this.registerType('torch.StreamObjType', class extends torch.Type {
  10148. constructor() {
  10149. super('StreamObjType');
  10150. }
  10151. str() {
  10152. return 'Stream';
  10153. }
  10154. __str__() {
  10155. return 'Stream';
  10156. }
  10157. });
  10158. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10159. constructor() {
  10160. super('GeneratorType');
  10161. }
  10162. static get() {
  10163. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10164. return torch._C._GeneratorType.value;
  10165. }
  10166. str() {
  10167. return 'Generator';
  10168. }
  10169. __str__() {
  10170. return 'Generator';
  10171. }
  10172. });
  10173. this.registerType('torch.InterfaceType', class extends torch.Type {
  10174. constructor() {
  10175. super('InterfaceType');
  10176. }
  10177. });
  10178. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10179. constructor() {
  10180. super('DynamicType');
  10181. }
  10182. });
  10183. this.registerType('torch._C.FunctionType', class extends torch.Type {
  10184. constructor(func) {
  10185. super('FunctionType');
  10186. this._func = func;
  10187. }
  10188. static create(func) {
  10189. return new torch._C.FunctionType(func);
  10190. }
  10191. function() {
  10192. return this._func;
  10193. }
  10194. });
  10195. this.registerType('torch._C.VarType', class extends torch.Type {
  10196. constructor(name) {
  10197. super('VarType', name);
  10198. }
  10199. static create(name) {
  10200. return new torch._C.VarType(name);
  10201. }
  10202. name() {
  10203. return this._annotation_str;
  10204. }
  10205. hasFreeVariables() {
  10206. return true;
  10207. }
  10208. });
  10209. this.registerType('torch._C.AliasInfo', class {
  10210. constructor() {
  10211. this.is_write = false;
  10212. this.before_set = [];
  10213. this.after_set = [];
  10214. this.containedTypes = [];
  10215. }
  10216. addBeforeSet(value) {
  10217. this.before_set.push(value);
  10218. }
  10219. addAfterSet(value) {
  10220. this.after_set.push(value);
  10221. }
  10222. addContainedType(alias_info) {
  10223. this.containedTypes.push(alias_info);
  10224. }
  10225. str() {
  10226. const list = ['('];
  10227. list.push(this.before_set.join('|'));
  10228. if (this.after_set.length > 0) {
  10229. list.push(' -> ');
  10230. list.push(this.after_set.join('|'));
  10231. }
  10232. if (this.is_write) {
  10233. list.push('!');
  10234. }
  10235. list.push(')');
  10236. return list.join('');
  10237. }
  10238. });
  10239. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  10240. if (str.startsWith('"') && str.endsWith('"')) {
  10241. return str.slice(1, -1);
  10242. }
  10243. if (str.startsWith("'") && str.endsWith("'")) {
  10244. return str.slice(1, -1);
  10245. }
  10246. throw new python.Error(`Invalid string literal '${str}'.`);
  10247. // inline std::string parseStringLiteral(
  10248. });
  10249. this.registerType('torch._C.Token', class {
  10250. constructor() {
  10251. this.kind = '';
  10252. this.value = '';
  10253. }
  10254. text() {
  10255. return this.value;
  10256. }
  10257. });
  10258. this.registerType('torch._C.Lexer', class {
  10259. constructor(buffer) {
  10260. this.buffer = buffer;
  10261. this.position = 0;
  10262. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  10263. this.next();
  10264. }
  10265. cur() {
  10266. return this.next_tokens[0];
  10267. }
  10268. lookahead() {
  10269. if (!this.next_tokens[1].kind) {
  10270. this.position += this.cur().text().length;
  10271. this.lex(this.next_tokens[1]);
  10272. }
  10273. return this.next_tokens[1];
  10274. }
  10275. next() {
  10276. const [cur] = this.next_tokens;
  10277. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  10278. this.next_tokens[1].kind = '';
  10279. this.next_tokens[3] = cur;
  10280. const [token] = this.next_tokens;
  10281. if (token.kind) {
  10282. return cur;
  10283. }
  10284. this.position += cur.text().length;
  10285. this.lex(token);
  10286. return cur;
  10287. }
  10288. nextIf(kind) {
  10289. if (this.cur().kind !== kind) {
  10290. return false;
  10291. }
  10292. this.next();
  10293. return true;
  10294. }
  10295. expect(kind) {
  10296. if (this.cur().kind !== kind) {
  10297. throw new python.Error(`Unexpected '${this.kind}' instead of '${kind}'.`);
  10298. }
  10299. return this.next();
  10300. }
  10301. lex(token) {
  10302. while (this.buffer[this.position] === ' ') {
  10303. this.position += 1;
  10304. }
  10305. let i = this.position;
  10306. if (i >= this.buffer.length) {
  10307. token.kind = '\0';
  10308. token.value = '';
  10309. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  10310. token.kind = '...';
  10311. token.value = '...';
  10312. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  10313. this.kind = '[]';
  10314. this.value = '[]'; */
  10315. } 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] === '|') {
  10316. token.kind = this.buffer[i];
  10317. token.value = this.buffer[i];
  10318. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  10319. i += 1;
  10320. 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] === '_')) {
  10321. i += 1;
  10322. }
  10323. token.kind = 'id';
  10324. token.value = this.buffer.slice(this.position, i);
  10325. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  10326. token.kind = '->';
  10327. token.value = '->';
  10328. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  10329. i += 1;
  10330. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  10331. i += 1;
  10332. }
  10333. token.kind = '#';
  10334. token.value = this.buffer.slice(this.position, i);
  10335. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  10336. const quote = this.buffer[i];
  10337. i += 1;
  10338. while (i < this.buffer.length && this.buffer[i] !== quote) {
  10339. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  10340. }
  10341. i += 1;
  10342. token.kind = 'string';
  10343. token.value = this.buffer.slice(this.position, i);
  10344. } else {
  10345. throw new python.Error(`Unsupported token at '${this.position}'.`);
  10346. }
  10347. }
  10348. });
  10349. this.registerType('torch._C.SchemaTypeParser', class {
  10350. constructor(L, complete_tensor_types, allow_typevars) {
  10351. this.L = L;
  10352. this.complete_tensor_types = complete_tensor_types;
  10353. this._allow_typevars = allow_typevars;
  10354. }
  10355. parseType() {
  10356. const r = this.parseFakeAndRealType();
  10357. return { first: r[0], second: r[2] };
  10358. }
  10359. parseBaseType() {
  10360. const L = this.L;
  10361. const tok = L.cur();
  10362. const text = tok.text();
  10363. L.next();
  10364. switch (text) {
  10365. case 'Tensor': return torch.TensorType.get();
  10366. case 'bool': return torch.BoolType.get();
  10367. case 'int': return torch.IntType.get();
  10368. case 'float': return torch.FloatType.get();
  10369. case 'complex': return torch.ComplexType.get();
  10370. case 'str': return torch.StringType.get();
  10371. case 'SymInt': return torch.SymIntType.get();
  10372. case 'Scalar': return torch.NumberType.get();
  10373. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  10374. case 'Device': return torch.DeviceObjType.get();
  10375. case 'Layout': return torch.Type.get('Layout');
  10376. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  10377. case 'Generator': return torch._C._GeneratorType.get();
  10378. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  10379. case 'Any': return torch.AnyType.get();
  10380. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  10381. case 'Dimname': return torch.StringType.get();
  10382. case 'QScheme': return torch.Type.get('QSchemeType');
  10383. case 'Stream': return torch.StreamObjType.get();
  10384. case 'Storage': return torch.Type.get('Storage');
  10385. case 'AnyClassType': return torch.Type.get('AnyClassType');
  10386. case 'NoneType': return torch.NoneType.get();
  10387. default: throw new python.Error(`Unsupported type '${text}'.`);
  10388. }
  10389. }
  10390. parseFakeAndRealType() {
  10391. const L = this.L;
  10392. let fake_value = null;
  10393. let real_value = null;
  10394. let alias_info = null;
  10395. if (L.nextIf('(')) {
  10396. const types = [];
  10397. while (!L.nextIf(')')) {
  10398. const r = this.parseType();
  10399. types.push(r.first);
  10400. if (alias_info && r.second) {
  10401. alias_info.addContainedType(r.second);
  10402. }
  10403. L.nextIf(',');
  10404. }
  10405. real_value = torch.TupleType.create(types);
  10406. fake_value = real_value;
  10407. } else if (L.cur().text() === 'Future') {
  10408. L.next();
  10409. L.expect('(');
  10410. const p = this.parseType();
  10411. const subtype = p.first;
  10412. // const subalias = p.second;
  10413. L.expect(')');
  10414. real_value = torch.FutureType.create(subtype);
  10415. fake_value = real_value;
  10416. } else if (L.cur().text() === 'Await') {
  10417. L.next();
  10418. L.expect('(');
  10419. const p = this.parseType();
  10420. const subtype = p.first;
  10421. // const subalias = p.second;
  10422. L.expect(')');
  10423. real_value = torch.AwaitType.get(subtype);
  10424. fake_value = real_value;
  10425. } else if (L.cur().text() === 'RRef') {
  10426. L.next();
  10427. L.expect('(');
  10428. const p = this.parseType();
  10429. const subtype = p.first;
  10430. // const subalias = p.second;
  10431. L.expect(')');
  10432. real_value = torch.RRefType.create(subtype);
  10433. fake_value = real_value;
  10434. } else if (L.cur().text() === 'Tensor') {
  10435. L.next();
  10436. real_value = torch.TensorType.get();
  10437. fake_value = real_value;
  10438. alias_info = this.parseAliasAnnotation();
  10439. } else if (L.cur().text() === 'Dict') {
  10440. L.next();
  10441. L.expect('(');
  10442. const key_type = this.parseType().first;
  10443. L.expect(',');
  10444. const value_type = this.parseType().first;
  10445. L.expect(')');
  10446. alias_info = this.parseAliasAnnotation();
  10447. real_value = torch.DictType.create(key_type, value_type);
  10448. fake_value = real_value;
  10449. } else if (L.nextIf('Union')) {
  10450. L.next();
  10451. L.expect('(');
  10452. const types = [];
  10453. types.push(this.parseType().first);
  10454. while (L.cur().kind !== ')') {
  10455. L.expect(',');
  10456. types.push(this.parseType().first);
  10457. }
  10458. L.expect(')');
  10459. alias_info = this.parseAliasAnnotation();
  10460. real_value = new torch.UnionType(types);
  10461. fake_value = real_value;
  10462. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  10463. fake_value = real_value = parseRefinedTensor();
  10464. alias_info = parseAliasAnnotation(); */
  10465. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  10466. L.next();
  10467. L.expect('.');
  10468. const torch_tok = L.expect('id');
  10469. if (torch_tok.text() !== 'torch') {
  10470. throw new python.Error('Expected classes namespace.');
  10471. }
  10472. L.expect('.');
  10473. const classes_tok = L.expect('id');
  10474. if (classes_tok.text() !== 'classes') {
  10475. throw new python.Error('Expected classes namespace.');
  10476. }
  10477. L.expect('.');
  10478. const ns_tok = L.expect('id');
  10479. L.expect('.');
  10480. const class_tok = L.expect('id');
  10481. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  10482. fake_value = real_value;
  10483. if (!fake_value) {
  10484. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  10485. }
  10486. } else {
  10487. real_value = this.parseBaseType();
  10488. fake_value = real_value;
  10489. if (real_value.kind() === 'ScalarTypeType' ||
  10490. real_value.kind() === 'MemoryFormat' ||
  10491. real_value.kind() === 'Layout' ||
  10492. real_value.kind() === 'SymIntType') {
  10493. fake_value = torch.IntType.get();
  10494. }
  10495. alias_info = this.parseAliasAnnotation();
  10496. }
  10497. while (true) {
  10498. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  10499. L.expect('[');
  10500. L.expect(']');
  10501. fake_value = torch.ListType.create(fake_value);
  10502. real_value = torch.ListType.create(real_value);
  10503. let container = this.parseAliasAnnotation();
  10504. if (alias_info) {
  10505. if (!container) {
  10506. container = new torch._C.AliasInfo();
  10507. container.is_write = alias_info.is_write;
  10508. }
  10509. container.addContainedType(alias_info);
  10510. }
  10511. alias_info = container;
  10512. } else if (L.nextIf('?')) {
  10513. fake_value = torch.OptionalType.create(fake_value);
  10514. real_value = torch.OptionalType.create(real_value);
  10515. } else {
  10516. break;
  10517. }
  10518. }
  10519. return [fake_value, real_value, alias_info];
  10520. }
  10521. parseAliasAnnotation() {
  10522. const L = this.L;
  10523. let alias_info = null;
  10524. if (L.nextIf('(')) {
  10525. alias_info = new torch._C.AliasInfo();
  10526. do {
  10527. alias_info.addBeforeSet(L.cur().text());
  10528. L.next();
  10529. if (L.nextIf('!')) {
  10530. alias_info.is_write = true;
  10531. }
  10532. }
  10533. while (L.nextIf('|'));
  10534. if (L.nextIf('->')) {
  10535. do {
  10536. alias_info.addAfterSet(L.cur().text());
  10537. L.next();
  10538. }
  10539. while (L.nextIf('|'));
  10540. }
  10541. L.expect(')');
  10542. }
  10543. return alias_info;
  10544. }
  10545. });
  10546. this.registerType('torch.Argument', class {
  10547. constructor(...args) {
  10548. // torch/aten/src/ATen/core/function_schema.h
  10549. this.N = null;
  10550. this.default_value = null;
  10551. this.kwarg_only = false;
  10552. this.alias_info = null;
  10553. if (args.length === 2) {
  10554. [this.name, this.type] = args;
  10555. this.real_type = this.type;
  10556. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  10557. [this.name, this.type, this.real_type] = args;
  10558. } else if (args.length === 6) {
  10559. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  10560. } else if (args.length === 7) {
  10561. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  10562. } else {
  10563. throw new python.Error('Invalid arguments.');
  10564. }
  10565. const is_alias = this.alias_info && this.alias_info.is_write;
  10566. this.is_out = this.kwarg_only && is_alias;
  10567. }
  10568. has_default_value() {
  10569. return this.default_value !== undefined;
  10570. }
  10571. is_inferred_type() {
  10572. if (this.type instanceof torch.TensorType) {
  10573. return this.type.isInferredType();
  10574. }
  10575. return false;
  10576. }
  10577. str() {
  10578. const list = [];
  10579. const type = this.real_type;
  10580. const is_opt = type instanceof torch.OptionalType;
  10581. const unopt_type = is_opt ? type.getElementType() : type;
  10582. if (unopt_type instanceof torch.ListType) {
  10583. list.push(unopt_type.getElementType().str());
  10584. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  10585. list.push(this.alias_info.containedTypes[0].str());
  10586. }
  10587. list.push(this.N === null ? `[]` : `[${this.N}]`);
  10588. } else {
  10589. list.push(unopt_type.str());
  10590. }
  10591. if (this.alias_info && this.alias_info.before_set.length > 0) {
  10592. list.push(this.alias_info.str());
  10593. }
  10594. if (is_opt) {
  10595. list.push('?');
  10596. }
  10597. if (this.name) {
  10598. list.push(' ');
  10599. list.push(this.name);
  10600. }
  10601. if (this.default_value !== undefined) {
  10602. const value = this.default_value;
  10603. if (value === null) {
  10604. list.push('=None');
  10605. } else if (typeof value === 'boolean') {
  10606. list.push('=');
  10607. list.push(value ? 'True' : 'False');
  10608. } else if (typeof value === 'string') {
  10609. list.push(`="${value}"`);
  10610. } else if (typeof value === 'number') {
  10611. list.push(`=${value}`);
  10612. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  10613. list.push(`.`);
  10614. }
  10615. } else if (Array.isArray(value)) {
  10616. list.push(`=[${value.join(', ')}]`);
  10617. }
  10618. }
  10619. return list.join('');
  10620. }
  10621. });
  10622. torch._C.TypeKind = {
  10623. StringType: 'StringType',
  10624. NumberType: 'NumberType',
  10625. IntType: 'IntType',
  10626. BoolType: 'BoolType',
  10627. DynamicType: 'DynamicType',
  10628. OptionalType: 'OptionalType',
  10629. FloatType: 'FloatType',
  10630. ComplexType: 'ComplexType',
  10631. ListType: 'ListType',
  10632. };
  10633. this.registerType('torch._C.List', class extends Array {
  10634. constructor(type, elements) {
  10635. super(elements ? elements.length : 0);
  10636. if (Array.isArray(elements)) {
  10637. for (let i = 0; i < elements.length; i++) {
  10638. this[i] = elements[i];
  10639. }
  10640. }
  10641. this.type = type;
  10642. }
  10643. elementType() {
  10644. return this.type;
  10645. }
  10646. });
  10647. this.registerType('torch._C.SchemaParser', class {
  10648. constructor(str, allow_typevars) {
  10649. this.L = new torch._C.Lexer(str);
  10650. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  10651. }
  10652. parseName() {
  10653. const L = this.L;
  10654. let name = L.expect('id').text();
  10655. if (L.nextIf(':')) {
  10656. L.expect(':');
  10657. name = `${name}::${L.expect('ident').text()}`;
  10658. }
  10659. let overload_name = '';
  10660. if (L.nextIf('.')) {
  10661. overload_name = L.expect('ident').text();
  10662. }
  10663. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  10664. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  10665. return new torch._C.OperatorName(name, overload_name);
  10666. }
  10667. parseDeclaration() {
  10668. const L = this.L;
  10669. const name = this.parseName();
  10670. if (L.cur().kind !== '(') {
  10671. return name;
  10672. }
  10673. throw new python.Error('Not implemented.');
  10674. }
  10675. parseExactlyOneDeclaration() {
  10676. // const L = this.L;
  10677. const result = this.parseDeclaration();
  10678. // L.nextIf(TK_NEWLINE);
  10679. // L.expect(TK_EOF);
  10680. return result;
  10681. }
  10682. parseArgument(idx, is_return, kwarg_only) {
  10683. const L = this.L;
  10684. const type_parser = this.type_parser;
  10685. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  10686. let N = null;
  10687. if (L.nextIf('[')) {
  10688. fake_type = torch.ListType.create(fake_type);
  10689. real_type = torch.ListType.create(real_type);
  10690. if (L.cur().kind === '#') {
  10691. N = Number(L.cur().text());
  10692. L.next();
  10693. }
  10694. L.expect(']');
  10695. let container = type_parser.parseAliasAnnotation();
  10696. if (alias_info) {
  10697. if (!container) {
  10698. container = new torch._C.AliasInfo();
  10699. container.is_write = alias_info.is_write;
  10700. }
  10701. container.addContainedType(alias_info);
  10702. }
  10703. alias_info = container;
  10704. if (L.nextIf('?')) {
  10705. fake_type = torch.OptionalType.create(fake_type);
  10706. real_type = torch.OptionalType.create(real_type);
  10707. }
  10708. }
  10709. let name = null;
  10710. /* eslint-disable no-undef-init */
  10711. let default_value = undefined;
  10712. /* eslint-enable no-undef-init */
  10713. if (is_return) {
  10714. kwarg_only = false;
  10715. if (L.cur().kind === 'id') {
  10716. name = L.next().text();
  10717. } else {
  10718. name = '';
  10719. }
  10720. } else {
  10721. name = L.expect('id').text();
  10722. if (L.nextIf('=')) {
  10723. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  10724. }
  10725. }
  10726. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  10727. }
  10728. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  10729. // auto range = L.cur().range;
  10730. const L = this.L;
  10731. const range = null;
  10732. switch (kind) {
  10733. case torch._C.TypeKind.StringType:
  10734. case torch._C.TypeKind.OptionalType:
  10735. case torch._C.TypeKind.NumberType:
  10736. case torch._C.TypeKind.IntType:
  10737. case torch._C.TypeKind.BoolType:
  10738. case torch._C.TypeKind.FloatType:
  10739. case torch._C.TypeKind.ComplexType:
  10740. return this.parseSingleConstant(arg_type, kind, real_type);
  10741. case torch._C.TypeKind.ListType: {
  10742. const elem_type = arg_type.containedType(0);
  10743. const real_elem_type = real_type.containedType(0);
  10744. if (L.cur().kind === 'id') {
  10745. return this.parseTensorDefault(range);
  10746. } else if (arg_N && L.cur().kind !== '[') {
  10747. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  10748. const repeated = Array(arg_N).fill(v);
  10749. // std::vector<IValue> repeated(arg_N, v);
  10750. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  10751. }
  10752. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  10753. }
  10754. case torch._C.TypeKind.DynamicType:
  10755. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  10756. default:
  10757. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  10758. }
  10759. }
  10760. parseSingleConstant(type, kind, real_type) {
  10761. const L = this.L;
  10762. if (kind === torch._C.TypeKind.DynamicType) {
  10763. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  10764. }
  10765. // const auto& str2dtype = c10::getStringToDtypeMap();
  10766. if (L.cur().kind === 'id') {
  10767. if (L.cur().text() === 'True') {
  10768. L.next();
  10769. return new torch._C.IValue(true);
  10770. }
  10771. if (L.cur().text() === 'False') {
  10772. L.next();
  10773. return new torch._C.IValue(false);
  10774. }
  10775. if (L.cur().text() === 'None') {
  10776. L.next();
  10777. return new torch._C.IValue();
  10778. }
  10779. } else if (L.cur().kind === 'string') {
  10780. const token = L.next();
  10781. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  10782. } else if (L.cur().kind === '#') {
  10783. let n = '';
  10784. if (L.nextIf('-')) {
  10785. n = `-${L.expect('#').text()}`; // # .text();
  10786. } else {
  10787. n = L.expect('#').text(); // # .text();
  10788. }
  10789. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  10790. throw new Error("Complex type not implemented.");
  10791. /*
  10792. const imag = std::stod(n.substr(0, n.size() - 1));
  10793. return c10::complex<double>(0, imag);
  10794. */
  10795. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  10796. const v = parseFloat(n);
  10797. return new torch._C.IValue(v, 'Double');
  10798. } else {
  10799. const v = parseInt(n, 10);
  10800. return new torch._C.IValue(v, 'Int');
  10801. }
  10802. }
  10803. throw new python.Error('Not implemented.');
  10804. /*
  10805. switch (L.cur().kind) {
  10806. case TK_TRUE:
  10807. L.next();
  10808. return true;
  10809. case TK_FALSE:
  10810. L.next();
  10811. return false;
  10812. case TK_NONE:
  10813. L.next();
  10814. return IValue();
  10815. case TK_STRINGLITERAL: {
  10816. const token = L.next();
  10817. return parseStringLiteral(token.range, token.text());
  10818. }
  10819. case TK_IDENT: {
  10820. const tok = L.next();
  10821. const text_view = tok.text_view();
  10822. // NB: float/complex/long are here for BC purposes. Other dtypes
  10823. // are handled via str2dtype.
  10824. // Please don't add more cases to this if-else block.
  10825. if ("float" == text_view) {
  10826. return static_cast<int64_t>("at::kFloat");
  10827. } else if ("complex" == text_view) {
  10828. return static_cast<int64_t>("at::kComplexFloat");
  10829. } else if ("long" == text_view) {
  10830. return static_cast<int64_t>("at::kLong");
  10831. } else if ("strided" == text_view) {
  10832. return static_cast<int64_t>("at::kStrided");
  10833. } else if ("Mean" == text_view) {
  10834. return static_cast<int64_t>("at::Reduction::Mean");
  10835. } else if ("contiguous_format" == text_view) {
  10836. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  10837. } else {
  10838. const text = tok.text();
  10839. if (isPossiblyOptionalScalarType(real_type) &&
  10840. str2dtype.count(text) > 0) {
  10841. return static_cast<int64_t>(str2dtype.at(text));
  10842. } else {
  10843. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  10844. }
  10845. }
  10846. }
  10847. default: {
  10848. let n;
  10849. if (L.nextIf('-')) {
  10850. n = "-" + L.expect(TK_NUMBER).text();
  10851. }
  10852. else {
  10853. n = L.expect(TK_NUMBER).text();
  10854. }
  10855. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  10856. throw new python.Error('Complex type not implemented.');
  10857. const imag = std::stod(n.substr(0, n.size() - 1));
  10858. return c10::complex<double>(0, imag);
  10859. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  10860. throw new python.Error('Float type not implemented.');
  10861. return std::stod(n);
  10862. } else {
  10863. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  10864. int64_t v = std::stoll(n);
  10865. return v;
  10866. }
  10867. }
  10868. }
  10869. */
  10870. }
  10871. parseConstantList(type, kind, real_type) {
  10872. const L = this.L;
  10873. const tok = L.expect('[');
  10874. const vs = [];
  10875. if (L.cur().kind !== ']') {
  10876. do {
  10877. vs.push(this.parseSingleConstant(type, kind, real_type));
  10878. } while (L.nextIf(','));
  10879. }
  10880. L.expect(']');
  10881. return this.convertToList(type, kind, tok.range, vs);
  10882. }
  10883. convertToList(type, kind, range, vs) {
  10884. switch (kind) {
  10885. case torch._C.TypeKind.ComplexType:
  10886. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  10887. case torch._C.TypeKind.FloatType:
  10888. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  10889. case torch._C.TypeKind.IntType:
  10890. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  10891. case torch._C.TypeKind.BoolType:
  10892. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  10893. case torch._C.TypeKindDynamicType:
  10894. return this.convertToList(type.dynamicKind(), range, vs);
  10895. default:
  10896. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  10897. throw new python.Error('lists are only supported for float, int and complex types');
  10898. }
  10899. }
  10900. });
  10901. this.registerType('torch.FunctionSchema', class {
  10902. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  10903. const index = name.indexOf('(');
  10904. if (index === -1) {
  10905. this._name = name;
  10906. this._overload_name = overload_name || '';
  10907. this._arguments = args || [];
  10908. this._returns = returns || [];
  10909. this._is_vararg = is_vararg || false;
  10910. this._is_varret = is_varret || false;
  10911. } else {
  10912. const value = name.substring(0, index).trim();
  10913. const dot = value.indexOf('.');
  10914. if (dot === -1) {
  10915. this._name = value;
  10916. this._overload_name = '';
  10917. } else {
  10918. this._name = value.substring(0, dot);
  10919. this._overload_name = value.substring(dot + 1, value.length);
  10920. }
  10921. this._buffer = name.substring(index, name.length);
  10922. }
  10923. }
  10924. static parse(schema) {
  10925. return new torch.FunctionSchema(schema);
  10926. }
  10927. get name() {
  10928. return this._name;
  10929. }
  10930. get overload_name() {
  10931. return this._overload_name;
  10932. }
  10933. get arguments() {
  10934. this._parse();
  10935. return this._arguments;
  10936. }
  10937. get returns() {
  10938. this._parse();
  10939. return this._returns;
  10940. }
  10941. get is_vararg() {
  10942. this._parse();
  10943. return this._is_vararg;
  10944. }
  10945. get is_varret() {
  10946. this._parse();
  10947. return this._is_varret;
  10948. }
  10949. argumentIndexWithName(name) {
  10950. const index = this.arguments.findIndex((arg) => arg.name === name);
  10951. return index === -1 ? null : index;
  10952. }
  10953. _parse() {
  10954. if (this._buffer) {
  10955. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  10956. const L = parser.L;
  10957. this._arguments = [];
  10958. this._is_vararg = false;
  10959. this._kwarg_only = false;
  10960. let idx = 0;
  10961. L.expect('(');
  10962. if (!L.nextIf(')')) {
  10963. while (true) {
  10964. if (this._is_vararg) {
  10965. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  10966. }
  10967. if (L.nextIf('*')) {
  10968. this._kwarg_only = true;
  10969. } else if (L.nextIf('...')) {
  10970. this._is_vararg = true;
  10971. } else {
  10972. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  10973. this._arguments.push(argument);
  10974. }
  10975. if (!L.nextIf(',')) {
  10976. break;
  10977. }
  10978. }
  10979. L.expect(')');
  10980. }
  10981. L.expect('->');
  10982. this._returns = [];
  10983. this._is_varret = false;
  10984. if (L.nextIf('...')) {
  10985. this._is_varret = true;
  10986. } else if (L.nextIf('(')) {
  10987. if (!L.nextIf(')')) {
  10988. while (true) {
  10989. if (this._is_varret) {
  10990. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  10991. }
  10992. if (L.nextIf('...')) {
  10993. this._is_varret = true;
  10994. } else {
  10995. const argument = parser.parseArgument(idx++, true, false);
  10996. this._returns.push(argument);
  10997. }
  10998. if (!L.nextIf(',')) {
  10999. break;
  11000. }
  11001. }
  11002. L.expect(')');
  11003. }
  11004. } else {
  11005. this._returns.push(parser.parseArgument(0, true, false));
  11006. }
  11007. delete this._buffer;
  11008. }
  11009. }
  11010. __str__() {
  11011. const list = [this.name];
  11012. const overload_name = this.overload_name;
  11013. if (overload_name !== '' && overload_name !== 'default') {
  11014. list.push(`.${this.overload_name}`);
  11015. }
  11016. list.push('(');
  11017. let first = true;
  11018. let kwarg_only = false;
  11019. for (const argument of this.arguments) {
  11020. if (!first) {
  11021. list.push(', ');
  11022. }
  11023. if (argument.kwarg_only && !kwarg_only) {
  11024. list.push('*, ');
  11025. kwarg_only = true;
  11026. }
  11027. first = false;
  11028. list.push(argument.str());
  11029. }
  11030. if (this.is_vararg) {
  11031. if (!first) {
  11032. list.push(', ');
  11033. }
  11034. first = true;
  11035. list.push('...');
  11036. }
  11037. list.push(') -> ');
  11038. const returns = this.returns;
  11039. const braces = !this.is_varret &&
  11040. (returns.length !== 1 ||
  11041. returns[0].name ||
  11042. returns[0].real_type instanceof torch.TupleType ||
  11043. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  11044. if (braces) {
  11045. list.push('(');
  11046. }
  11047. first = true;
  11048. for (const argument of this.returns) {
  11049. if (!first) {
  11050. list.push(', ');
  11051. }
  11052. first = false;
  11053. list.push(argument.str());
  11054. }
  11055. if (this.is_varret) {
  11056. if (!first) {
  11057. list.push(', ');
  11058. }
  11059. first = true;
  11060. list.push('...');
  11061. }
  11062. if (braces) {
  11063. list.push(')');
  11064. }
  11065. return list.join('');
  11066. }
  11067. aliasAnalysis() {
  11068. return this._alias_kind || 'CONSERVATIVE';
  11069. }
  11070. setAliasAnalysis(v) {
  11071. this._alias_kind = v;
  11072. }
  11073. hasAnyAliasInfo() {
  11074. for (const arg of this.arguments) {
  11075. if (arg.alias_info !== null) {
  11076. return true;
  11077. }
  11078. }
  11079. for (const ret of this.returns) {
  11080. if (ret.alias_info !== null) {
  11081. return true;
  11082. }
  11083. }
  11084. return false;
  11085. }
  11086. is_mutable() {
  11087. return this.arguments.some((arg) => {
  11088. const aliasInfo = arg.alias_info;
  11089. return aliasInfo && aliasInfo.is_write;
  11090. });
  11091. }
  11092. });
  11093. this.registerType('torch._C.SchemaInfo', class {
  11094. constructor(schema) {
  11095. this._schema = schema;
  11096. this._alias_maps_current = false;
  11097. this._has_init = false;
  11098. }
  11099. is_nondeterministic() {
  11100. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  11101. //
  11102. }
  11103. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  11104. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  11105. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  11106. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  11107. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  11108. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  11109. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  11110. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  11111. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  11112. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  11113. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  11114. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  11115. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  11116. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  11117. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  11118. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  11119. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  11120. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  11121. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  11122. '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',
  11123. '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',
  11124. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  11125. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  11126. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  11127. ]);
  11128. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  11129. return true;
  11130. }
  11131. /*
  11132. const auto& op = c10::Dispatcher::singleton().findOp(
  11133. c10::OperatorName(schema_.name(), schema_.overload_name()));
  11134. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  11135. */
  11136. return false;
  11137. }
  11138. });
  11139. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11140. return new Map();
  11141. });
  11142. this.registerFunction('torch._C.string_to_type_lut', () => {
  11143. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11144. const map = new Map();
  11145. map.set('Tensor', torch.TensorType.get());
  11146. map.set('int', torch.IntType.get());
  11147. map.set('float', torch.FloatType.get());
  11148. map.set('bool', torch.BoolType.get());
  11149. map.set('complex', torch.ComplexType.get());
  11150. map.set('str', torch.StringType.get());
  11151. map.set('Device', torch.DeviceObjType.get());
  11152. map.set('number', torch.NumberType.get());
  11153. map.set('None', torch.NoneType.get());
  11154. map.set('NoneType', torch.NoneType.get());
  11155. map.set('Any', torch.AnyType.get());
  11156. map.set('list', torch.Type.get('AnyListType'));
  11157. map.set('tuple', torch.Type.get('AnyTupleType'));
  11158. torch._C.string_to_type_lut.basePythonTypes = map;
  11159. }
  11160. return torch._C.string_to_type_lut.basePythonTypes;
  11161. });
  11162. this.registerType('torch._C.ScriptTypeParser', class {
  11163. constructor(resolver) {
  11164. this._resolver = resolver;
  11165. }
  11166. parseSchemaFromDef(def, skip_self) {
  11167. const name = def.name;
  11168. const args = this.parseArgsFromDecl(def, skip_self);
  11169. const returns = this.parseReturnFromDecl(def);
  11170. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11171. }
  11172. parseArgsFromDecl(decl, skip_self) {
  11173. const retval = [];
  11174. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11175. throw new python.Error('Unsupported function argument.');
  11176. }
  11177. const params = decl.args.args.slice();
  11178. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11179. const start = skip_self ? 1 : 0;
  11180. for (let i = start; i < params.length; i++) {
  11181. const decl_arg = params[i];
  11182. const N = null;
  11183. const default_value = undefined;
  11184. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11185. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11186. retval.push(arg);
  11187. }
  11188. return retval;
  11189. }
  11190. parseReturnFromDecl(decl) {
  11191. if (!decl.returns) {
  11192. return [];
  11193. }
  11194. if (this.parseBroadcastList(decl.returns)) {
  11195. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11196. }
  11197. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11198. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11199. }
  11200. parseTypeFromExpr(expr) {
  11201. if (this._resolver) {
  11202. if (expr instanceof ast.Name) {
  11203. const type = this._resolver.resolveType(expr.id);
  11204. if (type) {
  11205. return type;
  11206. }
  11207. }
  11208. }
  11209. return this.parseTypeFromExprImpl(expr);
  11210. }
  11211. parseTypeFromExprImpl(expr) {
  11212. if (expr instanceof ast.Subscript) {
  11213. const value_name = this.parseBaseTypeName(expr.value);
  11214. if (!value_name) {
  11215. throw new python.Error('Subscripted type must be a type identifier.');
  11216. }
  11217. return this.subscriptToType(value_name, expr);
  11218. }
  11219. const name = this.parseBaseTypeName(expr);
  11220. if (name) {
  11221. const itr = torch._C.string_to_type_lut().get(name);
  11222. if (itr) {
  11223. return itr;
  11224. }
  11225. if (this._resolver) {
  11226. const typePtr = this._resolver.resolveType(name, expr);
  11227. if (typePtr) {
  11228. return typePtr;
  11229. }
  11230. }
  11231. }
  11232. throw new python.Error(`Unknown type name '${name}'.`);
  11233. }
  11234. parseBaseTypeName(expr) {
  11235. if (expr instanceof ast.Name) {
  11236. return expr.id;
  11237. } else if (expr instanceof ast.Constant && expr.value === null) {
  11238. return 'None';
  11239. } else if (expr instanceof ast.Attribute) {
  11240. const name = expr.attr;
  11241. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11242. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11243. return name;
  11244. }
  11245. return torch._C.collectQualname(expr);
  11246. }
  11247. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11248. }
  11249. parseBroadcastList(/* expr */) {
  11250. return null;
  11251. }
  11252. parseType(str) {
  11253. const expr = ast.parse(str);
  11254. return this.parseTypeFromExpr(expr.body[0].value);
  11255. }
  11256. subscriptToType(typeName, subscript) {
  11257. if (typeName === 'Tuple' || typeName === 'tuple') {
  11258. const subscript_expr_types = [];
  11259. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11260. for (const expr of elts) {
  11261. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11262. }
  11263. return torch.TupleType.create(subscript_expr_types);
  11264. } else if (typeName === 'List' || typeName === 'list') {
  11265. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11266. throw new python.Error('List type must have exactly one element type.');
  11267. }
  11268. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11269. return torch.ListType.create(elem_type);
  11270. } else if (typeName === 'Optional') {
  11271. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11272. throw new python.Error('Optional type must have exactly one element type.');
  11273. }
  11274. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11275. return torch.OptionalType.create(elem_type);
  11276. } else if (typeName === 'Union') {
  11277. const subscript_expr_types = [];
  11278. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11279. for (const expr of elts) {
  11280. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11281. }
  11282. return torch.UnionType.create(subscript_expr_types);
  11283. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11284. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11285. if (elts.length !== 1) {
  11286. throw new python.Error('Future type must have exactly one element type.');
  11287. }
  11288. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11289. return torch.FutureType.create(elem_type);
  11290. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11291. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11292. if (elts.length !== 1) {
  11293. throw new python.Error('Await type must have exactly one element type.');
  11294. }
  11295. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11296. return torch.AwaitType.create(elem_type);
  11297. } else if (typeName === 'RRef') {
  11298. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11299. if (elts.length !== 1) {
  11300. throw new python.Error('RRef type must have exactly one element type.');
  11301. }
  11302. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11303. return torch.RRefType.create(elem_type);
  11304. } else if (typeName === 'Dict' || typeName === 'dict') {
  11305. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11306. if (elts.length !== 2) {
  11307. throw new python.Error('Dict type must have exactly two element types.');
  11308. }
  11309. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11310. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11311. return torch.DictType.create(key_type, value_type);
  11312. }
  11313. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11314. }
  11315. });
  11316. this.registerFunction('torch._C.isTorch', (expr) => {
  11317. return expr instanceof ast.Name && expr.id === 'torch';
  11318. });
  11319. this.registerFunction('torch._C.collectQualname', (select) => {
  11320. const base = select.value;
  11321. if (base instanceof ast.Name) {
  11322. return `${base.id}.${select.attr}`;
  11323. }
  11324. const basename = torch._C.collectQualname(base);
  11325. return `${basename}.${select.attr}`;
  11326. });
  11327. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11328. constructor(overloadpacket, op, op_dk, schema, tags) {
  11329. super();
  11330. this._op = op;
  11331. this._op_dk = op_dk;
  11332. this._schema = schema;
  11333. this._overloadpacket = overloadpacket;
  11334. this._tags = tags;
  11335. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11336. this._name = this._schema.name;
  11337. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11338. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11339. this.__module__ = overloadpacket.__module__;
  11340. op.__module__ = overloadpacket.__module__;
  11341. this.__qualname__ = self._name;
  11342. this.__annotations__ = {};
  11343. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11344. let is_write = null;
  11345. for (const a of this._schema.arguments) {
  11346. if (a.alias_info) {
  11347. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11348. }
  11349. }
  11350. this.is_view = is_write !== null && !is_write;
  11351. }
  11352. name() {
  11353. return this._name;
  11354. }
  11355. });
  11356. this.registerType('torch._ops.OpOverloadPacket', class {
  11357. constructor(qualified_op_name, op_name, op, overload_names) {
  11358. this._qualified_op_name = qualified_op_name;
  11359. this.__name__ = op_name;
  11360. this._op = op;
  11361. this._overload_names = overload_names;
  11362. this._dir = [];
  11363. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11364. }
  11365. get _schemas() {
  11366. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11367. }
  11368. __getattr__(key) {
  11369. key = key === 'default' ? '' : key;
  11370. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11371. const [op_, op_dk_, tags] = op_dk_tags;
  11372. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11373. const overload = this._has_script_object_arg(schema) ?
  11374. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11375. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11376. builtins.setattr(self, key, overload);
  11377. this._dir.push(key);
  11378. return overload;
  11379. }
  11380. _has_script_object_arg(schema) {
  11381. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11382. }
  11383. __call__(...args) {
  11384. const fn = execution._operators.get(this._qualified_op_name);
  11385. if (!fn) {
  11386. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11387. }
  11388. return fn(...args);
  11389. }
  11390. });
  11391. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11392. constructor(name) {
  11393. super(`torch.ops.${name}`);
  11394. this.name = name;
  11395. this._dir = [];
  11396. }
  11397. __getattr__(op_name) {
  11398. const namespace_name = this.name;
  11399. const qualified_op_name = `${namespace_name}::${op_name}`;
  11400. const module_name = `${this.__module__}.${namespace_name}`;
  11401. let op = null;
  11402. let overload_names = null;
  11403. try {
  11404. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11405. } catch {
  11406. // continue regardless of error
  11407. }
  11408. if (!op) {
  11409. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11410. }
  11411. op.__module__ = module_name;
  11412. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11413. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11414. builtins.setattr(this, op_name, opoverloadpacket);
  11415. this._dir.push(op_name);
  11416. return opoverloadpacket;
  11417. }
  11418. _get_packet(qualname, op_module) {
  11419. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11420. if (op) {
  11421. // torch.jit._builtins._register_builtin(op, qualname);
  11422. }
  11423. op.__module__ = op_module;
  11424. return [op, overload_names];
  11425. }
  11426. });
  11427. this.registerType('torch._C.graph_node_list', class {
  11428. constructor(head) {
  11429. this.head = head;
  11430. }
  11431. front() {
  11432. return this.head.next;
  11433. }
  11434. end() {
  11435. return this.head.prev;
  11436. }
  11437. [Symbol.iterator]() {
  11438. let current = this.head.next;
  11439. const prev = this.head.prev;
  11440. return {
  11441. next() {
  11442. if (current !== prev) {
  11443. const value = current;
  11444. current = current.next;
  11445. return { value, done: false };
  11446. }
  11447. return { done: true };
  11448. }
  11449. };
  11450. }
  11451. });
  11452. this.registerType('torch.Graph', class {
  11453. constructor() {
  11454. this._next_unique = 0;
  11455. this._unique_names = new Map();
  11456. this._name_base_suffix = new Map();
  11457. this.all_nodes = new Set();
  11458. this.all_values = new Set();
  11459. this.all_blocks = new Set();
  11460. this._block = new torch.Block(this, null);
  11461. this._insert_before = this.return_node();
  11462. }
  11463. insert(opname, args, kwargs, range) {
  11464. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11465. }
  11466. create(kind, ...args) {
  11467. let inputs = null;
  11468. let num_outputs = 1;
  11469. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11470. [inputs, num_outputs] = args;
  11471. } else if (args.length === 1) {
  11472. if (typeof args[0] === 'number') {
  11473. [num_outputs] = args;
  11474. } else if (Array.isArray(args[0])) {
  11475. [inputs] = args;
  11476. }
  11477. }
  11478. const n = new torch.Node(this, kind);
  11479. if (inputs) {
  11480. for (const i of inputs) {
  11481. n.addInput(i);
  11482. }
  11483. }
  11484. for (let i = 0; i < num_outputs; i++) {
  11485. n.addOutput();
  11486. }
  11487. return n;
  11488. }
  11489. createClone(n, value_map, copy_blocks) {
  11490. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11491. const r = n.allocNewInstance(this);
  11492. for (const o of n.outputs()) {
  11493. r.addOutput().copyMetadata(o);
  11494. }
  11495. r.cloneFrom(n);
  11496. for (const i of n.inputs()) {
  11497. r.addInput(value_map(i));
  11498. }
  11499. if (copy_blocks) {
  11500. for (const b of n.blocks()) {
  11501. r.addBlock().cloneFrom(b, value_map);
  11502. }
  11503. }
  11504. return r;
  11505. }
  11506. createNone() {
  11507. const n = this.create('prim::Constant');
  11508. n.output().setType(torch.NoneType.get());
  11509. return n;
  11510. }
  11511. createUninitialized(typ) {
  11512. const n = this.create('prim::Uninitialized');
  11513. n.output().setType(typ);
  11514. return n;
  11515. }
  11516. createEnumValue(e) {
  11517. const enum_type = e.type().expect(torch.EnumType);
  11518. const n = this.create('prim::EnumValue', [e]);
  11519. n.output().setType(enum_type.getValueType());
  11520. return n;
  11521. }
  11522. createList(contained_type, values) {
  11523. const n = this.create('prim::ListConstruct', values);
  11524. for (const v of values) {
  11525. if (!v.type().isSubtypeOf(contained_type)) {
  11526. throw new python.Error('Invalid list item.');
  11527. }
  11528. }
  11529. n.output().setType(torch.ListType.create(contained_type));
  11530. return n;
  11531. }
  11532. createListUnpack(v, size) {
  11533. const list_type = v.type().expect(torch.ListType);
  11534. const elem_type = list_type.getElementType();
  11535. const n = this.create('prim::ListUnpack', [v], 0);
  11536. for (let i = 0; i < size; i++) {
  11537. n.addOutput().setType(elem_type);
  11538. }
  11539. return n;
  11540. }
  11541. createTuple(values, tuple_type) {
  11542. if (!tuple_type) {
  11543. const types = values.map((v) => v.type());
  11544. tuple_type = torch.TupleType.create(types);
  11545. }
  11546. const n = this.create('prim::TupleConstruct', values);
  11547. n.output().setType(tuple_type);
  11548. return n;
  11549. }
  11550. createTupleUnpack(v) {
  11551. const tt = v.type().expect(torch.TupleType);
  11552. const n = this.create('prim::TupleUnpack', [v], 0);
  11553. for (const element of tt.elements()) {
  11554. n.addOutput().setType(element);
  11555. }
  11556. return n;
  11557. }
  11558. createTupleIndex(tup, idx, output_type) {
  11559. const n = this.create('prim::TupleIndex', [tup, idx]);
  11560. n.output().setType(output_type);
  11561. return n;
  11562. }
  11563. createTupleSlice(tup, beg, step_size, num_values) {
  11564. const new_vals = [];
  11565. const tt = tup.type().expect(torch.TupleType);
  11566. let i = beg;
  11567. for (let j = 0; j < num_values; j++) {
  11568. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11569. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11570. new_vals.push(tupleIndex.output());
  11571. i += step_size;
  11572. }
  11573. const n = this.createTuple(new_vals);
  11574. return n;
  11575. }
  11576. createDict(key_type, value_type, keys, values) {
  11577. if (keys.length !== values.length) {
  11578. throw new python.Error('Invalid dictionary size.');
  11579. }
  11580. const n = this.create('prim::DictConstruct');
  11581. const length = keys.length;
  11582. for (let i = 0; i < length; i++) {
  11583. if (!keys[i].type().isSubtypeOf(key_type)) {
  11584. throw new python.Error('Invalid key.');
  11585. }
  11586. if (!values[i].type().isSubtypeOf(value_type)) {
  11587. throw new python.Error('Invalid value.');
  11588. }
  11589. n.addInput(keys[i]);
  11590. n.addInput(values[i]);
  11591. }
  11592. n.output().setType(torch.DictType.create(key_type, value_type));
  11593. return n;
  11594. }
  11595. createObject(type) {
  11596. const node = this.create('prim::CreateObject');
  11597. node.output().setType(type);
  11598. return node;
  11599. }
  11600. createIsInstance(v, types) {
  11601. const n = this.create('prim::isinstance', [v], 1);
  11602. n.tys_('types', types);
  11603. n.output().setType(torch.BoolType.get());
  11604. return n;
  11605. }
  11606. createSetAttr(obj, field, newValue) {
  11607. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11608. n.s_('name', field);
  11609. return n;
  11610. }
  11611. createGetAttr(obj, field) {
  11612. const n = this.create('prim::GetAttr', [obj]);
  11613. n.s_('name', field);
  11614. const classType = obj.type();
  11615. const outputType = classType.getAttribute(field);
  11616. n.output().setType(outputType);
  11617. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11618. return n;
  11619. }
  11620. createLoad(name, type) {
  11621. const n = this.create('prim::Load', [], 1);
  11622. n.s_('name', name);
  11623. n.output().setType(type);
  11624. return n;
  11625. }
  11626. createStore(name, v) {
  11627. const n = this.create('prim::Store', [v], 0);
  11628. n.s_('name', name);
  11629. return n;
  11630. }
  11631. inputs() {
  11632. return this._block.inputs();
  11633. }
  11634. outputs() {
  11635. return this._block.outputs();
  11636. }
  11637. nodes() {
  11638. return this._block.nodes();
  11639. }
  11640. param_node() {
  11641. return this._block.param_node();
  11642. }
  11643. return_node() {
  11644. return this._block.return_node();
  11645. }
  11646. block() {
  11647. return this._block;
  11648. }
  11649. addInput(name) {
  11650. return this._block.addInput(name);
  11651. }
  11652. insertNode(node) {
  11653. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11654. return node.insertBefore(this._insert_before);
  11655. }
  11656. insertConstant(val, loc, scope) {
  11657. return torch._C.insertConstant(this, val, loc, scope);
  11658. }
  11659. insertMethodCall(method_name, matched) {
  11660. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11661. .s_('name', method_name)
  11662. .output().setType(matched.return_types[0]);
  11663. return result;
  11664. }
  11665. insertUncheckedCast(v, type) {
  11666. const n = this.create('prim::unchecked_cast', [v]);
  11667. this.insertNode(n);
  11668. n.output().setType(type);
  11669. return n.output();
  11670. }
  11671. insertToList(v, type) {
  11672. let dim = 0;
  11673. let ptr = type;
  11674. while (ptr instanceof torch.ListType) {
  11675. ptr = ptr.getElementType();
  11676. dim += 1;
  11677. }
  11678. let elem_ty = 0;
  11679. if (ptr instanceof torch.IntType) {
  11680. elem_ty = 0;
  11681. } else if (ptr instanceof torch.FloatType) {
  11682. elem_ty = 1;
  11683. } else if (ptr instanceof torch.BoolType) {
  11684. elem_ty = 2;
  11685. } else if (ptr instanceof torch.ComplexType) {
  11686. elem_ty = 3;
  11687. } else {
  11688. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  11689. }
  11690. const dim_val = this.insertConstant(dim);
  11691. const elem_ty_val = this.insertConstant(elem_ty);
  11692. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  11693. n.output().setType(type);
  11694. return n.output();
  11695. }
  11696. insertFunctionCall(callee, matched) {
  11697. const func_name = callee.name();
  11698. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  11699. const inputs = [fn_constant, ...matched.inputs];
  11700. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  11701. return result;
  11702. }
  11703. insertPoint() {
  11704. return this._insert_before;
  11705. }
  11706. setInsertPoint(node) {
  11707. if (node instanceof torch.Block) {
  11708. node = node.return_node();
  11709. }
  11710. this._insert_before = node;
  11711. }
  11712. freeNode(n) {
  11713. this.all_nodes.delete(n);
  11714. }
  11715. freeValue(v) {
  11716. v.setDebugName('');
  11717. this.all_values.delete(v);
  11718. }
  11719. freeBlock(b) {
  11720. this.all_blocks.delete(b);
  11721. }
  11722. copy() {
  11723. const new_g = new torch.Graph();
  11724. new_g.cloneFrom(this);
  11725. return new_g;
  11726. }
  11727. cloneFrom(src) {
  11728. const env = (v) => {
  11729. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  11730. };
  11731. this.block().cloneFrom(src.block(), env);
  11732. }
  11733. set_op_version(version) {
  11734. this._op_version = version;
  11735. }
  11736. get_op_version() {
  11737. return this._op_version;
  11738. }
  11739. print(out, print_source_locations) {
  11740. out.write('graph(');
  11741. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  11742. out.write('):\n');
  11743. const groups = [];
  11744. for (const node of this.nodes()) {
  11745. node.print(out, 1, groups, print_source_locations);
  11746. }
  11747. out.write(' return (');
  11748. torch._C.printValueRefs(out, this.outputs());
  11749. out.write(')\n');
  11750. for (let i = 0; i < groups.length; i++) {
  11751. const fg = groups[i];
  11752. out.write('with ');
  11753. out.write(fg.kind());
  11754. out.write(`_${i} = `);
  11755. out.write(fg.g('Subgraph'));
  11756. }
  11757. return out;
  11758. }
  11759. toString() {
  11760. const out = new io.StringIO();
  11761. this.print(out, true);
  11762. return out.toString();
  11763. }
  11764. });
  11765. this.registerType('torch.Block', class {
  11766. constructor(graph, node) {
  11767. this._graph = graph;
  11768. this._input = graph.create('prim::Param', 0);
  11769. this._output = graph.create('prim::Return', 0);
  11770. this._owning_node = node;
  11771. this._input.next = this._output;
  11772. this._input.prev = this._output;
  11773. this._output.next = this._input;
  11774. this._output.prev = this._input;
  11775. this._graph.all_blocks.add(this);
  11776. this._output._owning_block = this;
  11777. // output_.topo_position_ = kUpperBound;
  11778. this._input._owning_block = this;
  11779. // input_.topo_position_ = kLowerBound;
  11780. }
  11781. inputs() {
  11782. return this._input.outputs();
  11783. }
  11784. outputs() {
  11785. return this._output.inputs();
  11786. }
  11787. nodes() {
  11788. return new torch._C.graph_node_list(this._input);
  11789. }
  11790. return_node() {
  11791. return this._output;
  11792. }
  11793. param_node() {
  11794. return this._input;
  11795. }
  11796. owningNode() {
  11797. return this._owning_node;
  11798. }
  11799. owningGraph() {
  11800. return this._graph;
  11801. }
  11802. addInput(name) {
  11803. const value = this._input.addOutput();
  11804. value.setDebugName(name || '');
  11805. return value;
  11806. }
  11807. registerOutput(value) {
  11808. this._output.addInput(value);
  11809. return this.outputs().length - 1;
  11810. }
  11811. appendNode(n) {
  11812. if (n._graph !== this._graph || n.inBlockList()) {
  11813. throw new python.Error('Node not in graph.');
  11814. }
  11815. n.insertBefore(this._output);
  11816. return n;
  11817. }
  11818. cloneFrom(src, value_map) {
  11819. const local_map = new Map();
  11820. const env = (v) => {
  11821. if (local_map.has(v)) {
  11822. return local_map.get(v);
  11823. }
  11824. return value_map(v);
  11825. };
  11826. const graph = this.owningGraph();
  11827. for (const input of src.inputs()) {
  11828. local_map.set(input, this.addInput().copyMetadata(input));
  11829. }
  11830. for (const node of src.nodes()) {
  11831. const new_node = this.appendNode(graph.createClone(node, env));
  11832. for (let i = 0; i < node.outputs().length; i++) {
  11833. const oo = node.outputs()[i];
  11834. const no = new_node.outputs()[i];
  11835. local_map.set(oo, no);
  11836. no.copyMetadata(oo);
  11837. }
  11838. }
  11839. for (const output of src.outputs()) {
  11840. this.registerOutput(env(output));
  11841. }
  11842. }
  11843. eraseOutput(i) {
  11844. this._output.removeInput(i);
  11845. }
  11846. destroy() {
  11847. this._output.removeAllInputs();
  11848. for (const n of this.nodes()) {
  11849. n.destroy();
  11850. }
  11851. this._output.destroy();
  11852. this._input.destroy();
  11853. this._graph.freeBlock(this);
  11854. }
  11855. });
  11856. this.registerType('torch.Node', class {
  11857. constructor(graph, kind) {
  11858. this._kind = kind;
  11859. this._graph = graph;
  11860. this._owning_block = null;
  11861. this._values = new Map();
  11862. this._inputs = [];
  11863. this._outputs = [];
  11864. this._blocks = [];
  11865. this._graph.all_nodes.add(this);
  11866. this._prev = null;
  11867. this._next = null;
  11868. this._source_range = null;
  11869. this._op = null;
  11870. }
  11871. owningGraph() {
  11872. return this._graph;
  11873. }
  11874. owningBlock() {
  11875. return this._owning_block;
  11876. }
  11877. kind() {
  11878. return this._kind;
  11879. }
  11880. schema() {
  11881. if (this._op) {
  11882. return this._op.schema();
  11883. }
  11884. // Node::schema() throws while torch.Node.schema() does not.
  11885. const op = this.maybeOperator();
  11886. if (op) {
  11887. return op.schema();
  11888. }
  11889. return null;
  11890. // return this.getOperator().schema();
  11891. }
  11892. hasNamedInput(name) {
  11893. for (const argument of this.schema().arguments) {
  11894. if (argument.name === name) {
  11895. return true;
  11896. }
  11897. }
  11898. return false;
  11899. }
  11900. matches(schema) {
  11901. if (torch._C.isBlockListedSchema(schema)) {
  11902. return false;
  11903. }
  11904. if (this.kind() !== schema.name) {
  11905. return false;
  11906. }
  11907. const actuals = this.inputs();
  11908. const formals = schema.arguments;
  11909. if (actuals.length < formals.length) {
  11910. return false;
  11911. }
  11912. const type_env = new Map();
  11913. for (let i = 0; i < formals.length; i++) {
  11914. let formal = formals[i].type;
  11915. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  11916. if (!matched_type.success()) {
  11917. return false;
  11918. }
  11919. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  11920. if (resolved) {
  11921. formal = resolved;
  11922. }
  11923. if (!actuals[i].type().isSubtypeOf(formal)) {
  11924. return false;
  11925. }
  11926. }
  11927. if (!schema.is_vararg && actuals.length !== formals.length) {
  11928. return false;
  11929. }
  11930. return true;
  11931. }
  11932. mustBeNone() {
  11933. return this._kind === 'prim::AutogradZero' ||
  11934. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  11935. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  11936. }
  11937. maybeSchema() {
  11938. const op = this.maybeOperator();
  11939. if (op) {
  11940. return op.schema();
  11941. }
  11942. return null;
  11943. }
  11944. maybeOperator() {
  11945. if (!this._op) {
  11946. const candidates = torch._C.getAllOperatorsFor(this.kind());
  11947. for (const candidate of candidates) {
  11948. if (this.matches(candidate.schema())) {
  11949. this._op = candidate;
  11950. break;
  11951. }
  11952. }
  11953. }
  11954. return this._op;
  11955. }
  11956. getOperator() {
  11957. const maybe = this.maybeOperator();
  11958. if (maybe) {
  11959. return maybe;
  11960. }
  11961. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  11962. }
  11963. getOperation() {
  11964. return this.getOperator().getOperation(this);
  11965. }
  11966. isNondeterministic() {
  11967. const schema = this.maybeSchema();
  11968. if (!this.kind().startsWith('aten::')) {
  11969. return false;
  11970. }
  11971. if (!schema) {
  11972. return false;
  11973. }
  11974. const schema_info = new torch._C.SchemaInfo(schema);
  11975. if (this.hasNamedInput('train')) {
  11976. throw new python.Error('Not Implemented.');
  11977. // const value = constant_as<bool>(this.namedInput("train"));
  11978. // if (value) {
  11979. // schema_info.addArgumentValue('train', value);
  11980. // }
  11981. }
  11982. return schema_info.is_nondeterministic();
  11983. }
  11984. hasSideEffects() {
  11985. switch (this._kind) {
  11986. case 'prim::PythonOp':
  11987. case 'prim::IgnoredPythonOp':
  11988. case 'prim::Print':
  11989. case 'prim::RaiseException':
  11990. case 'aten::warn':
  11991. case 'aten::save':
  11992. case 'aten::manual_seed':
  11993. case 'prim::AddStatValue':
  11994. case 'prim::TimePoint':
  11995. case 'prim::CallFunction':
  11996. case 'prim::CallMethod':
  11997. case 'prim::BailoutTemplate':
  11998. case 'prim::BailOut':
  11999. case 'prim::rpc_async':
  12000. case 'prim::rpc_sync':
  12001. case 'prim::rpc_remote':
  12002. case 'aten::wait':
  12003. case 'cuda::set_stream':
  12004. case 'cuda::_set_device':
  12005. case 'cuda::_current_device':
  12006. case 'cuda::synchronize':
  12007. case 'prim::Enter':
  12008. case 'prim::Exit':
  12009. return true;
  12010. default:
  12011. break;
  12012. }
  12013. const op = this.maybeOperator();
  12014. if (!op) {
  12015. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12016. return false;
  12017. }
  12018. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12019. torch._C.TORCH_INTERNAL_ASSERT(
  12020. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12021. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12022. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12023. }
  12024. switch (op.aliasAnalysisKind()) {
  12025. case 'PURE_FUNCTION':
  12026. case 'FROM_SCHEMA':
  12027. case 'INTERNAL_SPECIAL_CASE':
  12028. return false;
  12029. case 'CONSERVATIVE':
  12030. return true;
  12031. default:
  12032. break;
  12033. }
  12034. torch._C.TORCH_INTERNAL_ASSERT(false);
  12035. return false;
  12036. }
  12037. inputs() {
  12038. return this._inputs;
  12039. }
  12040. outputs() {
  12041. return this._outputs;
  12042. }
  12043. input(i) {
  12044. if (i === undefined) {
  12045. torch._C.AT_ASSERT(this._inputs.length === 1);
  12046. return this._inputs[0];
  12047. }
  12048. return this._inputs[i];
  12049. }
  12050. output(i) {
  12051. if (i === undefined) {
  12052. torch._C.AT_ASSERT(this._outputs.length === 1);
  12053. return this._outputs[0];
  12054. }
  12055. return this._outputs[i];
  12056. }
  12057. hasUses() {
  12058. for (const o of this.outputs()) {
  12059. if (o.uses().length > 0) {
  12060. return true;
  12061. }
  12062. }
  12063. return false;
  12064. }
  12065. blocks() {
  12066. return this._blocks;
  12067. }
  12068. insertInput(i, value) {
  12069. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12070. this._op = null;
  12071. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12072. const use = this.findUseForInput(use_itr);
  12073. use.offset += 1;
  12074. }
  12075. this._inputs.splice(i, 0, value);
  12076. value._uses.push(new torch.Use(this, i));
  12077. return value;
  12078. }
  12079. addInput(value) {
  12080. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12081. this._op = null;
  12082. const use = new torch.Use(this, this._inputs.length);
  12083. value.uses().push(use);
  12084. this._inputs.push(value);
  12085. return value;
  12086. }
  12087. addOutput() {
  12088. const value = new torch.Value(this, this._outputs.length);
  12089. this._outputs.push(value);
  12090. return value;
  12091. }
  12092. addBlock() {
  12093. this._op = null;
  12094. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12095. return this._blocks[this._blocks.length - 1];
  12096. }
  12097. get prev() {
  12098. return this._prev;
  12099. }
  12100. set prev(value) {
  12101. this._prev = value;
  12102. }
  12103. get next() {
  12104. return this._next;
  12105. }
  12106. set next(value) {
  12107. this._next = value;
  12108. }
  12109. insertBefore(n) {
  12110. if (!n.inBlockList()) {
  12111. throw new python.Error('Node not in block.');
  12112. }
  12113. this.insertAfter(n.prev);
  12114. return this;
  12115. }
  12116. insertAfter(n) {
  12117. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12118. torch._C.AT_ASSERT(n.owningBlock());
  12119. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12120. this._owning_block = n.owningBlock();
  12121. const next = n.next;
  12122. n.next = this;
  12123. this.prev = n;
  12124. this.next = next;
  12125. next.prev = this;
  12126. // this.assignTopoPosition();
  12127. return this;
  12128. }
  12129. allocNewInstance(g) {
  12130. return new torch.Node(g, this.kind());
  12131. }
  12132. cloneFrom(s) {
  12133. this._source_range = s._source_range;
  12134. if (s._scope && !s._scope.isBlank()) {
  12135. this._scope = s._scope;
  12136. }
  12137. this.copyAttributes(s);
  12138. this._callstack = s._callstack;
  12139. }
  12140. copyAttributes(rhs) {
  12141. this._values = new Map(rhs._values);
  12142. return this;
  12143. }
  12144. dropInput(i) {
  12145. torch._C.AT_ASSERT(i < this._inputs.length);
  12146. const input_node = this._inputs[i];
  12147. const use_it = this.findUseForInput(i);
  12148. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12149. this._inputs[i] = null;
  12150. return input_node;
  12151. }
  12152. eraseOutput(i) {
  12153. torch._C.AT_ASSERT(i < this._outputs.length);
  12154. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12155. this._op = null;
  12156. const n = this._outputs[i];
  12157. this._outputs.splice(i, 1);
  12158. this.owningGraph().freeValue(n);
  12159. for (let j = i; j < this._outputs.length; j++) {
  12160. this._outputs[j]._offset--;
  12161. }
  12162. }
  12163. eraseBlock(i) {
  12164. this._op = null;
  12165. const n = this._blocks[i];
  12166. this._blocks.splice(i, 1);
  12167. n.destroy();
  12168. }
  12169. findUseForInput(i) {
  12170. const input_uses = this._inputs[i]._uses;
  12171. for (const use_it of input_uses) {
  12172. if (use_it.user === this && use_it.offset === i) {
  12173. return use_it;
  12174. }
  12175. }
  12176. throw new python.Error('Input use not found.');
  12177. }
  12178. moveBefore(n) {
  12179. this.removeFromList();
  12180. this.insertBefore(n);
  12181. }
  12182. removeInput(i) {
  12183. this._op = null;
  12184. this.dropInput(i);
  12185. for (let j = i + 1; j < this._inputs.length; j++) {
  12186. const it = this.findUseForInput(j);
  12187. it.offset--;
  12188. }
  12189. this._inputs.splice(i, 1);
  12190. }
  12191. removeAllInputs() {
  12192. this._op = null;
  12193. for (let i = 0; i < this._inputs.length; i++) {
  12194. this.dropInput(i);
  12195. }
  12196. this._inputs = [];
  12197. }
  12198. inBlockList() {
  12199. return this.next !== null;
  12200. }
  12201. removeFromList() {
  12202. this._owning_block = null;
  12203. const next = this.next;
  12204. const prev = this.prev;
  12205. prev.next = next;
  12206. next.prev = prev;
  12207. this.next = null;
  12208. this.prev = null;
  12209. }
  12210. destroy() {
  12211. while (this.outputs().length > 0) {
  12212. this.eraseOutput(this.outputs().length - 1);
  12213. }
  12214. while (this.blocks().length > 0) {
  12215. this.eraseBlock(this.blocks().length - 1);
  12216. }
  12217. this.removeAllInputs();
  12218. if (this.inBlockList()) {
  12219. this.removeFromList();
  12220. }
  12221. this._graph.freeNode(this);
  12222. }
  12223. replaceAllUsesWith(n) {
  12224. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12225. const nOutputs = this.outputs().length;
  12226. for (let i = 0; i < nOutputs; i++) {
  12227. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12228. }
  12229. }
  12230. s_(name, value) {
  12231. this._values.set(name, [value, 's']);
  12232. return this;
  12233. }
  12234. s(name) {
  12235. return this._values.get(name)[0];
  12236. }
  12237. ss_(name, value) {
  12238. this._values.set(name, [value, 'ss']);
  12239. return this;
  12240. }
  12241. ss(name) {
  12242. return this._values.get(name)[0];
  12243. }
  12244. i_(name, value) {
  12245. this._values.set(name, [value, 'i']);
  12246. return this;
  12247. }
  12248. i(name) {
  12249. return this._values.get(name)[0];
  12250. }
  12251. f_(name, value) {
  12252. this._values.set(name, [value, 'f']);
  12253. return this;
  12254. }
  12255. f(name) {
  12256. return this._values.get(name)[0];
  12257. }
  12258. t_(name, value) {
  12259. this._values.set(name, [value, 't']);
  12260. return this;
  12261. }
  12262. t(name) {
  12263. return this._values.get(name)[0];
  12264. }
  12265. tys_(name, value) {
  12266. this._values.set(name, [value, 'tys']);
  12267. return this;
  12268. }
  12269. tys(name) {
  12270. return this._values.get(name)[0];
  12271. }
  12272. ival_(name, value) {
  12273. this._values.set(name, [value, 'ival']);
  12274. return this;
  12275. }
  12276. ival(name) {
  12277. return this._values.get(name)[0];
  12278. }
  12279. hasAttribute(name) {
  12280. return this._values.has(name);
  12281. }
  12282. hasAttributes() {
  12283. return this._values.size > 0;
  12284. }
  12285. attributeNames() {
  12286. return Array.from(this._values.keys());
  12287. }
  12288. kindOf(name) {
  12289. return this._values.get(name)[1];
  12290. }
  12291. setSourceRange(r) {
  12292. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12293. this._source_range = r;
  12294. return this;
  12295. }
  12296. sourceRange() {
  12297. if (this._source_range) {
  12298. return this._source_range;
  12299. }
  12300. return new torch._C.SourceRange();
  12301. }
  12302. print_attributes(out, ignore_subgraph) {
  12303. ignore_subgraph = ignore_subgraph || false;
  12304. out.write('[');
  12305. const names = this.attributeNames();
  12306. for (let i = 0; i < names.length; i++) {
  12307. const name = names[i];
  12308. if (ignore_subgraph && name === 'Subgraph') {
  12309. continue;
  12310. }
  12311. if (i > 0) {
  12312. out.write(', ');
  12313. }
  12314. out.write(`${name}=`);
  12315. this.printAttrValue(out, name);
  12316. }
  12317. out.write(']');
  12318. }
  12319. printTypeList(out, items) {
  12320. out.write('[');
  12321. for (let i = 0; i < items.length; i++) {
  12322. const item = items[i];
  12323. if (i++ > 0) {
  12324. out.write(', ');
  12325. }
  12326. out.write(item.str());
  12327. }
  12328. out.write(']');
  12329. }
  12330. printAttrValue(out, name) {
  12331. const kind = this.kindOf(name);
  12332. switch (kind) {
  12333. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12334. case 'ss': case 'ival': case 'ty':
  12335. out.write(this[kind](name));
  12336. break;
  12337. case 's':
  12338. out.write(`"${this.s(name)}"`);
  12339. break;
  12340. case 't':
  12341. out.write(`"{}"`);
  12342. break;
  12343. case 'ts': out.write('[<Tensors>]'); break;
  12344. case 'g': out.write('[<Graph>]'); break;
  12345. case 'gs': out.write('[<Graphs>]'); break;
  12346. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12347. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12348. }
  12349. }
  12350. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12351. print_source_locations = print_source_locations === false ? false : true;
  12352. print_attributes = print_attributes === false ? false : true;
  12353. print_scopes = print_scopes === false ? false : true;
  12354. print_body = print_body === false ? false : true;
  12355. const outs = this.outputs();
  12356. torch._C.indent(out, level);
  12357. torch._C.const_value_list_with_types(out, outs, ', ');
  12358. out.write(' = ');
  12359. if (this.kind() === 'prim::PythonOp') {
  12360. throw new python.Error('Not implemented.');
  12361. } else if (this.hasAttribute('Subgraph') && groups) {
  12362. throw new python.Error('Not implemented.');
  12363. } else {
  12364. out.write(this.kind());
  12365. if (print_attributes && this.hasAttributes()) {
  12366. this.print_attributes(out);
  12367. }
  12368. }
  12369. out.write('(');
  12370. torch._C.printValueRefs(out, this.inputs());
  12371. out.write(')');
  12372. if (print_scopes) {
  12373. //
  12374. }
  12375. if (print_source_locations) {
  12376. let r = this.sourceRange();
  12377. if (r.source()) {
  12378. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12379. if (orig) {
  12380. r = orig;
  12381. }
  12382. }
  12383. const file_line_col = r.file_line_col();
  12384. if (file_line_col !== null) {
  12385. const [filename, line, col] = file_line_col;
  12386. out.write(` # ${filename}:${line}:${col}`);
  12387. }
  12388. }
  12389. if (!print_body) {
  12390. return out;
  12391. }
  12392. out.write('\n');
  12393. for (let i = 0; i < this.blocks().length; i++) {
  12394. const b = this.blocks()[i];
  12395. torch._C.indent(out, level + 1);
  12396. out.write(`block${i}(`);
  12397. torch._C.const_value_list_with_types(out, b.inputs());
  12398. out.write('):\n');
  12399. for (const nested of b.nodes()) {
  12400. nested.print(out, level + 2, groups);
  12401. }
  12402. torch._C.indent(out, level + 2);
  12403. out.write('-> (');
  12404. torch._C.printValueRefs(out, b.outputs());
  12405. out.write(')\n');
  12406. }
  12407. return out;
  12408. }
  12409. toString() {
  12410. const out = new io.StringIO();
  12411. this.print(out, 0, true);
  12412. return out.toString();
  12413. }
  12414. });
  12415. this.registerType('torch.Value', class {
  12416. constructor(node, offset) {
  12417. this._node = node;
  12418. this._offset = offset;
  12419. this._unique = node._graph._next_unique++;
  12420. this._uses = [];
  12421. this._node._graph.all_values.add(this);
  12422. }
  12423. unique() {
  12424. return this._unique;
  12425. }
  12426. node() {
  12427. return this._node;
  12428. }
  12429. owningGraph() {
  12430. return this._node.owningGraph();
  12431. }
  12432. uses() {
  12433. return this._uses;
  12434. }
  12435. hasUses() {
  12436. return this._uses.length > 0;
  12437. }
  12438. mustBeNone() {
  12439. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12440. }
  12441. mustNotBeNone() {
  12442. return this._node.kind() !== 'prim::AutogradAdd' &&
  12443. this.type() !== torch.NoneType.get() &&
  12444. !(this.type() instanceof torch.OptionalType) &&
  12445. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12446. }
  12447. isValidName(name) {
  12448. if (name.length === 0) {
  12449. return true;
  12450. }
  12451. if (torch._C.isNumber(name)) {
  12452. return false;
  12453. }
  12454. return true;
  12455. }
  12456. hasDebugName() {
  12457. return this._unique_name && this._unique_name.length > 0;
  12458. }
  12459. setDebugName(name) {
  12460. if (!this.isValidName(name)) {
  12461. throw new python.Error(`Invalid name '${name}'.`);
  12462. }
  12463. const names = this.node().owningGraph()._unique_names;
  12464. if (this.hasDebugName()) {
  12465. names.delete(this._unique_name);
  12466. this._unique_name = '';
  12467. }
  12468. if (!name) {
  12469. return this;
  12470. }
  12471. const old_owner_of_name = names.get(name);
  12472. if (old_owner_of_name) {
  12473. let suffix = 1;
  12474. let name_base = name;
  12475. const last_dot_pos = name.lastIndexOf('.');
  12476. if (last_dot_pos !== -1) {
  12477. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12478. suffix = Number(name.substring(last_dot_pos + 1));
  12479. name_base = name.substring(0, last_dot_pos);
  12480. }
  12481. }
  12482. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12483. if (names_suffixes.has(name_base)) {
  12484. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12485. }
  12486. let replacement_name = null;
  12487. do {
  12488. replacement_name = `${name_base}.${suffix++}`;
  12489. } while (names.has(replacement_name));
  12490. names_suffixes.set(name_base, suffix);
  12491. old_owner_of_name.setDebugName(replacement_name);
  12492. }
  12493. names.set(name, this);
  12494. this._unique_name = name;
  12495. return this;
  12496. }
  12497. debugName() {
  12498. if (this.hasDebugName()) {
  12499. return this._unique_name;
  12500. }
  12501. return this.unique().toString();
  12502. }
  12503. type() {
  12504. return this._type;
  12505. }
  12506. setType(type) {
  12507. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12508. if (type instanceof torch._C.DynamicType) {
  12509. type = type.fallback();
  12510. }
  12511. this._type = type;
  12512. for (const use of this._uses) {
  12513. use.user._op = null;
  12514. }
  12515. return this;
  12516. }
  12517. set value(value) { // remove
  12518. if (value instanceof torch.Value) {
  12519. throw new python.Error('Value cannot be a value.');
  12520. }
  12521. this._value = value;
  12522. }
  12523. get value() { // remove
  12524. return this._value;
  12525. }
  12526. replaceFirstUseWith(newValue) {
  12527. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12528. const [u] = this.uses();
  12529. u.user._inputs[u.offset] = newValue;
  12530. newValue._uses.push(u);
  12531. this._uses.shift();
  12532. }
  12533. replaceAllUsesWith(newValue) {
  12534. while (this.uses().length > 0) {
  12535. this.replaceFirstUseWith(newValue);
  12536. }
  12537. }
  12538. copyMetadata(from) {
  12539. this.setType(from.type());
  12540. if (from.hasDebugName()) {
  12541. this.setDebugName(from.debugName());
  12542. }
  12543. return this;
  12544. }
  12545. toString() {
  12546. return `${this.debugName()} : ${this.type().toString()}`;
  12547. }
  12548. });
  12549. this.registerType('torch.Use', class {
  12550. constructor(user, offset) {
  12551. this.user = user;
  12552. this.offset = offset;
  12553. }
  12554. });
  12555. this.registerType('torch._C.IValue', class {
  12556. constructor(value, tag) {
  12557. this.value = value;
  12558. if (tag) {
  12559. this.tag = tag;
  12560. } else if (value === undefined) {
  12561. this.tag = 'None';
  12562. this.value = null;
  12563. } else if (typeof value === 'boolean') {
  12564. this.tag = 'Bool';
  12565. } else if (typeof value === 'string') {
  12566. this.tag = 'String';
  12567. } else if (value instanceof torch.Tensor) {
  12568. this.tag = 'Tensor';
  12569. } else if (value instanceof torch.ScriptObject) {
  12570. this.tag = 'Object';
  12571. } else if (Array.isArray(value)) {
  12572. this.tag = 'GenericList';
  12573. } else if (value instanceof torch._C.Tuple) {
  12574. this.tag = 'Tuple';
  12575. } else if (value instanceof torch.device) {
  12576. this.tag = 'Device';
  12577. } else if (Number.isInteger(value)) {
  12578. this.tag = 'Int';
  12579. } else if (typeof value === 'number') {
  12580. this.tag = 'Double';
  12581. } else if (value instanceof torch._C.EnumHolder) {
  12582. this.tag = 'Enum';
  12583. } else {
  12584. throw new python.Error('Unsupported type.');
  12585. }
  12586. }
  12587. isNone() {
  12588. return this.tag === 'None';
  12589. }
  12590. isBool() {
  12591. return this.tag === 'Bool';
  12592. }
  12593. toBool() {
  12594. return this.value;
  12595. }
  12596. isObject() {
  12597. return this.tag === 'Object';
  12598. }
  12599. toObject() {
  12600. return this.value;
  12601. }
  12602. isTensor() {
  12603. return this.tag === 'Tensor';
  12604. }
  12605. toTensor() {
  12606. return this.value;
  12607. }
  12608. isDouble() {
  12609. return this.tag === 'Double';
  12610. }
  12611. toDouble() {
  12612. return this.value;
  12613. }
  12614. isComplexDouble() {
  12615. return this.tag === 'ComplexDouble';
  12616. }
  12617. isInt() {
  12618. return this.tag === 'Int';
  12619. }
  12620. toInt() {
  12621. if (this.isInt()) {
  12622. return this.value;
  12623. } else if (this.isSymInt()) {
  12624. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12625. }
  12626. throw new python.Error('Expected int.');
  12627. }
  12628. isString() {
  12629. return this.tag === 'String';
  12630. }
  12631. toStringRef() {
  12632. return this.value;
  12633. }
  12634. isList() {
  12635. return this.tag === 'GenericList';
  12636. }
  12637. toList() {
  12638. return this.value;
  12639. }
  12640. toListRef() {
  12641. return this.value;
  12642. }
  12643. isBoolList() {
  12644. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12645. }
  12646. isIntList() {
  12647. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12648. }
  12649. isDoubleList() {
  12650. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12651. }
  12652. isDevice() {
  12653. return this.tag === 'Device';
  12654. }
  12655. toDevice() {
  12656. return this.value;
  12657. }
  12658. isGenerator() {
  12659. return this.tag === 'Generator';
  12660. }
  12661. isStream() {
  12662. return this.tag === 'Stream';
  12663. }
  12664. isGenericDict() {
  12665. return this.tag === 'GenericDict';
  12666. }
  12667. isEnum() {
  12668. return this.tag === 'Enum';
  12669. }
  12670. toEnumHolder() {
  12671. return this.value;
  12672. }
  12673. isTuple() {
  12674. return this.tag === 'Tuple';
  12675. }
  12676. toTupleRef() {
  12677. return this.value;
  12678. }
  12679. isCustomClass() {
  12680. return torch._C.isCustomClass(this);
  12681. }
  12682. equals(rhs) {
  12683. switch (this.tag) {
  12684. case 'None': return rhs.isNone();
  12685. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  12686. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  12687. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  12688. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  12689. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  12690. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  12691. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  12692. case 'GenericList': {
  12693. if (rhs.isList()) {
  12694. const a = this.toList();
  12695. const b = rhs.toList();
  12696. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  12697. }
  12698. return false;
  12699. }
  12700. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  12701. }
  12702. }
  12703. is(rhs) {
  12704. return this.equals(rhs);
  12705. }
  12706. type() {
  12707. switch (this.tag) {
  12708. case 'None': return torch.NoneType.get();
  12709. case 'Bool': return torch.BoolType.get();
  12710. case 'Int': return torch.IntType.get();
  12711. case 'Double': return torch.FloatType.get();
  12712. case 'String': return torch.StringType.get();
  12713. case 'Device': return torch.DeviceObjType.get();
  12714. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  12715. case 'Enum': return this.toEnumHolder().type();
  12716. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  12717. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  12718. }
  12719. }
  12720. });
  12721. this.registerFunction('torch._C.indent', (out, level) => {
  12722. for (let i = 0; i < level; i++) {
  12723. out.write(' ');
  12724. }
  12725. return out;
  12726. });
  12727. this.registerFunction('torch._C.printValueRef', (out, n) => {
  12728. out.write(`%${n.debugName()}`);
  12729. });
  12730. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  12731. for (let i = 0; i < nodes.length; i++) {
  12732. const n = nodes[i];
  12733. if (i > 0) {
  12734. out.write(', ');
  12735. }
  12736. torch._C.printValueRef(out, n);
  12737. }
  12738. return out;
  12739. });
  12740. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  12741. for (let i = 0; i < values.length; i++) {
  12742. const n = values[i];
  12743. if (i > 0) {
  12744. out.write(delim);
  12745. }
  12746. torch._C.printValueRef(out, n);
  12747. out.write(' : ');
  12748. out.write(n.type().str());
  12749. }
  12750. });
  12751. this.register('torch.jit._script');
  12752. this.register('torch.jit._trace');
  12753. this.registerType('torch._C.Parser', class {
  12754. constructor(source) {
  12755. this.L = source;
  12756. }
  12757. parse() {
  12758. const p = ast.parse(this.L.text_str(), this.L.filename());
  12759. return p;
  12760. }
  12761. parseExp() {
  12762. const expr = ast.parse(this.L.text_str());
  12763. return expr.body[0].value;
  12764. }
  12765. });
  12766. this.registerType('torch._C.StringCordView', class {
  12767. });
  12768. this.registerType('torch._C.Source', class {
  12769. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  12770. if (text_view instanceof Uint8Array) {
  12771. const decoder = new TextDecoder('utf-8');
  12772. this._text_view = decoder.decode(text_view);
  12773. } else if (typeof text_view === 'string') {
  12774. this._text_view = text_view;
  12775. } else {
  12776. throw new python.Error('Invalid text view.');
  12777. }
  12778. this._filename = filename;
  12779. this._starting_line_no = starting_line_no;
  12780. this._gen_ranges = gen_ranges;
  12781. this.calc_line_start_offsets();
  12782. }
  12783. text_str() {
  12784. return this._text_view;
  12785. }
  12786. size() {
  12787. return this._text_view.length;
  12788. }
  12789. filename() {
  12790. return this._filename;
  12791. }
  12792. calc_line_start_offsets() {
  12793. let pos = 0;
  12794. this._line_starting_offsets = [0];
  12795. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  12796. pos += 1;
  12797. this._line_starting_offsets.push(pos);
  12798. }
  12799. }
  12800. offset_for_line(line) {
  12801. return this._line_starting_offsets[line];
  12802. }
  12803. lineno_for_offset(offset) {
  12804. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  12805. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  12806. }
  12807. lineno_to_source_lineno(lineno) {
  12808. if (this._filename) {
  12809. return lineno + this._starting_line_no;
  12810. }
  12811. return lineno;
  12812. }
  12813. findSourceRangeThatGenerated(range) {
  12814. if (!this._gen_ranges) {
  12815. return null;
  12816. }
  12817. return this._gen_ranges.findSourceRangeThatGenerated(range);
  12818. }
  12819. });
  12820. this.registerType('torch._C.SourceRange', class {
  12821. constructor(...args) {
  12822. if (args.length === 0) {
  12823. this._source_view = null;
  12824. } else if (args.length === 2) {
  12825. let node = null;
  12826. [this._source_view, node] = args;
  12827. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  12828. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  12829. } else if (args.length === 3) {
  12830. [this._source_view, this._start, this._end] = args;
  12831. } else {
  12832. throw new python.Error('Not implemented.');
  12833. }
  12834. }
  12835. source() {
  12836. return this._source_view;
  12837. }
  12838. file_line_col() {
  12839. if (!this._source_view || this.source().filename() === null) {
  12840. return null;
  12841. }
  12842. const lineno = this._source_view.lineno_for_offset(this._start);
  12843. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  12844. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  12845. }
  12846. start() {
  12847. return this._start;
  12848. }
  12849. toString() {
  12850. const loc = this.file_line_col();
  12851. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  12852. }
  12853. });
  12854. this.registerType('torch._C.QualifiedName', class {
  12855. constructor(...args) {
  12856. let name = null;
  12857. if (args.length === 1 && typeof args[0] === 'string') {
  12858. [name] = args;
  12859. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  12860. name = args[0].join('.');
  12861. } else {
  12862. name = `${args[0].qualifiedName()}.${args[1]}`;
  12863. }
  12864. const index = name.lastIndexOf('.');
  12865. this._qualifiedName = name;
  12866. this._prefix = index === -1 ? '' : name.substring(0, index);
  12867. this._name = index === -1 ? name : name.substring(index + 1);
  12868. }
  12869. qualifiedName() {
  12870. return this._qualifiedName; // "foo.bar.baz"
  12871. }
  12872. prefix() {
  12873. return this._prefix; // "foo.bar"
  12874. }
  12875. name() {
  12876. return this._name; // "baz"
  12877. }
  12878. atoms() {
  12879. return this._qualifiedName.split('.');
  12880. }
  12881. });
  12882. this.registerType('torch._C.Resolver', class {
  12883. resolveValue() {
  12884. throw new python.Error('Not implemented.');
  12885. }
  12886. resolveType() {
  12887. throw new python.Error('Not implemented.');
  12888. }
  12889. });
  12890. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  12891. torch._C.customClasses = torch._C.customClasses || new Map();
  12892. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  12893. const name = class_type.name().qualifiedName();
  12894. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  12895. torch._C.customClasses.set(name, class_type);
  12896. });
  12897. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  12898. torch._C.customClasses = torch._C.customClasses || new Map();
  12899. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  12900. return ret;
  12901. });
  12902. this.registerFunction('torch._C.isCustomClass', (v) => {
  12903. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  12904. });
  12905. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  12906. constructor(cu, constant_table, source_loader, version) {
  12907. super();
  12908. this._cu = cu;
  12909. this._constant_table = constant_table;
  12910. this._source_loader = source_loader;
  12911. this._version = version;
  12912. this._loaded_sources = new Set();
  12913. this._sources = new Map();
  12914. const sources = this._sources;
  12915. ast.AST.prototype.range = function() {
  12916. if (!this._range) {
  12917. if (sources.has(this.filename)) {
  12918. const source_view = sources.get(this.filename);
  12919. this._range = new torch._C.SourceRange(source_view, this);
  12920. } else {
  12921. this._range = new torch._C.SourceRange();
  12922. }
  12923. }
  12924. return this._range;
  12925. };
  12926. this._to_be_defined = new Map();
  12927. this._env = new Map([
  12928. ['torch', new torch._C.BuiltinModule('aten', version)],
  12929. ['ops', new torch._C.OpsValue(version)],
  12930. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  12931. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  12932. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  12933. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  12934. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  12935. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  12936. ]);
  12937. }
  12938. loadType(name) {
  12939. const type_parser = new torch._C.ScriptTypeParser(this);
  12940. return type_parser.parseType(name.qualifiedName());
  12941. }
  12942. resolveType(name) {
  12943. name = new torch._C.QualifiedName(name);
  12944. return this.findNamedType(name);
  12945. }
  12946. resolveValue(name, m, loc) {
  12947. if (this._env.has(name)) {
  12948. return this._env.get(name);
  12949. }
  12950. const graph = m.graph();
  12951. switch (name) {
  12952. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  12953. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  12954. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  12955. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  12956. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  12957. default: return null;
  12958. }
  12959. }
  12960. findNamedType(name) {
  12961. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  12962. if (custom_class) {
  12963. return custom_class;
  12964. }
  12965. this.parseSourceIfNeeded(name.prefix());
  12966. const key = name.qualifiedName();
  12967. const it = this._to_be_defined.get(key);
  12968. if (it && it instanceof ast.ClassDef) {
  12969. this._to_be_defined.delete(key);
  12970. this.importNamedType(name.prefix(), it);
  12971. }
  12972. return this._cu.get_type(name);
  12973. }
  12974. importNamedType(qualifier, class_def) {
  12975. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  12976. if (class_def.bases.length === 0) {
  12977. this.importClass(qualified_name, class_def, false);
  12978. return;
  12979. }
  12980. const superclass_name = class_def.bases[0].id;
  12981. if (superclass_name === 'Module') {
  12982. this.importClass(qualified_name, class_def, true);
  12983. } else if (superclass_name === 'NamedTuple') {
  12984. this.importNamedTuple(qualified_name, class_def);
  12985. } else if (superclass_name === 'Interface') {
  12986. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  12987. } else if (superclass_name === 'ModuleInterface') {
  12988. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  12989. } else if (superclass_name === 'Enum') {
  12990. this.importEnum(qualified_name, class_def);
  12991. } else {
  12992. throw new python.Error('TorchScript does not support class inheritance.');
  12993. }
  12994. }
  12995. importClass(qualified_classname, class_def, is_module) {
  12996. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  12997. return;
  12998. }
  12999. const parameter_names = new Set();
  13000. const buffer_names = new Set();
  13001. const methods = [];
  13002. const method_resolvers = [];
  13003. const attributes = [];
  13004. const constants = [];
  13005. const pre_hook_names = new Set();
  13006. const pre_hook_def_map = new Map();
  13007. const hook_names = new Set();
  13008. const hook_def_map = new Map();
  13009. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13010. for (const stmt of class_def.body) {
  13011. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13012. let target = null;
  13013. let annotation = null;
  13014. let value = null;
  13015. if (stmt instanceof ast.Assign) {
  13016. [target] = stmt.targets;
  13017. value = stmt.value;
  13018. } else {
  13019. target = stmt.target;
  13020. annotation = stmt.annotation;
  13021. value = stmt.value;
  13022. }
  13023. if (target instanceof ast.Name) {
  13024. const name = this._cu.execution.identifier(target);
  13025. switch (name) {
  13026. case '__annotations__': {
  13027. continue;
  13028. }
  13029. case '__parameters__': {
  13030. for (const elt of value.elts) {
  13031. parameter_names.add(elt.value);
  13032. }
  13033. break;
  13034. }
  13035. case '__buffers__': {
  13036. for (const elt of value.elts) {
  13037. buffer_names.add(elt.value);
  13038. }
  13039. break;
  13040. }
  13041. case '__forward_pre_hooks__': {
  13042. for (const elt of value.elts) {
  13043. pre_hook_names.add(elt.value);
  13044. }
  13045. break;
  13046. }
  13047. case '__forward_hooks__': {
  13048. for (const elt of value.elts) {
  13049. hook_names.add(elt.value);
  13050. }
  13051. break;
  13052. }
  13053. default: {
  13054. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13055. if (fixed_up) {
  13056. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13057. } else if (value) {
  13058. constants.push({ name, value, annotation });
  13059. } else {
  13060. attributes.push({ name, value, annotation });
  13061. }
  13062. break;
  13063. }
  13064. }
  13065. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13066. const name = target.slice.value;
  13067. attributes.push({ name, value, annotation: stmt.value });
  13068. continue;
  13069. } else {
  13070. throw new python.Error('Unexpected statement kind in module metadata.');
  13071. }
  13072. } else if (stmt instanceof ast.FunctionDef) {
  13073. const def = stmt;
  13074. const def_name = def.name;
  13075. if (pre_hook_names.has(def_name)) {
  13076. pre_hook_def_map.set(def_name, def);
  13077. } else if (hook_names.has(def_name)) {
  13078. hook_def_map.set(def_name, def);
  13079. } else {
  13080. methods.push(def);
  13081. method_resolvers.push(this);
  13082. }
  13083. } else {
  13084. throw new python.Error('Unexpected statement kind in class body.');
  13085. }
  13086. }
  13087. const type_parser = new torch._C.ScriptTypeParser(this);
  13088. for (const assign of attributes) {
  13089. const name = assign.name;
  13090. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13091. const is_parameter = parameter_names.has(name);
  13092. const is_buffer = buffer_names.has(name);
  13093. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13094. }
  13095. for (const constant of constants) {
  13096. class_type.addConstant(constant.name, constant.value);
  13097. }
  13098. this._cu.register_type(class_type);
  13099. const self = new torch._C.SimpleSelf(class_type);
  13100. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13101. }
  13102. importEnum(qualified_name, enum_def) {
  13103. const names_values = [];
  13104. let value_type = null;
  13105. const set_or_check_type = (t) => {
  13106. if (!value_type) {
  13107. value_type = t;
  13108. } else if (value_type !== t) {
  13109. throw new python.Error('Enum class with varying value types are not supported.');
  13110. }
  13111. };
  13112. for (const stmt of enum_def.body) {
  13113. if (stmt instanceof ast.Assign === false) {
  13114. throw new python.Error('Unexpected statement in Enum class body.');
  13115. }
  13116. const assign = stmt;
  13117. const name = assign.targets[0].id;
  13118. let ivalue = null;
  13119. const rhs = assign.value;
  13120. switch (rhs.type) {
  13121. case 'str':
  13122. ivalue = new torch._C.IValue(rhs.value, 'String');
  13123. set_or_check_type(torch.StringType.get());
  13124. break;
  13125. case 'int':
  13126. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13127. set_or_check_type(torch.IntType.get());
  13128. break;
  13129. case 'float':
  13130. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13131. set_or_check_type(torch.FloatType.get());
  13132. break;
  13133. default:
  13134. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13135. }
  13136. names_values.push([name, ivalue]);
  13137. }
  13138. if (!value_type) {
  13139. throw new python.Error('No enum values defined.');
  13140. }
  13141. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13142. this._cu.register_type(enum_type);
  13143. }
  13144. importNamedTuple(qualified_name, named_tuple_def) {
  13145. const type_parser = new torch._C.ScriptTypeParser(this);
  13146. const field_names = [];
  13147. const field_types = [];
  13148. const field_defaults = [];
  13149. for (const stmt of named_tuple_def.body) {
  13150. if (stmt instanceof ast.AnnAssign === false) {
  13151. throw new python.Error('Unexpected statement in NamedTuple body.');
  13152. }
  13153. const assign = stmt;
  13154. const target = this._cu.execution.identifier(stmt.target);
  13155. // const annotation = this._cu.execution.type(stmt.annotation);
  13156. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13157. field_names.push(target);
  13158. // field_types.push(annotation);
  13159. field_types.push(type);
  13160. }
  13161. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13162. this._cu.register_type(tt);
  13163. }
  13164. importFunction(qualifier, def) {
  13165. const definitions = [def];
  13166. const resolvers = [this];
  13167. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13168. }
  13169. parseSourceIfNeeded(qualifier) {
  13170. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13171. return;
  13172. }
  13173. this._loaded_sources.add(qualifier);
  13174. const src = this._source_loader(qualifier);
  13175. if (!src) {
  13176. return;
  13177. }
  13178. this._sources.set(src.filename(), src);
  13179. const p = new torch._C.Parser(src);
  13180. const L = p.parse();
  13181. this.parsePossibleVersionNumber(p);
  13182. for (const stmt of L.body) {
  13183. if (stmt instanceof ast.ClassDef) {
  13184. const name = `${qualifier}.${stmt.name}`;
  13185. this._to_be_defined.set(name, stmt);
  13186. } else if (stmt instanceof ast.FunctionDef) {
  13187. const name = `${qualifier}.${stmt.name}`;
  13188. this._to_be_defined.set(name, stmt);
  13189. }
  13190. }
  13191. }
  13192. parsePossibleVersionNumber(/* p */) {
  13193. }
  13194. parseImports(/* p */) {
  13195. }
  13196. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13197. const replacements = new Map([
  13198. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13199. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13200. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13201. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13202. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13203. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13204. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13205. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13206. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13207. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13208. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13209. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13210. ]);
  13211. const mangleRe = /\.___torch_mangle_\d+/g;
  13212. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13213. if (replacements.has(demangled_classname)) {
  13214. const lhs = assign.target;
  13215. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13216. return null;
  13217. }
  13218. const type = assign.annotation.id;
  13219. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13220. if (lhs.id === attr_name && type === expected_type) {
  13221. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13222. const typename_expr = p.parseExp();
  13223. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13224. }
  13225. }
  13226. return null;
  13227. }
  13228. LEGACY_import_methods(mod, src) {
  13229. const self = new torch._C.SimpleSelf(mod.type());
  13230. const prefix = mod.type().name();
  13231. const p = new torch._C.Parser(src);
  13232. const L = p.parse();
  13233. this.parsePossibleVersionNumber(L);
  13234. this.parseImports(L);
  13235. const definitions = [];
  13236. const resolvers = [];
  13237. for (const def of L.body) {
  13238. if (def instanceof ast.FunctionDef) {
  13239. definitions.push(def);
  13240. resolvers.push(this);
  13241. }
  13242. }
  13243. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13244. }
  13245. findFunction(name) {
  13246. this.parseSourceIfNeeded(name.prefix());
  13247. const key = name.qualifiedName();
  13248. const it = this._to_be_defined.get(key);
  13249. if (it && it instanceof ast.FunctionDef) {
  13250. this._to_be_defined.delete(key);
  13251. this.importFunction(name.prefix(), it);
  13252. }
  13253. return this._cu.find_function(name);
  13254. }
  13255. });
  13256. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13257. constructor(otherResolver, functionTable) {
  13258. super();
  13259. this._otherResolver = otherResolver;
  13260. this._functionTable = functionTable;
  13261. }
  13262. resolveValue(name, m, loc) {
  13263. const it = this._functionTable.get(name);
  13264. if (it) {
  13265. return new torch._C.FunctionValue(it);
  13266. }
  13267. return this._otherResolver.resolveValue(name, m, loc);
  13268. }
  13269. resolveType(name, loc) {
  13270. return this._otherResolver.resolveType(name, loc);
  13271. }
  13272. });
  13273. this.registerType('torch._C.SourceRangeDeserializer', class {
  13274. constructor(text_table) {
  13275. this.cached_sources = new Map();
  13276. this._text_table = text_table || [];
  13277. }
  13278. deserialize(iv) {
  13279. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13280. const [file, start, end] = iv;
  13281. const source = this.deserialize_source(file);
  13282. return new torch._C.SourceRange(source, start, end);
  13283. }
  13284. deserialize_source(iv) {
  13285. const tup = iv;
  13286. if (this.cached_sources.has(tup)) {
  13287. return this.cached_sources.get(tup);
  13288. }
  13289. let source = null;
  13290. const tup_elems = tup;
  13291. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13292. if (this._text_table.length > 0) {
  13293. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13294. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13295. const filename = this._text_table[fnameIndex];
  13296. const pieces = [];
  13297. const strs = [];
  13298. for (const i of textIndex) {
  13299. pieces.push(this._text_table[i]);
  13300. strs.push(this._text_table[i]);
  13301. }
  13302. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13303. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13304. } else {
  13305. const [text, filename, starting_line_no] = tup_elems;
  13306. source = new torch._C.Source(text, filename, starting_line_no);
  13307. }
  13308. this.cached_sources.set(tup, source);
  13309. return source;
  13310. }
  13311. });
  13312. this.registerType('torch._C.SourceRangeUnpickler', class {
  13313. });
  13314. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13315. constructor (data) {
  13316. super();
  13317. this.data = data;
  13318. this.deserializer = null;
  13319. this.unpickled_records = null;
  13320. }
  13321. unpickle() {
  13322. if (this.unpickled_records) {
  13323. return;
  13324. }
  13325. const unpickler = new pickle.Unpickler(this.data);
  13326. const ivalues = unpickler.load();
  13327. torch._C.TORCH_CHECK(ivalues.length > 0);
  13328. this.unpickled_records = [];
  13329. let lines = null;
  13330. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13331. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13332. /* eslint-disable prefer-destructuring */
  13333. lines = ivalues[2];
  13334. /* eslint-enable prefer-destructuring */
  13335. } else {
  13336. this.deserializer = new torch._C.SourceRangeDeserializer();
  13337. lines = ivalues;
  13338. }
  13339. for (const tup_elems of lines) {
  13340. const [offset, range] = tup_elems;
  13341. const source_range = this.deserializer.deserialize(range);
  13342. this.unpickled_records.push([offset, source_range]);
  13343. }
  13344. }
  13345. findSourceRangeThatGenerated(range) {
  13346. this.unpickle();
  13347. const start = range.start();
  13348. const records = this.unpickled_records;
  13349. for (let i = 0; i < records.length; i++) {
  13350. const [offset, target] = records[i];
  13351. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13352. if (start >= offset && start < next) {
  13353. return target;
  13354. }
  13355. }
  13356. return null;
  13357. }
  13358. });
  13359. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13360. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13361. });
  13362. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13363. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13364. if (!reader.has_record(path)) {
  13365. return null;
  13366. }
  13367. const stream = reader.get_record(path);
  13368. let gen_ranges = null;
  13369. const debug_file = `${path}.debug_pkl`;
  13370. if (reader.has_record(debug_file)) {
  13371. const debug_stream = reader.get_record(debug_file);
  13372. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13373. }
  13374. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13375. });
  13376. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13377. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13378. this._compilation_unit = cu;
  13379. this._reader = reader;
  13380. this._storage_context = storage_context;
  13381. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13382. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13383. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13384. this._constant_table = [];
  13385. const SourceLoader = (qualifier) => {
  13386. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13387. };
  13388. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13389. }
  13390. deserialize() {
  13391. const execution = this._compilation_unit.execution;
  13392. const code_prefix = this._code_prefix;
  13393. for (const name of this._reader.get_all_records()) {
  13394. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13395. const file = name.substring(code_prefix.length);
  13396. const stream = this._reader.get_record(name);
  13397. const buffer = stream.peek();
  13398. execution.add(file, buffer);
  13399. }
  13400. }
  13401. const torch = execution.import('torch');
  13402. execution.builtins.torch = torch;
  13403. execution.builtins.Tensor = torch.Tensor;
  13404. execution.builtins.ops = torch.ops;
  13405. execution.builtins.inf = torch.inf;
  13406. execution.builtins.CONSTANTS = {};
  13407. execution._resolver = this._source_importer;
  13408. if (this._reader.has_record('model.json')) {
  13409. return this.LEGACY_deserialize();
  13410. }
  13411. const constants = this.readArchive('constants');
  13412. for (let i = 0; i < constants.length; i++) {
  13413. let val = constants[i];
  13414. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13415. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13416. const obj = torch.ScriptObject.create(type);
  13417. obj._ivalue = val;
  13418. val = obj;
  13419. }
  13420. execution.builtins.CONSTANTS[`c${i}`] = val;
  13421. this._constant_table.push(val);
  13422. }
  13423. const obj = this.readArchive('data');
  13424. const convertObject = (obj) => {
  13425. if (obj.__class__) {
  13426. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13427. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13428. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13429. for (let i = 0; i < type.numAttributes(); i++) {
  13430. const k = type.getAttributeName(i);
  13431. const t = type.getAttribute(i);
  13432. const v = obj[k];
  13433. if (t instanceof torch.ClassType) {
  13434. module.__setattr__(k, convertObject(v));
  13435. } else {
  13436. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13437. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13438. type._attributes[i].type = this._source_importer.resolveType(name);
  13439. }
  13440. module.__setattr__(k, obj[k]);
  13441. }
  13442. }
  13443. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13444. if (value && value.__class__ === builtins.method) {
  13445. module[key] = value;
  13446. }
  13447. }
  13448. return module;
  13449. }
  13450. throw new python.Error('Module class not found.');
  13451. };
  13452. return convertObject(obj);
  13453. }
  13454. LEGACY_deserialize() {
  13455. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13456. const execution = this._compilation_unit.execution;
  13457. const caffe2 = execution.proto.caffe2;
  13458. const torch = execution.import('torch');
  13459. const stream = this._reader.get_record('model.json');
  13460. const buffer = stream.peek();
  13461. const decoder = new TextDecoder('utf-8');
  13462. const content = decoder.decode(buffer);
  13463. const obj = JSON.parse(content);
  13464. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13465. const tensorTypeMap = new Map([
  13466. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13467. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13468. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13469. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13470. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13471. [caffe2.TensorProto.DataType.INT64, 'Long']
  13472. ]);
  13473. const tensor_table = (model.tensors || []).map((constant) => {
  13474. const key = constant.data.key;
  13475. if (!tensorTypeMap.has(constant.data_type)) {
  13476. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13477. }
  13478. const type = tensorTypeMap.get(constant.data_type);
  13479. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13480. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13481. const storage_type = execution.resolve(`torch.${type}Storage`);
  13482. const size = (shape || []).reduce((a, b) => a * b, 1);
  13483. const offset = parseInt(constant.offset, 10) || 0;
  13484. const storage = new storage_type(size);
  13485. const itemsize = storage.dtype.itemsize();
  13486. const stream = this._reader.get_record(key);
  13487. if (stream) {
  13488. const buffer = stream.peek();
  13489. const length = size * itemsize;
  13490. const data = buffer.slice(offset, offset + length);
  13491. storage._set_cdata(data);
  13492. }
  13493. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13494. tensor.name = key;
  13495. return tensor;
  13496. });
  13497. execution.builtins.CONSTANTS = {};
  13498. for (let i = 0; i < tensor_table.length; i++) {
  13499. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13500. }
  13501. const attributes = [];
  13502. if (this._reader.has_record('attributes.pkl')) {
  13503. const stream = this._reader.get_record('attributes.pkl');
  13504. const buffer = stream.peek();
  13505. const unpickler = new pickle.Unpickler(buffer);
  13506. const obj = unpickler.load();
  13507. attributes.push(...obj);
  13508. }
  13509. this._LEGACY_moduleStack = ['__torch__'];
  13510. const module_def = model.main_module;
  13511. for (const tensor of tensor_table) {
  13512. this._constant_table.push(tensor);
  13513. }
  13514. return this.LEGACY_convertModule(module_def);
  13515. }
  13516. LEGACY_convertModule(module_def) {
  13517. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13518. const numPushed = atoms.length;
  13519. for (const atom of atoms) {
  13520. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13521. this._LEGACY_moduleStack.push(sanitized);
  13522. }
  13523. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13524. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13525. for (const sub_def of module_def.submodules || []) {
  13526. const submodule = this.LEGACY_convertModule(sub_def);
  13527. module.register_module(sub_def.name, submodule);
  13528. }
  13529. for (const param_def of module_def.parameters || []) {
  13530. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13531. if (param_def.isBuffer) {
  13532. module.register_buffer(param_def.name, tensor);
  13533. } else {
  13534. module.register_parameter(param_def.name, tensor, false);
  13535. }
  13536. }
  13537. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13538. for (const attr_def of module_def.attributes || []) {
  13539. if (module.hasattr(attr_def.name)) {
  13540. continue;
  13541. }
  13542. throw new python.Error('Not implemented.');
  13543. // IValue ivalue;
  13544. // if (attr_def.id() >= 0) {
  13545. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13546. // }
  13547. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13548. }
  13549. if (module_def.torchscript_arena) {
  13550. const key = module_def.torchscript_arena.key;
  13551. const file = key.substring('code/'.length);
  13552. const name = file.replace(/\.py$/, '').split('/').join('.');
  13553. const code = execution.import(name);
  13554. if (code.forward.__class__ === execution.builtins.function) {
  13555. module.forward = code.forward;
  13556. }
  13557. }
  13558. // let gen_ranges = null;
  13559. if (module_def.torchscript_debug_arena) {
  13560. throw new python.Error('Not implemented.');
  13561. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13562. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13563. }
  13564. if (module_def.torchscript_arena) {
  13565. const filename = module_def.torchscript_arena.key;
  13566. const stream = this._reader.get_record(filename);
  13567. const data = stream.peek();
  13568. const src = new torch._C.Source(data, filename);
  13569. this._source_importer.LEGACY_import_methods(module, src);
  13570. }
  13571. if (module_def.get_state_attribute_id) {
  13572. throw new python.Error('Not implemented.');
  13573. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13574. }
  13575. /*
  13576. const module_type = module._ivalue().type();
  13577. const N = module_type.numAttributes();
  13578. for (let i = 0; i < N; ++i) {
  13579. const v = module._ivalue().getSlot(i);
  13580. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13581. torch._C.TORCH_CHECK(!v.isNone());
  13582. }
  13583. }
  13584. */
  13585. for (let i = 0; i < numPushed; i++) {
  13586. this._LEGACY_moduleStack.pop();
  13587. }
  13588. return module;
  13589. }
  13590. readArchive(archive_name) {
  13591. const type_resolver = (qn) => {
  13592. const cls = this._source_importer.loadType(qn);
  13593. return cls;
  13594. };
  13595. const ObjLoaderFunc = (/* type, ivalue */) => {
  13596. };
  13597. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13598. }
  13599. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13600. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13601. const stream = stream_reader.get_record(picklename);
  13602. if (!stream) {
  13603. throw new python.Error(`File '${picklename}' is not found.`);
  13604. }
  13605. const buffer = stream.peek();
  13606. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13607. const read_record = (name) => {
  13608. const stream = stream_reader.get_record(tensor_dir_path + name);
  13609. return stream.length <= 0x40000 ? stream.peek() : stream;
  13610. };
  13611. const execution = this._compilation_unit.execution;
  13612. const pickle = execution.__import__('pickle');
  13613. const Unpickler = class extends pickle.Unpickler {
  13614. find_class(module, name) {
  13615. return super.find_class(module, name);
  13616. }
  13617. };
  13618. const unpickler = new Unpickler(buffer);
  13619. unpickler.persistent_load = (saved_id) => {
  13620. if (saved_id[0] !== 'storage') {
  13621. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13622. }
  13623. const [, storage_type, key, , size] = saved_id;
  13624. if (storage_context && storage_context.has_storage(key)) {
  13625. return storage_context.get_storage(key);
  13626. }
  13627. const storage = new storage_type(size);
  13628. const storage_ptr = read_record(key);
  13629. storage._set_cdata(storage_ptr);
  13630. if (storage_context) {
  13631. storage_context.add_storage(key);
  13632. }
  13633. return storage;
  13634. };
  13635. return unpickler.load();
  13636. }
  13637. });
  13638. this.registerType('torch._C.WithInsertPoint', class {
  13639. constructor(...args) {
  13640. let n = null;
  13641. if (args.length === 1 && args[0] instanceof torch.Block) {
  13642. const [b] = args;
  13643. n = b.return_node();
  13644. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13645. [n] = args;
  13646. } else {
  13647. throw new python.Error('Invalid arguments.');
  13648. }
  13649. this._prev = n.owningGraph().insertPoint();
  13650. n.owningGraph().setInsertPoint(n);
  13651. }
  13652. dispose() {
  13653. this._prev.owningGraph().setInsertPoint(this._prev);
  13654. }
  13655. });
  13656. this.registerType('torch._C.Environment', class {
  13657. constructor(method, resolver, b, next) {
  13658. this.method = method;
  13659. this.resolver = resolver;
  13660. this.b = b;
  13661. this.next = next;
  13662. this.value_table = new Map();
  13663. this.type_table = new Map();
  13664. this.error_messages = new Map();
  13665. }
  13666. setVariableTypeError(name, msg) {
  13667. /* eslint-disable consistent-this */
  13668. let runner = this;
  13669. /* eslint-enable consistent-this */
  13670. while (runner.next) {
  13671. runner = runner.next;
  13672. }
  13673. runner.error_messages.set(name, msg);
  13674. }
  13675. insertLoad(name, type) {
  13676. const g = this.b.owningGraph();
  13677. const load = g.insertNode(g.createLoad(name, type));
  13678. if (torch._C.meaningfulName(name)) {
  13679. load.output().setDebugName(name);
  13680. }
  13681. return new torch._C.SimpleValue(load.output());
  13682. }
  13683. insertStore(name, loc, v, type) {
  13684. const g = this.b.owningGraph();
  13685. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  13686. this.type_table.set(name, type);
  13687. }
  13688. findInThisFrame(name) {
  13689. if (this.value_table.has(name)) {
  13690. return this.value_table.get(name);
  13691. }
  13692. if (this.type_table.has(name)) {
  13693. return this.insertLoad(name, this.type_table.get(name));
  13694. }
  13695. return null;
  13696. }
  13697. findInParentFrame(name) {
  13698. return this.next ? this.next.findInAnyFrame(name) : null;
  13699. }
  13700. setType(name, type) {
  13701. this.type_table.set(name, type);
  13702. }
  13703. findInAnyFrame(name) {
  13704. /* eslint-disable consistent-this */
  13705. const self = this;
  13706. /* eslint-enable consistent-this */
  13707. for (let runner = self; runner; runner = runner.next) {
  13708. const r = runner.findInThisFrame(name);
  13709. if (r) {
  13710. return r;
  13711. }
  13712. }
  13713. return null;
  13714. }
  13715. block() {
  13716. return this.b;
  13717. }
  13718. setVar(loc, name, value) {
  13719. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  13720. }
  13721. setSugaredVar(loc, name, value, annotated_type) {
  13722. let as_simple_value = torch._C.asSimple(value);
  13723. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  13724. as_simple_value.setDebugName(name);
  13725. }
  13726. const parent = this.findInParentFrame(name);
  13727. if (parent) {
  13728. if (annotated_type) {
  13729. throw new python.Error('Type already defined in an outer block.');
  13730. }
  13731. if (!as_simple_value) {
  13732. throw new python.Error('Only reassignments to first-class values are allowed.');
  13733. }
  13734. const simple_parent = torch._C.asSimple(parent);
  13735. if (!simple_parent) {
  13736. throw new python.Error('Only reassignments to first-class values are allowed.');
  13737. }
  13738. const parent_type = torch._C.unshapedType(simple_parent.type());
  13739. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  13740. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  13741. throw new python.Error('Incompatible types.');
  13742. }
  13743. }
  13744. if (as_simple_value) {
  13745. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  13746. throw new python.Error('Invalid type.');
  13747. }
  13748. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  13749. this.insertStore(name, loc, as_simple_value, value_store_type);
  13750. } else {
  13751. this.value_table.set(name, value);
  13752. }
  13753. }
  13754. getSugaredVar(ident, range, required) {
  13755. required = required || true;
  13756. let retval = this.findInAnyFrame(ident);
  13757. if (!retval) {
  13758. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  13759. ['print', new torch._C.PrintValue()],
  13760. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  13761. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  13762. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  13763. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  13764. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  13765. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  13766. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  13767. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  13768. ['range', torch._C.SpecialFormValue.create('prim::range')],
  13769. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  13770. ]);
  13771. if (torch._C.Environment.globals.has(ident)) {
  13772. retval = torch._C.Environment.globals.get(ident);
  13773. }
  13774. }
  13775. if (!retval) {
  13776. const type = this.resolver.resolveType(ident, range);
  13777. if (type instanceof torch.TupleType) {
  13778. retval = new torch.jit.NamedTupleConstructor(type);
  13779. }
  13780. }
  13781. if (!retval) {
  13782. retval = this.resolver.resolveValue(ident, this.method, range);
  13783. }
  13784. if (!retval) {
  13785. const type = this.resolver.resolveType(ident, range);
  13786. if (type instanceof torch.ClassType) {
  13787. retval = new torch.jit.ClassValue(type);
  13788. }
  13789. }
  13790. if (!retval && required) {
  13791. throw new python.Error(`The name '${ident}' is not defined.`);
  13792. }
  13793. return retval;
  13794. }
  13795. getVar(ident, range) {
  13796. return this.getSugaredVar(ident, range).asValue(range, this.method);
  13797. }
  13798. definedVariables() {
  13799. return Array.from(this.type_table.keys());
  13800. }
  13801. });
  13802. this.registerType('torch._C.Refinement', class {
  13803. constructor(identifier, type) {
  13804. this._identifier = identifier;
  13805. this._type = type;
  13806. }
  13807. identifier() {
  13808. return this._identifier;
  13809. }
  13810. type() {
  13811. return this._type;
  13812. }
  13813. });
  13814. this.registerType('torch._C.RefinementSet', class {
  13815. constructor(...args) {
  13816. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  13817. this._true_refinements = [args[0]];
  13818. this._false_refinements = [];
  13819. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  13820. this._true_refinements = [args[0]];
  13821. this._false_refinements = [args[1]];
  13822. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  13823. [this._true_refinements, this._false_refinements] = args;
  13824. } else {
  13825. throw new python.Error('Not implemented.');
  13826. }
  13827. }
  13828. Not() {
  13829. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  13830. }
  13831. activeRefinements() {
  13832. return this._true_refinements;
  13833. }
  13834. });
  13835. this.registerFunction('torch._C.CondValue', class {
  13836. constructor(...args) {
  13837. if (args.length === 3) {
  13838. [this._value, this._refinements, this._static_if] = args;
  13839. } else if (args.length === 4) {
  13840. const [g, loc, static_value, refinements] = args;
  13841. this._value = g.insertConstant(static_value, loc);
  13842. this._refinements = refinements;
  13843. this._static_if = static_value;
  13844. } else {
  13845. throw new python.Error('Invalid number of arguments.');
  13846. }
  13847. }
  13848. value() {
  13849. return this._value;
  13850. }
  13851. staticIf() {
  13852. return this._static_if;
  13853. }
  13854. refinements() {
  13855. return this._refinements;
  13856. }
  13857. });
  13858. this.registerFunction('torch._C.asSimple', (value) => {
  13859. if (value instanceof torch._C.SimpleValue) {
  13860. return value.getValue();
  13861. }
  13862. return null;
  13863. });
  13864. this.registerFunction('torch._C.isNumber', (str) => {
  13865. return /^[0-9]+$/.test(str);
  13866. });
  13867. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  13868. if (torch._C.isNumber(field)) {
  13869. return `_${field}`;
  13870. }
  13871. return field;
  13872. });
  13873. this.registerFunction('torch._C.meaningfulName', (name) => {
  13874. if (name.length === 0 && name[0] === '$') {
  13875. return false;
  13876. }
  13877. if (name[0] !== '_') {
  13878. return true;
  13879. }
  13880. return !/\d+/.test(name.slice(1));
  13881. });
  13882. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  13883. const key = `${val.value}:${val.tag}`;
  13884. const existing_constant = map.get(key);
  13885. if (existing_constant) {
  13886. return existing_constant;
  13887. }
  13888. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  13889. const new_constant = graph.insertConstant(val, r);
  13890. map.set(key, new_constant);
  13891. guard.dispose();
  13892. return new_constant;
  13893. });
  13894. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  13895. if (schema.overload_name) {
  13896. return `${schema.name}.${schema.overload_name}`;
  13897. }
  13898. return schema.name;
  13899. });
  13900. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  13901. const value_map_func = (v) => value_map.get(v);
  13902. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  13903. for (let i = 0; i < inputs.length; i++) {
  13904. value_map.set(callee.inputs()[i], inputs[i]);
  13905. }
  13906. for (const node of callee.nodes()) {
  13907. const new_node = g.insertNode(g.createClone(node, value_map_func));
  13908. for (let i = 0; i < node.outputs().length; i++) {
  13909. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  13910. }
  13911. }
  13912. const outputs = [];
  13913. for (const output of callee.outputs()) {
  13914. outputs.push(value_map_func(output));
  13915. }
  13916. return outputs;
  13917. });
  13918. this.registerType('TemplateEnv', class {
  13919. });
  13920. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  13921. constructor() {
  13922. this.state = 'UNINITIALIZED';
  13923. this._builtins_by_name = new Map();
  13924. }
  13925. getAllBuiltinFunctionsFor(name) {
  13926. if (this.state === 'UNINITIALIZED') {
  13927. this.loadBuiltinFunctions();
  13928. this.state = 'INITIALIZED';
  13929. }
  13930. if (!this._builtins_by_name.has(name)) {
  13931. return [];
  13932. }
  13933. return this._builtins_by_name.get(name);
  13934. }
  13935. loadBuiltinFunctions() {
  13936. /*
  13937. for (const scalar of ['float', 'int', 'complex']) {
  13938. const env = new torch.C.TemplateEnv();
  13939. env.s('Scalar', scalar);
  13940. this.loadSource(scalar_operators_source.format(env), 'aten');
  13941. }
  13942. for (const scalar of ['float', 'int']) {
  13943. const env = new torch.C.TemplateEnv();
  13944. env.s('Scalar', scalar);
  13945. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  13946. }
  13947. using str_pair = std::pair<std::string, std::string>;
  13948. const std::vector<str_pair> name_len = {
  13949. str_pair('single', '1'),
  13950. str_pair('pair', '2'),
  13951. str_pair('triple', '3'),
  13952. str_pair('quadruple', '4'),
  13953. };
  13954. for (const auto scalar : {'float', 'int'}) {
  13955. for (const auto& pair : name_len) {
  13956. const env = new torch.C.TemplateEnv();
  13957. env.s('Scalar', scalar);
  13958. env.s('name', pair.first);
  13959. env.s('Length', pair.second);
  13960. this.loadSource(_ntuple_ops.format(env), 'aten');
  13961. }
  13962. }
  13963. for (auto rhs : {'number', 'Tensor'}) {
  13964. at::jit::TemplateEnv env;
  13965. env.s('Rhs_Type', rhs);
  13966. this.loadSource(floordiv.format(env), 'aten');
  13967. }
  13968. this.loadSource(aten_ops, 'aten');
  13969. this.loadSource(aten_ops_additional, 'aten');
  13970. this.loadSource(tensor_properties, 'prim');
  13971. */
  13972. }
  13973. loadSource(/* source, the_namespace */) {
  13974. }
  13975. });
  13976. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  13977. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  13978. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  13979. });
  13980. this.registerFunction('torch._C.get_operator_version_map', () => {
  13981. return new Map();
  13982. });
  13983. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  13984. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  13985. let arg_type = arg.type;
  13986. if (arg_type instanceof torch._C.DynamicType) {
  13987. arg_type = arg_type.fallback();
  13988. }
  13989. const argument_is_list = arg_type instanceof torch.ListType;
  13990. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  13991. const arg_is_broadcasting_list = arg.N > 0;
  13992. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  13993. });
  13994. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  13995. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  13996. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  13997. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  13998. return true;
  13999. }
  14000. return false;
  14001. });
  14002. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14003. if (opt_type instanceof torch._C.DynamicType) {
  14004. return torch._C.unwrapOptional(opt_type.fallback());
  14005. }
  14006. if (opt_type instanceof torch.OptionalType) {
  14007. return opt_type.getElementType();
  14008. }
  14009. return opt_type;
  14010. });
  14011. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14012. const possibleSchemas = [];
  14013. if (version === undefined) {
  14014. return possibleSchemas;
  14015. }
  14016. for (const entry of torch._C.get_operator_version_map()) {
  14017. const old_symbol_name = entry.first;
  14018. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14019. if (base_name === name) {
  14020. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14021. if (possibleUpgrader.has_value()) {
  14022. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14023. }
  14024. }
  14025. }
  14026. return possibleSchemas;
  14027. });
  14028. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14029. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14030. return current_version < latest_update;
  14031. });
  14032. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14033. const it = torch._C.get_operator_version_map().get(name);
  14034. if (it) {
  14035. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14036. }
  14037. return true;
  14038. });
  14039. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14040. if (values.length === 1) {
  14041. return values[0];
  14042. }
  14043. let named_tuple = null;
  14044. if (field_names) {
  14045. const types = values.map((v) => v.type());
  14046. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14047. }
  14048. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14049. });
  14050. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14051. const v_type = value.type();
  14052. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14053. return false;
  14054. }
  14055. const arg_type = torch._C.unwrapOptional(arg.type);
  14056. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14057. });
  14058. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14059. const list_type = list_type_;
  14060. if (list_type instanceof torch.ListType === false) {
  14061. return false;
  14062. }
  14063. if (type.isSubtypeOf(list_type_)) {
  14064. return true;
  14065. }
  14066. if (type instanceof torch.TupleType) {
  14067. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14068. }
  14069. return false;
  14070. });
  14071. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14072. for (let i = 0; i < kwargs.length; i++) {
  14073. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14074. return i;
  14075. }
  14076. if (kwargs[i].name() === name) {
  14077. return i;
  14078. }
  14079. }
  14080. return null;
  14081. });
  14082. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14083. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14084. const list_elements = [];
  14085. for (const named_value of varargs) {
  14086. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14087. if (!matched_value) {
  14088. return null;
  14089. }
  14090. list_elements.push(matched_value);
  14091. }
  14092. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14093. });
  14094. this.registerType('torch._C.MatchTypeReturn', class {
  14095. constructor(reason) {
  14096. this._reason = reason;
  14097. }
  14098. static Success() {
  14099. return new torch._C.MatchTypeReturn(null);
  14100. }
  14101. success() {
  14102. return this._reason === null;
  14103. }
  14104. });
  14105. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14106. if (!formal.hasFreeVariables()) {
  14107. if (formal instanceof torch._C.DynamicType) {
  14108. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14109. }
  14110. return torch._C.MatchTypeReturn.Success();
  14111. }
  14112. if (formal instanceof torch._C.VarType) {
  14113. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14114. if (it === null) {
  14115. type_env.set(formal.name(), actual);
  14116. return torch._C.MatchTypeReturn.Success();
  14117. } else if (torch._C.unifyTypes(it, actual)) {
  14118. return torch._C.MatchTypeReturn.Success();
  14119. }
  14120. return new torch._C.MatchTypeReturn('Cannot match var.');
  14121. } else if (formal instanceof torch.ListType) {
  14122. if (actual instanceof torch.ListType) {
  14123. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14124. if (!innerMatch.success()) {
  14125. return innerMatch;
  14126. }
  14127. return torch._C.MatchTypeReturn.Success();
  14128. } else if (actual instanceof torch.TupleType) {
  14129. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14130. if (maybe_tuple_unified) {
  14131. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14132. }
  14133. }
  14134. return new torch._C.MatchTypeReturn('Cannot match list.');
  14135. } else if (formal instanceof torch.TupleType) {
  14136. if (actual instanceof torch.TupleType) {
  14137. if (formal.elements().length !== actual.elements().length) {
  14138. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14139. }
  14140. for (let i = 0; i < formal.elements().length; i++) {
  14141. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14142. if (!result.success()) {
  14143. return result;
  14144. }
  14145. }
  14146. return torch._C.MatchTypeReturn.Success();
  14147. }
  14148. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14149. } else if (formal instanceof torch.FutureType) {
  14150. if (actual instanceof torch.FutureType) {
  14151. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14152. if (!innerMatch.success()) {
  14153. return innerMatch;
  14154. }
  14155. return torch._C.MatchTypeReturn.Success();
  14156. }
  14157. return new torch._C.MatchTypeReturn('Cannot match future.');
  14158. } else if (formal instanceof torch.AwaitType) {
  14159. if (actual instanceof torch.AwaitType) {
  14160. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14161. if (!innerMatch.success()) {
  14162. return innerMatch;
  14163. }
  14164. return torch._C.MatchTypeReturn.Success();
  14165. }
  14166. return new torch._C.MatchTypeReturn('Cannot match await.');
  14167. } else if (formal instanceof torch.RRefType) {
  14168. if (actual instanceof torch.RRefType) {
  14169. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14170. if (!innerMatch.success()) {
  14171. return innerMatch;
  14172. }
  14173. return torch._C.MatchTypeReturn.Success();
  14174. }
  14175. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14176. } else if (formal instanceof torch.OptionalType) {
  14177. if (actual instanceof torch.OptionalType) {
  14178. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14179. if (!optionedMatch.success()) {
  14180. return optionedMatch;
  14181. }
  14182. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14183. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14184. }
  14185. return torch._C.MatchTypeReturn.Success();
  14186. } else if (formal instanceof torch.DictType) {
  14187. if (actual instanceof torch.DictType) {
  14188. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14189. if (!key_match.success()) {
  14190. return key_match;
  14191. }
  14192. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14193. if (!value_match.success()) {
  14194. return value_match;
  14195. }
  14196. return torch._C.MatchTypeReturn.Success();
  14197. }
  14198. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14199. }
  14200. throw new python.Error('Unhandled free variable container.');
  14201. });
  14202. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14203. let value = named_value.value(graph);
  14204. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14205. const repeated = Array(arg.N).fill(value);
  14206. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14207. }
  14208. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14209. if (!matched.success()) {
  14210. if (failure_messages) {
  14211. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14212. }
  14213. return null;
  14214. }
  14215. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14216. if (!concrete_type) {
  14217. if (failure_messages) {
  14218. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14219. }
  14220. return null;
  14221. }
  14222. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14223. if (!value.type().isSubtypeOf(concrete_type)) {
  14224. if (failure_messages) {
  14225. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14226. }
  14227. return null;
  14228. }
  14229. return value;
  14230. });
  14231. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14232. if (concrete_type instanceof torch.OptionalType) {
  14233. const op = concrete_type;
  14234. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14235. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14236. }
  14237. }
  14238. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14239. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14240. }
  14241. if (value.type() instanceof torch.TupleType) {
  14242. const value_tuple = value.type();
  14243. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14244. const unpacked = torch._C.createTupleUnpack(value);
  14245. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14246. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14247. }
  14248. if (concrete_type instanceof torch.TupleType) {
  14249. const concrete_tuple = concrete_type;
  14250. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14251. concrete_tuple.elements().length === value_tuple.elements().length) {
  14252. const unpacked = torch._C.createTupleUnpack(value);
  14253. const converted = [];
  14254. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14255. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14256. }
  14257. value = graph.insertNode(graph.createTuple(converted)).output();
  14258. }
  14259. }
  14260. }
  14261. if (allow_conversions) {
  14262. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14263. const value_equals_number = value.type() === torch.NumberType.get();
  14264. const concrete_float = concrete_type === torch.FloatType.get();
  14265. const concrete_complex = concrete_type === torch.ComplexType.get();
  14266. const concrete_int = concrete_type === torch.IntType.get();
  14267. const concrete_number = concrete_type === torch.NumberType.get();
  14268. if (value_isa_tensor) {
  14269. if (concrete_float) {
  14270. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14271. } else if (concrete_complex) {
  14272. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14273. } else if (concrete_int) {
  14274. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14275. } else if (concrete_number) {
  14276. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14277. }
  14278. } else if (value_equals_number) {
  14279. if (concrete_float) {
  14280. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14281. } else if (concrete_complex) {
  14282. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14283. } else if (concrete_int) {
  14284. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14285. }
  14286. } else if (value.type() === torch.BoolType.get()) {
  14287. if (concrete_float) {
  14288. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14289. } else if (concrete_int || concrete_number) {
  14290. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14291. }
  14292. }
  14293. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14294. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14295. }
  14296. }
  14297. return value;
  14298. });
  14299. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14300. if (!type.hasFreeVariables()) {
  14301. if (type instanceof torch._C.DynamicType) {
  14302. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14303. }
  14304. return type;
  14305. }
  14306. if (type instanceof torch._C.VarType) {
  14307. return type_env.get(type.annotation_str);
  14308. }
  14309. const contained = type.containedTypes();
  14310. if (contained.length === 0) {
  14311. return type;
  14312. }
  14313. const new_contained = [];
  14314. for (const t of contained) {
  14315. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14316. if (!r) {
  14317. return null;
  14318. }
  14319. new_contained.push(r);
  14320. }
  14321. return type.withContained(new_contained);
  14322. });
  14323. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14324. if (torch._C.isBlockListedSchema(schema)) {
  14325. return null;
  14326. }
  14327. const err = null;
  14328. const type_env = new Map();
  14329. const positional_inputs = [];
  14330. const used_kwarg = kwargs.map(() => false);
  14331. const is_aten = schema.name.startsWith('aten::');
  14332. let used_args = 0;
  14333. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14334. const arg = schema.arguments[schema_i];
  14335. let actual_named_value = null;
  14336. if (arg.name === 'self' && self) {
  14337. actual_named_value = self;
  14338. self = null;
  14339. } else if (!arg.kwarg_only && used_args < args.length) {
  14340. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14341. const value = args[used_args].value(graph);
  14342. const actual_type = value.type();
  14343. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14344. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14345. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14346. if (!list) {
  14347. return null;
  14348. }
  14349. used_args = args.length;
  14350. positional_inputs.push(list);
  14351. continue;
  14352. }
  14353. }
  14354. actual_named_value = args[used_args];
  14355. used_args++;
  14356. } else {
  14357. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14358. if (Number.isInteger(kwarg_idx)) {
  14359. const nv = kwargs[kwarg_idx];
  14360. if (used_kwarg[kwarg_idx]) {
  14361. if (failure_messages) {
  14362. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14363. }
  14364. return null;
  14365. }
  14366. used_kwarg[kwarg_idx] = true;
  14367. actual_named_value = nv;
  14368. } else if (arg.has_default_value()) {
  14369. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14370. } else {
  14371. if (failure_messages) {
  14372. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14373. }
  14374. return null;
  14375. }
  14376. }
  14377. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14378. if (!positional) {
  14379. return null;
  14380. }
  14381. positional_inputs.push(positional);
  14382. }
  14383. if (self !== null) {
  14384. if (failure_messages) {
  14385. throw new python.Error('Provided self argument not used in schema.');
  14386. }
  14387. return null;
  14388. }
  14389. if (schema.is_vararg) {
  14390. for (; used_args < args.length; used_args++) {
  14391. positional_inputs.push(args[used_args].value(graph));
  14392. }
  14393. }
  14394. if (used_args < args.length) {
  14395. if (failure_messages) {
  14396. throw new python.Error('Too many positional arguments.');
  14397. }
  14398. return null;
  14399. }
  14400. for (let i = 0; i < kwargs.length; i++) {
  14401. const nv = kwargs[i];
  14402. if (!used_kwarg[i]) {
  14403. if (failure_messages) {
  14404. if (schema.argumentIndexWithName(nv.name()) === null) {
  14405. throw new python.Error('Keyword argument unknown.');
  14406. } else {
  14407. throw new python.Error('Keyword argument specified twice.');
  14408. }
  14409. }
  14410. return null;
  14411. }
  14412. }
  14413. const returns = schema.returns;
  14414. const return_types = returns.map((r) => {
  14415. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14416. if (!result) {
  14417. throw new python.Error('Unbound type variable.');
  14418. }
  14419. return result;
  14420. });
  14421. const return_has_field_names = returns.every((r) => !r.name);
  14422. let return_field_names = null;
  14423. if (return_has_field_names) {
  14424. return_field_names = returns.map((r) => r.name);
  14425. }
  14426. const schema_name = torch._C.getFullSchemaName(schema);
  14427. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14428. });
  14429. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14430. self = self || null;
  14431. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14432. if (result) {
  14433. return result;
  14434. }
  14435. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14436. });
  14437. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14438. self = self || null;
  14439. render_errors = render_errors || false;
  14440. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14441. if (schemas.length === 1) {
  14442. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14443. }
  14444. for (const allow_conversions of [false, true]) {
  14445. for (let i = 0; i < schemas.length; i++) {
  14446. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14447. if (matched_schema) {
  14448. return [i, matched_schema];
  14449. }
  14450. }
  14451. }
  14452. if (!render_errors) {
  14453. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14454. }
  14455. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14456. });
  14457. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14458. const variants = torch._C.getAllOperatorsFor(name);
  14459. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14460. const graph_version = graph.get_op_version();
  14461. const schemas = [];
  14462. const upgrader_schemas = [];
  14463. for (const op of variants) {
  14464. let found_upgrader = false;
  14465. const op_name = torch._C.getFullSchemaName(op.schema());
  14466. if (Number.isInteger(graph_version)) {
  14467. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14468. if (version_entry) {
  14469. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14470. if (old_schema_entry.has_value()) {
  14471. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14472. upgrader_schemas.push(old_schema);
  14473. found_upgrader = true;
  14474. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14475. throw new python.Error('Valid upgrader must be present.');
  14476. }
  14477. }
  14478. }
  14479. if (!found_upgrader) {
  14480. schemas.push(op.schema());
  14481. }
  14482. }
  14483. if (variants.length === 0) {
  14484. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14485. for (const old_schema_entry of oldSchemas) {
  14486. const old_schema = torch._C.parseSchema(old_schema_entry);
  14487. upgrader_schemas.push(old_schema);
  14488. }
  14489. }
  14490. for (const schema of upgrader_schemas) {
  14491. schemas.push(schema);
  14492. }
  14493. for (const method of builtin_functions) {
  14494. method.ensure_defined();
  14495. schemas.push(method.getSchema());
  14496. }
  14497. if (schemas.length === 0) {
  14498. const user_function_name = name;
  14499. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  14500. }
  14501. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14502. if (matched[0] < variants.length + upgrader_schemas.length) {
  14503. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14504. }
  14505. const fn = builtin_functions[matched.first - variants.size()];
  14506. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14507. });
  14508. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14509. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14510. for (const ret of matched_schema.return_types) {
  14511. n.addOutput().setType(ret);
  14512. }
  14513. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14514. n.getOperation();
  14515. } else {
  14516. n.setHistoricSchemaName(matched_schema.schema_name);
  14517. }
  14518. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14519. });
  14520. this.registerFunction('torch._C.unshapedType', (type) => {
  14521. if (type.isSubtypeOf(torch.TensorType.get())) {
  14522. return torch.TensorType.get();
  14523. }
  14524. const contained = type.containedTypes();
  14525. if (contained.length === 0) {
  14526. return type;
  14527. }
  14528. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14529. });
  14530. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14531. default_to_union = default_to_union || false;
  14532. type_hint = type_hint || null;
  14533. if (t1.isSubtypeOf(t2)) {
  14534. return t2;
  14535. } else if (t2.isSubtypeOf(t1)) {
  14536. return t1;
  14537. }
  14538. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14539. return t1.merge(t2);
  14540. }
  14541. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14542. return torch.OptionalType.create(t2);
  14543. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14544. return torch.OptionalType.create(t1);
  14545. }
  14546. if (t1 instanceof torch.OptionalType) {
  14547. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14548. if (elem) {
  14549. return torch.OptionalType.create(elem);
  14550. }
  14551. } else if (t2 instanceof torch.OptionalType) {
  14552. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14553. if (elem) {
  14554. return torch.OptionalType.create(elem);
  14555. }
  14556. }
  14557. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14558. if (t1.elements().size() !== t2.elements().size()) {
  14559. return null;
  14560. }
  14561. const elements = [];
  14562. for (let i = 0; i < t1.elements().length; i++) {
  14563. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14564. if (elem) {
  14565. elements.push(elem);
  14566. } else {
  14567. return null;
  14568. }
  14569. }
  14570. return torch.TupleType.create(elements);
  14571. }
  14572. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14573. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14574. if (elem) {
  14575. return torch.FutureType.create(elem);
  14576. }
  14577. }
  14578. const t1_unshaped = torch._C.unshapedType(t1);
  14579. const t2_unshaped = torch._C.unshapedType(t2);
  14580. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14581. return t2_unshaped;
  14582. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14583. return t1_unshaped;
  14584. }
  14585. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14586. return type_hint;
  14587. }
  14588. return null;
  14589. });
  14590. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14591. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14592. if (default_to_union && !unified) {
  14593. return torch.UnionType.create([t1, t2]);
  14594. }
  14595. return unified;
  14596. });
  14597. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14598. if (elements.length === 0) {
  14599. return null;
  14600. }
  14601. let [ret_type] = elements;
  14602. for (let i = 1; i < elements.length && ret_type; i++) {
  14603. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14604. if (!maybe_unified) {
  14605. return null;
  14606. }
  14607. ret_type = maybe_unified;
  14608. }
  14609. return ret_type;
  14610. });
  14611. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14612. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14613. });
  14614. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14615. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14616. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14617. ivalue.isDevice() || ivalue.isEnum()) {
  14618. return true;
  14619. }
  14620. if (ivalue.isTensor()) {
  14621. return torch._C.insertableTensor(ivalue.toTensor());
  14622. }
  14623. if (ivalue.isList() || ivalue.isTuple()) {
  14624. let elems = [];
  14625. if (ivalue.isTuple()) {
  14626. elems = ivalue.toTupleRef().elements();
  14627. } else {
  14628. elems = ivalue.toListRef();
  14629. }
  14630. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14631. }
  14632. if (ivalue.isGenericDict()) {
  14633. const dict = ivalue.toGenericDict();
  14634. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14635. }
  14636. return false;
  14637. });
  14638. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14639. loc = loc || null;
  14640. scope = scope || null;
  14641. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14642. if (value !== undefined) {
  14643. return value;
  14644. }
  14645. throw new python.Error('Unsupported value kind.');
  14646. });
  14647. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14648. if (val instanceof torch._C.IValue) {
  14649. const n = g.create('prim::Constant');
  14650. if (val.isTensor()) {
  14651. const ref = val.toTensor();
  14652. if (!torch._C.insertableTensor(val.toTensor())) {
  14653. n.destroy();
  14654. return null;
  14655. }
  14656. if (!ref.defined()) {
  14657. n.destroy();
  14658. return g.insertNode(g.createNone()).output();
  14659. }
  14660. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  14661. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  14662. n.t_('value', ref);
  14663. } else if (val.isInt()) {
  14664. n.i_('value', val.toInt());
  14665. n.output().setType(torch.IntType.get());
  14666. } else if (val.isDouble()) {
  14667. n.f_('value', val.toDouble());
  14668. n.output().setType(torch.FloatType.get());
  14669. } else if (val.isComplexDouble()) {
  14670. n.c_('value', val.toComplexDouble());
  14671. n.output().setType(torch.ComplexType.get());
  14672. } else if (val.isBool()) {
  14673. n.i_('value', val.toBool());
  14674. n.output().setType(torch.BoolType.get());
  14675. } else if (val.isList()) {
  14676. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  14677. if (fast_path_list || torch._C.insertableIValue(val)) {
  14678. n.ival_('value', val);
  14679. n.output().setType(val.type());
  14680. } else {
  14681. n.destroy();
  14682. return null;
  14683. }
  14684. } else if (val.isString()) {
  14685. n.s_('value', val.toStringRef());
  14686. n.output().setType(torch.StringType.get());
  14687. } else if (val.isDevice()) {
  14688. n.s_('value', val.toDevice().__str__());
  14689. n.output().setType(torch.DeviceObjType.get());
  14690. } else if (val.isGenerator()) {
  14691. n.ival_('value', val.toGenerator());
  14692. n.output().setType(torch._C_._GeneratorType.get());
  14693. } else if (val.isStream()) {
  14694. n.ival_('value', val);
  14695. n.output().setType(torch.StreamObjType.get());
  14696. } else if (val.isNone()) {
  14697. n.output().setType(torch.NoneType.get());
  14698. // n.ival_('value', null); // remove
  14699. } else if (val.isTuple()) {
  14700. if (torch._C.insertableIValue(val)) {
  14701. n.ival_('value', val);
  14702. n.output().setType(val.type());
  14703. } else {
  14704. n.destroy();
  14705. return null;
  14706. }
  14707. } else if (val.isObject()) {
  14708. const ref = val.toObjectRef();
  14709. // see: [Constant Object Weak CompilationUnit Reference]
  14710. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  14711. n.ival_('value', val);
  14712. n.output().setType(val.type());
  14713. } else {
  14714. n.destroy();
  14715. return null;
  14716. }
  14717. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  14718. n.ival_('value', val);
  14719. n.output().setType(val.type());
  14720. } else {
  14721. n.destroy();
  14722. return null;
  14723. }
  14724. if (loc) {
  14725. n.setSourceRange(loc);
  14726. }
  14727. if (scope) {
  14728. n.setScope(scope);
  14729. }
  14730. return g.insertNode(n).output();
  14731. }
  14732. const n = g.create('prim::Constant');
  14733. let type = null;
  14734. if (val === null) {
  14735. n.ival_('value', val);
  14736. type = torch.NoneType.get();
  14737. } else if (typeof val === 'string') {
  14738. n.s_('value', val);
  14739. type = torch.StringType.get();
  14740. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  14741. n.ss_('value', val);
  14742. type = torch.ListType.create(torch.StringType.get());
  14743. } else if (typeof val === 'boolean') {
  14744. n.i_('value', val === true ? 1 : 0);
  14745. type = torch.BoolType.get();
  14746. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  14747. n.i_('value', val);
  14748. type = torch.IntType.get();
  14749. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  14750. n.f_('value', val);
  14751. type = torch.FloatType.get();
  14752. } else if (val instanceof torch.Tensor) {
  14753. n.t_('value', val);
  14754. type = torch.TensorType.get();
  14755. } else if (val instanceof torch.ScriptObject) {
  14756. n.ival_('value', val);
  14757. type = val.type();
  14758. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  14759. n.ival_('value', val);
  14760. type = torch.ListType.create(torch.IntType.get());
  14761. } else {
  14762. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  14763. }
  14764. if (type) {
  14765. n.output().setType(type);
  14766. }
  14767. if (loc) {
  14768. n.setSourceRange(loc);
  14769. }
  14770. if (scope) {
  14771. n.setScope(scope);
  14772. }
  14773. return g.insertNode(n).output();
  14774. });
  14775. this.registerFunction('torch._C.toIValue', (v) => {
  14776. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  14777. return null;
  14778. }
  14779. const node = v.node();
  14780. const type = v.type();
  14781. if (type.isSubtypeOf(torch.TensorType.get())) {
  14782. return new torch._C.IValue(node.t('value'), 'Tensor');
  14783. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  14784. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  14785. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  14786. return new torch._C.IValue(node.i('value'), 'Int');
  14787. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  14788. return new torch._C.IValue(node.f('value'), 'Double');
  14789. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'c') {
  14790. return new torch._C.IValue(node.c('value'), 'Complex');
  14791. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  14792. let list = node.ival('value');
  14793. list = list.isList ? list : new torch._C.IValue(list); // remove
  14794. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  14795. return list;
  14796. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  14797. const dict = node.ival('value');
  14798. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  14799. return dict;
  14800. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  14801. const tup = node.ival('value');
  14802. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  14803. return tup;
  14804. } else if (type === torch.StringType.get()) {
  14805. const s = new torch._C.IValue(node.s('value'), 'String');
  14806. return s;
  14807. } else if (type === torch.DeviceObjType.get()) {
  14808. const d = new torch.device(node.s('value'));
  14809. return new torch._C.IValue(d);
  14810. } else if (type === torch._C._GeneratorType.get()) {
  14811. throw new python.Error('Not implemented.');
  14812. // const generator = node.ival('value').toGenerator();
  14813. // return generator;
  14814. } else if (type === torch.StreamObjType.get()) {
  14815. throw new python.Error('Not implemented.');
  14816. // const s = node.ival('value').toStream();
  14817. // return s;
  14818. } else if (node.mustBeNone()) {
  14819. return new torch._C.IValue();
  14820. } else if (type.kind() === 'EnumType') {
  14821. const enum_val = node.ival('value');
  14822. return enum_val;
  14823. } else if (type instanceof torch.ClassType && !type.is_module()) {
  14824. const class_val = node.ival('value');
  14825. return new torch._C.IValue(class_val, 'Object');
  14826. }
  14827. throw new python.Error('Unsupported constant literal.');
  14828. });
  14829. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  14830. const ivalue = torch._C.toIValue(v);
  14831. if (ivalue) {
  14832. return ivalue[target]();
  14833. }
  14834. return default_value === undefined ? null : default_value;
  14835. });
  14836. this.registerType('torch._C.NamedValue', class {
  14837. constructor(...args) {
  14838. if (args.length === 1) {
  14839. if (args[0] instanceof torch.Value) {
  14840. [this._value] = args;
  14841. } else {
  14842. [this._ivalue] = args;
  14843. }
  14844. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  14845. [this._loc, this._name, this._value] = args;
  14846. } else {
  14847. throw new python.Error('Invalid argument.');
  14848. }
  14849. }
  14850. name() {
  14851. return this._name;
  14852. }
  14853. value(g) {
  14854. if (!this._value) {
  14855. return torch._C.insertConstant(g, this._ivalue);
  14856. }
  14857. return this._value;
  14858. }
  14859. type() {
  14860. if (this._value) {
  14861. return this._value.type();
  14862. }
  14863. return this._ivalue.type();
  14864. }
  14865. });
  14866. this.registerType('torch._C.SugaredValue', class {
  14867. kind() {
  14868. throw new python.Error('Not implemented.');
  14869. }
  14870. shouldEmitUnrolled() {
  14871. return this.staticLen() !== null;
  14872. }
  14873. });
  14874. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  14875. constructor(value) {
  14876. super();
  14877. this._value = value;
  14878. }
  14879. kind() {
  14880. return `value of type '${this._value.type().annotation_str}'`;
  14881. }
  14882. asValue(/* range, m */) {
  14883. return this._value;
  14884. }
  14885. getValue() {
  14886. return this._value;
  14887. }
  14888. asTuple(loc, m, size_hint) {
  14889. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  14890. if (this._value.type() instanceof torch.TupleType) {
  14891. const outputs = torch._C.createTupleUnpack(this._value);
  14892. return outputs.map((v) => make_simple_value(v));
  14893. } else if (this._value.type() instanceof torch.ListType) {
  14894. if (!size_hint) {
  14895. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  14896. }
  14897. const graph = this._value.owningGraph();
  14898. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  14899. return unpack.outputs().map((v) => make_simple_value(v));
  14900. } else if (this._value.type().kind() === 'AnyTupleType') {
  14901. throw new python.Error('Provided tuple is not fully defined including its element types.');
  14902. }
  14903. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  14904. }
  14905. attr(loc, m, field) {
  14906. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  14907. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  14908. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  14909. }
  14910. }
  14911. if (this._value.type() instanceof torch.TupleType) {
  14912. throw new python.Error('Not implemented.');
  14913. }
  14914. if (this._value.type() instanceof torch.AwaitType) {
  14915. throw new python.Error('Not implemented.');
  14916. }
  14917. if (this._value.type() instanceof torch.ClassType) {
  14918. const classType = this._value.type();
  14919. if (classType.findMethod(field)) {
  14920. return new torch._C.MethodValue(this.getValue(), [field]);
  14921. }
  14922. if (classType.hasAttribute(field)) {
  14923. const g = m.graph();
  14924. const n = g.insertNode(g.createGetAttr(this._value, field));
  14925. return new torch._C.SimpleValue(n.output());
  14926. }
  14927. const prop = classType.getProperty(field);
  14928. if (prop) {
  14929. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  14930. }
  14931. } else if (this._value.type() instanceof torch.InterfaceType) {
  14932. throw new python.Error('Not implemented.');
  14933. } else if (this._value.type() instanceof torch.EnumType) {
  14934. const g = m.graph();
  14935. if (field === 'name') {
  14936. const n = g.insertNode(g.createEnumName(this._value));
  14937. return new torch._C.SimpleValue(n.output());
  14938. }
  14939. if (field === 'value') {
  14940. const n = g.insertNode(g.createEnumValue(this._value));
  14941. return new torch._C.SimpleValue(n.output());
  14942. }
  14943. }
  14944. if (field === 'type') {
  14945. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  14946. if (builtin) {
  14947. return builtin;
  14948. }
  14949. }
  14950. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  14951. if (builtin) {
  14952. return builtin;
  14953. }
  14954. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  14955. return torch._C.SpecialFormValue.create('prim::tolist');
  14956. }
  14957. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  14958. return torch._C.SpecialFormValue.create('aten::index');
  14959. }
  14960. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  14961. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  14962. if (builtin) {
  14963. return builtin;
  14964. }
  14965. }
  14966. throw new python.Error('Object has no attribute or method.');
  14967. }
  14968. setAttr(loc, m, field, newValue) {
  14969. const type = this._value.type();
  14970. if (type instanceof torch.ClassType === false) {
  14971. throw new python.Error('Cannot set attribute on non-class type.');
  14972. }
  14973. const classType = type;
  14974. let expectedType = classType.findAttribute(field);
  14975. if (!expectedType) {
  14976. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  14977. if (isInitializing) {
  14978. if (this.isRecursive(classType, newValue.type())) {
  14979. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  14980. }
  14981. classType.addAttribute(field, newValue.type());
  14982. expectedType = newValue.type();
  14983. const insertPoint = m.graph().insertPoint();
  14984. const topLevelBlock = m.graph().block();
  14985. if (insertPoint.owningBlock() !== topLevelBlock) {
  14986. throw new python.Error('First assignment cannot be in a control-flow block.');
  14987. }
  14988. } else {
  14989. const prop = classType.getProperty(field);
  14990. if (prop && prop.setter) {
  14991. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  14992. return;
  14993. }
  14994. if (prop && !prop.setter) {
  14995. throw new python.Error('Tried to set read-only attribute.');
  14996. }
  14997. throw new python.Error('Tried to set nonexistent attribute.');
  14998. }
  14999. }
  15000. torch._C.AT_ASSERT(expectedType);
  15001. const newType = newValue.type();
  15002. if (!newType.isSubtypeOf(expectedType)) {
  15003. throw new python.Error('Wrong type for attribute assignment.');
  15004. }
  15005. const g = m.graph();
  15006. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15007. }
  15008. getitem(loc, m, idx, type_hint) {
  15009. const val = this.getValue();
  15010. const val_type = val.type();
  15011. const g = m.graph();
  15012. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15013. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15014. } else if (val_type instanceof torch.DictType) {
  15015. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15016. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15017. 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));
  15018. } else if (val_type instanceof torch.ClassType) {
  15019. const class_type = val_type;
  15020. if (class_type.is_module() && type_hint) {
  15021. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15022. res.setType(type_hint);
  15023. return new torch._C.SimpleValue(res);
  15024. }
  15025. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15026. }
  15027. throw new python.Error('Object is not subscriptable.');
  15028. }
  15029. });
  15030. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15031. constructor(self, method_names) {
  15032. super();
  15033. this._self = self;
  15034. this._method_names = method_names;
  15035. }
  15036. call(loc, f, args, kwargs /*, n_binders */) {
  15037. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15038. const schemas = [];
  15039. for (const method_name of this._method_names) {
  15040. const type = this._self.type();
  15041. if (type instanceof torch.ClassType) {
  15042. const class_type = type;
  15043. const method = class_type.getMethod(method_name);
  15044. method.ensure_defined();
  15045. schemas.push(method.getSchema());
  15046. } else if (type instanceof torch.InterfaceType) {
  15047. const interface_type = type;
  15048. schemas.push(interface_type.getMethod(method_name));
  15049. } else {
  15050. throw new python.Error('Method constructed that is not a class or interface.');
  15051. }
  15052. }
  15053. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15054. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15055. output.node().setSourceRange(loc);
  15056. return new torch._C.SimpleValue(output);
  15057. }
  15058. });
  15059. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15060. constructor(type) {
  15061. super();
  15062. this._type = type;
  15063. }
  15064. attr(loc, m, field) {
  15065. const hook = this._type.findHook(field);
  15066. if (hook) {
  15067. return new torch._C.FunctionValue(hook);
  15068. }
  15069. if (field !== '__new__') {
  15070. throw new python.Error('Tried to lookup unknown attribute on class.');
  15071. }
  15072. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15073. }
  15074. });
  15075. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15076. constructor(type) {
  15077. super();
  15078. this._type = type;
  15079. }
  15080. call(loc, m, args, kwargs /*, n_binders */) {
  15081. const g = m.graph();
  15082. const schema = this._type.schema();
  15083. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15084. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15085. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15086. self.setType(this._type);
  15087. return new torch._C.SimpleValue(self);
  15088. }
  15089. });
  15090. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15091. constructor(enum_type) {
  15092. super();
  15093. this._enum_type = enum_type;
  15094. }
  15095. attr(loc, m, field) {
  15096. const names_values = this._enum_type.enumNamesValues();
  15097. const it = names_values.find((nv) => nv[0] === field);
  15098. if (it === null) {
  15099. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15100. }
  15101. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15102. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15103. }
  15104. });
  15105. this.registerType('torch._C.EnumHolder', class {
  15106. constructor(type, name, value) {
  15107. this._type = type;
  15108. this._name = name;
  15109. this._value = value;
  15110. }
  15111. name() {
  15112. return this._name;
  15113. }
  15114. type() {
  15115. return this._type;
  15116. }
  15117. });
  15118. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15119. constructor(...args) {
  15120. super();
  15121. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15122. this._callees = [args[0]];
  15123. } else {
  15124. throw new python.Error('Not implemented.');
  15125. }
  15126. }
  15127. call(loc, f, args, kwargs /*, n_binders */) {
  15128. const schemas = [];
  15129. for (const callee of this._callees) {
  15130. callee.ensure_defined();
  15131. schemas.push(callee.getSchema());
  15132. }
  15133. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15134. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15135. output.node().setSourceRange(loc);
  15136. return new torch._C.SimpleValue(output);
  15137. }
  15138. });
  15139. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15140. });
  15141. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15142. call(loc, m, args, kwargs /*, n_binders */) {
  15143. const g = m.graph();
  15144. if (kwargs.length > 0) {
  15145. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15146. }
  15147. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15148. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15149. return new torch._C.NoneValue();
  15150. }
  15151. });
  15152. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15153. constructor(form) {
  15154. super();
  15155. this._form = form;
  15156. }
  15157. form() {
  15158. return this._form;
  15159. }
  15160. static create(form) {
  15161. return new torch._C.SpecialFormValue(form);
  15162. }
  15163. });
  15164. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15165. return new torch._C.MagicMethod(name, base);
  15166. });
  15167. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15168. constructor(symbol, self) {
  15169. super();
  15170. this.symbol = symbol;
  15171. this.self = self;
  15172. }
  15173. call(loc, m, args, kwargs /*, n_binders */) {
  15174. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15175. }
  15176. static tryCreate(symbol, self) {
  15177. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15178. if (!self) {
  15179. return new torch._C.BuiltinFunction(symbol, null);
  15180. }
  15181. const index = op.schema().argumentIndexWithName('self');
  15182. if (index) {
  15183. const type_env = new Map();
  15184. const formal_type = op.schema().arguments()[index].type();
  15185. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15186. if (!matched.success()) {
  15187. continue;
  15188. }
  15189. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15190. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15191. continue;
  15192. }
  15193. return new torch._C.BuiltinFunction(symbol, self);
  15194. }
  15195. }
  15196. return null;
  15197. }
  15198. });
  15199. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15200. constructor(name, version) {
  15201. super();
  15202. this.name = name;
  15203. this.version = version || null;
  15204. }
  15205. attr(loc, m, field) {
  15206. if (field === 'autograd') {
  15207. return new torch._C.BuiltinModule('aten', this.version);
  15208. }
  15209. const sym = `${this.name}::${field}`;
  15210. return new torch._C.BuiltinFunction(sym, null);
  15211. }
  15212. });
  15213. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15214. constructor(version) {
  15215. super();
  15216. this._version = version;
  15217. }
  15218. attr(loc, m, field) {
  15219. return new torch._C.BuiltinModule(field, this._version);
  15220. }
  15221. });
  15222. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15223. constructor(constants) {
  15224. super();
  15225. this._constants = constants;
  15226. this.non_holding_object_cache = new Map();
  15227. }
  15228. attr(loc, m, field) {
  15229. const offset = parseInt(field.substring(1), 10);
  15230. if (!Number.isInteger(offset)) {
  15231. throw new python.Error(`Invalid constant identifier '${field}.`);
  15232. }
  15233. if (offset < 0 || offset >= this._constants.length) {
  15234. throw new python.Error('Invalid constant index.');
  15235. }
  15236. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15237. let value = null;
  15238. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15239. const obj = ivalue.toObject();
  15240. if (!this.non_holding_object_cache.has(obj)) {
  15241. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15242. }
  15243. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15244. } else {
  15245. value = m.graph().insertConstant(this._constants[offset], loc);
  15246. }
  15247. value.setType(torch._C.unshapedType(value.type()));
  15248. return new torch._C.SimpleValue(value);
  15249. }
  15250. });
  15251. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15252. constructor(type, method) {
  15253. super(method, null);
  15254. this._type = type;
  15255. }
  15256. call(loc, m, args, kwargs, n_binders) {
  15257. if (args.length === 1 && kwargs.length === 0) {
  15258. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15259. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15260. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15261. const v = args[0].value(m.graph());
  15262. if (v.type().isSubtypeOf(this._type)) {
  15263. return new torch._C.SimpleValue(v);
  15264. } 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)) {
  15265. const len = len_op.call(loc, m, [v], [], 1);
  15266. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15267. }
  15268. }
  15269. return super.call(loc, m, args, kwargs, n_binders);
  15270. }
  15271. });
  15272. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15273. constructor(desugared_name, base) {
  15274. super();
  15275. this._base_value = base;
  15276. this._desugared_name = desugared_name;
  15277. }
  15278. call(loc, m, args, kwargs, n_binders) {
  15279. if (args.length > 0) {
  15280. const self = args[0].value(m.graph());
  15281. if (self.type() instanceof torch.ClassType) {
  15282. return new torch._C.SimpleValue(self)
  15283. .attr(loc, m, this._desugared_name)
  15284. .call(loc, m, args.slice(1), kwargs, n_binders);
  15285. }
  15286. }
  15287. if (!this._base_value) {
  15288. throw new python.Error('Invalid magic method.');
  15289. }
  15290. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15291. }
  15292. });
  15293. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15294. constructor(loc, m, inputs, static_len) {
  15295. super();
  15296. static_len = static_len || null;
  15297. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15298. throw new python.Error('Invalid range inputs.');
  15299. }
  15300. const g = m.graph();
  15301. if (inputs.length === 1) {
  15302. [this._end] = inputs;
  15303. this._start = g.insertConstant(0, loc);
  15304. this._step = g.insertConstant(1, loc);
  15305. this._has_only_end = true;
  15306. } else {
  15307. [this._start, this._end] = inputs;
  15308. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15309. this._has_only_end = false;
  15310. }
  15311. this._static_len = static_len;
  15312. }
  15313. staticLen() {
  15314. return this._static_len;
  15315. }
  15316. iter() {
  15317. return this;
  15318. }
  15319. len(loc, m) {
  15320. if (this._static_len) {
  15321. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15322. }
  15323. if (this._has_only_end) {
  15324. return this._end;
  15325. }
  15326. const g = m.graph();
  15327. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15328. }
  15329. getitem(loc, m, idx /*, type_hint */) {
  15330. if (this._has_only_end) {
  15331. return new torch._C.SimpleValue(idx);
  15332. }
  15333. const g = m.graph();
  15334. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15335. }
  15336. });
  15337. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15338. });
  15339. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15340. constructor(name, si) {
  15341. super();
  15342. this._basename = name;
  15343. this._si = si;
  15344. }
  15345. attr(loc, m, name) {
  15346. const fullName = new torch._C.QualifiedName(this._basename, name);
  15347. const serializable_type = this._si.findNamedType(fullName);
  15348. if (serializable_type) {
  15349. if (serializable_type instanceof torch.ClassType) {
  15350. return new torch._C.ClassValue(serializable_type);
  15351. } else if (serializable_type instanceof torch.TupleType) {
  15352. return new torch._C.NamedTupleConstructor(serializable_type);
  15353. } else if (serializable_type instanceof torch.EnumType) {
  15354. return new torch._C.SugaredEnumClass(serializable_type);
  15355. }
  15356. }
  15357. const fn = this._si.findFunction(fullName);
  15358. if (fn) {
  15359. return new torch._C.FunctionValue(fn);
  15360. }
  15361. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15362. }
  15363. });
  15364. this.registerType('torch.package.PackageImporter', class {
  15365. constructor(reader) {
  15366. this.zip_reader = reader;
  15367. }
  15368. load_pickle(module, resource) {
  15369. const name = `${module.replace(/\./, '/')}/${resource}`;
  15370. const stream = this.zip_reader.get_record(name);
  15371. const loaded_reduces = new Map();
  15372. this.storage_context = new torch._C.DeserializationStorageContext();
  15373. const unpickler = new pickle.Unpickler(stream);
  15374. unpickler.persistent_load = (saved_id) => {
  15375. switch (saved_id[0]) {
  15376. case 'storage': {
  15377. const [, storage_type, key, , size] = saved_id;
  15378. if (!this.storage_context.has_storage(key)) {
  15379. const storage = new storage_type(size);
  15380. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15381. const buffer = stream.peek();
  15382. storage._set_cdata(buffer);
  15383. this.storage_context.add_storage(key, storage);
  15384. }
  15385. return this.storage_context.get_storage(key);
  15386. }
  15387. case 'reduce_package': {
  15388. if (saved_id.length === 2) {
  15389. const [, func, args] = saved_id;
  15390. return execution.invoke(func, args);
  15391. }
  15392. const [, reduce_id, func, args] = saved_id;
  15393. if (!loaded_reduces.has(reduce_id)) {
  15394. const value = execution.invoke(func, [this].concat(args));
  15395. loaded_reduces.set(reduce_id, value);
  15396. }
  15397. return loaded_reduces.get(reduce_id);
  15398. }
  15399. default: {
  15400. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15401. }
  15402. }
  15403. };
  15404. const obj = unpickler.load();
  15405. this.storage_context = null;
  15406. return obj;
  15407. }
  15408. import_module(name) {
  15409. return execution.import(name);
  15410. }
  15411. });
  15412. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15413. const cu = new torch.jit.CompilationUnit();
  15414. cu.execution = execution;
  15415. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15416. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15417. module.forward = cpp_module.forward; // remove
  15418. return module;
  15419. });
  15420. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15421. switch (arguments.length) {
  15422. case 4: {
  15423. const [device, extra_files] = args;
  15424. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15425. return deserializer.deserialize(device, extra_files);
  15426. }
  15427. case 5: {
  15428. const [storage_context, device, ts_id] = args;
  15429. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15430. return deserializer.deserialize(device, null);
  15431. }
  15432. default: {
  15433. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15434. }
  15435. }
  15436. });
  15437. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15438. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15439. });
  15440. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15441. if (value instanceof torch.Node) {
  15442. const n = value;
  15443. if (n.kind() === 'prim::CallFunction') {
  15444. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15445. const function_constant = n.input(0).node();
  15446. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15447. return torch._C.tryToGraphFunction(fun_type.function());
  15448. }
  15449. if (n.kind() === 'prim::CallMethod') {
  15450. const name = n.s('name');
  15451. const class_type = n.input(0).type();
  15452. if (class_type instanceof torch.ClassType) {
  15453. const fn = class_type.getMethod(name);
  15454. return torch._C.tryToGraphFunction(fn);
  15455. }
  15456. }
  15457. return null;
  15458. } else if (value instanceof torch._C.Function) {
  15459. const fn = value;
  15460. if (!fn.isGraphFunction()) {
  15461. return null;
  15462. }
  15463. return fn;
  15464. }
  15465. throw new python.Error('Not implemented.');
  15466. });
  15467. this.registerType('torch._C.ModuleInstanceInfo', class {
  15468. constructor(module_type, instance_name) {
  15469. this._module_type = module_type;
  15470. this._instance_name = instance_name;
  15471. }
  15472. });
  15473. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15474. torch._C.TORCH_CHECK(step !== 0);
  15475. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15476. if (start._ === Number.MAX_SAFE_INTEGER) {
  15477. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15478. }
  15479. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15480. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15481. }
  15482. if (start._ < 0) {
  15483. start._ += length;
  15484. if (start._ < 0) {
  15485. start._ = (step < 0) ? -1 : 0;
  15486. }
  15487. } else if (start._ >= length) {
  15488. start._ = (step < 0) ? length - 1 : length;
  15489. }
  15490. if (stop._ < 0) {
  15491. stop._ += length;
  15492. if (stop._ < 0) {
  15493. stop._ = (step < 0) ? -1 : 0;
  15494. }
  15495. } else if (stop._ >= length) {
  15496. stop._ = (step < 0) ? length - 1 : length;
  15497. }
  15498. if (step < 0) {
  15499. if (stop._ < start._) {
  15500. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15501. }
  15502. } else if (start._ < stop._) {
  15503. return Math.floor((stop._ - start._ - 1) / step + 1);
  15504. }
  15505. return 0;
  15506. });
  15507. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15508. if (v.node().kind() === 'prim::TupleConstruct') {
  15509. return v.node().inputs();
  15510. }
  15511. const g = v.owningGraph();
  15512. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15513. });
  15514. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15515. /*
  15516. const new_node_cs = new_node.callstack();
  15517. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15518. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15519. if (new_node_cs) {
  15520. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15521. } else {
  15522. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15523. }
  15524. }
  15525. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15526. for (const block of new_node.blocks()) {
  15527. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15528. }
  15529. */
  15530. });
  15531. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15532. if (arg === undefined || typeof arg === 'boolean') {
  15533. const inline_optimized_graph = arg === undefined ? true : arg;
  15534. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15535. return torch._C.inlineCallTo(to_replace, callee, graph);
  15536. }
  15537. if (arg instanceof torch.Graph === false) {
  15538. throw new python.Error('Invalid argument.');
  15539. }
  15540. const callee_graph = arg;
  15541. const guard = new torch._C.WithInsertPoint(to_replace);
  15542. const value_map = new Map();
  15543. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15544. const new_callstack_entries = new Map();
  15545. let module_instance_info = null;
  15546. if (to_replace.kind() === 'prim::CallMethod') {
  15547. const class_type_ptr = to_replace.input(0).type();
  15548. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15549. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15550. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15551. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15552. } else {
  15553. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15554. }
  15555. }
  15556. const updated_nodes = new Set();
  15557. for (const kv of value_map) {
  15558. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15559. if (is_graph_input === -1) {
  15560. continue;
  15561. }
  15562. const new_node = kv[1].node();
  15563. if (updated_nodes.has(new_node)) {
  15564. continue;
  15565. }
  15566. updated_nodes.add(new_node);
  15567. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15568. }
  15569. const old_outputs = to_replace.outputs();
  15570. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15571. for (let i = 0; i < old_outputs.length; i++) {
  15572. if (old_outputs[i].hasDebugName()) {
  15573. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15574. }
  15575. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15576. }
  15577. to_replace.destroy();
  15578. guard.dispose();
  15579. return new_outputs;
  15580. });
  15581. this.registerFunction('torch._C.inlineCalls', (block) => {
  15582. for (const cur of block.nodes()) {
  15583. switch (cur.kind()) {
  15584. case 'prim::CallFunction': {
  15585. const graphFunction = torch._C.tryToGraphFunction(cur);
  15586. if (graphFunction) {
  15587. const function_constant = cur.input(0).node();
  15588. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15589. cur.removeInput(0);
  15590. let g = null;
  15591. const fallback = function_constant.hasAttribute('fallback');
  15592. if (fallback && graphFunction.get_executor().isOptimized()) {
  15593. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15594. if (!exec_plans.empty()) {
  15595. g = exec_plans.begin().second.graph;
  15596. torch._C.Inline(g);
  15597. }
  15598. }
  15599. if (g === null) {
  15600. g = graphFunction.optimized_graph();
  15601. }
  15602. torch._C.inlineCallTo(cur, graphFunction, g);
  15603. }
  15604. break;
  15605. }
  15606. case 'prim::CallMethod': {
  15607. const graphFunction = torch._C.tryToGraphFunction(cur);
  15608. if (graphFunction) {
  15609. torch._C.inlineCallTo(cur, graphFunction);
  15610. }
  15611. break;
  15612. }
  15613. default: {
  15614. for (const b of cur.blocks()) {
  15615. torch._C.inlineCalls(b);
  15616. }
  15617. }
  15618. }
  15619. }
  15620. });
  15621. this.registerFunction('torch._C.Inline', (graph) => {
  15622. torch._C.inlineCalls(graph.block());
  15623. });
  15624. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15625. torch._C.Inline(graph);
  15626. });
  15627. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15628. });
  15629. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15630. const cu = new torch.jit.CompilationUnit();
  15631. cu.execution = execution;
  15632. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15633. return torch.jit._script.wrap_cpp_module(cpp_module);
  15634. });
  15635. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15636. const init_fn = (script_module) => {
  15637. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15638. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15639. }
  15640. };
  15641. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15642. });
  15643. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15644. has_storage(name) {
  15645. return this.has(name);
  15646. }
  15647. get_storage(name) {
  15648. return this.get(name);
  15649. }
  15650. add_storage(name, storage) {
  15651. return this.set(name, storage);
  15652. }
  15653. });
  15654. this.registerType('torch.ScriptFunction', class {
  15655. constructor(name, graph /*, function_creator */) {
  15656. this._name = name;
  15657. this._graph = graph;
  15658. }
  15659. });
  15660. this.registerType('torch.ScriptMethod', class {
  15661. constructor(owner, value) {
  15662. this._owner = owner;
  15663. this._function = value;
  15664. }
  15665. get name() {
  15666. return this._function.name();
  15667. }
  15668. get owner() {
  15669. return this._owner;
  15670. }
  15671. __call__(/* args, kwargs */) {
  15672. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  15673. }
  15674. get graph() {
  15675. return this._function.graph();
  15676. }
  15677. get schema() {
  15678. // return this.function().getSchema();
  15679. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  15680. }
  15681. get code() {
  15682. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  15683. }
  15684. get code_with_constants() {
  15685. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  15686. }
  15687. });
  15688. this.registerType('torch.ScriptObject', class {
  15689. constructor(type) {
  15690. this._typ = type;
  15691. this._ivalue = {};
  15692. }
  15693. static create(type) {
  15694. if (type.is_module()) {
  15695. return new torch.ScriptModule(type);
  15696. }
  15697. return new torch.ScriptObject(type);
  15698. }
  15699. type() {
  15700. return this._typ;
  15701. }
  15702. _type() {
  15703. return this._typ; // torch.ClassType
  15704. }
  15705. __setstate__(state) {
  15706. const [attrs, qualname] = state;
  15707. this._typ = torch._C.getCustomClass(qualname);
  15708. if (!this._typ) {
  15709. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  15710. }
  15711. for (let i = 0; i < this._typ.numAttributes(); i++) {
  15712. const name = this._typ.getAttributeName(i);
  15713. this.__setattr__(name, attrs[i]);
  15714. }
  15715. }
  15716. find_method(basename) {
  15717. for (const fn of this.type().methods()) {
  15718. if (fn.name() === basename) {
  15719. return new torch.ScriptMethod(this /* _value() */, fn);
  15720. }
  15721. }
  15722. return null;
  15723. }
  15724. _get_method(name) {
  15725. const method = this.find_method(name);
  15726. if (method) {
  15727. return method;
  15728. }
  15729. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  15730. return null;
  15731. }
  15732. _has_method(name) {
  15733. return this.find_method(name) ? true : false;
  15734. }
  15735. _method_names() {
  15736. return this.type().methods().map((fn) => fn.name());
  15737. }
  15738. __setattr__(name, value) {
  15739. // if (this._type.hasContant(name))
  15740. this._ivalue[name] = value;
  15741. }
  15742. __getattr__(name) {
  15743. return this._ivalue[name];
  15744. }
  15745. hasattr(name) {
  15746. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  15747. }
  15748. getattr(name) {
  15749. return this.__getattr__(name);
  15750. }
  15751. _properties() {
  15752. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  15753. }
  15754. is_weak_compilation_ref() {
  15755. return true; // not implemented
  15756. }
  15757. });
  15758. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  15759. constructor(...args) {
  15760. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  15761. const [class_name, cu, shouldMangle] = args;
  15762. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  15763. } else {
  15764. super(...args);
  15765. }
  15766. }
  15767. get qualified_name() {
  15768. return this.type().qualified_name();
  15769. }
  15770. get code_with_constants() {
  15771. const const_map = {};
  15772. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  15773. return [null, const_map];
  15774. }
  15775. get graph() {
  15776. if (!this._graph) {
  15777. const fn = this._typ.getMethod('forward');
  15778. this._graph = fn.graph();
  15779. }
  15780. return this._graph;
  15781. }
  15782. static create_module_object(class_name, cu, shouldMangle) {
  15783. shouldMangle = shouldMangle || false;
  15784. if (!class_name.prefix()) {
  15785. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  15786. }
  15787. if (shouldMangle && cu.get_class(class_name)) {
  15788. class_name = cu.mangle(class_name);
  15789. }
  15790. const cls = torch.ClassType.create(class_name, cu, true);
  15791. cu.register_type(cls);
  15792. return [cls, cu];
  15793. }
  15794. register_module(name, module) {
  15795. this.type().addOrCheckAttribute(name, module.type());
  15796. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  15797. }
  15798. register_buffer(name, v) {
  15799. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  15800. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  15801. }
  15802. register_parameter(name, v, is_buffer) {
  15803. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  15804. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  15805. }
  15806. register_attribute(name, t, v, is_param, is_buffer) {
  15807. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  15808. // _ivalue()->setAttr(name, v);
  15809. }
  15810. });
  15811. this.registerType('torch.ModuleDict', class {
  15812. constructor(mod) {
  15813. this._module = mod;
  15814. }
  15815. items() {
  15816. const result = new Map();
  15817. const type = this._module.type();
  15818. for (let i = 0; i < type.numAttributes(); i++) {
  15819. const k = type.getAttributeName(i);
  15820. const t = type.getAttribute(i);
  15821. if (t && t.is_module()) {
  15822. result.set(k, this._module.__getattr__(k));
  15823. }
  15824. }
  15825. return result;
  15826. }
  15827. });
  15828. this.registerType('torch.ParameterDict', class {
  15829. constructor(mod) {
  15830. this._module = mod;
  15831. }
  15832. items() {
  15833. const result = new Map();
  15834. const type = this._module.type();
  15835. for (let i = 0; i < type.numAttributes(); i++) {
  15836. if (type.is_parameter(i)) {
  15837. const k = type.getAttributeName(i);
  15838. const v = this._module.__getattr__(k);
  15839. if (v instanceof torch.Tensor) {
  15840. result.set(k, v);
  15841. }
  15842. }
  15843. }
  15844. return result;
  15845. }
  15846. });
  15847. this.registerType('torch.BufferDict', class {
  15848. constructor(mod) {
  15849. this._module = mod;
  15850. }
  15851. items() {
  15852. const result = new Map();
  15853. const type = this._module.type();
  15854. for (let i = 0; i < type.numAttributes(); i++) {
  15855. if (type.is_buffer(i)) {
  15856. const t = type.getAttribute(i);
  15857. if (t.isSubtypeOf(torch.TensorType.get())) {
  15858. const k = type.getAttributeName(i);
  15859. const v = this._module.__getattr__(k);
  15860. result.set(k, v);
  15861. }
  15862. }
  15863. }
  15864. return result;
  15865. }
  15866. });
  15867. this.registerType('torch._C.to_ir', class {
  15868. constructor(def, _resolver, self, method) {
  15869. this.method = method;
  15870. this.graph = method.graph();
  15871. this.resolver = _resolver;
  15872. this.integral_constants = new Map();
  15873. this.fp_constants = new Map();
  15874. this.complex_constants = new Map();
  15875. this.exit_blocks = new Set();
  15876. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  15877. this._loop_status = 'NOT_IN_LOOP';
  15878. this.environment_stack = null;
  15879. this._def_stack = [];
  15880. this._temp_name_count = 0;
  15881. torch._C.AT_ASSERT(this.resolver);
  15882. this.pushFrame(this.graph.block(), true);
  15883. if (self && def && def.args.args.length === 0) {
  15884. throw new python.Error('Method must have a self argument.');
  15885. }
  15886. method.setSchema(this.emitDef(def, self, this.graph.block()));
  15887. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  15888. torch._C.ConvertToSSA(this.graph);
  15889. torch._C.CanonicalizeModifiedLoops(this.graph);
  15890. torch._C.NormalizeOps(this.graph.block());
  15891. torch._C.runCleanupPasses(this.graph);
  15892. }
  15893. pushFrame(b, starts_def) {
  15894. starts_def = starts_def || false;
  15895. if (starts_def) {
  15896. this._def_stack.push({});
  15897. }
  15898. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  15899. }
  15900. popFrame(ends_def) {
  15901. const old_frame = this.environment_stack;
  15902. this.environment_stack = this.environment_stack.next;
  15903. if (ends_def) {
  15904. this._def_stack.pop();
  15905. }
  15906. return old_frame;
  15907. }
  15908. emitDef(def, self, block) {
  15909. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  15910. if (schema.returns.length === 1) {
  15911. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  15912. }
  15913. const args = this.emitFormalArguments(def, self, schema, block);
  15914. this.emitStatements(def.body);
  15915. this.handleMaybeNoReturn(def, block);
  15916. const returns = [this.emitOutput(def, schema, block)];
  15917. return new torch.FunctionSchema(def.name, '', args, returns);
  15918. }
  15919. emitFormalArguments(def, self, schema, block) {
  15920. const args = [];
  15921. const params = def.args.args;
  15922. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  15923. if (schema.arguments.length !== expected_annotation_size) {
  15924. throw new python.Error('Invalid formal arguments.');
  15925. }
  15926. let it = 0;
  15927. if (self) {
  15928. const param = params[it];
  15929. const name = param.arg;
  15930. const new_input = block.addInput().setDebugName(name);
  15931. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  15932. args.push(new torch.Argument(name, new_input.type()));
  15933. it++;
  15934. }
  15935. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  15936. let arg_annotation_idx = 0;
  15937. for (; it < params.length; it++) {
  15938. const param = params[it];
  15939. const name = param.arg;
  15940. const new_input = block.addInput();
  15941. if (torch._C.meaningfulName(name)) {
  15942. new_input.setDebugName(name);
  15943. }
  15944. let arg = schema.arguments[arg_annotation_idx++];
  15945. if (shouldDeriveType) {
  15946. if (schema.arguments.length === 1) {
  15947. throw new python.Error('Invalid schema.');
  15948. }
  15949. const inferredStateType = this.getTypeForSetStateArg(def, self);
  15950. arg = arg.cloneWithType(inferredStateType);
  15951. }
  15952. args.push(arg);
  15953. new_input.setType(arg.type);
  15954. this.environment_stack.setVar(param.range(), name, new_input);
  15955. }
  15956. return args;
  15957. }
  15958. emitOutput(range, schema, block) {
  15959. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  15960. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  15961. block.registerOutput(placeholder_return);
  15962. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  15963. }
  15964. emitStatements(stmts) {
  15965. for (let i = 0; i < stmts.length; i++) {
  15966. const stmt = stmts[i];
  15967. if (stmt instanceof ast.If) {
  15968. this.emitIf(stmt);
  15969. } else if (stmt instanceof ast.While) {
  15970. this.emitWhile(stmt);
  15971. } else if (stmt instanceof ast.For) {
  15972. this.emitFor(stmt);
  15973. } else if (stmt instanceof ast.Assign) {
  15974. this.emitAssignment(stmt);
  15975. } else if (stmt instanceof ast.AnnAssign) {
  15976. this.emitAssignment(stmt);
  15977. } else if (stmt instanceof ast.Expr) {
  15978. this.emitSugaredExpr(stmt.value, 0);
  15979. } else if (stmt instanceof ast.Return) {
  15980. this.emitReturn(stmt);
  15981. } else if (stmt instanceof ast.Pass) {
  15982. // pass
  15983. } else if (stmt instanceof ast.With) {
  15984. this.emitWith(stmt);
  15985. } else {
  15986. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  15987. }
  15988. if (this.exit_blocks.has(this.environment_stack.block())) {
  15989. return;
  15990. }
  15991. }
  15992. }
  15993. emitWith(stmt) {
  15994. const targets = stmt.items;
  15995. const entered = [];
  15996. for (const target of targets) {
  15997. const e = target.context_expr;
  15998. const rhs = this.emitExpr(e);
  15999. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16000. entered.push(rhs);
  16001. if (rhs.type() instanceof torch.ClassType === false) {
  16002. throw new python.Error('With item expression must return an object.');
  16003. }
  16004. const rhsClass = rhs.type();
  16005. const enterMethod = rhsClass.findMethod('__enter__');
  16006. const exitMethod = rhsClass.findMethod('__exit__');
  16007. if (!enterMethod || !exitMethod) {
  16008. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16009. }
  16010. const enterSchema = enterMethod.getSchema();
  16011. if (enterSchema.arguments.length !== 1) {
  16012. throw new python.Error('__enter__ must have only one argument and one return value.');
  16013. }
  16014. const exitSchema = exitMethod.getSchema();
  16015. if (exitSchema.arguments.length === 4) {
  16016. for (let i = 1; i < 4; i++) {
  16017. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16018. throw new python.Error('Argument of __exit__ must have Any type.');
  16019. }
  16020. }
  16021. } else {
  16022. throw new python.Error('__exit__ must have four arguments');
  16023. }
  16024. n.output(0).setType(enterSchema.returns[0].type);
  16025. if (target.optional_vars) {
  16026. throw new python.Error('Not implemented.');
  16027. // Var i = target.var().get();
  16028. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16029. }
  16030. }
  16031. this.emitStatements(stmt.body);
  16032. while (entered.length > 0) {
  16033. const input = entered.pop();
  16034. const n = this.graph.create('prim::Exit');
  16035. this.graph.insertNode(n);
  16036. n.addInput(input);
  16037. }
  16038. }
  16039. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16040. let max_trip_count_val = null;
  16041. if (iter_val === null) {
  16042. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16043. } else {
  16044. max_trip_count_val = iter_val.len(range, this.method);
  16045. }
  16046. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16047. const body_block = n.addBlock();
  16048. {
  16049. const condition_block = n.addBlock();
  16050. this.pushFrame(condition_block);
  16051. let out = null;
  16052. if (cond) {
  16053. const insert = new torch._C.WithInsertPoint(condition_block);
  16054. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16055. insert.dispose();
  16056. } else {
  16057. const insert = new torch._C.WithInsertPoint(n);
  16058. out = this.graph.insertConstant(true, range);
  16059. insert.dispose();
  16060. }
  16061. condition_block.registerOutput(out);
  16062. this.popFrame();
  16063. }
  16064. n.addInput(max_trip_count_val);
  16065. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16066. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16067. {
  16068. this.pushFrame(body_block);
  16069. const guard = new torch._C.WithInsertPoint(body_block);
  16070. if (iter_val !== null && targets) {
  16071. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16072. const sv = new torch._C.SimpleValue(cur_elem);
  16073. const target_exprs = targets;
  16074. this.validateAssignLhsExpr(target_exprs, range);
  16075. if (target_exprs.length > 1) {
  16076. throw new python.Error('Not implemented.');
  16077. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16078. // target_exprs = ListExpr.create(range, [tl]);
  16079. }
  16080. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16081. }
  16082. emit_body();
  16083. this.popFrame();
  16084. guard.dispose();
  16085. }
  16086. loop_guard.dispose();
  16087. }
  16088. emitFor(...args) {
  16089. if (args.length === 1 && args[0] instanceof ast.For) {
  16090. const [stmt] = args;
  16091. const emit_body = () => this.emitStatements(stmt.body);
  16092. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16093. } else if (args.length === 4) {
  16094. const [targets, itrs, loc, emit_body] = args;
  16095. if (itrs instanceof ast.Tuple) {
  16096. throw new python.Error('List of iterables is not supported currently.');
  16097. }
  16098. const sv = this.emitSugaredExpr(itrs, 1);
  16099. const iterable = sv.iter(loc, this.method);
  16100. if (iterable.shouldEmitUnrolled()) {
  16101. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16102. } else {
  16103. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16104. }
  16105. } else {
  16106. throw new python.Error('Not implemented.');
  16107. }
  16108. }
  16109. emitWhile(stmt) {
  16110. const cond = stmt.test;
  16111. const emit_body = () => this.emitStatements(stmt.body);
  16112. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16113. }
  16114. emitIsInstance(obj, classinfo) {
  16115. const lhs_val = this.emitExpr(obj);
  16116. const lhs_types = [];
  16117. const rhs_types = [];
  16118. const gather_rhs = (expr) => {
  16119. if (expr instanceof ast.Tuple) {
  16120. for (const e of expr.elts) {
  16121. gather_rhs(e);
  16122. }
  16123. return;
  16124. }
  16125. const type = this._typeParser.parseTypeFromExpr(expr);
  16126. rhs_types.push(type);
  16127. };
  16128. lhs_types.push(lhs_val.type());
  16129. gather_rhs(classinfo);
  16130. torch._C.standardizeVectorForUnion(lhs_types);
  16131. torch._C.standardizeVectorForUnion(rhs_types);
  16132. let refinement = new torch._C.RefinementSet([], []);
  16133. let unified_true = null;
  16134. let unified_false = null;
  16135. const isinstance_types = [];
  16136. const not_isinstance_types = [];
  16137. let true_refinements = [];
  16138. let false_refinements = [];
  16139. let all_lhs_subtype_some_rhs = true;
  16140. for (const lhs_type of lhs_types) {
  16141. if (lhs_type === torch.AnyType.get()) {
  16142. isinstance_types.push(...rhs_types);
  16143. not_isinstance_types.push(torch.AnyType.get());
  16144. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16145. all_lhs_subtype_some_rhs = false;
  16146. }
  16147. break;
  16148. }
  16149. const get_smaller_type = (t1, t2) => {
  16150. if (t1.isSubtypeOf(t2)) {
  16151. return t1;
  16152. } else if (t2.isSubtypeOf(t1)) {
  16153. return t2;
  16154. }
  16155. return null;
  16156. };
  16157. let found_refinement = null;
  16158. for (const rhs_type of rhs_types) {
  16159. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16160. if (!maybe_smaller_type) {
  16161. continue;
  16162. } else if (maybe_smaller_type === lhs_type) {
  16163. found_refinement = lhs_type;
  16164. } else if (maybe_smaller_type === rhs_type) {
  16165. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16166. }
  16167. }
  16168. if (found_refinement) {
  16169. if (found_refinement === lhs_type) {
  16170. all_lhs_subtype_some_rhs &= true;
  16171. }
  16172. isinstance_types.push(found_refinement);
  16173. } else {
  16174. not_isinstance_types.push(lhs_type);
  16175. all_lhs_subtype_some_rhs = false;
  16176. }
  16177. }
  16178. if (isinstance_types.length > 0) {
  16179. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16180. }
  16181. if (obj instanceof ast.Name && unified_true) {
  16182. const ident = obj.id;
  16183. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16184. }
  16185. if (not_isinstance_types.length > 0) {
  16186. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16187. }
  16188. if (obj instanceof ast.Name && unified_false) {
  16189. const ident = obj.id;
  16190. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16191. }
  16192. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16193. const is_statically_false = isinstance_types.length === 0;
  16194. if (all_lhs_subtype_some_rhs) {
  16195. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16196. }
  16197. if (is_statically_false) {
  16198. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16199. }
  16200. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16201. return new torch._C.CondValue(result, refinement, null);
  16202. }
  16203. emitIf(stmt) {
  16204. const cond_value = this.emitCondExpr(stmt.test);
  16205. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16206. }
  16207. emitCondExpr(expr) {
  16208. /*
  16209. switch (expr.kind()) {
  16210. case TK_AND:
  16211. case TK_OR: {
  16212. const binop = BinOp(expr);
  16213. return emitShortCircuitLogical(
  16214. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16215. }
  16216. case TK_NOT: {
  16217. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16218. Value* result = emitBuiltinCall(
  16219. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16220. std::optional<bool> static_if;
  16221. if (v.staticIf()) {
  16222. static_if = !*v.staticIf();
  16223. }
  16224. return CondValue(result, v.refinements().Not(), static_if);
  16225. } break;
  16226. case TK_IS:
  16227. case TK_ISNOT: {
  16228. // meta programming on AST for is/is not cases and emit branches base on
  16229. const cond_op = BinOp(expr);
  16230. Value* lhs_val = emitExpr(cond_op.lhs());
  16231. Value* rhs_val = emitExpr(cond_op.rhs());
  16232. const lhs_none = canBeNone(lhs_val);
  16233. const rhs_none = canBeNone(rhs_val);
  16234. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16235. // AA, -> statically IS always holds, IS_NOT never holds
  16236. // AN , NA-> statically IS_NOT always holds, IS never holds
  16237. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16238. bool its_is = expr.kind() == TK_IS;
  16239. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16240. return CondValue(*graph, expr.range(), its_is, {});
  16241. } else if (
  16242. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16243. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16244. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16245. return CondValue(*graph, expr.range(), !its_is, {});
  16246. } else {
  16247. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16248. Value* cond_value = emitBuiltinCall(
  16249. expr.get()->range(),
  16250. *method.graph(),
  16251. kind,
  16252. {lhs_val, rhs_val},
  16253. {});
  16254. const refinements = RefinementSet(findIsNoneRefinements(
  16255. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16256. return CondValue(cond_value, refinements, null);
  16257. }
  16258. } break;
  16259. */
  16260. if (expr instanceof ast.UnaryOp) {
  16261. throw new python.Error('Not implemented.');
  16262. }
  16263. if (expr instanceof ast.Call) {
  16264. const apply = expr;
  16265. const callee = expr.func;
  16266. if (callee instanceof ast.Name) {
  16267. if (callee.id === 'isinstance') {
  16268. this.checkApplyNumInputs(apply, 2);
  16269. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16270. }
  16271. if (callee.id === 'hasattr') {
  16272. this.checkApplyNumInputs(apply, 2);
  16273. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16274. }
  16275. const sv = this.emitSugaredExpr(callee, 1);
  16276. if (sv instanceof torch._C.SpecialFormValue) {
  16277. if (sv.form() === 'prim::isinstance') {
  16278. this.checkApplyNumInputs(apply, 2);
  16279. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16280. }
  16281. }
  16282. }
  16283. }
  16284. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16285. let static_if = null;
  16286. const kind = expr_out.node().kind();
  16287. if (kind === 'aten::is_scripting') {
  16288. static_if = true;
  16289. } else if (kind === 'aten::has_torch_function') {
  16290. static_if = false;
  16291. }
  16292. const maybe_ivalue = torch._C.toIValue(expr_out);
  16293. if (maybe_ivalue) {
  16294. static_if = maybe_ivalue.toBool();
  16295. }
  16296. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16297. }
  16298. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16299. if (cond_value.staticIf() !== null) {
  16300. if (cond_value.staticIf()) {
  16301. this.insertRefinements(loc, cond_value.refinements());
  16302. this.emitStatements(trueBranch);
  16303. } else {
  16304. this.insertRefinements(loc, cond_value.refinements().Not());
  16305. this.emitStatements(falseBranch);
  16306. }
  16307. return;
  16308. }
  16309. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16310. n.addInput(cond_value.value());
  16311. const true_block = n.addBlock();
  16312. const false_block = n.addBlock();
  16313. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16314. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16315. const true_exits = this.exit_blocks.has(true_block);
  16316. const false_exits = this.exit_blocks.has(false_block);
  16317. if (true_exits && false_exits) {
  16318. this.exit_blocks.add(n.owningBlock());
  16319. }
  16320. const mutated_variables = new Set();
  16321. for (const v of save_true.definedVariables()) {
  16322. const insert = new torch._C.WithInsertPoint(false_block);
  16323. if (save_false.findInAnyFrame(v) || false_exits) {
  16324. mutated_variables.add(v);
  16325. } else {
  16326. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16327. }
  16328. insert.dispose();
  16329. }
  16330. for (const v of save_false.definedVariables()) {
  16331. const insert = new torch._C.WithInsertPoint(true_block);
  16332. if (save_true.findInAnyFrame(v) || true_exits) {
  16333. mutated_variables.add(v);
  16334. } else {
  16335. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16336. }
  16337. insert.dispose();
  16338. }
  16339. for (const x of mutated_variables) {
  16340. let tv = null;
  16341. let fv = null;
  16342. {
  16343. const insert = new torch._C.WithInsertPoint(true_block);
  16344. if (!true_exits) {
  16345. tv = save_true.getVar(x, loc);
  16346. }
  16347. insert.dispose();
  16348. }
  16349. {
  16350. const insert = new torch._C.WithInsertPoint(false_block);
  16351. if (!false_exits) {
  16352. fv = save_false.getVar(x, loc);
  16353. }
  16354. insert.dispose();
  16355. }
  16356. if (true_exits && false_exits) {
  16357. continue;
  16358. } else if (true_exits) {
  16359. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16360. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16361. } else if (false_exits) {
  16362. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16363. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16364. }
  16365. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16366. let full_type = null;
  16367. if (maybe_sugared_x) {
  16368. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16369. if (maybe_simple) {
  16370. full_type = maybe_simple.type();
  16371. }
  16372. }
  16373. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16374. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16375. if (!unified) {
  16376. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16377. throw new python.Error('Type mismatch.');
  16378. } else {
  16379. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16380. continue;
  16381. }
  16382. }
  16383. this.environment_stack.setType(x, unified);
  16384. }
  16385. }
  16386. emitSingleIfBranch(b, branch, refinements) {
  16387. this.pushFrame(b);
  16388. const guard = new torch._C.WithInsertPoint(b);
  16389. this.insertRefinements(branch, refinements);
  16390. this.emitStatements(branch);
  16391. const frame = this.popFrame();
  16392. guard.dispose();
  16393. return frame;
  16394. }
  16395. create(kind, loc, n_outputs) {
  16396. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16397. }
  16398. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16399. is_dict_constructor = is_dict_constructor || false;
  16400. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16401. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16402. if (!is_dict_constructor && candidate_types.length === 0) {
  16403. throw new python.Error("No matching types found in Union type annotation.");
  16404. } else if (candidate_types.length === 1) {
  16405. [refined_type_hint_ptr._] = candidate_types;
  16406. } else {
  16407. all_candidates._ = candidate_types;
  16408. }
  16409. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16410. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16411. }
  16412. if (is_dict_constructor) {
  16413. return;
  16414. }
  16415. if (all_candidates._.length === 0) {
  16416. if (type_match(refined_type_hint_ptr._)) {
  16417. do_if_match();
  16418. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16419. do_if_anytype();
  16420. } else {
  16421. throw new python.Error('Invalid annotation type.');
  16422. }
  16423. }
  16424. }
  16425. emitToBool(loc, v) {
  16426. let out = null;
  16427. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16428. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16429. if (!out) {
  16430. throw new python.Error('Could not cast value to bool.');
  16431. }
  16432. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16433. throw new python.Error('Expected a bool expression for condition.');
  16434. }
  16435. return out;
  16436. }
  16437. emitUnaryOp(tree, magicMethod, opSymbol) {
  16438. const inputs = [tree.operand];
  16439. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16440. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16441. if (val.node().kind() !== opSymbol) {
  16442. return val;
  16443. }
  16444. const maybe_out_stack = this.runNodeIfInputsAreConstant(val.node());
  16445. if (!maybe_out_stack) {
  16446. return val;
  16447. }
  16448. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16449. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16450. }
  16451. emitAssignment(stmt) {
  16452. if (stmt instanceof ast.AnnAssign) {
  16453. return this.emitSingleAssignment(stmt);
  16454. }
  16455. if (stmt.targets.length === 1) {
  16456. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16457. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16458. for (const [key, value] of entries) {
  16459. assign[key] = value;
  16460. }
  16461. return this.emitSingleAssignment(assign);
  16462. }
  16463. if (stmt.targets.length <= 1) {
  16464. throw new python.Error('Invalid assignment.');
  16465. }
  16466. throw new python.Error('Not implemented.');
  16467. /*
  16468. const tmp_name = this.createTempName('$tmp_assign_');
  16469. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16470. const ident = new ast.Name(tmp_name);
  16471. for (const expr of lhs_list) {
  16472. const assign = new ast.Assign(targets, value, ctx);
  16473. this.emitSingleAssignment(Assign.create(stmt,
  16474. List<Expr>.create(expr.range(), [expr]),
  16475. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16476. Maybe<Expr>::create(stmt.range())));
  16477. }
  16478. */
  16479. }
  16480. emitSingleAssignment(stmt) {
  16481. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16482. const rhs = stmt.value;
  16483. const lhs = stmt.target;
  16484. if (lhs instanceof ast.Name) {
  16485. let type = null;
  16486. if (stmt.annotation) {
  16487. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16488. }
  16489. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16490. // BC HACK
  16491. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16492. } else if (lhs instanceof ast.Tuple) {
  16493. this.emitTupleAssign(lhs, rhs);
  16494. } else if (lhs instanceof ast.Attribute) {
  16495. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16496. } else {
  16497. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16498. }
  16499. }
  16500. emitSelectAssign(lhs, rhs, type, loc) {
  16501. if (!rhs) {
  16502. throw new python.Error('Expected RHS for assignment.');
  16503. }
  16504. let type_hint = null;
  16505. if (type) {
  16506. type_hint = this._typeParser.parseTypeFromExpr(type);
  16507. }
  16508. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16509. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16510. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16511. }
  16512. emitTupleAssign(...args) {
  16513. if (args.length === 2) {
  16514. const [tl, rhs] = args;
  16515. let n_binders = tl.elts.length;
  16516. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16517. if (starred_unpack) {
  16518. n_binders--;
  16519. }
  16520. const output = this.emitSugaredExpr(rhs, n_binders);
  16521. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16522. } else if (args.length === 5) {
  16523. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16524. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16525. if (outputs.length < n_binders) {
  16526. throw new python.Error('Not enough values to unpack.');
  16527. }
  16528. if (outputs.length > n_binders && !starred_unpack) {
  16529. throw new python.Error('Too many values to unpack.');
  16530. }
  16531. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16532. } else {
  16533. throw new python.Error('Not implemented.');
  16534. }
  16535. }
  16536. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16537. let i = 0;
  16538. for (const assignee of lhs_exprs) {
  16539. if (assignee instanceof ast.Subscript) {
  16540. throw new python.Error('Not implemented.');
  16541. /*
  16542. this.emitSubscriptAssign(
  16543. rhs_loc,
  16544. Subscript(assignee),
  16545. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16546. i++;
  16547. */
  16548. } else if (assignee instanceof ast.Name) {
  16549. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16550. i++;
  16551. } else if (assignee instanceof ast.Starred) {
  16552. throw new python.Error('Not implemented.');
  16553. /*
  16554. const var = Starred(assignee).expr();
  16555. if (var.kind() != TK_VAR) {
  16556. throw(
  16557. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16558. }
  16559. size_t n_matched = outputs.size() - n_binders;
  16560. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16561. const values = fmap(
  16562. outputs_ref.slice(i, n_matched),
  16563. [&](const std::shared_ptr<SugaredValue>& v) {
  16564. return v.asValue(assignee.range(), method);
  16565. });
  16566. const tup = graph.insertNode(graph.createTuple(values)).output();
  16567. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16568. i += n_matched;
  16569. */
  16570. } else if (assignee instanceof ast.Tuple) {
  16571. throw new python.Error('Not implemented.');
  16572. /*
  16573. // recursively emit tuple assignments on tuple literal input
  16574. TupleLiteral sub_tl = TupleLiteral(assignee);
  16575. size_t sub_n_binders = sub_tl.inputs().length;
  16576. bool sub_starred_unpack =
  16577. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16578. if (sub_starred_unpack)
  16579. sub_n_binders--;
  16580. emitTupleAssign(
  16581. sub_tl,
  16582. outputs.at(i),
  16583. rhs_loc,
  16584. sub_n_binders,
  16585. sub_starred_unpack);
  16586. i++;
  16587. */
  16588. } else if (assignee instanceof ast.Attribute) {
  16589. throw new python.Error('Not implemented.');
  16590. /*
  16591. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16592. i++;
  16593. */
  16594. } else {
  16595. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16596. }
  16597. }
  16598. }
  16599. emitReturn(stmt) {
  16600. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16601. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16602. if (declared_return_type) {
  16603. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16604. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16605. }
  16606. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16607. throw new python.Error(`Invalid return type.`);
  16608. }
  16609. } else {
  16610. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16611. if (!declared_return_type) {
  16612. declared_return_type = actual_return.type();
  16613. }
  16614. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16615. if (!merged_return_type) {
  16616. throw new python.Error(`Invalid return type.`);
  16617. }
  16618. declared_return_type = merged_return_type;
  16619. }
  16620. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16621. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16622. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16623. }
  16624. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16625. this.exit_blocks.add(this.environment_stack.block());
  16626. }
  16627. getNamedValues(trees, maybe_unpack) {
  16628. const values = [];
  16629. for (const tree of trees) {
  16630. if (maybe_unpack && tree instanceof ast.Starred) {
  16631. throw new python.Error('Starred argument not supported.');
  16632. } else {
  16633. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16634. }
  16635. }
  16636. return values;
  16637. }
  16638. getValues(trees, maybe_unpack) {
  16639. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16640. }
  16641. emitExpr(tree, type_hint) {
  16642. type_hint = type_hint || null;
  16643. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16644. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16645. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16646. }
  16647. return out_val;
  16648. }
  16649. emitSugaredExpr(tree, n_binders, type_hint) {
  16650. if (tree instanceof ast.Name) { // TK_VAR
  16651. return this.environment_stack.getSugaredVar(tree.id);
  16652. } else if (tree instanceof ast.Attribute) {
  16653. const sv = this.emitSugaredExpr(tree.value, 1);
  16654. return sv.attr(tree.range(), this.method, tree.attr);
  16655. } else if (tree instanceof ast.Call) { // TK_APPLY
  16656. return this.emitApplyExpr(tree, n_binders, type_hint);
  16657. } if (tree instanceof ast.Subscript) {
  16658. return this.emitSubscript(tree, type_hint);
  16659. }
  16660. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  16661. }
  16662. emitApplyExpr(apply, n_binders, type_hint) {
  16663. type_hint = type_hint || null;
  16664. const sv = this.emitSugaredExpr(apply.func, 1);
  16665. const loc = apply.func.range();
  16666. if (sv instanceof torch._C.SpecialFormValue) {
  16667. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  16668. }
  16669. const args = this.getNamedValues(apply.args, true);
  16670. const kwargs = this.emitAttributes(apply.keywords);
  16671. return sv.call(loc, this.method, args, kwargs, n_binders);
  16672. }
  16673. emitAttributes(attributes) {
  16674. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  16675. }
  16676. emitApplySpecialForm(form, apply, sv, type_hint) {
  16677. switch (form) {
  16678. case 'prim::fork': {
  16679. throw new python.Error('Not implemented.');
  16680. }
  16681. case 'prim::awaitable': {
  16682. throw new python.Error('Not implemented.');
  16683. }
  16684. case 'prim::annotate': {
  16685. this.checkApplyNumInputs(apply, 2);
  16686. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16687. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  16688. if (!expr.type().isSubtypeOf(type)) {
  16689. throw new python.Error('Invalid expression type.');
  16690. }
  16691. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  16692. const none = this.graph.createNone();
  16693. none.output().setType(type);
  16694. this.graph.insertNode(none);
  16695. expr = none.output();
  16696. }
  16697. return new torch._C.SimpleValue(expr);
  16698. }
  16699. case 'prim::unchecked_cast': {
  16700. this.checkApplyNumInputs(apply, 2);
  16701. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16702. let v = this.emitExpr(apply.args[1]);
  16703. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  16704. v = this.graph.insertUncheckedCast(v, type);
  16705. }
  16706. return new torch._C.SimpleValue(v);
  16707. }
  16708. case 'prim::GetAttr': {
  16709. this.checkApplyNumInputsRange(apply, 2, 3);
  16710. const obj = this.emitSugaredExpr(apply.args[0], 1);
  16711. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  16712. throw new python.Error('Invalid argument.');
  16713. }
  16714. const name = apply.args[1].value;
  16715. if (apply.args.length === 2) {
  16716. return obj.attr(apply, this.method, name);
  16717. } else if (obj.hasAttr(apply, this.method, name)) {
  16718. return obj.attr(apply, this.method, name);
  16719. }
  16720. return this.emitSugaredExpr(apply.inputs()[2], 1);
  16721. }
  16722. case 'prim::Uninitialized': {
  16723. this.checkApplyNumInputs(apply, 1);
  16724. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16725. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  16726. return new torch._C.SimpleValue(out.output());
  16727. }
  16728. case 'prim::TupleConstruct': {
  16729. throw new python.Error('Not implemented.');
  16730. }
  16731. case 'prim::isinstance': {
  16732. this.checkApplyNumInputs(apply, 2);
  16733. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  16734. return new torch._C.SimpleValue(result.value());
  16735. }
  16736. case 'prim::tolist': {
  16737. const value = apply.func.value;
  16738. const operand = this.emitSugaredExpr(value, 1);
  16739. if (!type_hint) {
  16740. throw new python.Error('Expected type hint for result of tolist().');
  16741. }
  16742. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  16743. }
  16744. case 'prim::HasAttr': {
  16745. throw new python.Error('Not implemented.');
  16746. }
  16747. case 'prim::CreateObject': {
  16748. if (apply.args.length !== 1) {
  16749. throw python.Error('Only one argument to __new__ allowed.');
  16750. }
  16751. const arg = this.emitSugaredExpr(apply.args[0], 1);
  16752. if (arg instanceof torch._C.ClassValue === false) {
  16753. throw python.Error('Expected class value as argument to __new__.');
  16754. }
  16755. const class_arg = arg;
  16756. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  16757. createNode.setSourceRange(apply.range());
  16758. return new torch._C.SimpleValue(createNode.output());
  16759. }
  16760. case 'prim::range': {
  16761. const input_vals = this.getValues(apply.args, true);
  16762. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  16763. }
  16764. case 'prim::enumerate': {
  16765. throw new python.Error('Not implemented.');
  16766. }
  16767. case 'prim::zip': {
  16768. throw new python.Error('Not implemented.');
  16769. }
  16770. case 'prim::list': {
  16771. throw new python.Error('Not implemented.');
  16772. }
  16773. case 'prim::dict': {
  16774. throw new python.Error('Not implemented.');
  16775. }
  16776. case 'aten::index': {
  16777. throw new python.Error('Not implemented.');
  16778. }
  16779. default: {
  16780. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  16781. }
  16782. }
  16783. }
  16784. emitSimpleExpr(tree, type_hint) {
  16785. if (tree instanceof ast.Constant) {
  16786. if (tree.value === true) {
  16787. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  16788. } else if (tree.value === false) {
  16789. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  16790. } else if (tree.value === null) {
  16791. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  16792. } else if (typeof tree.value === 'string') {
  16793. return this.emitStringLiteral(tree);
  16794. }
  16795. return this.emitConst(tree);
  16796. } else if (tree instanceof ast.List) {
  16797. return this.emitListLiteral(tree, type_hint);
  16798. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  16799. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  16800. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  16801. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  16802. } else if (tree instanceof ast.BinOp) {
  16803. return this.emitBinaryOp(tree);
  16804. } else if (tree instanceof ast.Dict) {
  16805. return this.emitDictLiteral(tree, type_hint);
  16806. } else if (tree instanceof ast.Tuple) {
  16807. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  16808. return this.graph.insertNode(this.graph.createTuple(values)).output();
  16809. }
  16810. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  16811. }
  16812. getNodeKind(kind /*, ninputs */) {
  16813. if (kind instanceof ast.Add) {
  16814. return 'aten::add';
  16815. } else if (kind instanceof ast.Sub) {
  16816. return 'aten::sub';
  16817. } else if (kind instanceof ast.Mult) {
  16818. return 'aten::mul';
  16819. }
  16820. /*
  16821. case TK_UNARY_MINUS: return 'aten::neg';
  16822. case TK_POW: return 'aten::pow';
  16823. case '@': return 'aten::matmul';
  16824. case TK_STARRED: return 'prim::Starred';
  16825. case '/': return 'aten::div';
  16826. case '%': return 'aten::remainder';
  16827. case TK_NE: return 'aten::ne';
  16828. case TK_EQ: return 'aten::eq';
  16829. case '<': return 'aten::lt';
  16830. case '>': return 'aten::gt';
  16831. case TK_LE: return 'aten::le';
  16832. case TK_GE: return 'aten::ge';
  16833. case TK_AND: return 'aten::__and__';
  16834. case TK_OR: return 'aten::__or__';
  16835. case TK_IS: return 'aten::__is__';
  16836. case TK_ISNOT: return 'aten::__isnot__';
  16837. case TK_NOT: return 'aten::__not__';
  16838. case TK_FLOOR_DIV: return 'aten::floordiv';
  16839. case TK_LSHIFT: return 'aten::__lshift__';
  16840. case TK_RSHIFT: return 'aten::__rshift__';
  16841. case '&': return 'aten::__and__';
  16842. case '|': return 'aten::__or__';
  16843. case '^': return 'aten::__xor__';
  16844. case TK_IN: return 'aten::__contains__';
  16845. */
  16846. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  16847. }
  16848. getOperatorOverload(kind /*, ninputs */) {
  16849. if (kind instanceof ast.Add) {
  16850. return '__add__';
  16851. } else if (kind instanceof ast.Sub) {
  16852. return '__sub__';
  16853. } else if (kind instanceof ast.Mult) {
  16854. return '__mul__';
  16855. }
  16856. /*
  16857. case TK_UNARY_MINUS: return "__neg__";
  16858. case '~': return "__invert__";
  16859. case TK_POW: return "__pow__";
  16860. case '/': return "__truediv__";
  16861. case '%': return "__mod__";
  16862. case TK_NE: return "__ne__";
  16863. case TK_EQ: return "__eq__";
  16864. case '<': return "__lt__";
  16865. case '>': return "__gt__";
  16866. case TK_LE: return "__le__";
  16867. case TK_GE: return "__ge__";
  16868. case '&': return "__and__";
  16869. case '|': return "__or__";
  16870. case '^': return "__xor__";
  16871. case TK_IN: return "__contains__";
  16872. case TK_LSHIFT: return "__lshift__";
  16873. case TK_RSHIFT: return "__rshift__";
  16874. */
  16875. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  16876. }
  16877. emitBinaryOp(tree) {
  16878. const inputs = [tree.left, tree.right];
  16879. const kind = this.getNodeKind(tree.op, inputs.length);
  16880. const overload = this.getOperatorOverload(tree.op, inputs.length);
  16881. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16882. if (tree.op instanceof ast.In) {
  16883. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  16884. throw new python.Error('Not implemented.');
  16885. }
  16886. if (named_values[0].type() instanceof torch.TupleType &&
  16887. named_values[1].type() instanceof torch.TupleType &&
  16888. kind === 'aten::add') {
  16889. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  16890. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  16891. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  16892. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  16893. }
  16894. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  16895. }
  16896. emitDictLiteral(dl, type_hint) {
  16897. const key_trees = dl.keys;
  16898. const value_trees = dl.values;
  16899. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  16900. const keys = [];
  16901. const values = [];
  16902. let rhs_value_type = null;
  16903. for (let i = 0; i < key_trees.length; i++) {
  16904. keys.push(this.emitExpr(key_trees[i]));
  16905. values.push(this.emitExpr(value_trees[i]));
  16906. if (i === 0) {
  16907. rhs_value_type = values[i].type();
  16908. } else {
  16909. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  16910. throw new python.Error('Dict keys must contain only a single type.');
  16911. }
  16912. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  16913. }
  16914. }
  16915. const refined_type_hint = { _: type_hint };
  16916. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  16917. const all_candidates = { _: [] };
  16918. const default_refined_type_hint_setter = () => {
  16919. if (keys.length === 0) {
  16920. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  16921. } else {
  16922. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  16923. if (rhs_value_type instanceof torch.UnionType) {
  16924. throw new python.Error('Dict values consist of heterogeneous types.');
  16925. }
  16926. }
  16927. };
  16928. if (type_hint) {
  16929. const type_match = (t) => t instanceof torch.DictType;
  16930. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  16931. if (all_candidates._.length > 0 && values.length === 0) {
  16932. throw new python.Error('Cannot assign an empty dict.');
  16933. }
  16934. } else {
  16935. default_refined_type_hint_setter();
  16936. }
  16937. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  16938. if (values.length > 0) {
  16939. if (all_candidates._.length > 0) {
  16940. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  16941. }
  16942. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  16943. throw new python.Error('Type annotation does not match key type.');
  16944. }
  16945. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  16946. throw new python.Error('Type annotation does not match value type.');
  16947. }
  16948. }
  16949. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  16950. if (annotated_union_type) {
  16951. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  16952. n.output().setType(annotated_union_type);
  16953. result = n;
  16954. }
  16955. return result.output();
  16956. }
  16957. emitStringLiteral(c) {
  16958. return torch._C.insertConstant(this.graph, c.value, c.range());
  16959. }
  16960. emitConst(c) {
  16961. if (c.type === 'int') {
  16962. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  16963. } else if (c.type === 'complex') {
  16964. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  16965. } else if (c.type === 'float') {
  16966. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  16967. }
  16968. throw new python.Error(`Unsupported constant type.`);
  16969. }
  16970. emitListLiteral(ll, type_hint) {
  16971. type_hint = type_hint || null;
  16972. const values = this.getValues(ll.elts, true);
  16973. if (values.length === 0 && type_hint === null) {
  16974. throw new python.Error('Not implemented.');
  16975. }
  16976. let inferred_elem_type = torch.TensorType.get();
  16977. const refined_type_hint = { _: type_hint };
  16978. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  16979. const all_candidates = { _: [] };
  16980. if (refined_type_hint._) {
  16981. const do_if_type_match = () => {
  16982. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  16983. };
  16984. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  16985. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  16986. if (all_candidates._.length > 0 && values.len === 0) {
  16987. throw new python.Error('Cannot assign an empty list.');
  16988. }
  16989. }
  16990. if (values.length !== 0) {
  16991. const types = values.map((v) => v.type());
  16992. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  16993. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  16994. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  16995. throw new python.Error('Not implemented.');
  16996. }
  16997. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  16998. throw new python.Error('Not implemented.');
  16999. }
  17000. if (all_candidates._.length !== 0) {
  17001. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17002. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17003. }
  17004. if (!refined_type_hint._) {
  17005. inferred_elem_type = unified_elem_type;
  17006. }
  17007. }
  17008. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17009. if (annotated_union_type) {
  17010. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17011. n.output().setType(annotated_union_type);
  17012. result = n;
  17013. }
  17014. return result.output();
  17015. }
  17016. insertRefinements(loc, ref) {
  17017. for (const r of ref.activeRefinements()) {
  17018. const v = this.environment_stack.getVar(r.identifier(), loc);
  17019. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17020. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17021. }
  17022. }
  17023. shouldDeriveSetStateType(def, schema) {
  17024. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17025. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17026. if (!shouldInfer) {
  17027. return false;
  17028. }
  17029. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17030. throw new python.Error(`Invalid '__setstate' method.`);
  17031. }
  17032. return true;
  17033. }
  17034. checkApplyNumInputs(apply, expected_inputs) {
  17035. if (apply.args.length !== expected_inputs) {
  17036. throw new python.Error('Invalid number of arguments.');
  17037. }
  17038. if (apply.keywords.length > 0) {
  17039. throw new python.Error('Invalid number of keyword arguments.');
  17040. }
  17041. }
  17042. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17043. const position_arg_size = apply.args.length;
  17044. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17045. throw new python.Error('Invalid number of arguments.');
  17046. }
  17047. if (apply.keywords.length > 0) {
  17048. throw new python.Error('Invalid number of keyword arguments.');
  17049. }
  17050. }
  17051. validateAssignLhsExpr(lhs /*, r */) {
  17052. let num_normal_assign = 0;
  17053. let num_starred = 0;
  17054. for (const assignee of lhs) {
  17055. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17056. num_normal_assign++;
  17057. } else if (assignee instanceof ast.Starred) {
  17058. num_starred++;
  17059. } else {
  17060. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17061. }
  17062. }
  17063. if (num_starred > 1) {
  17064. throw new python.Error('Only one starred expression is allowed.');
  17065. }
  17066. if (num_starred > 0 && num_normal_assign === 0) {
  17067. throw new python.Error('Invalid starred expression.');
  17068. }
  17069. return num_starred;
  17070. }
  17071. createTempName(prefix) {
  17072. return `${prefix}${this._temp_name_count++}`;
  17073. }
  17074. handleMaybeNoReturn(def, block) {
  17075. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17076. if (this.exit_blocks.size === 0) {
  17077. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17078. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17079. }
  17080. const b = new torch._C.WithInsertPoint(block.nodes()[-1]);
  17081. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17082. b.dispose();
  17083. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17084. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17085. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17086. }
  17087. }
  17088. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17089. let adj_index = input_index;
  17090. const tuple_len = tuple_type.elements().length;
  17091. if (input_index < 0) {
  17092. adj_index = tuple_len + input_index;
  17093. }
  17094. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17095. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17096. }
  17097. return adj_index;
  17098. }
  17099. emitTupleIndex(loc, tuple_val, idx_val) {
  17100. const tuple_typ = tuple_val.type();
  17101. const elems = tuple_typ.elements();
  17102. let output_type = null;
  17103. if (idx_val.type() !== torch.IntType.get()) {
  17104. throw new python.Error('Tuple index must be an integer.');
  17105. }
  17106. const idx = torch._C.toIValue(idx_val);
  17107. if (idx) {
  17108. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17109. output_type = elems[adj_index];
  17110. } else {
  17111. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17112. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17113. }
  17114. [output_type] = elems;
  17115. }
  17116. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17117. }
  17118. getSliceInd(idx_val, loc) {
  17119. const ivalue = torch._C.toIValue(idx_val);
  17120. if (ivalue && ivalue.isInt()) {
  17121. return ivalue.toInt();
  17122. }
  17123. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17124. }
  17125. emitTupleSlice(loc, tuple_val, tuple_args) {
  17126. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17127. const tuple_len = tuple_type.elements().length;
  17128. const [beg_val, end_val, step] = tuple_args;
  17129. let step_size = 1;
  17130. if (step) {
  17131. const val = torch._C.toIValue(step.value(this.graph));
  17132. torch._C.TORCH_CHECK(val.isInt());
  17133. step_size = val.toInt();
  17134. }
  17135. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17136. if (beg_val) {
  17137. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17138. }
  17139. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17140. if (end_val) {
  17141. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17142. }
  17143. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17144. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17145. }
  17146. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17147. const args = [];
  17148. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17149. if (dim) {
  17150. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17151. args.emplace_back(new torch._C.NamedValue(dim));
  17152. } else {
  17153. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17154. }
  17155. if (sliceable.type() instanceof torch.TupleType) {
  17156. const tuple_args = [];
  17157. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17158. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17159. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17160. return this.emitTupleSlice(loc, args[0], tuple_args);
  17161. }
  17162. if (!step) {
  17163. step = this.graph.insertConstant(1, loc);
  17164. }
  17165. args.push(new torch._C.NamedValue(loc, 'start', start));
  17166. args.push(new torch._C.NamedValue(loc, 'end', end));
  17167. args.push(new torch._C.NamedValue(loc, 'step', step));
  17168. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17169. }
  17170. emitSlice(loc, input, dim, slice) {
  17171. let start = null;
  17172. let end = null;
  17173. let step = null;
  17174. if (slice.lower) {
  17175. start = this.emitExpr(slice.lower);
  17176. }
  17177. if (slice.upper) {
  17178. end = this.emitExpr(slice.upper);
  17179. }
  17180. if (slice.step) {
  17181. step = this.emitExpr(slice.step);
  17182. }
  17183. return this.emitSliceOp(loc, input, dim, start, end, step);
  17184. }
  17185. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17186. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17187. const slice_exp = subscript_exprs;
  17188. let maybe_dim = null;
  17189. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17190. maybe_dim = this.graph.insertConstant(0, loc);
  17191. }
  17192. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17193. }
  17194. emitSubscript(subscript, type_hint) {
  17195. type_hint = type_hint === undefined ? null : type_hint;
  17196. const sv = this.emitSugaredExpr(subscript.value, 1);
  17197. const subscript_exprs = subscript.slice;
  17198. const range = subscript.range();
  17199. const val_range = subscript.value;
  17200. if (subscript_exprs instanceof ast.Tuple) {
  17201. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17202. }
  17203. if (subscript_exprs instanceof ast.Slice) {
  17204. if (sv.kind() === 'module') {
  17205. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17206. const [slice] = subscript_exprs;
  17207. const tuple_args = [];
  17208. if (slice.start().present()) {
  17209. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17210. tuple_args.push(begin);
  17211. } else {
  17212. tuple_args.push(null);
  17213. }
  17214. if (slice.end().present()) {
  17215. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17216. tuple_args.push(end);
  17217. } else {
  17218. tuple_args.push(null);
  17219. }
  17220. if (slice.step().present()) {
  17221. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17222. tuple_args.push(step);
  17223. } else {
  17224. tuple_args.push(null);
  17225. }
  17226. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17227. return new torch._C.SimpleValue(tupleSliceValue);
  17228. }
  17229. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17230. }
  17231. const sliceable = sv.asValue(val_range, this.method);
  17232. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17233. if (subscript_sv instanceof torch._C.SliceValue) {
  17234. const slice_value = subscript_sv;
  17235. let dim = null;
  17236. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17237. dim = this.method.graph().insertConstant(0, val_range);
  17238. }
  17239. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17240. return new torch._C.SimpleValue(sliced);
  17241. }
  17242. const idx = subscript_sv.asValue(val_range, this.method);
  17243. if (sliceable.type() instanceof torch.TupleType) {
  17244. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17245. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17246. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17247. }
  17248. return sv.getitem(range, this.method, idx, type_hint);
  17249. }
  17250. });
  17251. this.registerType('torch.jit.CompilationUnit', class {
  17252. constructor() {
  17253. this._functions = new Map();
  17254. this._classes = new Map();
  17255. }
  17256. register_type(namedType) {
  17257. this._classes.set(namedType.annotation_str, namedType);
  17258. }
  17259. register_function(fn) {
  17260. const name = fn.qualname().qualifiedName();
  17261. torch._C.TORCH_CHECK(!this._functions.has(name));
  17262. this._functions.set(name, fn);
  17263. return fn;
  17264. }
  17265. define(...args) {
  17266. if (Array.isArray(args[1])) {
  17267. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17268. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17269. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17270. const functions = [];
  17271. const function_table = new Map();
  17272. const record_function = (fn) => {
  17273. function_table.set(fn.name(), fn);
  17274. functions.push(fn);
  17275. this.register_function(fn);
  17276. };
  17277. for (let i = 0; i < properties.length; i++) {
  17278. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17279. const getter_fn = property_fns.getGetter();
  17280. const setter_fn = property_fns.getSetter();
  17281. record_function(getter_fn);
  17282. if (setter_fn) {
  17283. record_function(setter_fn);
  17284. }
  17285. }
  17286. for (let i = 0; i < definitions.length; i++) {
  17287. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17288. record_function(fn);
  17289. }
  17290. for (const [name, fn] of function_table) {
  17291. if (name === '__init__') {
  17292. fn.ensure_defined();
  17293. }
  17294. }
  17295. for (const fn of functions) {
  17296. fn.ensure_defined();
  17297. }
  17298. return functions;
  17299. } else if (args[1] instanceof ast.FunctionDef) {
  17300. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17301. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17302. const creator = (method) => {
  17303. return new torch._C.to_ir(def, _resolver, self, method);
  17304. };
  17305. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17306. if (shouldMangle && this.find_function(name)) {
  17307. name = this.mangle(name);
  17308. }
  17309. const graph = new torch.Graph();
  17310. graph.set_op_version(operator_set_version);
  17311. const fn = new torch._C.GraphFunction(name, graph, creator);
  17312. fn.__ast__ = def; // remove
  17313. if (self) {
  17314. if (type === 'hook') {
  17315. self.getClassType().addForwardHook(fn);
  17316. } else if (type === 'prehook') {
  17317. self.getClassType().addPreHook(fn);
  17318. } else {
  17319. self.getClassType().addMethod(fn);
  17320. }
  17321. }
  17322. return fn;
  17323. }
  17324. throw new python.Error('Invalid arguments.');
  17325. }
  17326. get_type(name) {
  17327. return this._classes.get(name.qualifiedName());
  17328. }
  17329. get_class(name) {
  17330. return this.get_type(name);
  17331. }
  17332. find_function(name) {
  17333. const key = name.qualifiedName();
  17334. return this._functions.get(key);
  17335. }
  17336. });
  17337. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17338. const ctrl = new torch._C.ControlFlowLoadStores();
  17339. ctrl.run(graph);
  17340. const exit_vars = new torch._C.LoopContinuations();
  17341. exit_vars.run(graph);
  17342. torch._C.InlineLoopCondition(graph);
  17343. const erase_loads_stores = new torch._C.EraseLoadStores();
  17344. erase_loads_stores.run(graph);
  17345. torch._C.TransformExits(graph);
  17346. });
  17347. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17348. /*
  17349. LoopView loop(n);
  17350. if (loop.loopType() != LoopView::ModifiedLoop) {
  17351. return;
  17352. }
  17353. const g = n.owningGraph();
  17354. WithInsertPoint node_insert(n);
  17355. const zero = g.insertConstant(0);
  17356. const one = g.insertConstant(1);
  17357. const max_trip_count = loop.maxTripCount();
  17358. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17359. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17360. const inp_condition = toIValue(loop.inputCond());
  17361. if (inp_condition == null || inp_condition.toBool() == false) {
  17362. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17363. }
  17364. loop.replaceInputCondition(condition);
  17365. n.addOutput().setType(IntType::get());
  17366. WithInsertPoint loop_insert(loop.bodyBlock());
  17367. n.addInput(zero);
  17368. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17369. // unset unique name for jitter, its replacement does not have a name
  17370. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17371. const inc_iter = g.insert(aten::add, {new_iter, one});
  17372. loop.bodyBlock().registerOutput(inc_iter);
  17373. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17374. const loop_continue = loop.nextCond();
  17375. const new_condition =
  17376. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17377. loop.bodyBlock().eraseOutput(0);
  17378. loop.bodyBlock().insertOutput(0, new_condition);
  17379. */
  17380. });
  17381. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17382. for (const n of block.nodes()) {
  17383. for (const b of n.blocks()) {
  17384. torch._C.canonicalizeModifiedLoops(b);
  17385. }
  17386. if (n.kind() === 'prim::Loop') {
  17387. torch._C.canonicalizeModifiedLoop(n);
  17388. }
  17389. }
  17390. });
  17391. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17392. torch._C.canonicalizeModifiedLoops(graph.block());
  17393. });
  17394. this.registerType('torch._C.MiniEnvironment', class {
  17395. constructor(b, next) {
  17396. this.next = next || null;
  17397. this.table = new Map();
  17398. }
  17399. setVar(name, value) {
  17400. this.table.set(name, value);
  17401. }
  17402. definedVariables() {
  17403. const result = Array.from(this.table.keys());
  17404. return result.sort();
  17405. }
  17406. findInThisFrame(name) {
  17407. if (this.table.has(name)) {
  17408. return this.table.get(name);
  17409. }
  17410. return null;
  17411. }
  17412. findInAnyFrame(name) {
  17413. /* eslint-disable consistent-this */
  17414. const self = this;
  17415. /* eslint-enable consistent-this */
  17416. for (let runner = self; runner; runner = runner.next) {
  17417. const r = runner.findInThisFrame(name);
  17418. if (r) {
  17419. return r;
  17420. }
  17421. }
  17422. return null;
  17423. }
  17424. });
  17425. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17426. });
  17427. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17428. });
  17429. this.registerType('torch._C.ControlFlowLoadStores', class {
  17430. constructor() {
  17431. this.environment_stack = null;
  17432. }
  17433. pushFrame(b) {
  17434. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17435. }
  17436. popFrame() {
  17437. const old_frame = this.environment_stack;
  17438. this.environment_stack = this.environment_stack.next;
  17439. return old_frame;
  17440. }
  17441. addBlockInput(b, type, name) {
  17442. const g = b.owningGraph();
  17443. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17444. }
  17445. addBlockOutput(exit_block, type, name) {
  17446. const insert = new torch._C.WithInsertPoint(exit_block);
  17447. const g = exit_block.owningGraph();
  17448. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17449. exit_block.registerOutput(block_exit);
  17450. insert.dispose();
  17451. }
  17452. addNodeOutput(n, type, name) {
  17453. const out = n.addOutput().setType(type);
  17454. if (torch._C.meaningfulName(name)) {
  17455. out.setDebugName(name);
  17456. }
  17457. const g = n.owningGraph();
  17458. g.createStore(name, out).insertAfter(n);
  17459. }
  17460. addNodeInput(n, type, name) {
  17461. const g = n.owningGraph();
  17462. const inp = g.createLoad(name, type).insertBefore(n).output();
  17463. n.addInput(inp);
  17464. }
  17465. addIfLoadStores(n) {
  17466. const [true_block, false_block] = n.blocks();
  17467. const true_vars = this.addControlFlowLoadStores(true_block);
  17468. const false_vars = this.addControlFlowLoadStores(false_block);
  17469. const mutated_variables = new Set();
  17470. for (const v of true_vars.definedVariables()) {
  17471. if (false_vars.findInAnyFrame(v)) {
  17472. mutated_variables.add(v);
  17473. }
  17474. }
  17475. for (const v of false_vars.definedVariables()) {
  17476. if (true_vars.findInAnyFrame(v)) {
  17477. mutated_variables.add(v);
  17478. }
  17479. }
  17480. for (const x of mutated_variables) {
  17481. const true_type = true_vars.findInAnyFrame(x);
  17482. const false_type = false_vars.findInAnyFrame(x);
  17483. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17484. this.addBlockOutput(true_block, true_type, x);
  17485. this.addBlockOutput(false_block, false_type, x);
  17486. this.addNodeOutput(n, unified, x);
  17487. }
  17488. }
  17489. addLoopLoadStores(n) {
  17490. const [body_block] = n.blocks();
  17491. const loop_vars = this.addControlFlowLoadStores(body_block);
  17492. for (const name of loop_vars.definedVariables()) {
  17493. const parent_type = this.environment_stack.findInAnyFrame(name);
  17494. if (!parent_type) {
  17495. continue;
  17496. }
  17497. const block_type = loop_vars.findInThisFrame(name);
  17498. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17499. this.addNodeInput(n, parent_type, name);
  17500. this.addBlockInput(body_block, unified_type, name);
  17501. this.addBlockOutput(body_block, block_type, name);
  17502. this.addNodeOutput(n, unified_type, name);
  17503. }
  17504. }
  17505. addControlFlowLoadStores(block) {
  17506. this.pushFrame(block);
  17507. for (const n of block.nodes()) {
  17508. switch (n.kind()) {
  17509. case 'prim::If': {
  17510. this.addIfLoadStores(n);
  17511. break;
  17512. }
  17513. case 'prim::Loop': {
  17514. this.addLoopLoadStores(n);
  17515. break;
  17516. }
  17517. case 'prim::Closure': {
  17518. for (const b of n.blocks()) {
  17519. this.addControlFlowLoadStores(b);
  17520. }
  17521. break;
  17522. }
  17523. case 'prim::Store': {
  17524. this.environment_stack.setVar(n.s('name'), n.input().type());
  17525. break;
  17526. }
  17527. case 'prim::ComprehensionScope': {
  17528. this.addControlFlowLoadStores(n.blocks()[0]);
  17529. break;
  17530. }
  17531. default: {
  17532. break;
  17533. }
  17534. }
  17535. }
  17536. return this.popFrame();
  17537. }
  17538. run(graph) {
  17539. this.addControlFlowLoadStores(graph.block());
  17540. }
  17541. });
  17542. this.registerType('torch._C.LoopContinuations', class {
  17543. constructor() {
  17544. this._graph = null;
  17545. this._false_val = null;
  17546. this._curr_loop = null;
  17547. }
  17548. assignExitContinuations(block) {
  17549. for (const n of block.nodes()) {
  17550. switch (n.kind()) {
  17551. case 'prim::If': {
  17552. this.assignExitContinuations(n.blocks()[0]);
  17553. this.assignExitContinuations(n.blocks()[1]);
  17554. break;
  17555. }
  17556. case 'prim::Closure': {
  17557. const closure_block = new torch._C.LoopContinuations();
  17558. closure_block.run(n.blocks()[0]);
  17559. break;
  17560. }
  17561. case 'prim::Loop': {
  17562. const prev_loop = this._curr_loop;
  17563. this._curr_loop = n;
  17564. this.assignExitContinuations(n.blocks()[0]);
  17565. this._curr_loop = prev_loop;
  17566. break;
  17567. }
  17568. case 'prim::ContinueStmt': {
  17569. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17570. const header_block = loop_continuation.addBlock();
  17571. const [, pre_header] = this._curr_loop.blocks();
  17572. header_block.cloneFrom(pre_header, (v) => v);
  17573. this.InlineBlockBeforeNode(n, header_block);
  17574. loop_continuation.addInput(header_block.outputs()[0]);
  17575. loop_continuation.eraseBlock(0);
  17576. this.addLoopCarriedOutputs(loop_continuation);
  17577. n.destroy();
  17578. break;
  17579. }
  17580. case 'prim::BreakStmt': {
  17581. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17582. loop_exit.addInput(this._false_val);
  17583. this.addLoopCarriedOutputs(loop_exit);
  17584. n.destroy();
  17585. break;
  17586. }
  17587. default: {
  17588. break;
  17589. }
  17590. }
  17591. }
  17592. }
  17593. run(...args) {
  17594. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17595. const [graph] = args;
  17596. this.run(graph.block());
  17597. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17598. const [b] = args;
  17599. {
  17600. this._graph = b.owningGraph();
  17601. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17602. this._false_val = this._graph.insertConstant(false);
  17603. guard.dispose();
  17604. }
  17605. this.assignExitContinuations(b);
  17606. } else {
  17607. throw new python.Error('Not implemented.');
  17608. }
  17609. }
  17610. });
  17611. this.registerType('torch._C.LoopView', class {
  17612. constructor(node) {
  17613. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17614. this._node = node;
  17615. }
  17616. bodyBlock() {
  17617. return this._node.blocks()[0];
  17618. }
  17619. nextCond() {
  17620. return this.bodyBlock().outputs()[0];
  17621. }
  17622. carriedOutputs() {
  17623. return this._node.outputs();
  17624. }
  17625. bodyCarriedInputs() {
  17626. return this.bodyBlock().inputs().slice(1);
  17627. }
  17628. bodyCarriedOutputs() {
  17629. return this.bodyBlock().outputs().slice(1);
  17630. }
  17631. });
  17632. this.registerType('torch._C.WithLoopStatus', class {
  17633. constructor(to_ir, new_status) {
  17634. this._to_ir = to_ir;
  17635. this._prev = this._to_ir._loop_status;
  17636. this._to_ir._loop_status = new_status;
  17637. }
  17638. dispose() {
  17639. this._to_ir._loop_status = this._prev;
  17640. }
  17641. });
  17642. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17643. for (const block_node of block.nodes()) {
  17644. block_node.moveBefore(before_node);
  17645. }
  17646. });
  17647. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  17648. if (args.length === 1 && args[0] instanceof torch.Block) {
  17649. const [block] = args;
  17650. for (const n of block.nodes()) {
  17651. for (const b of n.blocks()) {
  17652. torch._C.inlineLoopCondition(b);
  17653. }
  17654. if (n.kind() === 'prim::Loop') {
  17655. torch._C.inlineLoopCondition(n);
  17656. }
  17657. }
  17658. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  17659. const [n] = args;
  17660. const [body_block, pre_header] = n.blocks();
  17661. const temp_block = n.addBlock();
  17662. temp_block.cloneFrom(pre_header, (v) => v);
  17663. torch._C.InlineBlockBeforeNode(n, temp_block);
  17664. n.insertInput(1, temp_block.outputs()[0]);
  17665. n.eraseBlock(2);
  17666. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  17667. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  17668. n.eraseBlock(1);
  17669. } else {
  17670. throw new python.Error('Not implemented.');
  17671. }
  17672. });
  17673. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  17674. torch._C.inlineLoopCondition(graph.block());
  17675. });
  17676. this.registerType('torch._C.EraseLoadStores', class {
  17677. pushFrame(b) {
  17678. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  17679. }
  17680. popFrame() {
  17681. const old_frame = this.environment_stack;
  17682. this.environment_stack = this.environment_stack.next;
  17683. return old_frame;
  17684. }
  17685. eraseBlockLoadStores(block) {
  17686. this.pushFrame(block);
  17687. for (const n of block.nodes()) {
  17688. switch (n.kind()) {
  17689. case 'prim::Store': {
  17690. this.environment_stack.setVar(n.s('name'), n.input());
  17691. n.destroy();
  17692. break;
  17693. }
  17694. case 'prim::Load': {
  17695. const name = n.s('name');
  17696. const value = this.environment_stack.findInAnyFrame(name);
  17697. torch._C.TORCH_INTERNAL_ASSERT(value);
  17698. n.output().replaceAllUsesWith(value);
  17699. n.destroy();
  17700. break;
  17701. }
  17702. case 'prim::ComprehensionScope': {
  17703. const [body] = n.blocks();
  17704. this.eraseBlockLoadStores(body);
  17705. for (const body_node of body.nodes()) {
  17706. body_node.moveBefore(n);
  17707. }
  17708. n.destroy();
  17709. break;
  17710. }
  17711. default: {
  17712. for (const b of n.blocks()) {
  17713. this.eraseBlockLoadStores(b);
  17714. }
  17715. break;
  17716. }
  17717. }
  17718. }
  17719. this.popFrame();
  17720. }
  17721. run(graph) {
  17722. this.eraseBlockLoadStores(graph.block());
  17723. }
  17724. });
  17725. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  17726. });
  17727. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  17728. });
  17729. this.registerType('torch._C.ExitPair', class {
  17730. constructor(exit_v, exit_val_ref) {
  17731. const exit_vals = [];
  17732. for (const v of exit_val_ref) {
  17733. exit_vals.push(v);
  17734. }
  17735. if (exit_v.type() !== torch.BoolType.get()) {
  17736. throw new python.Error('Invalid exit value type.');
  17737. }
  17738. this.first = exit_v;
  17739. this.second = exit_vals;
  17740. }
  17741. hasExited() {
  17742. return this.first;
  17743. }
  17744. exitValues() {
  17745. return this.second;
  17746. }
  17747. });
  17748. this.registerType('torch._C.ExitTransformer', class {
  17749. constructor(graph) {
  17750. this._graph = graph;
  17751. this._target_block = null;
  17752. this._unit_values = new Map();
  17753. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  17754. this._true_val = this._graph.insertConstant(true);
  17755. this._false_val = this._graph.insertConstant(false);
  17756. this._throws_val = this.getUnitValue(torch.BoolType.get());
  17757. guard.dispose();
  17758. }
  17759. getUnitValue(type) {
  17760. const maybe_val = this._unit_values.get(type);
  17761. if (maybe_val) {
  17762. return maybe_val;
  17763. }
  17764. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  17765. this._unit_values.set(type, unit);
  17766. return unit;
  17767. }
  17768. transformReturnStmts() {
  17769. this._current_exit_kind = 'prim::ReturnStmt';
  17770. this.transformExits(this._graph.block());
  17771. }
  17772. transformLoopContinuations() {
  17773. this._current_exit_kind = 'prim::LoopContinuation';
  17774. this.transformExits(this._graph.block());
  17775. }
  17776. destroyNodeAfterExit(n) {
  17777. for (const output of n.outputs()) {
  17778. if (output.uses().length > 0) {
  17779. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  17780. }
  17781. }
  17782. n.destroy();
  17783. }
  17784. deleteAfterExitNodes(block, iter) {
  17785. const nodes = block.nodes();
  17786. if (iter === nodes.end()) {
  17787. return;
  17788. }
  17789. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  17790. for (const it of Array.from(nodes).reverse()) {
  17791. if (it === iter) {
  17792. break;
  17793. }
  17794. if (it !== block.return_node()) {
  17795. this.destroyNodeAfterExit(it);
  17796. }
  17797. }
  17798. this.destroyNodeAfterExit(iter);
  17799. insert.dispose();
  17800. }
  17801. updateTargetBlock(block) {
  17802. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  17803. this._target_block = block;
  17804. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  17805. this._target_block = block;
  17806. }
  17807. }
  17808. transformLoop(node) {
  17809. const loop = new torch._C.LoopView(node);
  17810. const body = loop.bodyBlock();
  17811. const exit_pair = this.transformExits(body);
  17812. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  17813. return this.constructWontExitPair();
  17814. }
  17815. const insert = new torch._C.WithInsertPoint(body);
  17816. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  17817. new_if.addInput(exit_pair.hasExited());
  17818. new_if.addBlock().registerOutput(this._false_val);
  17819. new_if.addBlock().registerOutput(loop.nextCond());
  17820. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  17821. loop.bodyBlock().eraseOutput(0);
  17822. loop.bodyBlock().insertOutput(0, new_condition);
  17823. node.addInput(this._false_val);
  17824. body.addInput().setType(torch.BoolType.get());
  17825. body.registerOutput(exit_pair.hasExited());
  17826. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  17827. for (const exit_value of exit_pair.exitValues()) {
  17828. const typ = exit_value.type();
  17829. node.addInput(this.getUnitValue(typ));
  17830. node.addOutput().setType(typ);
  17831. body.addInput().setType(typ);
  17832. body.registerOutput(exit_value);
  17833. }
  17834. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  17835. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  17836. insert.dispose();
  17837. return result;
  17838. }
  17839. calcIfExitStatus(then_status, else_status) {
  17840. if (then_status === 'THROWS') {
  17841. return else_status;
  17842. } else if (else_status === 'THROWS') {
  17843. return then_status;
  17844. }
  17845. if (then_status === 'WONT' && else_status === 'WONT') {
  17846. return 'WONT';
  17847. }
  17848. if (then_status === 'WILL' && else_status === 'WILL') {
  17849. return 'WILL';
  17850. }
  17851. return 'MIGHT';
  17852. }
  17853. transformIf(node) {
  17854. const [then_block, else_block] = node.blocks();
  17855. let then_pair = this.transformExits(then_block);
  17856. let else_pair = this.transformExits(else_block);
  17857. const then_status = this.getExitStatus(then_pair);
  17858. const else_status = this.getExitStatus(else_pair);
  17859. const if_status = this.calcIfExitStatus(then_status, else_status);
  17860. if (if_status === 'THROWS') {
  17861. return this.constructThrowsExitPair();
  17862. }
  17863. if (if_status === 'WONT') {
  17864. return this.constructWontExitPair();
  17865. }
  17866. if (then_status === 'WONT' || then_status === 'THROWS') {
  17867. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  17868. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  17869. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  17870. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  17871. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  17872. }
  17873. let has_exited = null;
  17874. if (if_status === 'WILL') {
  17875. has_exited = this._true_val;
  17876. } else {
  17877. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  17878. has_exited = node.outputs().at(node.outputs().length - 1);
  17879. }
  17880. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  17881. const num_exit_vals = then_pair.exitValues().size();
  17882. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  17883. return new torch._C.ExitPair(has_exited, exit_vals);
  17884. }
  17885. transformExits(block) {
  17886. const prev_target_block = this._target_block;
  17887. this.updateTargetBlock(block);
  17888. let exit_pair = this.constructWontExitPair();
  17889. for (const node of block.nodes()) {
  17890. const it = node.next;
  17891. switch (node.kind()) {
  17892. case 'prim::RaiseException': {
  17893. exit_pair = this.constructThrowsExitPair();
  17894. break;
  17895. }
  17896. case 'prim::ReturnStmt':
  17897. case 'prim::LoopContinuation': {
  17898. if (node.kind() === this._current_exit_kind) {
  17899. exit_pair = this.constructWillExitPair(node.inputs());
  17900. node.destroy();
  17901. }
  17902. break;
  17903. }
  17904. case 'prim::If': {
  17905. exit_pair = this.transformIf(node);
  17906. break;
  17907. }
  17908. case 'prim::With': {
  17909. exit_pair = this.transformWith(node);
  17910. break;
  17911. }
  17912. case 'prim::Closure': {
  17913. this.transformExits(node.blocks()[0]);
  17914. break;
  17915. }
  17916. case 'prim::Loop': {
  17917. exit_pair = this.transformLoop(node);
  17918. break;
  17919. }
  17920. default: {
  17921. break;
  17922. }
  17923. }
  17924. const status = this.getExitStatus(exit_pair);
  17925. if (status === 'WILL' || status === 'THROWS') {
  17926. this.deleteAfterExitNodes(block, it);
  17927. break;
  17928. }
  17929. if (status === 'MIGHT') {
  17930. throw new python.Error('Not implemented.');
  17931. // const nodes = block.nodes();
  17932. // if (node === nodes[nodes.length - 1]) {
  17933. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  17934. // }
  17935. // break;
  17936. }
  17937. }
  17938. if (this._target_block === block) {
  17939. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  17940. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  17941. new_if.addBlock();
  17942. new_if.addBlock();
  17943. new_if.addInput(exit_pair.hasExited());
  17944. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  17945. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  17946. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  17947. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  17948. }
  17949. exit_pair = this.constructWontExitPair();
  17950. }
  17951. this._target_block = prev_target_block;
  17952. return exit_pair;
  17953. }
  17954. constructThrowsExitPair() {
  17955. return new torch._C.ExitPair(this._throws_val, []);
  17956. }
  17957. constructWontExitPair() {
  17958. return new torch._C.ExitPair(this._false_val, []);
  17959. }
  17960. constructWillExitPair(exit_val_ref) {
  17961. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  17962. }
  17963. getExitStatus(exit_pair) {
  17964. const exit_v = exit_pair.hasExited();
  17965. if (exit_v === this._true_val) {
  17966. return 'WILL';
  17967. } else if (exit_v === this._false_val) {
  17968. return 'WONT';
  17969. } else if (exit_v === this._throws_val) {
  17970. return 'THROWS';
  17971. }
  17972. return 'MIGHT';
  17973. }
  17974. static owningNodeKind(block) {
  17975. if (block.owningNode()) {
  17976. return block.owningNode().kind();
  17977. }
  17978. return null;
  17979. }
  17980. static isGraphOrClosureBlock(block) {
  17981. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  17982. }
  17983. static removeOutputs(b) {
  17984. while (b.outputs().length > 0) {
  17985. b.eraseOutput(0);
  17986. }
  17987. }
  17988. static registerBlockOutputs(b, outs) {
  17989. for (const out of outs) {
  17990. b.registerOutput(out);
  17991. }
  17992. }
  17993. static replaceBlockOutputs(b, outs) {
  17994. torch._C.ExitTransformer.removeOutputs(b);
  17995. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  17996. }
  17997. });
  17998. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  17999. });
  18000. this.registerFunction('torch._C.TransformExits', (graph) => {
  18001. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18002. const e_loop = new torch._C.ExitTransformer(graph);
  18003. e_loop.transformLoopContinuations();
  18004. const e_ret = new torch._C.ExitTransformer(graph);
  18005. e_ret.transformReturnStmts();
  18006. torch._C.inlineConsecutiveIfs(graph.block());
  18007. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18008. });
  18009. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18010. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18011. const args = iter.inputs();
  18012. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18013. newSub.replaceInput(0, args[1]);
  18014. newSub.replaceInput(1, args[0]);
  18015. iter.destroyCurrent();
  18016. return true;
  18017. }
  18018. return false;
  18019. });
  18020. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18021. });
  18022. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18023. const args = iter.inputs();
  18024. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18025. if (iter.kind() === 'aten::__is__') {
  18026. iter.replaceWithNewSymbol('aten::eq');
  18027. iter.destroyCurrent();
  18028. return true;
  18029. }
  18030. if (iter.kind() === 'aten::__isnot__') {
  18031. iter.replaceWithNewSymbol('aten::ne');
  18032. iter.destroyCurrent();
  18033. return true;
  18034. }
  18035. }
  18036. return false;
  18037. });
  18038. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18039. for (const it of block.nodes()) {
  18040. for (const sub of it.blocks()) {
  18041. torch._C.NormalizeOps(sub);
  18042. }
  18043. if (torch._C.normalizeRSub(it)) {
  18044. continue;
  18045. }
  18046. if (torch._C.normalizeOpAliases(it)) {
  18047. continue;
  18048. }
  18049. if (torch._C.normalizeIsBool(it)) {
  18050. continue;
  18051. }
  18052. }
  18053. });
  18054. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18055. return false;
  18056. });
  18057. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18058. /*
  18059. torch._C.liftClosures(to_clean);
  18060. torch._C.inlineForkedClosures(to_clean);
  18061. */
  18062. if (torch._C.getInlineEverythingMode()) {
  18063. torch._C.Inline(to_clean);
  18064. }
  18065. /*
  18066. torch._C.eraseListLiterals(to_clean);
  18067. */
  18068. torch._C.LowerSimpleTuples(to_clean);
  18069. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18070. torch._C.ConstantPooling(to_clean);
  18071. /*
  18072. torch._C.CanonicalizeOutputs(to_clean);
  18073. torch._C.AnnotateWarns(to_clean);
  18074. */
  18075. });
  18076. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18077. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18078. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18079. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18080. constructor(cpp_module) {
  18081. super();
  18082. this._initializing = true;
  18083. this._c = cpp_module;
  18084. }
  18085. static _construct(cpp_module, init_fn) {
  18086. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18087. init_fn(script_module);
  18088. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18089. return script_module;
  18090. }
  18091. static _finalize_scriptmodule(script_module) {
  18092. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18093. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18094. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18095. script_module._initializing = false;
  18096. }
  18097. get graph() {
  18098. // return this._c._get_method('forward').graph;
  18099. return this._c.graph;
  18100. }
  18101. get code_with_constants() {
  18102. // return this.forward.code_with_constants;
  18103. return this._c.code_with_constants;
  18104. }
  18105. __setattr__(name, value) {
  18106. if (this._initializing) {
  18107. super.__setattr__(name, value);
  18108. } else if (this._modules.has(name)) {
  18109. this._modules.set(name, value);
  18110. } else if (this._c.hasattr(name)) {
  18111. this._c.setattr(name, value);
  18112. } else {
  18113. //
  18114. }
  18115. }
  18116. __getattr__(name) {
  18117. if (this._initializing) {
  18118. return super.__getattr__(name);
  18119. }
  18120. if (this._modules.has(name)) {
  18121. return this._modules.get(name);
  18122. }
  18123. if (this._c.hasattr(name)) {
  18124. return this._c.getattr(name);
  18125. }
  18126. if (this._c._has_method(name)) {
  18127. //
  18128. }
  18129. return super.__getattr__(name);
  18130. }
  18131. });
  18132. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18133. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18134. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18135. torch.CompilationUnit = torch.jit.CompilationUnit;
  18136. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18137. torch._C.ScriptModule = torch.ScriptModule;
  18138. torch._C.ClassType = torch.ClassType;
  18139. this.registerType('torch._C.FlatBuffersLoader', class {
  18140. constructor(cu) {
  18141. this._cu = cu;
  18142. const torch = cu.execution.__import__('torch');
  18143. this._torch = torch;
  18144. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18145. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18146. this._ivalue_parsers = new Map();
  18147. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18148. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18149. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18150. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18151. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18152. }
  18153. parseModule(module) {
  18154. this._module = module;
  18155. this._all_functions = new Map();
  18156. this._all_ivalues = new Array(module.ivalues.length);
  18157. this._all_types = new Array(module.object_types.length);
  18158. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18159. for (let i = 0; i < mobile_ivalue_size; i++) {
  18160. this.parseAndPopulate(i, module.ivalues[i]);
  18161. }
  18162. const m = this._all_ivalues[module.state_obj];
  18163. for (const [name, value] of this._all_functions) {
  18164. const class_index = module.ivalues[name].val.class_type;
  18165. const class_type = this._all_types[class_index];
  18166. if (value) {
  18167. class_type.addMethod(value);
  18168. }
  18169. }
  18170. m._min_operator_version = module.operator_version;
  18171. m._bytecode_version = module.bytecode_version;
  18172. return m;
  18173. }
  18174. parseAndPopulate(i, ivalue) {
  18175. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18176. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18177. } else {
  18178. this._all_ivalues[i] = this.parseIValue(ivalue);
  18179. }
  18180. }
  18181. parseFunction(/* val */) {
  18182. return null;
  18183. }
  18184. parseIValue(ivalue) {
  18185. if (ivalue.val) {
  18186. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18187. return callback(ivalue);
  18188. }
  18189. return null;
  18190. }
  18191. parseTensor(ivalue) {
  18192. return this.parseTensorFromMetadata(ivalue.val);
  18193. }
  18194. parseTensorFromMetadata(metadata) {
  18195. if (metadata.quantized_schema) {
  18196. throw new torch.Error('Quantized schema not implemented.');
  18197. }
  18198. const index = metadata.storage_location_index;
  18199. const data = this._module.storage_data[index].data;
  18200. const dtype = this._dtypes.get(metadata.scalar_type);
  18201. const size = data.length / dtype.itemsize();
  18202. const storage = new torch.storage.TypedStorage(size, dtype);
  18203. storage._set_cdata(data);
  18204. const tensor = new torch.Tensor();
  18205. const shape = Array.from(metadata.sizes);
  18206. const stride = Array.from(metadata.strides);
  18207. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18208. return tensor;
  18209. }
  18210. parseObject(ivalue) {
  18211. const object = ivalue.val;
  18212. const obj_type = this._module.object_types[object.type_index];
  18213. const cls = this.getOrCreateClassTypeForObject(object);
  18214. switch (obj_type.type) {
  18215. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18216. const torch = this._torch;
  18217. const obj = torch.ScriptObject.create(cls);
  18218. for (let i = 0; i < object.attrs.length; i++) {
  18219. const attr_name = obj_type.attr_names[i];
  18220. const val = this._all_ivalues[object.attrs[i]];
  18221. obj.__setattr__(attr_name, val);
  18222. }
  18223. return obj;
  18224. }
  18225. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18226. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18227. default: {
  18228. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18229. }
  18230. }
  18231. }
  18232. getOrCreateClassTypeForObject(object) {
  18233. let cls = this._all_types[object.type_index];
  18234. const obj_type = this._module.object_types[object.type_index];
  18235. if (!cls) {
  18236. const name = obj_type.type_name;
  18237. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18238. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18239. if (!cls) {
  18240. const torch = this._torch;
  18241. cls = torch.ClassType.create(name, this._cu, true);
  18242. this._cu.register_type(cls);
  18243. }
  18244. } else {
  18245. // cls = c10::parseType(qn_str).cast<ClassType>();
  18246. }
  18247. this._all_types[object.type_index] = cls;
  18248. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18249. for (let i = 0; i < object.attrs.length; i++) {
  18250. // const val = this._all_ivalues[object.attrs[i]];
  18251. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18252. }
  18253. }
  18254. }
  18255. return cls;
  18256. }
  18257. });
  18258. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18259. constructor(export_module, flat_args_adapter) {
  18260. super();
  18261. const export_graph = copy.deepcopy(export_module.graph);
  18262. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18263. this.graph = torch.fx.Graph();
  18264. this.graph.owning_module = this;
  18265. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18266. this.flat_args_adapter = flat_args_adapter;
  18267. this.adapted = false;
  18268. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18269. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18270. }
  18271. });
  18272. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18273. constructor(input_specs, output_specs) {
  18274. this.input_specs = input_specs;
  18275. this.output_specs = output_specs;
  18276. }
  18277. get user_inputs() {
  18278. const user_inputs = [];
  18279. for (const s of this.input_specs) {
  18280. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18281. continue;
  18282. }
  18283. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18284. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18285. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18286. user_inputs.push(s.arg.name);
  18287. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18288. user_inputs.push(s.arg.value);
  18289. } else {
  18290. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18291. }
  18292. }
  18293. return user_inputs;
  18294. }
  18295. get user_outputs() {
  18296. const user_outputs = [];
  18297. for (const s of this.output_specs) {
  18298. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18299. continue;
  18300. }
  18301. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18302. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18303. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18304. user_outputs.push(s.arg.name);
  18305. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18306. user_outputs.push(s.arg.value);
  18307. } else {
  18308. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18309. }
  18310. }
  18311. return user_outputs;
  18312. }
  18313. get inputs_to_parameters() {
  18314. return new Map(this.input_specs
  18315. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18316. .map((s) => [s.arg.name, s.target]));
  18317. }
  18318. get inputs_to_buffers() {
  18319. return new Map(this.input_specs
  18320. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18321. .map((s) => [s.arg.name, s.target]));
  18322. }
  18323. get inputs_to_lifted_tensor_constants() {
  18324. return new Map(this.input_specs
  18325. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18326. .map((s) => [s.arg.name, s.target]));
  18327. }
  18328. });
  18329. torch.export.graph_signature.InputKind = {
  18330. USER_INPUT: 0,
  18331. PARAMETER: 1,
  18332. BUFFER: 2,
  18333. CONSTANT_TENSOR: 3,
  18334. CUSTOM_OBJ: 4,
  18335. TOKEN: 5
  18336. };
  18337. this.registerType('torch.export.graph_signature.InputSpec', class {
  18338. constructor(kind, arg, target, persistent) {
  18339. this.kind = kind;
  18340. this.arg = arg;
  18341. this.target = target;
  18342. this.persistent = persistent || null;
  18343. }
  18344. });
  18345. torch.export.graph_signature.OutputKind = {
  18346. USER_OUTPUT: 0,
  18347. LOSS_OUTPUT: 1,
  18348. BUFFER_MUTATION: 2,
  18349. GRADIENT_TO_PARAMETER: 3,
  18350. GRADIENT_TO_USER_INPUT: 4,
  18351. USER_INPUT_MUTATION: 5,
  18352. TOKEN: 6
  18353. };
  18354. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18355. constructor(kind, arg, target) {
  18356. this.kind = kind;
  18357. this.arg = arg;
  18358. this.target = target;
  18359. }
  18360. });
  18361. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18362. constructor(name, value) {
  18363. this.name = name;
  18364. this.value = value; // Union[int, float, bool, str, None]
  18365. }
  18366. });
  18367. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18368. constructor(name) {
  18369. this.name = name;
  18370. }
  18371. });
  18372. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18373. constructor(name) {
  18374. this.name = name;
  18375. }
  18376. });
  18377. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18378. constructor(name, class_fqn, fake_val) {
  18379. this.name = name;
  18380. this.class_fqn = class_fqn;
  18381. this.fake_val = fake_val;
  18382. }
  18383. });
  18384. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18385. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18386. // graph._codegen = torch.fx.graph.CodeGen()
  18387. this._graph_module = this._create_graph_module_for_export(root, graph);
  18388. if (root instanceof torch.fx.GraphModule) {
  18389. // this._graph_module.meta.update(root.meta);
  18390. }
  18391. this._graph_signature = graph_signature;
  18392. this._state_dict = state_dict;
  18393. this._range_constraints = range_constraints;
  18394. this._module_call_graph = module_call_graph;
  18395. this._example_inputs = example_inputs;
  18396. this._constants = tensor_constants || constants || {};
  18397. }
  18398. _create_graph_module_for_export(root, graph) {
  18399. let gm = null;
  18400. try {
  18401. gm = new torch.fx.GraphModule(root, graph);
  18402. } catch {
  18403. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18404. gm._graph = graph;
  18405. }
  18406. return gm;
  18407. }
  18408. get graph_module() {
  18409. return this._graph_module;
  18410. }
  18411. get graph() {
  18412. return this._graph_module.graph;
  18413. }
  18414. get graph_signature() {
  18415. return this._graph_signature;
  18416. }
  18417. get state_dict() {
  18418. return this._state_dict;
  18419. }
  18420. get constants() {
  18421. return this._constants;
  18422. }
  18423. });
  18424. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18425. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18426. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18427. module = torch.export._remove_effect_tokens(module);
  18428. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18429. });
  18430. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18431. return new torch.fx.graph_module.GraphModule(root, graph);
  18432. });
  18433. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18434. constructor(exported_program, state_dict, constants, example_inputs) {
  18435. this.exported_program = exported_program;
  18436. this.state_dict = state_dict;
  18437. this.constants = constants;
  18438. this.example_inputs = example_inputs;
  18439. }
  18440. });
  18441. torch._export.serde.serialize._SYM_OPS = new Set([
  18442. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18443. operator.neg, operator.pos, operator.and_, operator.or_,
  18444. math.trunc, torch.sym_not,
  18445. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18446. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18447. operator.truediv, operator.and_
  18448. ]);
  18449. this.registerType('torch._export.serde.union._Union', class {
  18450. constructor(obj) {
  18451. if (obj.$type) {
  18452. this.type = obj.$type;
  18453. this[obj.$type] = obj.$value;
  18454. delete obj.$type;
  18455. delete obj.$value;
  18456. } else if (obj.type) {
  18457. this.type = obj.type;
  18458. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18459. this[obj.type] = Object.fromEntries(entries);
  18460. } else {
  18461. let entries = Object.entries(obj);
  18462. if (entries.length > 1) {
  18463. entries = entries.filter(([, value]) => value !== null);
  18464. }
  18465. if (entries.length !== 1) {
  18466. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18467. }
  18468. const [entry] = entries;
  18469. const [type, value] = entry;
  18470. this.type = type;
  18471. this[type] = value;
  18472. }
  18473. }
  18474. get value() {
  18475. return this[this.type];
  18476. }
  18477. });
  18478. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18479. constructor(obj) {
  18480. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18481. this.name = obj.name;
  18482. }
  18483. });
  18484. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18485. constructor(obj) {
  18486. super(obj);
  18487. switch (this.type) {
  18488. case 'as_int':
  18489. case 'as_ints':
  18490. case 'as_float':
  18491. case 'as_floats':
  18492. case 'as_bool':
  18493. case 'as_bools':
  18494. case 'as_string':
  18495. case 'as_strings':
  18496. case 'as_scalar_type':
  18497. case 'as_device':
  18498. case 'as_memory_format':
  18499. case 'as_layout':
  18500. break;
  18501. case 'as_none':
  18502. this.as_none = null;
  18503. break;
  18504. case 'as_tensor':
  18505. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18506. break;
  18507. case 'as_tensors':
  18508. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18509. break;
  18510. case 'as_graph':
  18511. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18512. break;
  18513. case 'as_sym_int':
  18514. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18515. break;
  18516. case 'as_sym_ints':
  18517. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18518. break;
  18519. case 'as_sym_bool':
  18520. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18521. break;
  18522. case 'as_sym_bools':
  18523. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18524. break;
  18525. case 'as_sym_float':
  18526. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18527. break;
  18528. case 'as_sym_floats':
  18529. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18530. break;
  18531. case 'as_optional_tensors':
  18532. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18533. break;
  18534. case 'as_custom_obj':
  18535. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18536. break;
  18537. // case 'as_graph': GraphArgument
  18538. default:
  18539. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18540. }
  18541. }
  18542. });
  18543. this.registerType('torch._export.serde.schema.Node', class {
  18544. constructor(obj) {
  18545. this.target = obj.target;
  18546. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18547. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18548. this.metadata = new Map(Object.entries(obj.metadata));
  18549. }
  18550. });
  18551. torch._export.serde.schema.ScalarType = {
  18552. UNKNOWN: 0,
  18553. BYTE: 1,
  18554. CHAR: 2,
  18555. SHORT: 3,
  18556. INT: 4,
  18557. LONG: 5,
  18558. HALF: 6,
  18559. FLOAT: 7,
  18560. DOUBLE: 8,
  18561. COMPLEXHALF: 9,
  18562. COMPLEXFLOAT: 10,
  18563. COMPLEXDOUBLE: 11,
  18564. BOOL: 12,
  18565. BFLOAT16: 13
  18566. };
  18567. torch._export.serde.schema.Layout = {
  18568. Unknown: 0,
  18569. SparseCoo: 1,
  18570. SparseCsr: 2,
  18571. SparseCsc: 3,
  18572. SparseBsr: 4,
  18573. SparseBsc: 5,
  18574. _mkldnn: 6,
  18575. Strided: 7
  18576. };
  18577. torch._export.serde.schema.MemoryFormat = {
  18578. Unknown: 0,
  18579. ContiguousFormat: 1,
  18580. ChannelsLast: 2,
  18581. ChannelsLast3d: 3,
  18582. PreserveFormat: 4,
  18583. };
  18584. this.registerType('torch._export.serde.schema.Device', class {
  18585. constructor(obj) {
  18586. Object.assign(this, { ...obj });
  18587. }
  18588. });
  18589. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18590. constructor(obj) {
  18591. obj = obj.meta || obj;
  18592. this.dtype = obj.dtype;
  18593. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18594. this.requires_grad = obj.requires_grad;
  18595. this.device = obj.device;
  18596. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18597. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18598. this.layout = obj.layout;
  18599. }
  18600. });
  18601. this.registerType('torch._export.serde.schema.Graph', class {
  18602. constructor(obj) {
  18603. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18604. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18605. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18606. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18607. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18608. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18609. this.is_single_tensor_return = obj.is_single_tensor_return;
  18610. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18611. if (obj.contants) {
  18612. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18613. // graph_signature -> input_specs -> tensor_constant
  18614. }
  18615. }
  18616. });
  18617. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18618. constructor(obj) {
  18619. Object.assign(this, { ...obj });
  18620. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18621. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18622. }
  18623. });
  18624. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18625. constructor(obj) {
  18626. Object.assign(this, { ...obj });
  18627. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18628. }
  18629. });
  18630. this.registerType('torch._export.serde.schema.GraphModule', class {
  18631. constructor(obj) {
  18632. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18633. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18634. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18635. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18636. }
  18637. });
  18638. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  18639. constructor(obj) {
  18640. Object.assign(this, { ...obj });
  18641. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  18642. }
  18643. });
  18644. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  18645. this.registerType('torch._export.serde.schema.SymExpr', class {
  18646. constructor(obj) {
  18647. this.expr_str = obj.expr_str;
  18648. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  18649. }
  18650. });
  18651. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  18652. constructor(obj) {
  18653. super(obj);
  18654. if (this.type === 'as_int') {
  18655. // continue
  18656. } else if (this.type === 'as_expr') {
  18657. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18658. } else {
  18659. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  18660. }
  18661. }
  18662. });
  18663. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  18664. constructor(obj) {
  18665. super(obj);
  18666. if (this.type === 'as_bool') {
  18667. // continue
  18668. } else if (this.type === 'as_expr') {
  18669. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18670. } else {
  18671. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  18672. }
  18673. }
  18674. });
  18675. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  18676. constructor(obj) {
  18677. super(obj);
  18678. Object.assign(this, { ...obj });
  18679. }
  18680. });
  18681. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  18682. constructor(obj) {
  18683. super(obj);
  18684. Object.assign(this, { ...obj });
  18685. }
  18686. });
  18687. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  18688. constructor(obj) {
  18689. super(obj);
  18690. Object.assign(this, { ...obj });
  18691. }
  18692. });
  18693. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  18694. constructor(obj) {
  18695. Object.assign(this, { ...obj });
  18696. }
  18697. });
  18698. this.registerType('torch._export.serde.schema.GraphSignature', class {
  18699. constructor(obj) {
  18700. this.input_specs = [];
  18701. if (Array.isArray(obj.input_specs)) {
  18702. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  18703. }
  18704. if (Array.isArray(obj.user_inputs)) {
  18705. for (const user_input of obj.user_inputs) {
  18706. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  18707. }
  18708. }
  18709. if (obj.inputs_to_parameters) {
  18710. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  18711. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  18712. }
  18713. }
  18714. this.output_specs = [];
  18715. if (Array.isArray(obj.output_specs)) {
  18716. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  18717. }
  18718. }
  18719. });
  18720. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  18721. constructor(obj) {
  18722. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18723. }
  18724. });
  18725. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  18726. constructor(obj) {
  18727. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18728. this.parameter_name = obj.parameter_name;
  18729. }
  18730. });
  18731. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  18732. constructor(obj) {
  18733. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18734. this.buffer_name = obj.buffer_name;
  18735. }
  18736. });
  18737. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  18738. constructor(obj) {
  18739. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18740. this.tensor_constant_name = obj.tensor_constant_name;
  18741. }
  18742. });
  18743. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  18744. constructor(obj) {
  18745. this.name = obj.name;
  18746. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  18747. }
  18748. });
  18749. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  18750. constructor(obj) {
  18751. super(obj);
  18752. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  18753. // continue
  18754. } else if (this.type === 'as_none') {
  18755. this.as_none = null;
  18756. } else {
  18757. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  18758. }
  18759. }
  18760. });
  18761. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  18762. constructor(obj) {
  18763. super(obj);
  18764. if (this.type === 'user_input') {
  18765. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  18766. } else if (this.type === 'parameter') {
  18767. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  18768. } else if (this.type === 'buffer') {
  18769. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  18770. } else if (this.type === 'tensor_constant') {
  18771. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  18772. } else if (this.type === 'constant_input') {
  18773. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  18774. } else {
  18775. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  18776. }
  18777. /*
  18778. custom_obj: InputToCustomObjSpec
  18779. token: InputTokenSpec
  18780. */
  18781. }
  18782. });
  18783. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  18784. constructor(obj) {
  18785. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18786. }
  18787. });
  18788. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  18789. constructor(obj) {
  18790. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18791. this.buffer_name = obj.buffer_name;
  18792. }
  18793. });
  18794. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  18795. constructor(obj) {
  18796. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18797. this.parameter_name = obj.parameter_name;
  18798. }
  18799. });
  18800. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  18801. constructor(obj) {
  18802. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18803. this.user_input_name = obj.user_input_name;
  18804. }
  18805. });
  18806. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  18807. constructor(obj) {
  18808. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18809. this.user_input_name = obj.user_input_name;
  18810. }
  18811. });
  18812. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  18813. constructor(obj) {
  18814. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  18815. }
  18816. });
  18817. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  18818. constructor(obj) {
  18819. super(obj);
  18820. if (this.type === 'user_output') {
  18821. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  18822. } else if (this.type === 'loss_output') {
  18823. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  18824. } else if (this.type === 'buffer_mutation') {
  18825. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  18826. } else if (this.type === 'gradient_to_parameter') {
  18827. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  18828. } else if (this.type === 'gradient_to_user_input') {
  18829. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  18830. } else if (this.type === 'user_input_mutation') {
  18831. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  18832. } else if (this.type === 'token') {
  18833. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  18834. }
  18835. }
  18836. });
  18837. this.registerType('torch._export.serde.schema.TensorArgument', class {
  18838. constructor(obj) {
  18839. this.name = obj.name;
  18840. }
  18841. });
  18842. this.registerType('torch._export.serde.schema.TokenArgument', class {
  18843. constructor(obj) {
  18844. this.name = obj.name;
  18845. }
  18846. });
  18847. this.registerType('torch._export.serde.schema.GraphArgument', class {
  18848. constructor(obj) {
  18849. this.name = obj.name;
  18850. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18851. }
  18852. });
  18853. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  18854. constructor(obj) {
  18855. super(obj);
  18856. if (this.type === 'as_tensor') {
  18857. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  18858. } else if (this.type === 'as_none') {
  18859. this.as_none = null;
  18860. } else {
  18861. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  18862. }
  18863. }
  18864. });
  18865. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  18866. const exported_programs = new Map();
  18867. for (const name of f.keys()) {
  18868. const match = name.match(/^models\/([^/]+)\.json$/);
  18869. if (match) {
  18870. const [, model_name] = match;
  18871. const serialized_exported_program = f.get(`models/${model_name}.json`);
  18872. const serialized_state_dict = f.get(`data/weights/${model_name}.pt`);
  18873. const serialized_constants = f.get(`data/constants/${model_name}.pt`);
  18874. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`);
  18875. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  18876. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  18877. exported_programs.set(model_name, exported_program);
  18878. }
  18879. }
  18880. return { exported_programs };
  18881. });
  18882. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  18883. if (data === null) {
  18884. return data;
  18885. }
  18886. if (cls) {
  18887. return new cls(data);
  18888. }
  18889. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  18890. });
  18891. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  18892. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  18893. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  18894. });
  18895. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  18896. constructor(expected_opset_version) {
  18897. this.expected_opset_version = expected_opset_version;
  18898. }
  18899. deserialize(exported_program, state_dict, constants, example_inputs) {
  18900. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  18901. /*
  18902. symbol_name_to_range = {
  18903. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  18904. for k, v in exported_program.range_constraints.items()
  18905. }
  18906. */
  18907. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  18908. const res = deserializer.deserialize(
  18909. exported_program.graph_module,
  18910. state_dict,
  18911. constants,
  18912. example_inputs,
  18913. symbol_name_to_range);
  18914. const range_constraints = null;
  18915. /*
  18916. range_constraints = self.deserialize_range_constraints(
  18917. symbol_name_to_range, res.names_to_symbols,
  18918. )
  18919. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  18920. self._validate_model_opset_version(model_opset_version)
  18921. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  18922. */
  18923. return new torch.export.exported_program.ExportedProgram(
  18924. res.graph_module, res.graph_module.graph, res.signature,
  18925. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  18926. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  18927. res.constants);
  18928. // return upgrader.upgrade(exported_program)
  18929. }
  18930. });
  18931. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  18932. if (!serialized) {
  18933. return new builtins.dict();
  18934. }
  18935. const artifact = torch.load(serialized);
  18936. return artifact;
  18937. });
  18938. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  18939. constructor() {
  18940. this.serialized_name_to_node = new Map();
  18941. this.serialized_name_to_meta = new Map();
  18942. this.graph = new torch.fx.Graph();
  18943. this.module = new torch.nn.Module();
  18944. }
  18945. deserialize_graph_output(output) {
  18946. if (output.type === 'as_tensor') {
  18947. return this.serialized_name_to_node.get(output.as_tensor.name);
  18948. } else if (output.type === 'as_sym_int') {
  18949. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  18950. } else if (output.type === 'as_sym_bool') {
  18951. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  18952. } else if (output.type === 'as_int') {
  18953. return this.serialized_name_to_node.get(output.as_int.as_name);
  18954. } else if (output.type === 'as_none') {
  18955. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  18956. }
  18957. throw new python.Error(`Unsupported graph node ${output.type}.`);
  18958. }
  18959. deserialize_graph(serialized_graph) {
  18960. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  18961. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  18962. this.serialized_name_to_meta.set(name, meta_val);
  18963. }
  18964. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  18965. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  18966. }
  18967. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  18968. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  18969. }
  18970. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  18971. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  18972. }
  18973. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  18974. const input = serialized_graph.inputs[i];
  18975. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  18976. const node_name = input.value.name;
  18977. const placeholder_node = this.graph.placeholder(node_name);
  18978. placeholder_node.name = node_name;
  18979. this.sync_fx_node(node_name, placeholder_node);
  18980. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  18981. const node_name = this.signature.input_specs[i].arg.name;
  18982. const placeholder_node = this.graph.placeholder(node_name);
  18983. placeholder_node.meta.set('val', this.deserialize_input(input));
  18984. } else {
  18985. throw new python.Error(`Invalid input ${input.type}.`);
  18986. }
  18987. }
  18988. for (const serialized_node of serialized_graph.nodes) {
  18989. const target = this.deserialize_operator(serialized_node.target);
  18990. this.deserialize_node(serialized_node, target);
  18991. }
  18992. let outputs = [];
  18993. for (const output of serialized_graph.outputs) {
  18994. outputs.push(this.deserialize_graph_output(output));
  18995. }
  18996. if (serialized_graph.is_single_tensor_return) {
  18997. [outputs] = outputs;
  18998. } else {
  18999. outputs = new builtins.tuple(outputs);
  19000. }
  19001. const output_node = this.graph.output(outputs);
  19002. if (serialized_graph.is_single_tensor_return) {
  19003. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19004. } else {
  19005. /* output_node.meta['val'] = tuple(
  19006. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19007. for arg in output_node.args[0]
  19008. ) */
  19009. }
  19010. return self.graph;
  19011. }
  19012. deserialize_operator(serialized_target) {
  19013. let module = null;
  19014. let serialized_target_names = null;
  19015. if (serialized_target.startsWith('_operator')) {
  19016. module = operator;
  19017. serialized_target_names = serialized_target.split('.').slice(1);
  19018. } else if (serialized_target.startsWith('torch')) {
  19019. module = torch;
  19020. serialized_target_names = serialized_target.split('.').slice(1);
  19021. } else if (serialized_target.startsWith('#')) {
  19022. return self.deserialize_extension_operator(serialized_target);
  19023. } else {
  19024. return serialized_target;
  19025. }
  19026. let target = module;
  19027. for (const name of serialized_target_names) {
  19028. target = builtins.getattr(target, name);
  19029. if (!target) {
  19030. return serialized_target;
  19031. }
  19032. }
  19033. return target;
  19034. }
  19035. deserialize_node(serialized_node, target) {
  19036. let fx_node = null;
  19037. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19038. const name = serialized_node.outputs[0].value.as_name;
  19039. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19040. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19041. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19042. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19043. // 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.')
  19044. const [output] = serialized_node.outputs;
  19045. const name = output.type === 'as_tensor' ? output.value.name : null;
  19046. const args = serialized_node.inputs.map((input) => this.deserialize_input(input.arg));
  19047. fx_node = this.graph.create_node('call_function', target, args, {}, name);
  19048. if (output.as_tensor !== null) {
  19049. this.sync_fx_node(name, fx_node);
  19050. }
  19051. if (output.as_tensors !== null) {
  19052. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19053. }
  19054. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19055. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19056. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19057. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19058. this.deserialize_outputs(serialized_node, fx_node);
  19059. } else {
  19060. throw new python.Error(`Unsupported node target type '${target}'.`);
  19061. }
  19062. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19063. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19064. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19065. }
  19066. }
  19067. deserialize_input_spec(i) {
  19068. if (i.type === 'user_input') {
  19069. return new torch.export.graph_signature.InputSpec(
  19070. torch.export.graph_signature.InputKind.USER_INPUT,
  19071. this.deserialize_argument_spec(i.user_input.arg),
  19072. null);
  19073. } else if (i.type === 'parameter') {
  19074. return new torch.export.graph_signature.InputSpec(
  19075. torch.export.graph_signature.InputKind.PARAMETER,
  19076. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19077. i.parameter.parameter_name,
  19078. );
  19079. } else if (i.type === 'buffer') {
  19080. return new torch.export.graph_signature.InputSpec(
  19081. torch.export.graph_signature.InputKind.BUFFER,
  19082. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19083. i.buffer.buffer_name,
  19084. i.buffer.persistent,
  19085. );
  19086. } else if (i.type === 'tensor_constant') {
  19087. return new torch.export.graph_signature.InputSpec(
  19088. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19089. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19090. i.tensor_constant.tensor_constant_name);
  19091. } else if (i.type === 'custom_obj') {
  19092. return new torch.export.graph_signature.InputSpec(
  19093. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19094. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19095. i.custom_obj.custom_obj_name);
  19096. } else if (i.type === 'token') {
  19097. return new torch.export.graph_signature.InputSpec(
  19098. torch.export.graph_signature.InputKind.TOKEN,
  19099. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19100. null);
  19101. } else if (i.type === 'constant_input') {
  19102. return new torch.export.graph_signature.InputSpec(
  19103. torch.export.graph_signature.InputKind.USER_INPUT,
  19104. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19105. null);
  19106. }
  19107. throw new python.Error(`Unknown input spec ${i}`);
  19108. }
  19109. deserialize_constant_input(inp) {
  19110. if (inp.type === 'as_int') {
  19111. return inp.as_int;
  19112. } else if (inp.type === 'as_float') {
  19113. return inp.as_float;
  19114. } else if (inp.type === 'as_string') {
  19115. return inp.as_string;
  19116. } else if (inp.type === 'as_bool') {
  19117. return inp.as_bool;
  19118. } else if (inp.type === 'as_none') {
  19119. return null;
  19120. }
  19121. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19122. }
  19123. deserialize_output_spec(o) {
  19124. if (o.type === 'user_output') {
  19125. return new torch.export.graph_signature.OutputSpec(
  19126. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19127. this.deserialize_argument_spec(o.user_output.arg),
  19128. null);
  19129. } else if (o.type === 'loss_output') {
  19130. return new torch.export.graph_signature.OutputSpec(
  19131. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19132. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19133. null);
  19134. } else if (o.type === 'buffer_mutation') {
  19135. return new torch.export.graph_signature.OutputSpec(
  19136. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19137. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19138. o.buffer_mutation.buffer_name);
  19139. } else if (o.type === 'gradient_to_parameter') {
  19140. return new torch.export.graph_signature.OutputSpec(
  19141. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19142. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19143. o.gradient_to_parameter.parameter_name);
  19144. } else if (o.type === 'gradient_to_user_input') {
  19145. return new torch.export.graph_signature.OutputSpec(
  19146. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19147. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19148. o.gradient_to_user_input.user_input_name);
  19149. } else if (o.type === 'user_input_mutation') {
  19150. return new torch.export.graph_signature.OutputSpec(
  19151. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19152. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19153. o.user_input_mutation.user_input_name);
  19154. } else if (o.type === 'token') {
  19155. return new torch.export.graph_signature.OutputSpec(
  19156. torch.export.graph_signature.OutputKind.TOKEN,
  19157. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19158. null);
  19159. }
  19160. throw new python.Error(`Unknown output spec ${o}.`);
  19161. }
  19162. deserialize_signature(sig) {
  19163. return new torch.export.graph_signature.ExportGraphSignature(
  19164. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19165. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19166. }
  19167. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19168. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19169. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19170. this.sympy_functions = new Map([
  19171. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19172. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19173. ['Where', torch.utils._sympy.functions.Where],
  19174. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19175. ['Mod', torch.utils._sympy.functions.Mod],
  19176. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19177. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19178. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19179. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19180. ['LShift', torch.utils._sympy.functions.LShift],
  19181. ['RShift', torch.utils._sympy.functions.RShift],
  19182. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19183. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19184. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19185. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19186. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19187. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19188. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19189. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19190. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19191. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19192. ['Identity', torch.utils._sympy.functions.Identity],
  19193. ]);
  19194. this.symbol_name_to_symbol = new Map();
  19195. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19196. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19197. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19198. /*
  19199. if symbol_name_to_range:
  19200. for k, vr in symbol_name_to_range.items():
  19201. lower = int(vr.lower)
  19202. if vr.upper >= 2: # max is >= 2, not sym bool range
  19203. lower = max(2, lower)
  19204. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19205. */
  19206. this.example_inputs = null;
  19207. if (example_inputs && example_inputs.length > 0) {
  19208. torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19209. }
  19210. this.deserialize_graph(serialized_graph_module.graph);
  19211. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19212. return {
  19213. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19214. signature: this.signature,
  19215. module_call_graph,
  19216. names_to_symbols: this.symbol_name_to_symbol,
  19217. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19218. constants: this.constants,
  19219. example_inputs: this.example_inputs,
  19220. };
  19221. }
  19222. sync_fx_node(name, fx_node) {
  19223. if (this.serialized_name_to_node.has(name)) {
  19224. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19225. }
  19226. this.serialized_name_to_node.set(name, fx_node);
  19227. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19228. }
  19229. deserialize_sym_op_inputs(inputs) {
  19230. return inputs.map((input) => this.deserialize_input(input.arg));
  19231. }
  19232. deserialize_inputs(target, serialized_node) {
  19233. const schema_args = this._get_schema_from_target(target).arguments;
  19234. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19235. const args = new builtins.list();
  19236. const kwargs = new builtins.dict();
  19237. for (const schema_arg of schema_args) {
  19238. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19239. if (is_positional) {
  19240. args.push(actual_args.get(schema_arg.name));
  19241. } else if (actual_args.has(schema_arg.name)) {
  19242. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19243. }
  19244. }
  19245. return [args, kwargs];
  19246. }
  19247. deserialize_input(inp) {
  19248. const value = inp.value;
  19249. const typ_ = inp.type;
  19250. if (typ_ === 'as_none') {
  19251. return null;
  19252. } else if (typ_ === 'as_tensor') {
  19253. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19254. } else if (typ_ === 'as_scalar_type') {
  19255. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[inp.as_scalar_type];
  19256. } else if (typ_ === 'as_memory_format') {
  19257. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19258. } else if (typ_ === 'as_layout') {
  19259. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19260. } else if (typ_ === 'as_graph') {
  19261. /* assert isinstance(value, GraphArgument)
  19262. with this.save_graph_module():
  19263. this.deserialize_graph(value.graph)
  19264. submodule = ep._create_graph_module_for_export(this.module, this.graph)
  19265. this.module.register_module(value.name, submodule)
  19266. return this.graph.create_node(
  19267. 'get_attr',
  19268. value.name,
  19269. name=value.name,
  19270. )*/
  19271. } else if (typ_ === 'as_device') {
  19272. return this.deserialize_device(inp.as_device);
  19273. } else if (typ_ === 'as_int') {
  19274. return inp.as_int;
  19275. } else if (typ_ === 'as_float') {
  19276. return inp.as_float;
  19277. } else if (typ_ === 'as_bool') {
  19278. return inp.as_bool;
  19279. } else if (typ_ === 'as_string') {
  19280. return inp.as_string;
  19281. } else if (typ_ === 'as_sym_int') {
  19282. return this.deserialize_sym_argument(inp.as_sym_int);
  19283. } else if (typ_ === 'as_sym_float') {
  19284. return this.deserialize_sym_argument(inp.as_sym_float);
  19285. } else if (typ_ === 'as_sym_bool') {
  19286. return this.deserialize_sym_argument(inp.as_sym_bool);
  19287. } else if (Array.isArray(value)) {
  19288. if (value.length === 0) {
  19289. return [];
  19290. } else if (typ_ === 'as_tensors') {
  19291. const result = [];
  19292. for (const arg of value) {
  19293. result.push(this.serialized_name_to_node.get(arg.name));
  19294. }
  19295. return result;
  19296. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19297. return Array.from(value);
  19298. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19299. return value.map((arg) => this.deserialize_sym_argument(arg));
  19300. } else if (typ_ === 'as_optional_tensors') {
  19301. const deserialize_optional_tensor_args = (a) => {
  19302. if (a.type === 'as_none') {
  19303. return null;
  19304. } else if (a.type === 'as_tensor') {
  19305. return this.serialized_name_to_node.get(a.value.name);
  19306. }
  19307. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19308. };
  19309. return value.map((item) => deserialize_optional_tensor_args(item));
  19310. }
  19311. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19312. } else if (typ_ === 'as_custom_obj') {
  19313. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19314. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19315. }
  19316. return this.constants[inp.as_custom_obj.name];
  19317. } else if (typ_ === 'as_operator') {
  19318. return this.deserialize_operator(inp.as_operator);
  19319. }
  19320. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19321. }
  19322. deserialize_sym_argument(sym_arg) {
  19323. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19324. if (sym_arg.type === 'as_int') {
  19325. return sym_arg.as_int;
  19326. } else if (sym_arg.type === 'as_name') {
  19327. return this.serialized_name_to_node.get(sym_arg.as_name);
  19328. }
  19329. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19330. if (sym_arg.type === 'as_float') {
  19331. return sym_arg.as_float;
  19332. } else if (sym_arg.type === 'as_name') {
  19333. return this.serialized_name_to_node.get(sym_arg.as_name);
  19334. }
  19335. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19336. if (sym_arg.type === 'as_bool') {
  19337. return sym_arg.as_bool;
  19338. } else if (sym_arg.type === 'as_name') {
  19339. return this.serialized_name_to_node.get(sym_arg.as_name);
  19340. }
  19341. }
  19342. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19343. }
  19344. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19345. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19346. }
  19347. deserialize_outputs(serialized_node, fx_node) {
  19348. if (serialized_node.outputs.length === 0) {
  19349. return;
  19350. }
  19351. if (serialized_node.outputs.length === 1 &&
  19352. serialized_node.outputs[0].type === 'as_tensor') {
  19353. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19354. return;
  19355. } else if (serialized_node.outputs.length === 1 &&
  19356. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19357. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19358. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19359. return;
  19360. }
  19361. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19362. }
  19363. deserialize_multiple_outputs(serialized_node, fx_node) {
  19364. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19365. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19366. let name = '';
  19367. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19368. name = arg.name;
  19369. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19370. name = arg.as_name;
  19371. } else {
  19372. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19373. }
  19374. const individual_output = this.graph.create_node(
  19375. 'call_function',
  19376. operator.getitem,
  19377. new builtins.tuple([fx_node, idx]),
  19378. null,
  19379. name,
  19380. );
  19381. this.sync_fx_node(name, individual_output);
  19382. meta_val.push(this.serialized_name_to_meta.get(name));
  19383. individual_output.meta.update(deserialized_metadata);
  19384. };
  19385. const generate_getitems = (meta_val, fx_node, args) => {
  19386. for (let idx = 0; idx < args.length; idx++) {
  19387. let arg = args[idx];
  19388. if (arg instanceof torch._export.serde.schema.Argument) {
  19389. arg = arg.value;
  19390. }
  19391. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19392. generate_getitem(meta_val, fx_node, arg, idx);
  19393. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19394. const list_output = this.graph.create_node(
  19395. 'call_function',
  19396. operator.getitem,
  19397. (fx_node, idx),
  19398. );
  19399. meta_val.append([]);
  19400. generate_getitems(meta_val[-1], list_output, arg);
  19401. list_output.meta.update(deserialized_metadata);
  19402. list_output.meta.set('val', meta_val[-1]);
  19403. } else {
  19404. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19405. }
  19406. }
  19407. };
  19408. const meta_val = [];
  19409. if (serialized_node.outputs.length === 1) {
  19410. // assert isinstance(serialized_node.outputs[0].value, list)
  19411. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19412. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19413. } else {
  19414. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19415. }
  19416. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19417. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19418. }
  19419. deserialize_metadata(metadata) {
  19420. const ret = new builtins.dict();
  19421. const stack_trace = metadata.get('stack_trace');
  19422. if (stack_trace) {
  19423. ret.set('stack_trace', stack_trace);
  19424. }
  19425. const deserialize_meta_func = (serialized_target) => {
  19426. let module = null;
  19427. let serialized_target_names = [];
  19428. if (serialized_target.startsWith('torch.nn')) {
  19429. module = torch.nn;
  19430. serialized_target_names = serialized_target.split('.').slice(1);
  19431. } else if (serialized_target.startsWith('torch')) {
  19432. module = torch;
  19433. serialized_target_names = serialized_target.split('.').slice(1);
  19434. } else {
  19435. return this.deserialize_operator(serialized_target);
  19436. }
  19437. let target = module;
  19438. for (const name of serialized_target_names) {
  19439. if (!builtins.hasattr(target, name)) {
  19440. return serialized_target;
  19441. }
  19442. target = builtins.getattr(target, name);
  19443. }
  19444. return target;
  19445. };
  19446. const nn_module_stack_str = metadata.get('nn_module_stack');
  19447. if (nn_module_stack_str) {
  19448. const import_nn_module_stack = (key, path, ty) => {
  19449. return [key, [path, ty]];
  19450. };
  19451. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19452. ret.set('nn_module_stack', nn_module_stack);
  19453. }
  19454. const source_fn_st_str = metadata.get('source_fn_stack');
  19455. if (source_fn_st_str) {
  19456. const source_fn_st = [];
  19457. for (const source_fn_str of source_fn_st_str.split(';')) {
  19458. const [name, target_str] = source_fn_str.split(',');
  19459. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19460. }
  19461. ret.set('source_fn_stack', source_fn_st);
  19462. }
  19463. const torch_fn = metadata.get('torch_fn');
  19464. if (torch_fn) {
  19465. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19466. }
  19467. const custom_str = metadata.get('custom');
  19468. if (custom_str) {
  19469. ret.set('custom', JSON.parse(custom_str));
  19470. }
  19471. return ret;
  19472. }
  19473. deserialize_argument_spec(x) {
  19474. if (x.type === 'as_tensor') {
  19475. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19476. } else if (x.type === 'as_sym_int') {
  19477. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19478. } else if (x.type === 'as_custom_obj') {
  19479. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19480. }
  19481. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19482. }
  19483. deserialize_tensor_meta(tensor_meta) {
  19484. try {
  19485. this.fake_tensor_mode.__enter__();
  19486. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  19487. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  19488. const device = this.deserialize_device(tensor_meta.device);
  19489. const dtype = torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[tensor_meta.dtype];
  19490. return torch.empty_strided(sizes, strides, dtype, null, device);
  19491. } finally {
  19492. this.fake_tensor_mode.__exit__(null, null, null);
  19493. }
  19494. }
  19495. deserialize_script_obj_meta(script_obj_meta) {
  19496. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  19497. }
  19498. _parse_sym_expr(expr_str, hint) {
  19499. const _process_sym_expr = (sym, hint) => {
  19500. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  19501. return sym;
  19502. }
  19503. expr_str = sym.__str__();
  19504. for (const arg of sym.args) {
  19505. this._parse_sym_expr(arg);
  19506. }
  19507. if (this.symbol_name_to_symbol.has(expr_str)) {
  19508. sym = this.symbol_name_to_symbol.get(expr_str);
  19509. } else {
  19510. this.symbol_name_to_symbol.set(expr_str, sym);
  19511. if (builtins.isinstance(sym, sympy.core.symbol.Symbol) && torch.fx.experimental.symbolic_shapes.symbol_is_type(sym, [torch.utils._sympy.symbol.SymT.UNBACKED_INT, torch.utils._sympy.symbol.SymT.UNBACKED_FLOAT])) {
  19512. this.unbacked_symbols.add(sym);
  19513. }
  19514. }
  19515. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  19516. this.shape_env.add_var_to_val(sym, hint);
  19517. }
  19518. const vr = this.symbol_name_to_range.get(expr_str);
  19519. if (vr) {
  19520. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  19521. }
  19522. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  19523. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  19524. }
  19525. return sym;
  19526. };
  19527. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  19528. const expr = sympy.core.sympify.sympify(expr_str, locals);
  19529. return _process_sym_expr(expr, hint);
  19530. }
  19531. deserialize_sym_int(s) {
  19532. const val = s.value;
  19533. let hint = null;
  19534. if (s.type === 'as_expr') {
  19535. if (val.hint === null) {
  19536. hint = null;
  19537. } else {
  19538. // assert val.hint.type == "as_int"
  19539. hint = val.hint.value;
  19540. }
  19541. const sym = this._parse_sym_expr(val.expr_str, hint);
  19542. return this.shape_env.create_symintnode(sym, hint);
  19543. } else if (s.type === 'as_int') {
  19544. // assert type(val) is int
  19545. return val;
  19546. }
  19547. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  19548. }
  19549. deserialize_sym_bool(s) {
  19550. const val = s.value;
  19551. let hint = null;
  19552. if (s.type === 'as_expr') {
  19553. if (val.hint === null) {
  19554. hint = null;
  19555. } else {
  19556. // assert val.hint.type == "as_bool"
  19557. hint = val.hint.value;
  19558. }
  19559. const sym = this._parse_sym_expr(val.expr_str, hint);
  19560. return this.shape_env.create_symboolnode(sym, hint);
  19561. } else if (s.type === 'as_bool') {
  19562. // assert type(val) is bool
  19563. return val;
  19564. }
  19565. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  19566. }
  19567. deserialize_device(d) {
  19568. if (d.index === null) {
  19569. return new torch.device(d.type);
  19570. }
  19571. return new torch.device(d.type, d.index);
  19572. }
  19573. _get_schema_from_target(target) {
  19574. if (target instanceof torch._ops.OpOverload) {
  19575. return target._schema;
  19576. }
  19577. throw new python.Error(`Unsupported schema '${target.name}'.`);
  19578. }
  19579. _is_single_tensor_return(target) {
  19580. const schema = this._get_schema_from_target(target);
  19581. const returns = schema.returns;
  19582. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  19583. }
  19584. });
  19585. this.registerType('torch._export.verifier.Verifier', class {});
  19586. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  19587. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  19588. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  19589. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  19590. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  19591. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  19592. constructor(mod, dynamo_ctx) {
  19593. builtins.object.__setattr__(self, '_orig_mod', mod);
  19594. // this._super_module_initialized = false;
  19595. super();
  19596. // this._super_module_initialized = true;
  19597. this._orig_mod = mod;
  19598. this.dynamo_ctx = dynamo_ctx;
  19599. // this._initialize();
  19600. this.training = this._orig_mod.training;
  19601. }
  19602. });
  19603. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  19604. this.registerType('torch._dynamo.hooks.Hooks', class {});
  19605. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  19606. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  19607. this.registerType('torch._TorchCompileInductorWrapper', class {});
  19608. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  19609. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  19610. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  19611. const module = new types.ModuleType(name);
  19612. execution.register('sys').modules.set(name, module);
  19613. const context = new python.Execution.Context(module, null);
  19614. execution.exec(meta.get('module_src'), context);
  19615. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  19616. const state = meta.get('state');
  19617. if (state) {
  19618. if (obj.__setstate__) {
  19619. obj.__setstate__(state);
  19620. } else {
  19621. for (const [key, value] of state) {
  19622. obj[key] = value;
  19623. }
  19624. }
  19625. }
  19626. return obj;
  19627. });
  19628. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  19629. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  19630. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  19631. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  19632. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  19633. this.registerType('torch.device', class {
  19634. constructor(type, index) {
  19635. this.type = type;
  19636. this.index = index ? index : null;
  19637. }
  19638. __str__() {
  19639. return this.index === null ? this.type : `${this.type}:${this.index}`;
  19640. }
  19641. toString() {
  19642. const index = this.index === null ? '' : `, index=${this.index}`;
  19643. return `device(type='${this.type}'${index})`;
  19644. }
  19645. });
  19646. this.registerType('torch.memory_format', class {
  19647. constructor(name) {
  19648. this.name = name;
  19649. }
  19650. __str__() {
  19651. return `torch.${this.name}`;
  19652. }
  19653. toString() {
  19654. return this.__str__();
  19655. }
  19656. });
  19657. this.registerType('torch.dtype', class {
  19658. constructor(scalar_type, name, itemsize) {
  19659. this._scalar_type = scalar_type;
  19660. this._name = name;
  19661. this._itemsize = itemsize;
  19662. }
  19663. scalar_type() {
  19664. return this._scalar_type;
  19665. }
  19666. itemsize() {
  19667. return this._itemsize;
  19668. }
  19669. __reduce__() {
  19670. return this._name;
  19671. }
  19672. __str__() {
  19673. return `torch.${this._name}`;
  19674. }
  19675. toString() {
  19676. return this.__str__();
  19677. }
  19678. });
  19679. this.registerType('torch.layout', class {
  19680. constructor(name) {
  19681. this._name = name;
  19682. }
  19683. __str__() {
  19684. return `torch.${this._name}`;
  19685. }
  19686. toString() {
  19687. return this.__str__();
  19688. }
  19689. });
  19690. this.registerType('torch.qscheme', class {
  19691. constructor(name) {
  19692. this._name = name;
  19693. }
  19694. __str__() {
  19695. return this._name;
  19696. }
  19697. toString() {
  19698. return this.__str__();
  19699. }
  19700. });
  19701. this.registerType('torch.utils.hooks.RemovableHandle', class {
  19702. __setstate__(state) {
  19703. [this.hooks_dict_ref, this.id] = state;
  19704. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  19705. }
  19706. });
  19707. this.registerType('torch.storage._StorageBase', class {
  19708. constructor(size, dtype) {
  19709. this._size = size;
  19710. this._dtype = dtype;
  19711. this._device = null;
  19712. }
  19713. get device() {
  19714. return this._device;
  19715. }
  19716. get dtype() {
  19717. return this._dtype;
  19718. }
  19719. element_size() {
  19720. return this._dtype.element_size;
  19721. }
  19722. size() {
  19723. return this._size;
  19724. }
  19725. get data() {
  19726. return this._cdata;
  19727. }
  19728. _set_cdata(data) {
  19729. const length = this.size() * this.dtype.itemsize();
  19730. if (length !== data.length) {
  19731. throw new python.Error('Typed storage data size mismatch.');
  19732. }
  19733. this._cdata = data;
  19734. }
  19735. _set_from_file(unpickler) {
  19736. const buffer = unpickler.read(8);
  19737. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  19738. if (size !== this.size()) {
  19739. throw new python.Error('Typed storage size mismatch.');
  19740. }
  19741. const itemsize = this.dtype.itemsize();
  19742. const data = unpickler.stream(itemsize * size);
  19743. this._set_cdata(data);
  19744. }
  19745. static _new_with_file(unpickler) {
  19746. const buffer = unpickler.read(8);
  19747. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  19748. const storage = new this(size);
  19749. const itemsize = storage.dtype.itemsize();
  19750. const data = unpickler.stream(itemsize * size);
  19751. storage._set_cdata(data);
  19752. return storage;
  19753. }
  19754. });
  19755. this.registerType('torch.storage.UntypedStorage', class {
  19756. constructor(size) {
  19757. this._size = size;
  19758. }
  19759. _set_cdata(data) {
  19760. if (this._size !== data.length) {
  19761. throw new python.Error('Untyped storage data size mismatch.');
  19762. }
  19763. this._cdata = data;
  19764. }
  19765. });
  19766. this.registerType('torch.storage.TypedStorage', class {
  19767. constructor(...args) {
  19768. if (args.length === 0) {
  19769. this._size = 0;
  19770. } else if (args.length === 1 && Number.isInteger(args[0])) {
  19771. [this._size] = args;
  19772. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  19773. if (args[3] instanceof torch.device) {
  19774. [this._size, this.dtype, , this._device] = args;
  19775. } else {
  19776. [this._size, this.dtype] = args;
  19777. }
  19778. } else {
  19779. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  19780. }
  19781. }
  19782. get device() {
  19783. return this._device;
  19784. }
  19785. get dtype() {
  19786. return this._dtype;
  19787. }
  19788. set dtype(value) {
  19789. this._dtype = value;
  19790. }
  19791. element_size() {
  19792. return this._dtype.element_size;
  19793. }
  19794. size() {
  19795. return this._size;
  19796. }
  19797. get data() {
  19798. return this._cdata;
  19799. }
  19800. _set_cdata(data) {
  19801. const length = this.size() * this.dtype.itemsize();
  19802. if (length !== data.length) {
  19803. throw new python.Error('Storage data size mismatch.');
  19804. }
  19805. this._cdata = data;
  19806. }
  19807. _set_from_file(unpickler) {
  19808. const buffer = unpickler.read(8);
  19809. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  19810. if (size !== this.size()) {
  19811. throw new python.Error('Storage size mismatch.');
  19812. }
  19813. const itemsize = this.dtype.itemsize();
  19814. const data = unpickler.stream(itemsize * size);
  19815. this._set_cdata(data);
  19816. }
  19817. static _new_with_file(unpickler) {
  19818. const buffer = unpickler.read(8);
  19819. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  19820. const storage = new this(size);
  19821. const itemsize = storage.dtype.itemsize();
  19822. const data = unpickler.stream(itemsize * size);
  19823. storage._set_cdata(data);
  19824. return storage;
  19825. }
  19826. });
  19827. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  19828. });
  19829. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  19830. constructor(...args) {
  19831. /* eslint-disable no-constructor-return */
  19832. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  19833. /* eslint-enable no-constructor-return */
  19834. }
  19835. });
  19836. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  19837. constructor(...args) {
  19838. /* eslint-disable no-constructor-return */
  19839. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  19840. /* eslint-enable no-constructor-return */
  19841. }
  19842. });
  19843. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  19844. constructor(...args) {
  19845. /* eslint-disable no-constructor-return */
  19846. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  19847. /* eslint-enable no-constructor-return */
  19848. }
  19849. });
  19850. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  19851. constructor(...args) {
  19852. /* eslint-disable no-constructor-return */
  19853. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  19854. /* eslint-enable no-constructor-return */
  19855. }
  19856. });
  19857. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  19858. constructor(...args) {
  19859. /* eslint-disable no-constructor-return */
  19860. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  19861. /* eslint-enable no-constructor-return */
  19862. }
  19863. });
  19864. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  19865. constructor(...args) {
  19866. /* eslint-disable no-constructor-return */
  19867. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  19868. /* eslint-enable no-constructor-return */
  19869. }
  19870. });
  19871. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  19872. constructor(...args) {
  19873. /* eslint-disable no-constructor-return */
  19874. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  19875. /* eslint-enable no-constructor-return */
  19876. }
  19877. });
  19878. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  19879. constructor(...args) {
  19880. /* eslint-disable no-constructor-return */
  19881. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  19882. /* eslint-enable no-constructor-return */
  19883. }
  19884. });
  19885. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  19886. constructor(...args) {
  19887. /* eslint-disable no-constructor-return */
  19888. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  19889. /* eslint-enable no-constructor-return */
  19890. }
  19891. });
  19892. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  19893. constructor(...args) {
  19894. /* eslint-disable no-constructor-return */
  19895. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  19896. /* eslint-enable no-constructor-return */
  19897. }
  19898. });
  19899. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  19900. constructor(...args) {
  19901. /* eslint-disable no-constructor-return */
  19902. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  19903. /* eslint-enable no-constructor-return */
  19904. }
  19905. });
  19906. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  19907. constructor(...args) {
  19908. /* eslint-disable no-constructor-return */
  19909. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  19910. /* eslint-enable no-constructor-return */
  19911. }
  19912. });
  19913. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  19914. constructor(...args) {
  19915. /* eslint-disable no-constructor-return */
  19916. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  19917. /* eslint-enable no-constructor-return */
  19918. }
  19919. });
  19920. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  19921. constructor(...args) {
  19922. /* eslint-disable no-constructor-return */
  19923. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  19924. /* eslint-enable no-constructor-return */
  19925. }
  19926. });
  19927. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  19928. constructor(...args) {
  19929. /* eslint-disable no-constructor-return */
  19930. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  19931. /* eslint-enable no-constructor-return */
  19932. }
  19933. });
  19934. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  19935. constructor(...args) {
  19936. /* eslint-disable no-constructor-return */
  19937. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  19938. /* eslint-enable no-constructor-return */
  19939. }
  19940. });
  19941. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  19942. constructor(...args) {
  19943. /* eslint-disable no-constructor-return */
  19944. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  19945. /* eslint-enable no-constructor-return */
  19946. }
  19947. });
  19948. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  19949. constructor(...args) {
  19950. /* eslint-disable no-constructor-return */
  19951. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  19952. /* eslint-enable no-constructor-return */
  19953. }
  19954. });
  19955. this.registerType('torch.Size', class extends Array {
  19956. constructor(size) {
  19957. super(size.length);
  19958. for (let i = 0; i < size.length; i++) {
  19959. this[i] = size[i];
  19960. }
  19961. }
  19962. __len__() {
  19963. return this.length;
  19964. }
  19965. });
  19966. this.registerType('torch._C.TensorMeta', class {
  19967. });
  19968. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  19969. });
  19970. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  19971. constructor(storage, shape, dtype, layout, device, requires_grad) {
  19972. super();
  19973. if (storage) {
  19974. this._storage = storage;
  19975. }
  19976. if (shape !== null && shape !== undefined) {
  19977. this._shape = shape;
  19978. }
  19979. if (dtype) {
  19980. this._dtype = dtype;
  19981. }
  19982. this._layout = layout || torch.strided;
  19983. if (device) {
  19984. this._device = device;
  19985. }
  19986. if (requires_grad !== undefined) {
  19987. this.requires_grad = requires_grad;
  19988. }
  19989. }
  19990. get device() {
  19991. if (this._device !== undefined) {
  19992. return this._device;
  19993. }
  19994. return this.storage().device;
  19995. }
  19996. get dtype() {
  19997. if (this._dtype !== undefined) {
  19998. return this._dtype;
  19999. }
  20000. if (this._layout === torch.sparse_coo) {
  20001. return this._values.dtype;
  20002. }
  20003. return this.storage().dtype;
  20004. }
  20005. get shape() {
  20006. return this._shape;
  20007. }
  20008. get layout() {
  20009. return this._layout;
  20010. }
  20011. get values() {
  20012. if (this._layout === torch.sparse_coo) {
  20013. return this._values;
  20014. }
  20015. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20016. }
  20017. get indices() {
  20018. if (this._layout === torch.sparse_coo) {
  20019. return this._indices;
  20020. }
  20021. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20022. }
  20023. get is_quantized() {
  20024. return this.__quantized__ === true;
  20025. }
  20026. get is_nested() {
  20027. return this.__nested__ === true;
  20028. }
  20029. get is_sparse() {
  20030. return this.layout !== torch.strided;
  20031. }
  20032. size() {
  20033. return this._shape;
  20034. }
  20035. storage() {
  20036. return this._storage;
  20037. }
  20038. storage_offset() {
  20039. return this._storage_offset;
  20040. }
  20041. stride() {
  20042. return this._stride;
  20043. }
  20044. resize_(shape) {
  20045. this._shape = shape;
  20046. }
  20047. __len__() {
  20048. return this._shape[0];
  20049. }
  20050. __setstate__(state) {
  20051. switch (state.length) {
  20052. case 3:
  20053. break;
  20054. case 4:
  20055. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20056. break;
  20057. case 5:
  20058. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20059. break;
  20060. default:
  20061. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20062. }
  20063. }
  20064. set_(source, storage_offset, size, stride) {
  20065. this._storage = source;
  20066. this._storage_offset = storage_offset;
  20067. this._shape = size;
  20068. this._stride = stride;
  20069. }
  20070. __bool__() {
  20071. return true;
  20072. }
  20073. __int__() {
  20074. const storage = this.storage();
  20075. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20076. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20077. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20078. return view.getBigInt64(0, true);
  20079. }
  20080. return NaN;
  20081. }
  20082. __float__() {
  20083. const storage = this.storage();
  20084. if (storage && storage.dtype.__reduce__() === 'float32') {
  20085. if (storage.size() !== undefined && storage.data.length === 4) {
  20086. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20087. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20088. return view.getFloat32(0, true);
  20089. }
  20090. }
  20091. return NaN;
  20092. }
  20093. __str__() {
  20094. return 'tensor(...)';
  20095. }
  20096. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20097. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20098. t.__setstate__([null, storage_offset, size, stride]);
  20099. return t;
  20100. }
  20101. });
  20102. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20103. constructor(data, requires_grad) {
  20104. super();
  20105. this.data = data || new torch.Tensor([]);
  20106. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20107. }
  20108. });
  20109. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20110. });
  20111. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20112. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20113. super();
  20114. this.allow_fallback_kernels = allow_fallback_kernels;
  20115. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20116. this.shape_env = shape_env;
  20117. this.enter_stack = [];
  20118. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20119. }
  20120. __enter__() {
  20121. const prev_only_lift_cpu_tensors = null;
  20122. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20123. if (this === maybe_prev_fake_mode) {
  20124. torch._C._set_dispatch_mode(this);
  20125. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20126. } else {
  20127. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20128. return super.__enter__();
  20129. }
  20130. return this;
  20131. }
  20132. __exit__(exc_type, exc_value, traceback) {
  20133. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20134. if (live) {
  20135. super.__exit__(exc_type, exc_value, traceback);
  20136. if (maybe_prev_fake_mode !== null) {
  20137. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20138. }
  20139. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20140. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20141. }
  20142. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20143. }
  20144. }
  20145. });
  20146. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20147. constructor(requires_grad /*, device, dtype */) {
  20148. super(undefined, requires_grad);
  20149. }
  20150. });
  20151. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20152. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20153. constructor(...args) {
  20154. /* eslint-disable no-constructor-return */
  20155. return new torch.Tensor(...args);
  20156. /* eslint-enable no-constructor-return */
  20157. }
  20158. });
  20159. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20160. constructor(...args) {
  20161. /* eslint-disable no-constructor-return */
  20162. return new torch.Tensor(...args);
  20163. /* eslint-enable no-constructor-return */
  20164. }
  20165. });
  20166. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20167. constructor(...args) {
  20168. /* eslint-disable no-constructor-return */
  20169. return new torch.Tensor(...args);
  20170. /* eslint-enable no-constructor-return */
  20171. }
  20172. });
  20173. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20174. constructor(...args) {
  20175. /* eslint-disable no-constructor-return */
  20176. return new torch.Tensor(...args);
  20177. /* eslint-enable no-constructor-return */
  20178. }
  20179. });
  20180. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20181. constructor(...args) {
  20182. /* eslint-disable no-constructor-return */
  20183. return new torch.Tensor(...args);
  20184. /* eslint-enable no-constructor-return */
  20185. }
  20186. });
  20187. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20188. constructor(...args) {
  20189. /* eslint-disable no-constructor-return */
  20190. return new torch.Tensor(...args);
  20191. /* eslint-enable no-constructor-return */
  20192. }
  20193. });
  20194. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20195. constructor(...args) {
  20196. /* eslint-disable no-constructor-return */
  20197. return new torch.Tensor(...args);
  20198. /* eslint-enable no-constructor-return */
  20199. }
  20200. });
  20201. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20202. constructor(...args) {
  20203. /* eslint-disable no-constructor-return */
  20204. return new torch.Tensor(...args);
  20205. /* eslint-enable no-constructor-return */
  20206. }
  20207. });
  20208. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20209. constructor(...args) {
  20210. /* eslint-disable no-constructor-return */
  20211. return new torch.Tensor(...args);
  20212. /* eslint-enable no-constructor-return */
  20213. }
  20214. });
  20215. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20216. constructor(...args) {
  20217. /* eslint-disable no-constructor-return */
  20218. return new torch.Tensor(...args);
  20219. /* eslint-enable no-constructor-return */
  20220. }
  20221. });
  20222. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20223. constructor(...args) {
  20224. /* eslint-disable no-constructor-return */
  20225. return new torch.Tensor(...args);
  20226. /* eslint-enable no-constructor-return */
  20227. }
  20228. });
  20229. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20230. constructor(...args) {
  20231. /* eslint-disable no-constructor-return */
  20232. return new torch.Tensor(...args);
  20233. /* eslint-enable no-constructor-return */
  20234. }
  20235. });
  20236. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20237. constructor(...args) {
  20238. /* eslint-disable no-constructor-return */
  20239. return new torch.Tensor(...args);
  20240. /* eslint-enable no-constructor-return */
  20241. }
  20242. });
  20243. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20244. constructor(...args) {
  20245. /* eslint-disable no-constructor-return */
  20246. return new torch.Tensor(...args);
  20247. /* eslint-enable no-constructor-return */
  20248. }
  20249. });
  20250. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20251. constructor(...args) {
  20252. /* eslint-disable no-constructor-return */
  20253. return new torch.Tensor(...args);
  20254. /* eslint-enable no-constructor-return */
  20255. }
  20256. });
  20257. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20258. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20259. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20260. constructor(...args) {
  20261. /* eslint-disable no-constructor-return */
  20262. return new torch.Tensor(...args);
  20263. /* eslint-enable no-constructor-return */
  20264. }
  20265. });
  20266. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20267. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20268. constructor(...args) {
  20269. /* eslint-disable no-constructor-return */
  20270. return new torch.Tensor(...args);
  20271. /* eslint-enable no-constructor-return */
  20272. }
  20273. });
  20274. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20275. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20276. constructor(...args) {
  20277. /* eslint-disable no-constructor-return */
  20278. return new torch.Tensor(...args);
  20279. /* eslint-enable no-constructor-return */
  20280. }
  20281. });
  20282. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20283. this.registerType('torchao.dtypes.utils.Layout', class {});
  20284. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20285. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20286. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20287. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20288. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20289. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20290. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20291. this.registerType('torch.SymBool', class {
  20292. constructor(node) {
  20293. this.node = node;
  20294. }
  20295. });
  20296. this.registerType('torch.SymInt', class {
  20297. constructor(node) {
  20298. this.node = node;
  20299. }
  20300. toString() {
  20301. return this.node.__str__();
  20302. }
  20303. });
  20304. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20305. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20306. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20307. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20308. /* eslint-disable no-multi-assign */
  20309. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20310. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20311. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20312. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20313. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20314. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20315. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20316. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20317. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20318. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex32', 4);
  20319. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex64', 8);
  20320. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex128', 16);
  20321. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20322. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20323. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20324. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20325. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20326. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20327. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20328. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20329. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20330. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20331. torch.bits8 = new torch.dtype(21, 'bits8');
  20332. torch.bits16 = new torch.dtype(22, 'bits16');
  20333. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20334. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20335. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20336. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20337. torch.uint16 = new torch.dtype(27, 'uint16', 2);
  20338. torch.uint32 = new torch.dtype(28, 'uint32', 4);
  20339. torch.uint64 = new torch.dtype(29, 'uint64', 8);
  20340. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = Object.fromEntries([
  20341. ['uint8', 'BYTE'],
  20342. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20343. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20344. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20345. ['bool', 'BOOL'],
  20346. ['bfloat16', 'BFLOAT16']
  20347. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20348. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20349. torch.channels_last = new torch.memory_format('channels_last');
  20350. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20351. torch.preserve_format = new torch.memory_format('preserve_format');
  20352. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20353. ['contiguous_format', 'ContiguousFormat'],
  20354. ['channels_last', 'ChannelsLast'],
  20355. ['channels_last_3d', 'ChannelsLast3d'],
  20356. ['preserve_format', 'PreserveFormat']
  20357. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20358. /* eslint-enable no-multi-assign */
  20359. torch.strided = new torch.layout('strided');
  20360. torch.sparse_coo = new torch.layout('sparse_coo');
  20361. torch.sparse_csr = new torch.layout('sparse_csr');
  20362. torch.sparse_csc = new torch.layout('sparse_csc');
  20363. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20364. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20365. torch._mkldnn = new torch.layout('_mkldnn');
  20366. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20367. ['sparse_coo', 'SparseCoo'],
  20368. ['sparse_csr', 'SparseCsr'],
  20369. ['sparse_csc', 'SparseCsc'],
  20370. ['sparse_bsr', 'SparseBsr'],
  20371. ['sparse_bsc', 'SparseBsc'],
  20372. ['_mkldnn', '_mkldnn'],
  20373. ['strided', 'Strided'],
  20374. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20375. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20376. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20377. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20378. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20379. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20380. torch.inf = this.register('math').inf;
  20381. this.registerFunction('fastcore.basics._using_attr');
  20382. this.registerFunction('fastcore.imports.noop');
  20383. this.registerType('fastcore.basics.fastuple', class {});
  20384. this.registerType('fastcore.basics.GetAttr', class {});
  20385. this.registerType('fastcore.dispatch._TypeDict', class {});
  20386. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20387. this.registerType('fastcore.foundation.L', class {});
  20388. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20389. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20390. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20391. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20392. this.registerType('fastai.basic_train.Learner', class {});
  20393. this.registerType('fastai.basic_train.Recorder', class {});
  20394. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20395. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20396. return self.invoke(cls, [tensor]);
  20397. });
  20398. this.registerFunction('fastai.torch_core.trainable_params');
  20399. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20400. const tensor = self.invoke(type, [func(...args)]);
  20401. Object.assign(tensor, dict);
  20402. return tensor;
  20403. });
  20404. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20405. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20406. constructor(x) {
  20407. super();
  20408. Object.assign(this, x);
  20409. }
  20410. });
  20411. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20412. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20413. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20414. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20415. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20416. this.registerFunction('fastai.torch_core.uniform');
  20417. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20418. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20419. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20420. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20421. this.registerFunction('fastai.callback.hook._hook_inner');
  20422. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20423. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20424. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20425. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20426. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20427. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20428. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20429. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20430. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20431. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20432. this.registerType('fastai.data.core.Datasets', class {});
  20433. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20434. this.registerType('fastai.data.core.FilteredBase', class {});
  20435. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20436. this.registerType('fastai.data.core.TfmdLists', class {});
  20437. this.registerType('fastai.data.load._FakeLoader', class {});
  20438. this.registerFunction('fastai.data.load._wif');
  20439. this.registerType('fastai.data.transforms.Categorize', class {});
  20440. this.registerType('fastai.data.transforms.Category', class {});
  20441. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20442. this.registerType('fastai.data.transforms.ColReader', class {});
  20443. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20444. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20445. this.registerType('fastai.data.transforms.Normalize', class {});
  20446. this.registerType('fastai.data.transforms.parent_label', class {});
  20447. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20448. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20449. this.registerType('fastai.data.transforms.ToTensor', class {});
  20450. this.registerType('fastai.data_block.CategoryList', class {});
  20451. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20452. this.registerType('fastai.imports.noop', class {});
  20453. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20454. this.registerType('fastai.layers.ConvLayer', class {});
  20455. this.registerType('fastai.layers.Embedding', class {});
  20456. this.registerType('fastai.layers.Flatten', class {});
  20457. this.registerType('fastai.layers.FlattenedLoss', class {});
  20458. this.registerType('fastai.layers.LinBnDrop', class {});
  20459. this.registerType('fastai.layers.MergeLayer', class {});
  20460. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20461. this.registerType('fastai.layers.ResBlock', class {});
  20462. this.registerType('fastai.layers.SelfAttention', class {});
  20463. this.registerType('fastai.layers.SigmoidRange', class {});
  20464. this.registerType('fastai.layers.TimeDistributed', class {});
  20465. this.registerType('fastai.layers.ToTensorBase', class {});
  20466. this.registerType('fastai.learner._ConstantFunc', class {});
  20467. this.registerType('fastai.learner.Metric', class {});
  20468. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20469. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20470. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20471. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20472. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20473. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20474. this.registerType('fastai.learner.Recorder', class {});
  20475. this.registerType('fastai.losses.BaseLoss', class {});
  20476. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20477. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20478. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20479. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20480. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20481. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20482. this.registerType('fastai.metrics.Dice', class {});
  20483. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20484. this.registerFunction('fastai.metrics._rmse');
  20485. this.registerFunction('fastai.metrics.accuracy');
  20486. this.registerFunction('fastai.metrics.accuracy_multi');
  20487. this.registerFunction('fastai.metrics.foreground_acc');
  20488. this.registerFunction('fastai.metrics.mse');
  20489. this.registerFunction('fastai.metrics.error_rate');
  20490. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  20491. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  20492. this.registerFunction('fastai.optimizer.Adam');
  20493. this.registerFunction('fastai.optimizer.adam_step');
  20494. this.registerFunction('fastai.optimizer.average_grad');
  20495. this.registerFunction('fastai.optimizer.average_sqr_grad');
  20496. this.registerFunction('fastai.optimizer.RAdam');
  20497. this.registerFunction('fastai.optimizer.step_stat');
  20498. this.registerFunction('fastai.optimizer.weight_decay');
  20499. this.registerType('fastai.tabular.core.Categorify', class {});
  20500. this.registerType('fastai.tabular.core.FillMissing', class {});
  20501. this.registerType('fastai.tabular.core.FillStrategy', class {});
  20502. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  20503. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  20504. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  20505. this.registerType('fastai.tabular.core.Tabular', class {});
  20506. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  20507. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  20508. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  20509. this.registerType('fastai.tabular.model.TabularModel', class {});
  20510. this.registerFunction('fastai.vision.augment.aug_transforms');
  20511. this.registerFunction('fastai.vision.augment.dihedral_mat');
  20512. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  20513. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  20514. this.registerType('fastai.vision.augment._WarpCoord', class {});
  20515. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  20516. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  20517. this.registerType('fastai.vision.augment.Brightness', class {});
  20518. this.registerType('fastai.vision.augment.flip_mat', class {});
  20519. this.registerType('fastai.vision.augment.Flip', class {});
  20520. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  20521. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  20522. this.registerType('fastai.vision.augment.Resize', class {});
  20523. this.registerType('fastai.vision.augment.rotate_mat', class {});
  20524. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  20525. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  20526. this.registerType('fastai.vision.augment.zoom_mat', class {});
  20527. this.registerType('fastai.vision.core.PILImage', class {});
  20528. this.registerType('fastai.vision.core.PILMask', class {});
  20529. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  20530. this.registerType('fastai.vision.data.ImageList', class {});
  20531. this.registerType('fastai.vision.data.ImageItemList', class {});
  20532. this.registerType('fastai.vision.image.Image', class {});
  20533. this.registerType('fastai.vision.image.RandTransform', class {});
  20534. this.registerType('fastai.vision.image.TfmCrop', class {});
  20535. this.registerFunction('fastai.vision.learner._resnet_split');
  20536. this.registerFunction('fastai.vision.learner.default_split');
  20537. this.registerFunction('fastai.vision.learner.default_split');
  20538. this.registerType('fastai.vision.learner.TimmBody', class {});
  20539. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  20540. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  20541. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  20542. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  20543. this.registerFunction('fastai.vision.transform._crop_pad');
  20544. }
  20545. exec(code , context) {
  20546. const ast = this.ast;
  20547. const program = ast.parse(code, '', null, null);
  20548. if (!program) {
  20549. throw new python.Error("Module '?' parse error.");
  20550. }
  20551. this.block(program.body, context);
  20552. }
  20553. debug(/* file */) {
  20554. }
  20555. source(file) {
  20556. if (this._sources.has(file)) {
  20557. return this._sources.get(file);
  20558. }
  20559. return null;
  20560. }
  20561. read(file) {
  20562. const buffer = this.source(file);
  20563. if (buffer) {
  20564. const debug = this.debug(file);
  20565. return this.parse(file, buffer, debug);
  20566. }
  20567. return null;
  20568. }
  20569. parse(filename, buffer, debug) {
  20570. const ast = this.ast;
  20571. const source = this._utf8Decoder.decode(buffer);
  20572. const program = ast.parse(source, filename, null, debug);
  20573. if (!program) {
  20574. throw new python.Error(`Module '${filename}' parse error.`);
  20575. }
  20576. return program;
  20577. }
  20578. import(name, current, level) {
  20579. if (level) {
  20580. let bits = current.split('.');
  20581. if (bits.length < level) {
  20582. throw new python.Error('Invalid relative import beyond top-level package.');
  20583. }
  20584. bits = bits.slice(0, bits.length - level);
  20585. const base = bits.join('.');
  20586. name = name ? [base, name].join('.') : base;
  20587. }
  20588. const index = name.lastIndexOf('.');
  20589. let parent = null;
  20590. let child = null;
  20591. if (index > 0) {
  20592. parent = name.substring(0, index);
  20593. child = name.substring(index + 1);
  20594. this.import(parent);
  20595. }
  20596. if (!this._modules.has(name)) {
  20597. const module = this._registry.get(name) || new this.builtins.module(name);
  20598. module.__package__ = name;
  20599. this._modules.set(name, module);
  20600. const path = name.split('.').join('/');
  20601. module.__path__ = [path];
  20602. const file = `${path}.py`;
  20603. const program = this.read(file);
  20604. if (program) {
  20605. module.__file__ = file;
  20606. for (const [name, value] of Object.entries(this.builtins)) {
  20607. switch (name) {
  20608. case '__class__':
  20609. case '__package__':
  20610. case '__module__':
  20611. case '__name__':
  20612. case '__path__':
  20613. case '__file__':
  20614. break;
  20615. default:
  20616. module[name] = value;
  20617. break;
  20618. }
  20619. }
  20620. const context = new python.Execution.Context(module, null);
  20621. if (name !== 'builtins') {
  20622. context.set('__builtins__', this._modules.get('builtins'));
  20623. }
  20624. this.block(program.body, context);
  20625. }
  20626. if (parent) {
  20627. const parent_module = this._modules.get(parent);
  20628. parent_module[child] = module;
  20629. }
  20630. }
  20631. return this._modules.get(name);
  20632. }
  20633. __import__(name, globals, locals, fromlist, level) {
  20634. let module = null;
  20635. level = level || 0;
  20636. if (level === 0) {
  20637. module = this.import(name);
  20638. } else {
  20639. globals = globals || {};
  20640. let current = globals.__package__;
  20641. if (!current) {
  20642. const spec = globals.__spec__;
  20643. if (spec) {
  20644. current = spec.parent;
  20645. } else {
  20646. const name = globals.__name__;
  20647. const bits = name.split('.');
  20648. bits.pop();
  20649. current = bits.join('.');
  20650. }
  20651. }
  20652. module = this.import(name, current, level);
  20653. }
  20654. if (!fromlist) {
  20655. if (level === 0) {
  20656. return this.import(name.split('.')[0]);
  20657. } else if (name) {
  20658. throw new python.Error(`Unsupported relative import '${name}'.`);
  20659. // cut_off = len(name) - len(name.partition('.')[0])
  20660. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  20661. }
  20662. } else if (module.__path__) {
  20663. const handle_fromlist = (module, fromlist, recursive) => {
  20664. for (const name of fromlist) {
  20665. if (name === '*') {
  20666. if (!recursive && module.__all__) {
  20667. handle_fromlist(module, module.__all__, true);
  20668. }
  20669. } else if (!module[name]) {
  20670. this.import(`${module.__name__}.${name}`);
  20671. }
  20672. }
  20673. return module;
  20674. };
  20675. handle_fromlist(module, fromlist);
  20676. }
  20677. return module;
  20678. }
  20679. module(name) {
  20680. return this._modules.get(name);
  20681. }
  20682. resolve(name) {
  20683. const index = name.lastIndexOf('.');
  20684. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  20685. const moduleName = index === -1 ? '' : name.substring(0, index);
  20686. const module = this.import(moduleName);
  20687. let type = module ? module[memberName] : null;
  20688. if (!type) {
  20689. if (!this._unresolved.has(name)) {
  20690. const moduleName = name.split('.').shift();
  20691. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  20692. this.emit('resolve', name);
  20693. }
  20694. const type = this._createType(name, class {});
  20695. this._unresolved.set(name, type);
  20696. }
  20697. type = this._unresolved.get(name);
  20698. }
  20699. return type;
  20700. }
  20701. invoke(target, args) {
  20702. const builtins = this.builtins;
  20703. if (typeof target === 'string') {
  20704. target = this.resolve(target);
  20705. }
  20706. if (target) {
  20707. if (target.__class__ === builtins.type) {
  20708. if (target.prototype && target.prototype.__class__ === target) {
  20709. return Reflect.construct(target, args);
  20710. }
  20711. const obj = Object.create(target);
  20712. if (obj.__init__ && typeof obj.__init__ === 'function') {
  20713. obj.__init__(...args);
  20714. }
  20715. return obj;
  20716. } else if (target.__class__ === builtins.function) {
  20717. if (target.__call__) {
  20718. return target.__call__(args);
  20719. }
  20720. return target(...args);
  20721. }
  20722. }
  20723. throw new python.Error('Unsupported invoke target.');
  20724. }
  20725. call(target, name, args, keywords, context) {
  20726. const builtins = this.builtins;
  20727. const callTarget = this.target(target, context);
  20728. const callArguments = args.map((arg) => this.expression(arg, context));
  20729. if (!callTarget || (name !== null && !callTarget[name])) {
  20730. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  20731. name = null;
  20732. callArguments.shift();
  20733. } else {
  20734. const targetName = `${this.identifier(target)}.${name}`;
  20735. throw new python.Error(`Unknown function '${targetName}'.`);
  20736. }
  20737. }
  20738. const func = name ? callTarget[name] : callTarget;
  20739. if (func.__class__ === builtins.type) {
  20740. if (func.prototype && func.prototype.__class__ === func) {
  20741. return Reflect.construct(func, callArguments);
  20742. }
  20743. const obj = Object.create(func);
  20744. obj.__class__ = func;
  20745. if (obj.__init__ && typeof obj.__init__ === 'function') {
  20746. obj.__init__(...args);
  20747. }
  20748. return obj;
  20749. }
  20750. if (func.__class__ === builtins.function) {
  20751. if (func.__call__) {
  20752. return func.__call__(callArguments);
  20753. }
  20754. }
  20755. if (func.__class__ === builtins.method) {
  20756. if (func.__call__) {
  20757. return func.__call__([callTarget].concat(callArguments));
  20758. }
  20759. }
  20760. if (typeof func === 'function') {
  20761. return func.apply(callTarget, callArguments);
  20762. }
  20763. throw new python.Error('Unsupported call expression.');
  20764. }
  20765. apply(method, args, context) {
  20766. const locals = Array.prototype.slice.call(args);
  20767. context = new python.Execution.Context(context.globals, {});
  20768. args = method.args.posonlyargs.concat(method.args.args);
  20769. const default_pos = args.length - method.args.defaults.length;
  20770. for (let i = 0; i < method.args.args.length; i++) {
  20771. const arg = method.args.args[i];
  20772. let value = null;
  20773. if (locals.length > 0) {
  20774. value = locals.shift();
  20775. } else if (i >= default_pos) {
  20776. value = this.expression(method.args.defaults[i - default_pos], context);
  20777. } else {
  20778. throw new python.Error('Missing required positional argument.');
  20779. }
  20780. context.set(arg.arg, value);
  20781. }
  20782. return this.block(method.body, context);
  20783. }
  20784. block(statements, context) {
  20785. statements = Array.prototype.slice.call(statements);
  20786. while (statements.length > 0) {
  20787. const stmt = statements.shift();
  20788. const value = this.statement(stmt, context);
  20789. if (value !== undefined) {
  20790. return value;
  20791. }
  20792. }
  20793. return undefined;
  20794. }
  20795. statement(stmt, context) {
  20796. const ast = this.ast;
  20797. const builtins = this.builtins;
  20798. if (stmt instanceof ast.Pass) {
  20799. // pass
  20800. } else if (stmt instanceof ast.Constant) {
  20801. // pass
  20802. } else if (stmt instanceof ast.Return) {
  20803. return this.expression(stmt.value, context);
  20804. } else if (stmt instanceof ast.FunctionDef) {
  20805. const module = context.get('__name__');
  20806. /* eslint-disable consistent-this */
  20807. const self = this;
  20808. /* eslint-enable consistent-this */
  20809. const parent = context.get('__class__');
  20810. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  20811. const func = {
  20812. __class__: type,
  20813. __globals__: context,
  20814. __module__: module,
  20815. __name__: stmt.name,
  20816. __code__: stmt,
  20817. __call__(args) {
  20818. return self.apply(this.__code__, args, this.__globals__);
  20819. }
  20820. };
  20821. context.set(stmt.name, func);
  20822. } else if (stmt instanceof ast.ClassDef) {
  20823. const bases = stmt.bases.map((base) => this.base(base, context));
  20824. if (bases.length > 1) {
  20825. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  20826. }
  20827. const base = bases.length === 1 ? bases[0] : null;
  20828. const name = `${context.get('__name__')}.${stmt.name}`;
  20829. const value = this._createType(name, base ? class extends base {} : class {});
  20830. value.__bases__ = bases;
  20831. context.set(stmt.name, value);
  20832. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  20833. } else if (stmt instanceof ast.AnnAssign) {
  20834. const target = this.identifier(stmt.target, context);
  20835. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  20836. } else if (stmt instanceof ast.Assign) {
  20837. this.expression(stmt, context);
  20838. } else if (stmt instanceof ast.If) {
  20839. const test = this.expression(stmt.test, context);
  20840. if (test === true || test) {
  20841. const value = this.block(stmt.body, context);
  20842. if (value !== undefined) {
  20843. return value;
  20844. }
  20845. } else if (test === false) {
  20846. if (stmt.orelse) {
  20847. const value = this.block(stmt.orelse, context);
  20848. if (value !== undefined) {
  20849. return value;
  20850. }
  20851. }
  20852. } else {
  20853. throw new python.Error('Unsupported condition.');
  20854. }
  20855. } else if (stmt instanceof ast.For) {
  20856. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  20857. const range = this.expression(stmt.iter, context);
  20858. const variable = stmt.target;
  20859. for (const current of range) {
  20860. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  20861. const value = this.block(stmt.body.statements, context);
  20862. if (value !== undefined) {
  20863. return value;
  20864. }
  20865. }
  20866. } else {
  20867. throw new python.Error("Unsupported 'for' statement.");
  20868. }
  20869. } else if (stmt instanceof ast.While) {
  20870. const test = this.expression(stmt.test, context);
  20871. if (test) {
  20872. const value = this.block(stmt.body.statements, context);
  20873. if (value !== undefined) {
  20874. return value;
  20875. }
  20876. }
  20877. } else if (stmt instanceof ast.With) {
  20878. const items = [];
  20879. for (const item of stmt.items) {
  20880. items.push(this.expression(item.context_expr, context));
  20881. }
  20882. for (const item of items) {
  20883. if (item.__enter__ && item.__enter__.__call__) {
  20884. item.__enter__.__call__([item]);
  20885. }
  20886. }
  20887. const value = this.block(stmt.body, context);
  20888. for (const item of items) {
  20889. if (item.__exit__ && item.__exit__.__call__) {
  20890. item.__exit__.__call__([item]);
  20891. }
  20892. }
  20893. if (value !== undefined) {
  20894. return value;
  20895. }
  20896. } else if (stmt instanceof ast.Expr) {
  20897. this.expression(stmt.value, context);
  20898. } else if (stmt instanceof ast.Import) {
  20899. for (const alias of stmt.names) {
  20900. let module = this.__import__(alias.name, context);
  20901. if (alias.asname) {
  20902. const bits = alias.name.split('.').reverse();
  20903. bits.pop();
  20904. while (bits.length > 0) {
  20905. module = module[bits.pop()];
  20906. }
  20907. context.set(alias.asname, module);
  20908. } else {
  20909. context.set(alias.name.split('.')[0], module);
  20910. }
  20911. }
  20912. } else if (stmt instanceof ast.ImportFrom) {
  20913. const fromlist = stmt.names.map((name) => name.name);
  20914. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  20915. for (const entry of stmt.names) {
  20916. const name = entry.name;
  20917. const asname = entry.asname ? entry.asname : null;
  20918. if (!module[name]) {
  20919. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  20920. }
  20921. context.set(asname ? asname : name, module[name]);
  20922. }
  20923. } else {
  20924. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  20925. }
  20926. return undefined;
  20927. }
  20928. expression(expr, context) {
  20929. const ast = this.ast;
  20930. const builtins = this.builtins;
  20931. const typing = this.typing;
  20932. const self = context.get('self');
  20933. switch (expr.__class__.__name__) {
  20934. case 'Assign': {
  20935. const [target] = expr.targets;
  20936. if (target instanceof ast.Name) {
  20937. const value = this.expression(expr.value, context);
  20938. context.set(target.id, value);
  20939. return undefined;
  20940. } else if (target instanceof ast.Subscript) {
  20941. if (target.value instanceof ast.Name &&
  20942. target.slice instanceof ast.List &&
  20943. target.slice.elts.length === 1) {
  20944. const index = this.expression(target.slice.elts[0], context);
  20945. const id = target.value.id;
  20946. if (id === '__annotations__') {
  20947. context.set(id, context.get(id) || {});
  20948. }
  20949. const obj = context.get(id);
  20950. const value = this.expression(expr.value, context);
  20951. if (obj instanceof Map) {
  20952. obj.set(index, value);
  20953. } else {
  20954. obj[index] = value;
  20955. }
  20956. return undefined;
  20957. }
  20958. } else if (target instanceof ast.Attribute) {
  20959. const obj = this.expression(target.value, context);
  20960. const value = this.expression(expr.value, context);
  20961. obj[target.attr] = value;
  20962. return undefined;
  20963. } else if (target instanceof ast.Tuple) {
  20964. context.target.push(target.elts);
  20965. const value = this.expression(expr.value, context);
  20966. context.target.pop();
  20967. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  20968. if (target.elts.length < value.length) {
  20969. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  20970. }
  20971. if (target.elts.length > value.length) {
  20972. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  20973. }
  20974. for (let i = 0; i < value.length; i++) {
  20975. context.set(target.elts[i].id, value[i]);
  20976. }
  20977. return undefined;
  20978. }
  20979. }
  20980. break;
  20981. }
  20982. case 'List': {
  20983. return expr.elts.map((expr) => this.expression(expr, context));
  20984. }
  20985. case 'Constant': {
  20986. return expr.value;
  20987. }
  20988. case 'Subscript': {
  20989. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  20990. const id = expr.value.id;
  20991. if (context.get(id)) {
  20992. const index = this.expression(expr.slice, context);
  20993. const target = context.get(id);
  20994. if (target instanceof Map) {
  20995. return target.get(index);
  20996. }
  20997. return target[index < 0 ? target.length + index : index];
  20998. }
  20999. }
  21000. const value = this.expression(expr.value, context);
  21001. if (value && expr.slice instanceof ast.List &&
  21002. (value.__class__ === typing._TupleType ||
  21003. value.__class__ === typing._SpecialGenericAlias ||
  21004. value.__class__ === typing._SpecialForm)) {
  21005. const type = { ...value };
  21006. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21007. return type;
  21008. }
  21009. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21010. const index = this.expression(expr.slice.elts[0], context);
  21011. if (value instanceof Map) {
  21012. return value.get(index);
  21013. }
  21014. return value[index < 0 ? value.length + index : index];
  21015. }
  21016. break;
  21017. }
  21018. case 'Attribute': {
  21019. const value = this.target(expr.value, context);
  21020. return value[expr.attr];
  21021. }
  21022. case 'Call': {
  21023. const func = expr.func;
  21024. if (func instanceof ast.Attribute) {
  21025. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21026. }
  21027. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21028. }
  21029. case 'Name': {
  21030. const id = expr.id;
  21031. if (id === 'self') {
  21032. return self;
  21033. }
  21034. const type = (value) => {
  21035. return value &&
  21036. (value.__class__ === builtins.type ||
  21037. value.__class__ === typing._TupleType ||
  21038. value.__class__ === typing._SpecialGenericAlias ||
  21039. value.__class__ === typing._SpecialForm);
  21040. };
  21041. const builtin = builtins[id];
  21042. if (type(builtin)) {
  21043. return builtin;
  21044. }
  21045. const value = context.get(id);
  21046. if (value === undefined) {
  21047. const value = typing[id];
  21048. if (type(value)) {
  21049. return value;
  21050. }
  21051. }
  21052. return value;
  21053. }
  21054. case 'Tuple': {
  21055. return expr.elts.map((expr) => this.expression(expr, context));
  21056. }
  21057. case 'Dict': {
  21058. const dict = {};
  21059. for (let i = 0; i < expr.keys.length; i++) {
  21060. const key = this.expression(expr.keys[i], context);
  21061. const value = this.expression(expr.values[i], context);
  21062. dict[key] = value;
  21063. }
  21064. return dict;
  21065. }
  21066. case 'UnaryOp': {
  21067. if (expr.op instanceof ast.USub) {
  21068. return -this.expression(expr.operand, context);
  21069. }
  21070. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21071. }
  21072. case 'binary': {
  21073. switch (expr.op) {
  21074. case '==': {
  21075. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21076. }
  21077. default: {
  21078. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21079. }
  21080. }
  21081. }
  21082. default: {
  21083. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21084. }
  21085. }
  21086. return undefined;
  21087. }
  21088. base(expr, context) {
  21089. return this.expression(expr, context);
  21090. }
  21091. identifier(expr) {
  21092. const ast = this.ast;
  21093. if (expr instanceof ast.Name) {
  21094. return expr.id;
  21095. }
  21096. if (expr instanceof ast.Attribute) {
  21097. return `${this.identifier(expr.value)}.${expr.attr}`;
  21098. }
  21099. return null;
  21100. }
  21101. target(expr, context) {
  21102. const ast = this.ast;
  21103. let current = expr;
  21104. let path = [];
  21105. for (;;) {
  21106. if (current instanceof ast.Attribute) {
  21107. path.push(current.attr);
  21108. current = current.value;
  21109. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21110. path.push(current.id);
  21111. break;
  21112. } else {
  21113. path = null;
  21114. break;
  21115. }
  21116. }
  21117. if (path) {
  21118. let target = null;
  21119. for (let i = path.length - 1; i >= 0; i--) {
  21120. const name = path[i];
  21121. if (target) {
  21122. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21123. } else {
  21124. target = context.get(name);
  21125. }
  21126. if (!target) {
  21127. break;
  21128. }
  21129. }
  21130. if (!target) {
  21131. path.reverse();
  21132. const name = path.join('.');
  21133. const file = `${path.join('/')}.py`;
  21134. if (this._sources.has(file)) {
  21135. target = this.import(name);
  21136. } else {
  21137. target = this.resolve(name);
  21138. }
  21139. }
  21140. return target;
  21141. }
  21142. return this.expression(expr, context);
  21143. }
  21144. add(name, source) {
  21145. this._sources.set(name, source);
  21146. }
  21147. on(event, listener) {
  21148. const value = this._events.get(event) || [];
  21149. value.push(listener);
  21150. this._events.set(event, value);
  21151. }
  21152. emit(event, ...args) {
  21153. if (this._events.has(event)) {
  21154. for (const callback of this._events.get(event)) {
  21155. callback(this, ...args);
  21156. }
  21157. }
  21158. }
  21159. register(name, value) {
  21160. if (!this._registry.has(name)) {
  21161. value = value || new (this._registry.get('builtins').module)(name);
  21162. this._registry.set(name, value);
  21163. let current = name;
  21164. for (;;) {
  21165. const index = current.lastIndexOf('.');
  21166. if (index === -1) {
  21167. break;
  21168. }
  21169. const child = current.substring(index + 1);
  21170. current = current.substring(0, index);
  21171. if (!value.__module__) {
  21172. value.__module__ = current;
  21173. }
  21174. const parent = this.register(current);
  21175. parent[child] = value;
  21176. value = parent;
  21177. }
  21178. }
  21179. return this._registry.get(name);
  21180. }
  21181. registerFunction(name, value) {
  21182. const builtins = this.builtins;
  21183. const index = name.lastIndexOf('.');
  21184. if (!value) {
  21185. value = () => {
  21186. throw new python.Error(`'${name}' is not implemented.`);
  21187. };
  21188. }
  21189. value.__class__ = builtins.function;
  21190. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21191. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21192. const module = this.register(value.__module__);
  21193. if (module[name]) {
  21194. throw new python.Error(`Function '${name}' is already registered.`);
  21195. }
  21196. module[value.__name__] = value;
  21197. return value;
  21198. }
  21199. registerOperator(name, value) {
  21200. this._operators.set(name, value);
  21201. }
  21202. _createType(name, value) {
  21203. const builtins = this.builtins;
  21204. const index = name.lastIndexOf('.');
  21205. value.__class__ = builtins.type;
  21206. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21207. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21208. value.prototype.__class__ = value;
  21209. return value;
  21210. }
  21211. registerType(name, value) {
  21212. value = this._createType(name, value);
  21213. const parts = name.split('.');
  21214. const memberName = parts.pop();
  21215. const moduleName = parts.join('.');
  21216. const module = this.register(moduleName);
  21217. if (module[memberName]) {
  21218. throw new python.Error(`Class '${memberName}' is already registered.`);
  21219. }
  21220. module[memberName] = value;
  21221. return value;
  21222. }
  21223. };
  21224. python.Execution.Context = class {
  21225. constructor(globals, locals) {
  21226. this.globals = globals;
  21227. this.locals = locals;
  21228. }
  21229. set(name, value) {
  21230. if (this.locals) {
  21231. this.locals[name] = value;
  21232. } else {
  21233. this.globals[name] = value;
  21234. }
  21235. }
  21236. get(name) {
  21237. if (this.locals && name in this.locals) {
  21238. return this.locals[name];
  21239. }
  21240. if (name in this.globals) {
  21241. return this.globals[name];
  21242. }
  21243. return undefined;
  21244. }
  21245. get target() {
  21246. this._target = this._target || [];
  21247. return this._target;
  21248. }
  21249. };
  21250. python.BinaryReader = class {
  21251. constructor(buffer) {
  21252. this._buffer = buffer;
  21253. this._length = buffer.length;
  21254. this._position = 0;
  21255. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21256. this._utf8Decoder = new TextDecoder('utf-8');
  21257. this._asciiDecoder = new TextDecoder('ascii');
  21258. }
  21259. get position() {
  21260. return this._position;
  21261. }
  21262. get length() {
  21263. return this._length;
  21264. }
  21265. seek(position) {
  21266. this._position = position >= 0 ? position : this._length + position;
  21267. if (this._position > this._buffer.length) {
  21268. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21269. }
  21270. }
  21271. skip(offset) {
  21272. this._position += offset;
  21273. if (this._position > this._buffer.length) {
  21274. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21275. }
  21276. }
  21277. stream(length) {
  21278. const buffer = this.read(length);
  21279. return new python.BinaryReader(buffer);
  21280. }
  21281. peek(length) {
  21282. const position = this._position;
  21283. length = length === undefined ? this._length - this._position : length;
  21284. this.skip(length);
  21285. const end = this._position;
  21286. this.skip(-length);
  21287. if (position === 0 && length === this._length) {
  21288. return this._buffer;
  21289. }
  21290. return this._buffer.subarray(position, end);
  21291. }
  21292. read(length) {
  21293. const position = this._position;
  21294. length = length === undefined ? this._length - this._position : length;
  21295. this.skip(length);
  21296. if (position === 0 && length === this._length) {
  21297. return this._buffer;
  21298. }
  21299. return this._buffer.subarray(position, this._position);
  21300. }
  21301. byte() {
  21302. const position = this._position;
  21303. this.skip(1);
  21304. return this._view.getUint8(position);
  21305. }
  21306. uint16() {
  21307. const position = this._position;
  21308. this.skip(2);
  21309. return this._view.getUint16(position, true);
  21310. }
  21311. int32() {
  21312. const position = this._position;
  21313. this.skip(4);
  21314. return this._view.getInt32(position, true);
  21315. }
  21316. uint32() {
  21317. const position = this._position;
  21318. this.skip(4);
  21319. return this._view.getUint32(position, true);
  21320. }
  21321. int64() {
  21322. const position = this._position;
  21323. this.skip(8);
  21324. return this._view.getBigInt64(position, true);
  21325. }
  21326. float64() {
  21327. const position = this._position;
  21328. this.skip(8);
  21329. return this._view.getFloat64(position, false);
  21330. }
  21331. string(size, encoding) {
  21332. const data = this.read(size);
  21333. return (encoding === 'utf-8') ?
  21334. this._utf8Decoder.decode(data) :
  21335. this._asciiDecoder.decode(data);
  21336. }
  21337. line() {
  21338. const index = this._buffer.indexOf(0x0A, this._position);
  21339. if (index === -1) {
  21340. throw new python.Error('Could not find end of line.');
  21341. }
  21342. const size = index - this._position;
  21343. const text = this.string(size, 'ascii');
  21344. this.skip(1);
  21345. return text;
  21346. }
  21347. };
  21348. python.StreamReader = class {
  21349. constructor(stream) {
  21350. this._stream = stream;
  21351. this._length = stream.length;
  21352. this._position = 0;
  21353. this._utf8Decoder = new TextDecoder('utf-8');
  21354. this._asciiDecoder = new TextDecoder('ascii');
  21355. }
  21356. get position() {
  21357. return this._position;
  21358. }
  21359. get length() {
  21360. return this._length;
  21361. }
  21362. seek(position) {
  21363. this._stream.seek(position);
  21364. this._position = this._stream.position;
  21365. }
  21366. skip(offset) {
  21367. this._position += offset;
  21368. if (this._position > this._length) {
  21369. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21370. }
  21371. }
  21372. stream(length) {
  21373. this._stream.seek(this._position);
  21374. this.skip(length);
  21375. return this._stream.stream(length);
  21376. }
  21377. peek(length) {
  21378. this._stream.seek(this._position);
  21379. return this._stream.peek(length);
  21380. }
  21381. read(length) {
  21382. this._stream.seek(this._position);
  21383. this.skip(length);
  21384. return this._stream.read(length);
  21385. }
  21386. byte() {
  21387. const position = this._fill(1);
  21388. return this._view.getUint8(position);
  21389. }
  21390. uint16() {
  21391. const position = this._fill(2);
  21392. return this._view.getUint16(position, true);
  21393. }
  21394. int32() {
  21395. const position = this._fill(4);
  21396. return this._view.getInt32(position, true);
  21397. }
  21398. uint32() {
  21399. const position = this._fill(4);
  21400. return this._view.getUint32(position, true);
  21401. }
  21402. int64() {
  21403. const position = this._fill(8);
  21404. return this._view.getBigInt64(position, true);
  21405. }
  21406. float64() {
  21407. const position = this._fill(8);
  21408. return this._view.getFloat64(position, false);
  21409. }
  21410. string(size, encoding) {
  21411. const data = this.read(size);
  21412. return (encoding === 'utf-8') ?
  21413. this._utf8Decoder.decode(data) :
  21414. this._asciiDecoder.decode(data);
  21415. }
  21416. line() {
  21417. let position = this._fill(0);
  21418. let index = this._buffer.indexOf(0x0A, position);
  21419. if (index === -1) {
  21420. const size = Math.min(0x20000000, this._stream.length - this._position);
  21421. this._fill(size);
  21422. this.skip(-size);
  21423. position = this._fill(0);
  21424. index = this._buffer.indexOf(0x0A, position);
  21425. if (index === -1) {
  21426. throw new python.Error('Could not find end of line.');
  21427. }
  21428. }
  21429. const size = index - position;
  21430. const text = this.string(size, 'ascii');
  21431. this.skip(1);
  21432. return text;
  21433. }
  21434. _fill(length) {
  21435. if (this._position + length > this._length) {
  21436. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21437. }
  21438. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21439. this._offset = this._position;
  21440. this._stream.seek(this._offset);
  21441. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21442. this._buffer = this._stream.read(size);
  21443. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21444. }
  21445. const position = this._position;
  21446. this._position += length;
  21447. return position - this._offset;
  21448. }
  21449. };
  21450. python.Error = class extends Error {
  21451. constructor(message) {
  21452. super(message);
  21453. this.name = 'Python Error';
  21454. }
  21455. };
  21456. export const Execution = python.Execution;