python.js 952 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Execution = class {
  4. constructor(sources) {
  5. const self = this;
  6. const execution = self;
  7. this._sources = sources || new Map();
  8. this._events = new Map();
  9. this._utf8Decoder = new TextDecoder('utf-8');
  10. this._unresolved = new Map();
  11. const dict = class extends Map {
  12. constructor(items) {
  13. super();
  14. if (items) {
  15. if (items instanceof Map) {
  16. items = Array.from(items);
  17. } else if (!Array.isArray(items)) {
  18. items = Object.entries(items);
  19. }
  20. for (const [name, value] of items) {
  21. this.__setitem__(name, value);
  22. }
  23. }
  24. }
  25. __contains__(key) {
  26. return this.has(key);
  27. }
  28. __setitem__(key, value) {
  29. this.set(key, value);
  30. }
  31. __getitem__(key) {
  32. return this.get(key);
  33. }
  34. __delitem__(key) {
  35. this.delete(key);
  36. }
  37. get(key, defaultValue) {
  38. return super.get(key) || defaultValue;
  39. }
  40. setdefault(key, defaultValue) {
  41. if (this.has(key)) {
  42. return this.get(key);
  43. }
  44. const value = defaultValue || null;
  45. this.set(key, value);
  46. return value;
  47. }
  48. pop(key) {
  49. if (this.__contains__(key)) {
  50. const v = this.__getitem__(key);
  51. this.__delitem__(key);
  52. return v;
  53. }
  54. return null;
  55. }
  56. items() {
  57. return Array.from(this);
  58. }
  59. update(other) {
  60. for (const [key, value] of other) {
  61. this.set(key, value);
  62. }
  63. }
  64. };
  65. this._modules = new dict();
  66. this._registry = new Map();
  67. const module = class {
  68. constructor(name) {
  69. this.__name__ = name;
  70. }
  71. };
  72. const builtins = this.register('builtins', new module('builtins'));
  73. this.builtins = builtins;
  74. this._registry.set('__builtin__', builtins);
  75. this.registerType('builtins.type', class {
  76. constructor(...args) {
  77. if (args.length === 1) {
  78. const [obj] = args;
  79. if (obj === null) {
  80. /* eslint-disable no-constructor-return */
  81. return builtins.NoneType;
  82. /* eslint-enable no-constructor-return */
  83. }
  84. if (obj && obj.__class__) {
  85. /* eslint-disable no-constructor-return */
  86. return obj.__class__;
  87. /* eslint-enable no-constructor-return */
  88. }
  89. throw new python.Error(`Unknown type '${obj}'`);
  90. }
  91. if (args.length === 3) {
  92. const [name, bases, body] = args;
  93. const cls = bases.length > 0 ? class extends bases[0] {} : class {};
  94. execution.registerType(name, cls);
  95. for (const [key, value] of body) {
  96. cls[key] = value;
  97. }
  98. /* eslint-disable no-constructor-return */
  99. return cls;
  100. /* eslint-enable no-constructor-return */
  101. }
  102. throw new python.Error(`Invalid 'builtins.dict' argument count.`);
  103. }
  104. }).__class__ = builtins.type;
  105. this.registerType('builtins.module', module);
  106. this.registerType('builtins.method', class {});
  107. this.registerType('builtins.function', class {
  108. constructor(code, globals, name) {
  109. this.__code__ = code;
  110. this.__globals__ = globals;
  111. this.__name__ = name;
  112. }
  113. });
  114. this.registerType('builtins.classmethod', class {});
  115. this.registerType('builtins.code', class {});
  116. this.import('builtins');
  117. this.registerType('builtins.builtin_function_or_method', class {});
  118. const typing = this.register('typing');
  119. this.typing = typing;
  120. const operator = this.register('operator');
  121. this.register('_codecs');
  122. this.register('argparse');
  123. this._enum = this.register('enum');
  124. this.register('collections');
  125. const copy = this.register('copy');
  126. this.register('copy_reg');
  127. const ast = this.register('ast');
  128. this.ast = ast;
  129. this.register('cuml');
  130. const cloudpickle = this.register('cloudpickle');
  131. const datetime = this.register('datetime');
  132. this.register('gensim');
  133. const io = this.register('io');
  134. const joblib = this.register('joblib');
  135. const jax = this.register('jax');
  136. this.register('jax.numpy');
  137. this.register('jax._src.array');
  138. this.register('jax._src.device_array');
  139. const functools = this.register('functools');
  140. this.registerType('functools.partial', class {});
  141. const keras = this.register('keras');
  142. const catboost = this.register('catboost');
  143. this.register('lightgbm');
  144. this.register('nolearn');
  145. const fastcore = this.register('fastcore');
  146. const fastai = this.register('fastai');
  147. const math = this.register('math');
  148. math.inf = Infinity;
  149. const numpy = this.register('numpy');
  150. this.register('numpy.core.multiarray');
  151. this.register('numpy.core._multiarray_umath');
  152. this.register('numpy.matrixlib.defmatrix');
  153. const pandas = this.register('pandas');
  154. this.register('pandas.indexes.base');
  155. this.register('pandas.indexes.range');
  156. this.register('pandas._libs.tslib');
  157. this.register('pandas._libs.internals');
  158. const pickle = this.register('pickle');
  159. const shap = this.register('shap');
  160. this.register('shap.explainers.linear');
  161. const sklearn = this.register('sklearn');
  162. this.register('sklearn.externals.joblib.numpy_pickle');
  163. const torch = this.register('torch');
  164. this.torch = torch;
  165. const torchvision = this.register('torchvision');
  166. this.register('torch.storage');
  167. this.register('torch.nn.parameter');
  168. this.register('torch.ops');
  169. this.register('torch._ops');
  170. this.register('torch.ops.torchvision');
  171. this.register('torch.ops.torchaudio');
  172. this.register('torch.ops._caffe2');
  173. this.register('torchvision');
  174. this.register('__torch__');
  175. const sys = this.register('sys');
  176. sys.modules = this._modules;
  177. this.register('xgboost');
  178. this.registerType('ast.AST', class {});
  179. this.registerType('ast.mod', class extends ast.AST {});
  180. this.registerType('ast.expr', class extends ast.AST {});
  181. this.registerType('ast.unaryop', class extends ast.AST {});
  182. this.registerType('ast.binop', class extends ast.AST {});
  183. this.registerType('ast.operator', class extends ast.AST {});
  184. this.registerType('ast.boolop', class extends ast.AST {});
  185. this.registerType('ast.cmpop', class extends ast.AST {});
  186. this.registerType('ast.stmt', class extends ast.AST {});
  187. this.registerType('ast.excepthandler', class extends ast.AST {});
  188. this.registerType('ast.keyword', class extends ast.AST {
  189. constructor(arg, value) {
  190. super();
  191. this.arg = arg;
  192. this.value = value;
  193. }
  194. });
  195. this.registerType('ast.alias', class extends ast.AST {
  196. constructor(name, asname) {
  197. super();
  198. this.name = name;
  199. this.asname = asname;
  200. }
  201. });
  202. this.registerType('ast.Name', class extends ast.expr {
  203. constructor(id, ctx) {
  204. super();
  205. this.id = id;
  206. if (ctx) {
  207. this.ctx = ctx;
  208. }
  209. }
  210. });
  211. this.registerType('ast.Constant', class extends ast.expr {
  212. constructor(value, type) {
  213. super();
  214. this.value = value;
  215. this.type = type || null;
  216. }
  217. });
  218. this.registerType('ast.Ellipsis', class extends ast.Constant {
  219. constructor() {
  220. super(builtins.ellipsis);
  221. }
  222. });
  223. this.registerType('ast.Starred', class extends ast.expr {
  224. constructor(value, ctx) {
  225. super();
  226. this.value = value;
  227. if (ctx) {
  228. this.ctx = ctx;
  229. }
  230. }
  231. });
  232. this.registerType('ast.List', class extends ast.expr {
  233. constructor(elts, ctx) {
  234. super();
  235. this.elts = elts;
  236. if (ctx) {
  237. this.ctx = ctx;
  238. }
  239. }
  240. });
  241. this.registerType('ast.Set', class extends ast.expr {
  242. constructor(elts) {
  243. super();
  244. this.elts = elts;
  245. }
  246. });
  247. this.registerType('ast.Tuple', class extends ast.expr {
  248. constructor(elts, ctx) {
  249. super();
  250. this.elts = elts;
  251. if (ctx) {
  252. this.ctx = ctx;
  253. }
  254. }
  255. });
  256. this.registerType('ast.Dict', class extends ast.expr {
  257. constructor(keys, values) {
  258. super();
  259. this.keys = keys;
  260. this.values = values;
  261. }
  262. });
  263. this.registerType('ast.ListComp', class extends ast.expr {
  264. constructor(elt, generators) {
  265. super();
  266. this.elt = elt;
  267. this.generators = generators;
  268. }
  269. });
  270. this.registerType('ast.SetComp', class extends ast.expr {
  271. constructor(elt, generators) {
  272. super();
  273. this.elt = elt;
  274. this.generators = generators;
  275. }
  276. });
  277. this.registerType('ast.GeneratorExp', class extends ast.expr {
  278. constructor(elt, generators) {
  279. super();
  280. this.elt = elt;
  281. this.generators = generators;
  282. }
  283. });
  284. this.registerType('ast.DictComp', class extends ast.expr {
  285. constructor(key, value, generators) {
  286. super();
  287. this.key = key;
  288. this.value = value;
  289. this.generators = generators;
  290. }
  291. });
  292. this.registerType('ast.comprehension', class extends ast.AST {
  293. constructor(target, iter, ifs, is_async) {
  294. super();
  295. this.target = target;
  296. this.iter = iter;
  297. this.ifs = ifs;
  298. this.is_async = is_async;
  299. }
  300. });
  301. this.registerType('ast.Subscript', class extends ast.expr {
  302. constructor(value, slice, ctx) {
  303. super();
  304. this.value = value;
  305. this.slice = slice;
  306. if (ctx) {
  307. this.ctx = ctx;
  308. }
  309. }
  310. });
  311. this.registerType('ast.Slice', class extends ast.expr {
  312. constructor(lower, upper, step) {
  313. super();
  314. this.lower = lower;
  315. this.upper = upper;
  316. this.step = step;
  317. }
  318. });
  319. this.registerType('ast.UnaryOp', class extends ast.expr {
  320. constructor(op, operand) {
  321. super();
  322. this.op = op;
  323. this.operand = operand;
  324. }
  325. });
  326. this.registerType('ast.UAdd', class extends ast.unaryop {});
  327. this.registerType('ast.USub', class extends ast.unaryop {});
  328. this.registerType('ast.Not', class extends ast.unaryop {});
  329. this.registerType('ast.Invert', class extends ast.unaryop {});
  330. this.registerType('ast.BinOp', class extends ast.expr {
  331. constructor(left, op, right) {
  332. super();
  333. this.left = left;
  334. this.op = op;
  335. this.right = right;
  336. }
  337. });
  338. this.registerType('ast.Add', class extends ast.operator {});
  339. this.registerType('ast.Sub', class extends ast.operator {});
  340. this.registerType('ast.Mult', class extends ast.operator {});
  341. this.registerType('ast.Div', class extends ast.operator {});
  342. this.registerType('ast.FloorDiv', class extends ast.operator {});
  343. this.registerType('ast.Mod', class extends ast.operator {});
  344. this.registerType('ast.Pow', class extends ast.operator {});
  345. this.registerType('ast.LShift', class extends ast.operator {});
  346. this.registerType('ast.RShift', class extends ast.operator {});
  347. this.registerType('ast.BitOr', class extends ast.operator {});
  348. this.registerType('ast.BitXor', class extends ast.operator {});
  349. this.registerType('ast.BitAnd', class extends ast.operator {});
  350. this.registerType('ast.MatMult', class extends ast.operator {});
  351. this.registerType('ast.BoolOp', class extends ast.expr {
  352. constructor(op, values) {
  353. super();
  354. this.op = op;
  355. this.values = values;
  356. }
  357. });
  358. this.registerType('ast.And', class extends ast.boolop {});
  359. this.registerType('ast.Or', class extends ast.boolop {});
  360. this.registerType('ast.Compare', class extends ast.expr {
  361. constructor(left, ops, comparators) {
  362. super();
  363. this.left = left;
  364. this.ops = ops;
  365. this.comparators = comparators;
  366. }
  367. });
  368. this.registerType('ast.Eq', class extends ast.cmpop {});
  369. this.registerType('ast.NotEq', class extends ast.cmpop {});
  370. this.registerType('ast.Lt', class extends ast.cmpop {});
  371. this.registerType('ast.LtE', class extends ast.cmpop {});
  372. this.registerType('ast.Gt', class extends ast.cmpop {});
  373. this.registerType('ast.GtE', class extends ast.cmpop {});
  374. this.registerType('ast.Is', class extends ast.cmpop {});
  375. this.registerType('ast.IsNot', class extends ast.cmpop {});
  376. this.registerType('ast.In', class extends ast.cmpop {});
  377. this.registerType('ast.NotIn', class extends ast.cmpop {});
  378. this.registerType('ast.Call', class extends ast.expr {
  379. constructor(func, args, keywords) {
  380. super();
  381. this.func = func;
  382. this.args = args;
  383. this.keywords = keywords || [];
  384. }
  385. });
  386. this.registerType('ast.Attribute', class extends ast.expr {
  387. constructor(value, attr, ctx) {
  388. super();
  389. this.value = value;
  390. this.attr = attr;
  391. if (ctx) {
  392. this.ctx = ctx;
  393. }
  394. }
  395. });
  396. this.registerType('ast.Lambda', class extends ast.expr {
  397. constructor(args, body) {
  398. super();
  399. this.args = args;
  400. this.body = body;
  401. }
  402. });
  403. this.registerType('ast.IfExp', class extends ast.expr {
  404. constructor(test, body, orelse) {
  405. super();
  406. this.test = test;
  407. this.body = body;
  408. this.orelse = orelse;
  409. }
  410. });
  411. this.registerType('ast.NamedExpr', class extends ast.expr {
  412. constructor(target, value) {
  413. super();
  414. this.target = target;
  415. this.value = value;
  416. }
  417. });
  418. this.registerType('ast.Yield', class extends ast.expr {
  419. constructor(value) {
  420. super();
  421. this.value = value;
  422. }
  423. });
  424. this.registerType('ast.YieldFrom', class extends ast.expr {
  425. constructor(value) {
  426. super();
  427. this.value = value;
  428. }
  429. });
  430. this.registerType('ast.Expr', class extends ast.stmt {
  431. constructor(value) {
  432. super();
  433. this.value = value;
  434. }
  435. });
  436. this.registerType('ast.Assign', class extends ast.stmt {
  437. constructor(targets, value, ctx) {
  438. super();
  439. this.targets = targets;
  440. this.value = value;
  441. if (ctx) {
  442. this.ctx = ctx;
  443. }
  444. }
  445. });
  446. this.registerType('ast.AnnAssign', class extends ast.stmt {
  447. constructor(target, annotation, value, simple) {
  448. super();
  449. this.target = target;
  450. this.annotation = annotation;
  451. this.value = value;
  452. this.simple = simple;
  453. }
  454. });
  455. this.registerType('ast.AugAssign', class extends ast.stmt {
  456. constructor(target, op, value) {
  457. super();
  458. this.target = target;
  459. this.op = op;
  460. this.value = value;
  461. }
  462. });
  463. this.registerType('ast.If', class extends ast.stmt {
  464. constructor(test, body, orelse) {
  465. super();
  466. this.test = test;
  467. this.body = body;
  468. this.orelse = orelse;
  469. }
  470. });
  471. this.registerType('ast.For', class extends ast.stmt {
  472. constructor(target, iter, body, orelse /*, type_comment */) {
  473. super();
  474. this.target = target;
  475. this.iter = iter;
  476. this.body = body;
  477. this.orelse = orelse;
  478. }
  479. });
  480. this.registerType('ast.While', class extends ast.stmt {
  481. constructor(test, body, orelse /*, type_comment */) {
  482. super();
  483. this.test = test;
  484. this.body = body;
  485. this.orelse = orelse;
  486. }
  487. });
  488. this.registerType('ast.Del', class extends ast.stmt {
  489. constructor(targets) {
  490. super();
  491. this.targets = targets;
  492. }
  493. });
  494. this.registerType('ast.Return', class extends ast.stmt {
  495. constructor(value) {
  496. super();
  497. this.value = value;
  498. }
  499. });
  500. this.registerType('ast.Try', class extends ast.stmt {
  501. constructor(body, handlers, orelse, finalbody) {
  502. super();
  503. this.body = body;
  504. this.handlers = handlers;
  505. this.orelse = orelse;
  506. this.finalbody = finalbody;
  507. }
  508. });
  509. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  510. constructor(type, name, body) {
  511. super();
  512. this.type_ = type;
  513. this.name = name;
  514. this.body = body;
  515. }
  516. });
  517. this.registerType('ast.ClassDef', class extends ast.stmt {
  518. constructor(name, bases, keywords, body, decorator_list, type_params) {
  519. super();
  520. this.name = name;
  521. this.bases = bases;
  522. this.keywords = keywords;
  523. this.body = body;
  524. this.decorator_list = decorator_list;
  525. this.type_params = type_params;
  526. }
  527. });
  528. this.registerType('ast.FunctionDef', class extends ast.stmt {
  529. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  530. super();
  531. this.name = name;
  532. this.args = args;
  533. this.body = body;
  534. this.decorator_list = decorator_list;
  535. this.returns = returns;
  536. this.type_comment = type_comment;
  537. this.type_params = type_params;
  538. }
  539. });
  540. this.registerType('ast.arguments', class extends ast.AST {
  541. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  542. super();
  543. this.posonlyargs = posonlyargs;
  544. this.args = args;
  545. this.vararg = vararg;
  546. this.kwonlyargs = kwonlyargs;
  547. this.kw_defaults = kw_defaults;
  548. this.kwarg = kwarg;
  549. this.defaults = defaults;
  550. }
  551. });
  552. this.registerType('ast.arg', class extends ast.AST {
  553. constructor(arg, annotation, type_comment) {
  554. super();
  555. this.arg = arg;
  556. this.annotation = annotation;
  557. this.type_comment = type_comment;
  558. }
  559. });
  560. this.registerType('ast.Import', class extends ast.stmt {
  561. constructor(names) {
  562. super();
  563. this.names = names;
  564. }
  565. });
  566. this.registerType('ast.ImportFrom', class extends ast.stmt {
  567. constructor(module, names, level) {
  568. super();
  569. this.module = module;
  570. this.names = names;
  571. this.level = level;
  572. }
  573. });
  574. this.registerType('ast.Assert', class extends ast.stmt {
  575. constructor(test, msg) {
  576. super();
  577. this.test = test;
  578. this.msg = msg;
  579. }
  580. });
  581. this.registerType('ast.Raise', class extends ast.stmt {
  582. constructor(exc, cause) {
  583. super();
  584. this.exc = exc;
  585. this.cause = cause;
  586. }
  587. });
  588. this.registerType('ast.With', class extends ast.stmt {
  589. constructor(items, body, type_comment) {
  590. super();
  591. this.items = items;
  592. this.body = body;
  593. this.type_comment = type_comment;
  594. }
  595. });
  596. this.registerType('ast.withitem', class extends ast.AST {
  597. constructor(context_expr, optional_vars) {
  598. super();
  599. this.context_expr = context_expr;
  600. this.optional_vars = optional_vars;
  601. }
  602. });
  603. this.registerType('ast.Global', class extends ast.stmt {
  604. constructor(names) {
  605. super();
  606. this.names = names;
  607. }
  608. });
  609. this.registerType('ast.Nonlocal', class extends ast.stmt {
  610. constructor(names) {
  611. super();
  612. this.names = names;
  613. }
  614. });
  615. this.registerType('ast.Continue', class extends ast.stmt {});
  616. this.registerType('ast.Break', class extends ast.stmt {});
  617. this.registerType('ast.Pass', class extends ast.stmt {});
  618. this.registerType('ast.Await', class extends ast.stmt {
  619. constructor(value) {
  620. super();
  621. this.value = value;
  622. }
  623. });
  624. this.registerType('ast.Module', class extends ast.mod {
  625. constructor(body, type_ignores) {
  626. super();
  627. this.body = body;
  628. this.type_ignores = type_ignores;
  629. }
  630. });
  631. this.registerFunction('ast.parse', (source, filename, debug) => {
  632. const parser = new ast._Parser(source, filename, debug);
  633. return parser.parse();
  634. });
  635. this.registerType('ast._Parser', class {
  636. constructor(text, file, debug) {
  637. this._tokenizer = new ast._Tokenizer(text, file);
  638. this._debug = debug;
  639. ast._Parser._precedence = ast._Parser._precedence || {
  640. 'or': 2, 'and': 3, 'not' : 4,
  641. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  642. '|': 6, '^' : 7, '&' : 8,
  643. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  644. // '+': 12, '-': 12,
  645. '~': 13, '**': 14
  646. };
  647. }
  648. parse() {
  649. const position = this._position();
  650. const body = [];
  651. while (!this._tokenizer.match('eof')) {
  652. const statement = this._statement();
  653. if (statement) {
  654. body.push(statement);
  655. continue;
  656. }
  657. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type === 'eof') {
  658. continue;
  659. }
  660. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type === 'eof') {
  661. continue;
  662. }
  663. throw new python.Error(`Unsupported statement ${this._location()}`);
  664. }
  665. const node = new ast.Module(body);
  666. this._mark(node, position);
  667. return node;
  668. }
  669. _suite() {
  670. const body = [];
  671. let statement = null;
  672. if (this._tokenizer.eat('\n')) {
  673. if (this._tokenizer.eat('indent')) {
  674. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  675. if (this._tokenizer.eat(';')) {
  676. continue;
  677. }
  678. statement = this._statement();
  679. if (statement) {
  680. body.push(statement);
  681. continue;
  682. }
  683. if (this._tokenizer.eat('\n')) {
  684. continue;
  685. }
  686. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  687. continue;
  688. }
  689. throw new python.Error(`Empty statement ${this._location()}`);
  690. }
  691. }
  692. } else if (!this._tokenizer.eat('eof')) {
  693. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  694. if (this._tokenizer.eat(';')) {
  695. continue;
  696. }
  697. statement = this._statement();
  698. if (statement) {
  699. body.push(statement);
  700. continue;
  701. }
  702. throw new python.Error(`Empty statement ${this._location()}`);
  703. }
  704. this._tokenizer.eat('\n');
  705. }
  706. return body;
  707. }
  708. _statement() {
  709. let node = null;
  710. let position = this._position();
  711. if (this._eat('id', 'break')) {
  712. const node = new ast.Break();
  713. return this._mark(node, position);
  714. }
  715. if (this._eat('id', 'continue')) {
  716. const node = new ast.Continue();
  717. return this._mark(node, position);
  718. }
  719. if (this._eat('id', 'return')) {
  720. const value = this._expression(-1, [], true);
  721. const node = new ast.Return(value);
  722. return this._mark(node, position);
  723. }
  724. if (this._eat('id', 'raise')) {
  725. let exc = this._expression(-1, ['from']);
  726. let cause = null;
  727. if (this._tokenizer.eat('id', 'from')) {
  728. cause = this._expression();
  729. } else if (this._tokenizer.eat(',')) {
  730. exc = [exc];
  731. exc.push(this._expression());
  732. if (this._tokenizer.eat(',')) {
  733. exc.push(this._expression());
  734. }
  735. }
  736. node = new ast.Raise(exc, cause);
  737. return this._mark(node, position);
  738. }
  739. if (this._eat('id', 'assert')) {
  740. const test = this._expression(-1, [',']);
  741. let msg = null;
  742. if (this._tokenizer.eat(',')) {
  743. msg = this._expression();
  744. }
  745. node = new ast.Assert(test, msg);
  746. return this._mark(node, position);
  747. }
  748. if (this._eat('id', 'global')) {
  749. const names = [];
  750. do {
  751. const name = this._name(true);
  752. names.push(name.id);
  753. }
  754. while (this._tokenizer.eat(','));
  755. const node = new ast.Global(names);
  756. return this._mark(node, position);
  757. }
  758. if (this._eat('id', 'nonlocal')) {
  759. const names = [];
  760. do {
  761. const name = this._name(true);
  762. names.push(name.id);
  763. }
  764. while (this._tokenizer.eat(','));
  765. const node = new ast.Nonlocal(names);
  766. return this._mark(node, position);
  767. }
  768. if (this._eat('id', 'import')) {
  769. const names = [];
  770. do {
  771. const name = this._dottedName();
  772. let asname = null;
  773. if (this._tokenizer.eat('id', 'as')) {
  774. asname = this._name(true).id;
  775. }
  776. const node = new ast.alias(name, asname);
  777. names.push(node);
  778. }
  779. while (this._tokenizer.eat(','));
  780. const node = new ast.Import(names);
  781. return this._mark(node, position);
  782. }
  783. if (this._eat('id', 'from')) {
  784. let level = 0;
  785. const dots = this._tokenizer.peek();
  786. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  787. this._eat(dots.type);
  788. level = Array.from(dots.type).length;
  789. }
  790. const module = this._dottedName();
  791. this._tokenizer.expect('id', 'import');
  792. const names = [];
  793. const close = this._tokenizer.eat('(');
  794. do {
  795. const name = this._name(true).id;
  796. let asname = null;
  797. if (this._tokenizer.eat('id', 'as')) {
  798. asname = this._name(true).id;
  799. }
  800. const node = new ast.alias(name, asname);
  801. names.push(node);
  802. }
  803. while (this._tokenizer.eat(','));
  804. if (close) {
  805. this._tokenizer.expect(')');
  806. }
  807. const node = new ast.ImportFrom(module, names, level);
  808. return this._mark(node, position);
  809. }
  810. const decorator_list = this._decorator();
  811. position = this._position();
  812. if (this._eat('id', 'class')) {
  813. const name = this._name(true);
  814. const bases = [];
  815. if (this._tokenizer.eat('(')) {
  816. while (!this._tokenizer.eat(')')) {
  817. if (this._tokenizer.eat('\n')) {
  818. continue;
  819. }
  820. const expression = this._expression(-1, [], false);
  821. if (expression === null) {
  822. throw new python.Error(`Expected expression ${this._location()}`);
  823. }
  824. bases.push(expression);
  825. if (!this._tokenizer.eat(',')) {
  826. this._tokenizer.eat('\n');
  827. this._tokenizer.expect(')');
  828. break;
  829. }
  830. }
  831. }
  832. this._tokenizer.expect(':');
  833. const body = this._suite();
  834. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  835. return this._mark(node, position);
  836. }
  837. const async = this._eat('id', 'async') !== null;
  838. if (async &&
  839. !this._tokenizer.match('id', 'def') &&
  840. !this._tokenizer.match('id', 'with') &&
  841. !this._tokenizer.match('id', 'for')) {
  842. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  843. }
  844. if (this._eat('id', 'def')) {
  845. const name = this._name(true);
  846. this._tokenizer.expect('(');
  847. const args = this._arguments(')');
  848. let returns = null;
  849. if (this._tokenizer.eat('->')) {
  850. returns = this._type();
  851. }
  852. this._tokenizer.expect(':');
  853. const body = this._suite();
  854. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  855. if (async) {
  856. node.async = async;
  857. }
  858. return this._mark(node, position);
  859. }
  860. if (decorator_list && decorator_list.length > 0) {
  861. throw new python.Error('Unexpected decorator.');
  862. }
  863. if (this._eat('id', 'del')) {
  864. const targets = this._expression(-1, [], true);
  865. node = new ast.Del(targets);
  866. return this._mark(node, position);
  867. }
  868. if (this._eat('id', 'if')) {
  869. const test = this._expression();
  870. this._tokenizer.expect(':');
  871. const body = this._suite();
  872. const node = new ast.If(test, body);
  873. let current = node;
  874. this._tokenizer.eat('\n');
  875. while (this._tokenizer.eat('id', 'elif')) {
  876. const test = this._expression();
  877. this._tokenizer.expect(':');
  878. const body = this._suite();
  879. current.orelse = new ast.If(test, body);
  880. current = current.orelse;
  881. this._tokenizer.eat('\n');
  882. }
  883. if (this._tokenizer.eat('id', 'else')) {
  884. this._tokenizer.expect(':');
  885. current.orelse = this._suite();
  886. }
  887. return this._mark(node, position);
  888. }
  889. if (this._eat('id', 'while')) {
  890. const test = this._expression();
  891. this._tokenizer.expect(':');
  892. const body = this._suite();
  893. let orelse = null;
  894. if (this._tokenizer.eat('id', 'else')) {
  895. this._tokenizer.expect(':');
  896. orelse = this._suite();
  897. }
  898. const node = new ast.While(test, body, orelse);
  899. return this._mark(node, position);
  900. }
  901. if (this._eat('id', 'pass')) {
  902. const node = new ast.Pass();
  903. return this._mark(node, position);
  904. }
  905. if (this._eat('id', 'for')) {
  906. let target = this._expression(-1, ['in']);
  907. while (this._tokenizer.eat(',')) {
  908. if (target instanceof ast.Tuple === false) {
  909. target = new ast.Tuple([target]);
  910. }
  911. if (this._tokenizer.match('id', 'in')) {
  912. target.elts.push({});
  913. break;
  914. }
  915. target.elts.push(this._expression(-1, ['in']));
  916. }
  917. this._tokenizer.expect('id', 'in');
  918. let iter = this._expression();
  919. while (this._tokenizer.eat(',')) {
  920. if (iter.type !== 'tuple') {
  921. iter = new ast.Tuple([iter]);
  922. }
  923. if (this._tokenizer.match(':')) {
  924. iter.elts.push({});
  925. break;
  926. }
  927. iter.elts.push(this._expression(-1, ['in']));
  928. }
  929. this._tokenizer.expect(':');
  930. const body = this._suite();
  931. let orelse = null;
  932. if (this._tokenizer.eat('id', 'else')) {
  933. this._tokenizer.expect(':');
  934. orelse = this._suite();
  935. }
  936. const node = new ast.For(target, iter, body, orelse);
  937. return this._mark(node, position);
  938. }
  939. if (this._eat('id', 'with')) {
  940. const items = [];
  941. do {
  942. const context_expr = this._expression();
  943. let optional_vars = null;
  944. if (this._tokenizer.eat('id', 'as')) {
  945. optional_vars = this._expression();
  946. }
  947. const node = new ast.withitem(context_expr, optional_vars);
  948. items.push(node);
  949. }
  950. while (this._tokenizer.eat(','));
  951. this._tokenizer.expect(':');
  952. const body = this._suite();
  953. const node = new ast.With(items, body, null);
  954. if (async) {
  955. node.async = async;
  956. }
  957. return this._mark(node, position);
  958. }
  959. if (this._eat('id', 'try')) {
  960. this._tokenizer.expect(':');
  961. const body = this._suite();
  962. const handlers = [];
  963. let orelse = null;
  964. let finalbody = null;
  965. while (this._tokenizer.match('id', 'except')) {
  966. this._tokenizer.expect('id', 'except');
  967. const type = this._expression();
  968. const name = this._tokenizer.eat('id', 'as') ? this._expression() : null;
  969. this._tokenizer.expect(':');
  970. const body = this._suite();
  971. const except = new ast.ExceptHandler(type, name, body);
  972. handlers.push(except);
  973. }
  974. if (this._tokenizer.match('id', 'else')) {
  975. this._tokenizer.expect('id', 'else');
  976. this._tokenizer.expect(':');
  977. orelse = this._suite();
  978. }
  979. if (this._tokenizer.match('id', 'finally')) {
  980. this._tokenizer.expect('id', 'finally');
  981. this._tokenizer.expect(':');
  982. finalbody = this._suite();
  983. }
  984. const node = new ast.Try(body, handlers, orelse, finalbody);
  985. return this._mark(node, position);
  986. }
  987. const expr = this._expression(-1, [], true);
  988. if (expr) {
  989. if (expr instanceof ast.Name && this._tokenizer.eat(':')) {
  990. const position = this._position();
  991. const annotation = this._expression(-1, ['=']);
  992. let value = null;
  993. if (this._tokenizer.eat('=')) {
  994. value = this._expression();
  995. }
  996. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  997. return this._mark(node, position);
  998. }
  999. if (expr instanceof ast.stmt) {
  1000. return expr;
  1001. }
  1002. switch (expr.__class__.__name__) {
  1003. case 'AnnAssign':
  1004. case 'Assert':
  1005. case 'Assign':
  1006. case 'Attribute':
  1007. case 'AugAssign':
  1008. case 'Await':
  1009. case 'BinOp':
  1010. case 'Call':
  1011. case 'Compare':
  1012. case 'Constant':
  1013. case 'Ellipsis':
  1014. case 'For':
  1015. case 'If':
  1016. case 'Lambda':
  1017. case 'List':
  1018. case 'Name':
  1019. case 'NamedExpr':
  1020. case 'Raise':
  1021. case 'Subscript':
  1022. case 'Tuple':
  1023. case 'Yield':
  1024. // return expr;
  1025. return new ast.Expr(expr);
  1026. default:
  1027. throw new python.Error(`Unhandled expression ${this._location()}`);
  1028. }
  1029. }
  1030. return null;
  1031. }
  1032. _expression(minPrecedence, terminal, tuple) {
  1033. minPrecedence = minPrecedence || -1;
  1034. const terminalSet = new Set(terminal);
  1035. const stack = [];
  1036. for (;;) {
  1037. let position = this._position();
  1038. let node = null;
  1039. const token = this._tokenizer.peek();
  1040. if (stack.length === 1 && terminalSet.has(token.value)) {
  1041. break;
  1042. }
  1043. const precedence = ast._Parser._precedence[token.value];
  1044. if (precedence) {
  1045. if (precedence >= minPrecedence) {
  1046. this._tokenizer.read();
  1047. if (token.value === 'not' && this._tokenizer.eat('id', 'in')) {
  1048. token.value = 'not in';
  1049. } else if (token.value === 'is' && this._tokenizer.eat('id', 'not')) {
  1050. token.value = 'is not';
  1051. }
  1052. if (stack.length > 0) {
  1053. let op = null;
  1054. switch (token.value) {
  1055. case '+': op = new ast.Add(); break;
  1056. case '-': op = new ast.Sub(); break;
  1057. case '*': op = new ast.Mult(); break;
  1058. case '/': op = new ast.Div(); break;
  1059. case '//': op = new ast.FloorDiv(); break;
  1060. case '**': op = new ast.Pow(); break;
  1061. case '@': op = new ast.MatMult(); break;
  1062. case '&': op = new ast.BitAnd(); break;
  1063. case '^': op = new ast.BitXor(); break;
  1064. case '|': op = new ast.BitOr(); break;
  1065. case '%': op = new ast.Mod(); break;
  1066. case '>>': op = new ast.RShift(); break;
  1067. case '<<': op = new ast.LShift(); break;
  1068. default: break;
  1069. }
  1070. if (op) {
  1071. const left = stack.pop();
  1072. const right = this._expression(precedence, terminal, tuple === true ? true : false);
  1073. node = new ast.BinOp(left, op, right);
  1074. } else {
  1075. switch (token.value) {
  1076. case '==': op = new ast.Eq(); break;
  1077. case '!=': op = new ast.NotEq(); break;
  1078. case '>=': op = new ast.GtE(); break;
  1079. case '<=': op = new ast.LtE(); break;
  1080. case '<': op = new ast.Lt(); break;
  1081. case '>': op = new ast.Gt(); break;
  1082. case 'is': op = new ast.Is(); break;
  1083. case 'is not': op = new ast.IsNot(); break;
  1084. case 'in': op = new ast.In(); break;
  1085. case 'not in': op = new ast.NotIn(); break;
  1086. default: break;
  1087. }
  1088. const left = stack.pop();
  1089. const comparator = this._expression(precedence, terminal, tuple === true ? true : false);
  1090. node = new ast.Compare(left, [op], [comparator]);
  1091. }
  1092. } else if (token.value === '*') {
  1093. const value = this._expression(precedence, terminal, tuple === true ? true : false);
  1094. node = new ast.Starred(value);
  1095. } else if (token.value === '**') {
  1096. const value = this._expression(precedence, terminal, tuple === true ? true : false);
  1097. node = new ast.keyword(null, value);
  1098. } else {
  1099. let op = null;
  1100. switch (token.value) {
  1101. case '-': op = new ast.USub(); break;
  1102. case '+': op = new ast.UAdd(); break;
  1103. case '~': op = new ast.Invert(); break;
  1104. case 'not': op = new ast.Not(); break;
  1105. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1106. }
  1107. const operand = this._expression(precedence, terminal, tuple === true ? true : false);
  1108. node = new ast.UnaryOp(op, operand);
  1109. node = this._mark(node, position);
  1110. }
  1111. stack.push(node);
  1112. continue;
  1113. }
  1114. }
  1115. if (this._tokenizer.eat(':=')) {
  1116. const target = stack.pop();
  1117. const value = this._expression(-1, terminal, tuple === false ? false : true);
  1118. const node = new ast.NamedExpr(target, value);
  1119. this._mark(node, position);
  1120. stack.push(node);
  1121. continue;
  1122. }
  1123. if (this._tokenizer.eat('=')) {
  1124. const position = this._position();
  1125. const targets = stack.pop();
  1126. const value = this._expression(-1, terminal, tuple === false ? false : true);
  1127. const node = new ast.Assign([targets], value);
  1128. this._mark(node, position);
  1129. stack.push(node);
  1130. continue;
  1131. }
  1132. let op = null;
  1133. switch (token.type) {
  1134. case '+=': op = new ast.Add(); break;
  1135. case '-=': op = new ast.Sub(); break;
  1136. case '**=': op = new ast.Pow(); break;
  1137. case '*=': op = new ast.Mult(); break;
  1138. case '//=': op = new ast.FloorDiv(); break;
  1139. case '/=': op = new ast.Div(); break;
  1140. case '&=': op = new ast.BitAnd(); break;
  1141. case '%=': op = new ast.Mod(); break;
  1142. case '^=': op = new ast.BitXor(); break;
  1143. case '<<=': op = new ast.LShift(); break;
  1144. case '>>=': op = new ast.RShift(); break;
  1145. case '|=': op = new ast.BitOr(); break;
  1146. case '@=': op = new ast.MatMul(); break;
  1147. default: break;
  1148. }
  1149. if (op) {
  1150. this._tokenizer.expect(token.type);
  1151. const target = stack.pop();
  1152. const value = this._expression(-1, terminal, true);
  1153. const node = new ast.AugAssign(target, op, value);
  1154. stack.push(node);
  1155. continue;
  1156. }
  1157. position = this._position();
  1158. if (this._eat('id', 'if')) {
  1159. const body = stack.pop();
  1160. const test = this._expression();
  1161. this._tokenizer.expect('id', 'else');
  1162. const orelse = this._expression();
  1163. const node = new ast.IfExp(test, body, orelse);
  1164. this._mark(node, position);
  1165. stack.push(node);
  1166. continue;
  1167. }
  1168. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1169. throw new python.Error('Not implemented.');
  1170. }
  1171. if (this._eat('id', 'lambda')) {
  1172. const args = this._arguments(':');
  1173. const body = this._expression(-1, terminal, false);
  1174. const node = new ast.Lambda(args, body);
  1175. this._mark(node, position);
  1176. stack.push(node);
  1177. continue;
  1178. }
  1179. if (this._eat('id', 'yield')) {
  1180. if (this._tokenizer.eat('id', 'from')) {
  1181. const value = this._expression(-1, [], true);
  1182. node = new ast.YieldFrom(value);
  1183. stack.push(node);
  1184. } else {
  1185. const value = [];
  1186. do {
  1187. value.push(this._expression(-1, [], false));
  1188. }
  1189. while (this._tokenizer.eat(','));
  1190. node = new ast.Yield(value);
  1191. stack.push(node);
  1192. }
  1193. continue;
  1194. }
  1195. if (this._eat('id', 'await')) {
  1196. const value = this._expression(minPrecedence, terminal, tuple);
  1197. const node = new ast.Await(value);
  1198. this._mark(node, position);
  1199. stack.push(node);
  1200. continue;
  1201. }
  1202. if (this._eat('.')) {
  1203. const value = stack.pop();
  1204. const attr = this._name().id;
  1205. const node = new ast.Attribute(value, attr);
  1206. this._mark(node, position);
  1207. stack.push(node);
  1208. continue;
  1209. }
  1210. if (this._tokenizer.peek().type === '(') {
  1211. const position = this._position();
  1212. const args = [];
  1213. const keywords = [];
  1214. this._tokenizer.expect('(');
  1215. let tuple = false;
  1216. while (!this._tokenizer.eat(')')) {
  1217. if (this._tokenizer.eat('\n')) {
  1218. continue;
  1219. }
  1220. const position = this._position();
  1221. const expr = this._expression(-1, [], false);
  1222. if (expr === null) {
  1223. throw new python.Error(`Expected expression ${this._location()}`);
  1224. }
  1225. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1226. const [target] = expr.targets;
  1227. if (target instanceof ast.Name === false) {
  1228. throw new python.Error(`Expected name ${this._location()}`);
  1229. }
  1230. const node = new ast.keyword(target.id, expr.value);
  1231. this._mark(node, position);
  1232. keywords.push(node);
  1233. } else {
  1234. args.push(expr);
  1235. }
  1236. if (this._tokenizer.eat(',')) {
  1237. tuple = true;
  1238. } else {
  1239. this._tokenizer.eat('\n');
  1240. this._tokenizer.expect(')');
  1241. break;
  1242. }
  1243. }
  1244. if (stack.length === 0 && keywords.length === 0) {
  1245. if (args.length === 1 && !tuple) {
  1246. [node] = args;
  1247. } else {
  1248. node = new ast.Tuple(args);
  1249. this._mark(node, position);
  1250. }
  1251. } else {
  1252. const func = stack.pop();
  1253. node = new ast.Call(func, args, keywords);
  1254. this._mark(node, position);
  1255. }
  1256. stack.push(node);
  1257. continue;
  1258. }
  1259. if (this._tokenizer.peek().type === '[') {
  1260. if (stack.length === 0) {
  1261. stack.push(this._expressions());
  1262. } else {
  1263. const value = stack.pop();
  1264. const position = this._position();
  1265. const slice = this._slice();
  1266. node = new ast.Subscript(value, slice);
  1267. this._mark(node, position);
  1268. stack.push(node);
  1269. }
  1270. continue;
  1271. }
  1272. if (this._tokenizer.peek().type === '{') {
  1273. const elts = [];
  1274. const keys = [];
  1275. const values = [];
  1276. this._tokenizer.expect('{');
  1277. let dict = true;
  1278. while (!this._tokenizer.eat('}')) {
  1279. const item = this._expression(-1, [], false);
  1280. if (item === null) {
  1281. throw new python.Error(`Expected expression ${this._location()}`);
  1282. }
  1283. if (!this._tokenizer.eat(':')) {
  1284. dict = false;
  1285. }
  1286. if (dict) {
  1287. const value = this._expression(-1, ['for'], false);
  1288. if (value === null) {
  1289. throw new python.Error(`Expected expression ${this._location()}`);
  1290. }
  1291. if (this._eat('id', 'for')) {
  1292. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1293. throw new python.Error(`Invalid list expression ${this._location()}`);
  1294. }
  1295. const target = this._expression(-1, ['in'], true);
  1296. this._tokenizer.expect('id', 'in');
  1297. const iter = this._expression(-1, ['for', 'if'], true);
  1298. const ifs = [];
  1299. while (this._tokenizer.eat('id', 'if')) {
  1300. ifs.push(this._expression(-1, ['for', 'if']));
  1301. }
  1302. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1303. const generators = [comprehension];
  1304. this._tokenizer.expect('}');
  1305. return new ast.DictComp(item, value, generators);
  1306. }
  1307. keys.push(item);
  1308. values.push(value);
  1309. } else {
  1310. elts.push(item);
  1311. }
  1312. this._tokenizer.eat(',');
  1313. this._tokenizer.eat('\n');
  1314. if (this._tokenizer.eat('}')) {
  1315. break;
  1316. }
  1317. }
  1318. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1319. throw new python.Error(`Invalid set expression ${this._location()}`);
  1320. }
  1321. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1322. stack.push(node);
  1323. continue;
  1324. }
  1325. const literal = this._literal();
  1326. if (literal) {
  1327. if (stack.length > 0 &&
  1328. (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') &&
  1329. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  1330. const op = literal.value < 0 ? new ast.Sub() : new ast.Add();
  1331. const left = stack.pop();
  1332. const right = new ast.Constant(Math.abs(literal.value));
  1333. node = new ast.BinOp(left, op, right);
  1334. stack.push(node);
  1335. } else if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1336. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1337. } else {
  1338. let value = literal.value;
  1339. if (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') {
  1340. switch (value) {
  1341. case 'inf': value = Infinity; break;
  1342. case '-inf': value = -Infinity; break;
  1343. default: value = Number(value); break;
  1344. }
  1345. } else if (literal.type === 'str') {
  1346. value = literal.value.substring(1, literal.value.length - 1);
  1347. } else {
  1348. throw new python.Error(`Invalid literal ${this._location()}`);
  1349. }
  1350. const node = new ast.Constant(value, literal.type);
  1351. stack.push(node);
  1352. }
  1353. continue;
  1354. }
  1355. if (this._eat('id', 'False')) {
  1356. const node = new ast.Constant(false, 'bool');
  1357. this._mark(node, position);
  1358. stack.push(node);
  1359. continue;
  1360. }
  1361. if (this._eat('id', 'True')) {
  1362. const node = new ast.Constant(true, 'bool');
  1363. this._mark(node, position);
  1364. stack.push(node);
  1365. continue;
  1366. }
  1367. if (this._eat('id', 'None')) {
  1368. const node = new ast.Constant(null);
  1369. this._mark(node, position);
  1370. stack.push(node);
  1371. continue;
  1372. }
  1373. if (this._tokenizer.peek().keyword) {
  1374. break;
  1375. }
  1376. if (this._eat('...')) {
  1377. const node = new ast.Ellipsis();
  1378. this._mark(node, position);
  1379. stack.push(node);
  1380. continue;
  1381. }
  1382. const name = this._name();
  1383. if (name) {
  1384. stack.push(name);
  1385. continue;
  1386. }
  1387. if (tuple === true && stack.length === 1 && this._tokenizer.eat(',')) {
  1388. if (stack[0] instanceof ast.Tuple) {
  1389. [node] = stack;
  1390. } else {
  1391. const position = this._position();
  1392. const elts = [stack.pop()];
  1393. node = new ast.Tuple(elts);
  1394. this._mark(node, position);
  1395. stack.push(node);
  1396. }
  1397. // for, bar, = <expr>
  1398. if (this._tokenizer.peek().type === '=') {
  1399. continue;
  1400. }
  1401. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1402. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1403. const expression = this._expression(minPrecedence, nextTerminal, tuple);
  1404. if (expression) {
  1405. node.elts.push(expression);
  1406. continue;
  1407. }
  1408. }
  1409. break;
  1410. }
  1411. break;
  1412. }
  1413. if (stack.length === 1) {
  1414. return stack.pop();
  1415. }
  1416. if (stack.length !== 0) {
  1417. throw new python.Error(`Unexpected expression ${this._location()}`);
  1418. }
  1419. return null;
  1420. }
  1421. _decorator() {
  1422. const list = [];
  1423. while (this._tokenizer.eat('@')) {
  1424. const value = this._expression();
  1425. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1426. throw new python.Error(`Invalid decorator ${this._location()}`);
  1427. }
  1428. this._tokenizer.eat('\n');
  1429. list.push(value);
  1430. }
  1431. return list;
  1432. }
  1433. _expressions() {
  1434. const elts = [];
  1435. this._tokenizer.expect('[');
  1436. while (!this._tokenizer.eat(']')) {
  1437. const expression = this._expression(-1, ['for']);
  1438. if (this._eat('id', 'for')) {
  1439. if (elts.length > 0) {
  1440. throw new python.Error(`Invalid list expression ${this._location()}`);
  1441. }
  1442. const target = this._expression(-1, ['in'], true);
  1443. this._tokenizer.expect('id', 'in');
  1444. const iter = this._expression(-1, ['for', 'if'], true);
  1445. const ifs = [];
  1446. while (this._tokenizer.eat('id', 'if')) {
  1447. ifs.push(this._expression(-1, ['for', 'if']));
  1448. }
  1449. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1450. const generators = [comprehension];
  1451. this._tokenizer.expect(']');
  1452. return new ast.ListComp(expression, generators);
  1453. }
  1454. if (expression === null) {
  1455. throw new python.Error(`Expected expression ${this._location()}`);
  1456. }
  1457. elts.push(expression);
  1458. this._tokenizer.eat(',');
  1459. while (this._tokenizer.eat('\n')) {
  1460. // continue
  1461. }
  1462. if (this._tokenizer.eat(']')) {
  1463. break;
  1464. }
  1465. }
  1466. return new ast.List(elts);
  1467. }
  1468. _slice() {
  1469. const elts = [];
  1470. let slice = [null, null, null];
  1471. let index = 0;
  1472. let valid = false;
  1473. this._tokenizer.expect('[');
  1474. while (true) {
  1475. if (this._tokenizer.eat(':')) {
  1476. index++;
  1477. valid = true;
  1478. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1479. if (!valid || index > 2) {
  1480. throw new python.Error(`Invalid slice at ${this._location()}`);
  1481. }
  1482. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1483. slice = [null, null, null];
  1484. index = 0;
  1485. if (this._tokenizer.eat(']')) {
  1486. break;
  1487. }
  1488. this._tokenizer.expect(',');
  1489. } else {
  1490. const expression = this._expression();
  1491. if (expression === null) {
  1492. throw new python.Error(`Expected expression ${this._location()}`);
  1493. }
  1494. slice[index] = expression;
  1495. valid = true;
  1496. }
  1497. }
  1498. if (elts.length > 1) {
  1499. return new ast.Tuple(elts);
  1500. }
  1501. return elts[0];
  1502. }
  1503. _name(required) {
  1504. const token = this._tokenizer.peek();
  1505. if (token.type === 'id' && !token.keyword) {
  1506. const position = this._position();
  1507. this._tokenizer.read();
  1508. const node = new ast.Name(token.value);
  1509. return this._mark(node, position);
  1510. }
  1511. if (required) {
  1512. throw new python.Error(`Invalid syntax ${this._location()}`);
  1513. }
  1514. return null;
  1515. }
  1516. _dottedName() {
  1517. const list = [];
  1518. do {
  1519. const name = this._name(true);
  1520. list.push(name.id);
  1521. }
  1522. while (this._tokenizer.eat('.'));
  1523. return list.join('.');
  1524. }
  1525. _literal() {
  1526. const token = this._tokenizer.peek();
  1527. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1528. this._tokenizer.read();
  1529. return token;
  1530. }
  1531. return null;
  1532. }
  1533. _typeArguments() {
  1534. const list = [];
  1535. this._tokenizer.expect('[');
  1536. while (!this._tokenizer.eat(']')) {
  1537. const type = this._type();
  1538. if (type === null) {
  1539. throw new python.Error(`Expected type ${this._location()}`);
  1540. }
  1541. list.push(type);
  1542. if (!this._tokenizer.eat(',')) {
  1543. this._tokenizer.expect(']');
  1544. break;
  1545. }
  1546. }
  1547. return list;
  1548. }
  1549. _type() {
  1550. const target = this._expression(-1, ['[', '=']);
  1551. if (target) {
  1552. if (this._tokenizer.peek().value === '[') {
  1553. const list = this._expressions();
  1554. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1555. return new ast.Subscript(target, slice);
  1556. }
  1557. return target;
  1558. }
  1559. return null;
  1560. }
  1561. _arguments(terminal) {
  1562. let posonlyargs = [];
  1563. let args = [];
  1564. let vararg = null;
  1565. const kwonlyargs = [];
  1566. const kw_defaults = [];
  1567. let kwarg = null;
  1568. const defaults = [];
  1569. let is_slash = false;
  1570. let is_vararg = false; // '*'
  1571. let is_kwarg = false; // '**'
  1572. const read = (required) => {
  1573. const name = this._name(required);
  1574. if (name) {
  1575. const annotation = terminal !== ':' && this._tokenizer.eat(':') ? this._type() : null;
  1576. return new ast.arg(name.id, annotation, null);
  1577. }
  1578. return null;
  1579. };
  1580. while (!this._tokenizer.eat(terminal)) {
  1581. this._tokenizer.eat('\n');
  1582. if (this._tokenizer.eat('/')) {
  1583. if (is_slash || is_vararg || is_kwarg) {
  1584. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1585. }
  1586. is_slash = true;
  1587. } else if (this._tokenizer.eat('*')) {
  1588. if (is_vararg) {
  1589. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1590. }
  1591. is_vararg = true;
  1592. const arg = read(false);
  1593. vararg = arg ? arg : vararg;
  1594. } else if (this._tokenizer.eat('**')) {
  1595. if (is_kwarg) {
  1596. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1597. }
  1598. is_kwarg = true;
  1599. kwarg = read(true);
  1600. } else {
  1601. const arg = read(false);
  1602. if (!arg) {
  1603. this._tokenizer.expect(terminal);
  1604. break;
  1605. }
  1606. const default_value = this._tokenizer.eat('=') ? this._expression() : null;
  1607. if (!is_vararg && !is_kwarg) {
  1608. if (is_slash) {
  1609. args.push(arg);
  1610. } else {
  1611. posonlyargs.push(arg);
  1612. }
  1613. if (default_value !== null) {
  1614. defaults.push(default_value);
  1615. }
  1616. } else if (is_vararg && !is_kwarg) {
  1617. kwonlyargs.push(arg);
  1618. kw_defaults.push(default_value);
  1619. } else {
  1620. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1621. }
  1622. }
  1623. this._tokenizer.eat('\n');
  1624. if (!this._tokenizer.eat(',')) {
  1625. this._tokenizer.expect(terminal);
  1626. break;
  1627. }
  1628. }
  1629. if (!is_slash) {
  1630. args = posonlyargs.concat(args);
  1631. posonlyargs = [];
  1632. }
  1633. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1634. }
  1635. _eat(type, value) {
  1636. if (this._tokenizer.match(type, value)) {
  1637. const position = this._position();
  1638. this._tokenizer.expect(type, value);
  1639. return position;
  1640. }
  1641. return null;
  1642. }
  1643. _mark(node, position) {
  1644. node.filename = position.filename;
  1645. node.lineno = position.lineno;
  1646. node.col_offset = position.col_offset;
  1647. node.end_lineno = this._tokenizer.lineno;
  1648. node.end_col_offset = this._tokenizer.col_offset;
  1649. return node;
  1650. }
  1651. _position() {
  1652. return {
  1653. filename: this._tokenizer.filename,
  1654. lineno: this._tokenizer.lineno,
  1655. col_offset: this._tokenizer.col_offset
  1656. };
  1657. }
  1658. _location() {
  1659. return this._tokenizer.location();
  1660. }
  1661. });
  1662. this.registerType('ast._Tokenizer', class {
  1663. constructor(text, file) {
  1664. this._text = text;
  1665. this.filename = file;
  1666. this.linepos = 0;
  1667. this.lineno = 1;
  1668. this._position = 0;
  1669. this._token = { type: '', value: '' };
  1670. this._brackets = 0;
  1671. this._indentation = [];
  1672. this._outdent = 0;
  1673. if (!ast._Tokenizer._whitespace) {
  1674. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1675. 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';
  1676. 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';
  1677. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1678. /* eslint-disable no-misleading-character-class */
  1679. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1680. /* eslint-enable no-misleading-character-class */
  1681. }
  1682. }
  1683. peek() {
  1684. if (!this._cache) {
  1685. this._tokenize();
  1686. this._cache = true;
  1687. }
  1688. return this._token;
  1689. }
  1690. read() {
  1691. if (!this._cache) {
  1692. this._tokenize();
  1693. }
  1694. const next = this._position + this._token.value.length;
  1695. while (this._position < next) {
  1696. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1697. this._position = this._newLine(this._position);
  1698. this.linepos = this._position;
  1699. this.lineno++;
  1700. } else {
  1701. this._position++;
  1702. }
  1703. }
  1704. this._cache = false;
  1705. return this._token;
  1706. }
  1707. match(type, value) {
  1708. const token = this.peek();
  1709. if (token.type === type && (!value || token.value === value)) {
  1710. return true;
  1711. }
  1712. return false;
  1713. }
  1714. eat(type, value) {
  1715. const token = this.peek();
  1716. if (token.type === type && (!value || token.value === value)) {
  1717. this.read();
  1718. return true;
  1719. }
  1720. return false;
  1721. }
  1722. expect(type, value) {
  1723. const token = this.peek();
  1724. if (token.type !== type) {
  1725. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1726. }
  1727. if (value && token.value !== value) {
  1728. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1729. }
  1730. this.read();
  1731. }
  1732. location() {
  1733. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1734. }
  1735. get col_offset() {
  1736. return this._position - this.linepos + 1;
  1737. }
  1738. static _isSpace(c) {
  1739. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1740. return true;
  1741. }
  1742. if (c.charCodeAt(0) >= 0x1680) {
  1743. return ast._Tokenizer._whitespace.test(c);
  1744. }
  1745. return false;
  1746. }
  1747. static _isNewline(c) {
  1748. switch (c) {
  1749. case '\n':
  1750. case '\r':
  1751. case '\u2028': // 8232
  1752. case '\u2029': // 8233
  1753. return true;
  1754. default:
  1755. return false;
  1756. }
  1757. }
  1758. static _isIdentifierStartChar(c) {
  1759. if (c < 'A') {
  1760. return c === '$';
  1761. }
  1762. if (c <= 'Z') {
  1763. return true;
  1764. }
  1765. if (c < 'a') {
  1766. return c === '_';
  1767. }
  1768. if (c <= 'z') {
  1769. return true;
  1770. }
  1771. const code = c.charCodeAt(0);
  1772. if (code >= 0xAA) {
  1773. return ast._Tokenizer._identifierStart.test(c);
  1774. }
  1775. return false;
  1776. }
  1777. static _isIdentifierChar(c) {
  1778. if (c < '0') {
  1779. return c === '$';
  1780. }
  1781. if (c <= '9') {
  1782. return true;
  1783. }
  1784. if (c < 'A') {
  1785. return false;
  1786. }
  1787. if (c <= 'Z') {
  1788. return true;
  1789. }
  1790. if (c < 'a') {
  1791. return c === '_';
  1792. }
  1793. if (c <= 'z') {
  1794. return true;
  1795. }
  1796. const code = c.charCodeAt(0);
  1797. if (code >= 0xAA) {
  1798. return ast._Tokenizer._identifierChar.test(c);
  1799. }
  1800. return false;
  1801. }
  1802. _get(position) {
  1803. return position >= this._text.length ? '\0' : this._text[position];
  1804. }
  1805. _skipLine() {
  1806. while (this._position < this._text.length) {
  1807. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1808. break;
  1809. }
  1810. this._position++;
  1811. }
  1812. }
  1813. _skipWhitespace() {
  1814. while (this._position < this._text.length) {
  1815. const c = this._text[this._position];
  1816. if (c === '#') {
  1817. this._skipLine();
  1818. } else if (ast._Tokenizer._isSpace(c)) {
  1819. this._position++;
  1820. } else if (c === '\\') {
  1821. // Explicit Line Continuation
  1822. this._position++;
  1823. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1824. this._position = this._newLine(this._position);
  1825. this.linepos = this._position;
  1826. this.lineno += 1;
  1827. } else {
  1828. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1829. }
  1830. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1831. // Implicit Line Continuation
  1832. this._position = this._newLine(this._position);
  1833. this.linepos = this._position;
  1834. this.lineno += 1;
  1835. } else {
  1836. break;
  1837. }
  1838. }
  1839. }
  1840. _newLine(position) {
  1841. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1842. return position + 2;
  1843. }
  1844. return position + 1;
  1845. }
  1846. _tokenize() {
  1847. if (this._token.type !== '\n') {
  1848. this._skipWhitespace();
  1849. }
  1850. if (this._token.type === 'dedent') {
  1851. this._indentation.pop();
  1852. this._outdent--;
  1853. if (this._outdent > 0) {
  1854. this._token = { type: 'dedent', value: '' };
  1855. return;
  1856. }
  1857. }
  1858. if (this._token.type === '\n') {
  1859. let indent = '';
  1860. let i = this._position;
  1861. while (i < this._text.length) {
  1862. const c = this._text[i];
  1863. if (ast._Tokenizer._isSpace(c)) {
  1864. indent += c;
  1865. i++;
  1866. } else if (ast._Tokenizer._isNewline(c)) {
  1867. indent = '';
  1868. i = this._newLine(i);
  1869. this._position = i;
  1870. this.linepos = i;
  1871. this.lineno += 1;
  1872. } else if (c === '#') {
  1873. indent = '';
  1874. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1875. i++;
  1876. }
  1877. continue;
  1878. } else {
  1879. break;
  1880. }
  1881. }
  1882. let type = null;
  1883. if (indent.length > 0) {
  1884. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1885. if (indent.length > current.length) {
  1886. type = 'indent';
  1887. this._indentation.push(indent);
  1888. } else if (indent.length > 0 && indent.length < current.length) {
  1889. type = 'dedent';
  1890. this._outdent = 0;
  1891. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1892. this._outdent++;
  1893. }
  1894. } else {
  1895. this._position += indent.length;
  1896. }
  1897. } else if (i >= this._text.length) {
  1898. this._token = { type: 'eof', value: '' };
  1899. return;
  1900. } else if (this._indentation.length > 0) {
  1901. type = 'dedent';
  1902. this._outdent = this._indentation.length;
  1903. }
  1904. if (type === 'indent' || type === 'dedent') {
  1905. this._token = { type, value: indent };
  1906. return;
  1907. }
  1908. }
  1909. if (this._position >= this._text.length) {
  1910. this._token = { type: 'eof', value: '' };
  1911. return;
  1912. }
  1913. const c = this._get(this._position);
  1914. const string = this._string();
  1915. if (string) {
  1916. this._token = string;
  1917. return;
  1918. }
  1919. switch (c) {
  1920. case '(':
  1921. case '[':
  1922. case '{':
  1923. this._brackets++;
  1924. this._token = { type: c, value: c };
  1925. return;
  1926. case ')':
  1927. case ']':
  1928. case '}':
  1929. if (this._brackets === 0) {
  1930. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  1931. }
  1932. this._brackets--;
  1933. this._token = { type: c, value: c };
  1934. return;
  1935. case ',':
  1936. case ';':
  1937. case '?':
  1938. this._token = { type: c, value: c };
  1939. return;
  1940. default: {
  1941. const number = this._number();
  1942. if (number) {
  1943. this._token = number;
  1944. return;
  1945. }
  1946. if (c === '.') {
  1947. let end = this._position + 1;
  1948. while (this._get(end) === '.') {
  1949. end++;
  1950. }
  1951. const text = this._text.substring(this._position, end);
  1952. this._token = { type: text, value: text };
  1953. return;
  1954. }
  1955. const identifier = this._identifier();
  1956. if (identifier) {
  1957. this._token = identifier;
  1958. return;
  1959. }
  1960. const operator = this._operator();
  1961. if (operator) {
  1962. this._token = operator;
  1963. return;
  1964. }
  1965. break;
  1966. }
  1967. }
  1968. if (c === '.') {
  1969. this._token = { type: c, value: c };
  1970. return;
  1971. }
  1972. if (c === '\\') {
  1973. this._token = { type: '\\', value: c };
  1974. return;
  1975. }
  1976. if (ast._Tokenizer._isNewline(c)) {
  1977. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  1978. return;
  1979. }
  1980. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  1981. }
  1982. _number() {
  1983. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  1984. const binary = (c) => c === '0' || c === '1' || c === '_';
  1985. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  1986. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  1987. let c = this._get(this._position);
  1988. const sign = (c === '-' || c === '+') ? 1 : 0;
  1989. let i = this._position + sign;
  1990. c = this._get(i);
  1991. if (c === '0') {
  1992. let radix = 0;
  1993. const n = this._get(i + 1);
  1994. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  1995. i += 2;
  1996. while (hex(this._get(i))) {
  1997. i += 1;
  1998. }
  1999. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2000. i += 1;
  2001. }
  2002. radix = 16;
  2003. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2004. i += 2;
  2005. while (binary(this._get(i))) {
  2006. i++;
  2007. }
  2008. radix = 2;
  2009. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2010. i += 2;
  2011. while (octal(this._get(i))) {
  2012. i++;
  2013. }
  2014. radix = 8;
  2015. } else if (n >= '0' && n <= '7') {
  2016. i++;
  2017. while (octal(this._get(i))) {
  2018. i += 1;
  2019. }
  2020. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2021. i += 1;
  2022. }
  2023. radix = 8;
  2024. }
  2025. if (radix > 0 && this._get(i) !== '.') {
  2026. const radixText = this._text.substring(this._position, i);
  2027. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2028. if (!isNaN(parseInt(radixParseText, radix))) {
  2029. return { type: 'int', value: radixText };
  2030. }
  2031. }
  2032. }
  2033. i = this._position + sign;
  2034. let isDecimal = false;
  2035. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2036. while (decimal(this._get(i))) {
  2037. i++;
  2038. }
  2039. c = this._get(i).toLowerCase();
  2040. isDecimal = c !== '.' && c !== 'e';
  2041. }
  2042. if (this._get(i) === '0') {
  2043. i++;
  2044. c = this._get(i).toLowerCase();
  2045. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2046. }
  2047. if (isDecimal) {
  2048. if (this._get(i) === 'j' || this._get(i) === 'J' || this._get(i) === 'l' || this._get(i) === 'L') {
  2049. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2050. }
  2051. const intText = this._text.substring(this._position, i);
  2052. if (!isNaN(parseInt(intText, 10))) {
  2053. return { type: 'int', value: intText };
  2054. }
  2055. }
  2056. i = this._position + sign;
  2057. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2058. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2059. while (decimal(this._get(i))) {
  2060. i++;
  2061. }
  2062. if (this._get(i) === '.') {
  2063. i++;
  2064. }
  2065. while (decimal(this._get(i))) {
  2066. i++;
  2067. }
  2068. if (i > (this._position + sign)) {
  2069. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2070. i++;
  2071. if (this._get(i) === '-' || this._get(i) === '+') {
  2072. i++;
  2073. }
  2074. if (decimal(this._get(i))) {
  2075. while (decimal(this._get(i))) {
  2076. i++;
  2077. }
  2078. } else {
  2079. i = this._position;
  2080. }
  2081. } else {
  2082. while (decimal(this._get(i))) {
  2083. i++;
  2084. }
  2085. }
  2086. }
  2087. if (i > (this._position + sign)) {
  2088. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2089. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2090. }
  2091. const floatText = this._text.substring(this._position, i);
  2092. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2093. if (!isNaN(parseFloat(floatParseText))) {
  2094. return { type: 'float', value: floatText };
  2095. }
  2096. }
  2097. }
  2098. return null;
  2099. }
  2100. _identifier() {
  2101. let i = this._position;
  2102. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2103. i++;
  2104. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2105. i++;
  2106. }
  2107. }
  2108. if (i > this._position) {
  2109. const text = this._text.substring(this._position, i);
  2110. let keyword = false;
  2111. switch (text) {
  2112. case 'and':
  2113. case 'as':
  2114. case 'else':
  2115. case 'For':
  2116. case 'If':
  2117. case 'Import':
  2118. case 'in':
  2119. case 'is':
  2120. case 'not':
  2121. case 'or':
  2122. keyword = true;
  2123. break;
  2124. default:
  2125. break;
  2126. }
  2127. return { type: 'id', value: text, keyword };
  2128. }
  2129. return null;
  2130. }
  2131. _operator() {
  2132. let length = 0;
  2133. const c0 = this._get(this._position);
  2134. const c1 = this._get(this._position + 1);
  2135. const c2 = this._get(this._position + 2);
  2136. switch (c0) {
  2137. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2138. length = c1 === '=' ? 2 : 1;
  2139. break;
  2140. case '-':
  2141. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2142. break;
  2143. case '*':
  2144. switch (c1) {
  2145. case '*': length = c2 === '=' ? 3 : 2; break;
  2146. case '=': length = 2; break;
  2147. default: length = 1; break;
  2148. }
  2149. break;
  2150. case '/':
  2151. switch (c1) {
  2152. case '/': length = c2 === '=' ? 3 : 2; break;
  2153. case '=': length = 2; break;
  2154. default: length = 1; break;
  2155. }
  2156. break;
  2157. case '<':
  2158. switch (c1) {
  2159. case '>': length = 2; break;
  2160. case '<': length = c2 === '=' ? 3 : 2; break;
  2161. case '=': length = 2; break;
  2162. default: length = 1; break;
  2163. }
  2164. break;
  2165. case '>':
  2166. switch (c1) {
  2167. case '>': length = c2 === '=' ? 3 : 2; break;
  2168. case '=': length = 2; break;
  2169. default: length = 1; break;
  2170. }
  2171. break;
  2172. case '@':
  2173. length = c1 === '=' ? 2 : 1;
  2174. break;
  2175. case ':':
  2176. length = c1 === '=' ? 2 : 1;
  2177. break;
  2178. default:
  2179. return null;
  2180. }
  2181. const text = this._text.substring(this._position, this._position + length);
  2182. return { type: text, value: text };
  2183. }
  2184. _string() {
  2185. let i = this._position;
  2186. let prefix = -1;
  2187. if (this._get(i) === "'" || this._get(i) === '"') {
  2188. prefix = '';
  2189. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2190. const c = this._get(i);
  2191. const cc = c.toLowerCase();
  2192. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2193. prefix = c;
  2194. }
  2195. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2196. const c = this._text.substr(this._position, 2);
  2197. const cc = c.toLowerCase();
  2198. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2199. prefix = c;
  2200. }
  2201. }
  2202. if (prefix.length >= 0) {
  2203. i += prefix.length;
  2204. let quote = '';
  2205. let count = 0;
  2206. const q0 = this._get(i);
  2207. const q1 = this._get(i + 1);
  2208. const q2 = this._get(i + 2);
  2209. switch (q0) {
  2210. case "'":
  2211. quote = q0;
  2212. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2213. break;
  2214. case '"':
  2215. quote = q0;
  2216. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2217. break;
  2218. default:
  2219. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2220. }
  2221. i += count;
  2222. if (count === 1) {
  2223. while (i < this._text.length) {
  2224. if (this._text[i] === quote) {
  2225. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2226. } else if (this._text[i] === '\\' &&
  2227. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2228. i += 2;
  2229. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2230. break;
  2231. } else {
  2232. i++;
  2233. }
  2234. }
  2235. } else if (count === 3) {
  2236. while (i < this._text.length) {
  2237. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2238. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2239. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2240. i += 2;
  2241. continue;
  2242. }
  2243. i++;
  2244. }
  2245. }
  2246. }
  2247. i = this._position;
  2248. if (this._get(i) === '`') {
  2249. i++;
  2250. while (i < this._text.length) {
  2251. if (this._text[i] === '`') {
  2252. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2253. }
  2254. i++;
  2255. }
  2256. }
  2257. return null;
  2258. }
  2259. });
  2260. this.registerType('builtins.dict', dict);
  2261. this.registerType('builtins.ellipsis', class {});
  2262. this.registerType('builtins.cell', class {});
  2263. this.registerType('builtins.list', class extends Array {});
  2264. this.registerType('builtins.number', class {});
  2265. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2266. return execution.__import__(name, globals, locals, fromlist, level);
  2267. });
  2268. this.registerType('builtins.bool', class extends Boolean {
  2269. constructor(value) {
  2270. if (value && value.__bool__) {
  2271. value = value.__bool__();
  2272. } else if (value && value.__len__) {
  2273. value = value.__len__() > 0;
  2274. } else {
  2275. value = value ? true : false;
  2276. }
  2277. super(value);
  2278. }
  2279. });
  2280. this.registerType('builtins.int', class extends Number {
  2281. constructor(value) {
  2282. if (value && value.__int__) {
  2283. value = value.__int__();
  2284. } else if (!Number.isInteger(value)) {
  2285. value = NaN;
  2286. }
  2287. super(value);
  2288. }
  2289. });
  2290. this.registerType('builtins.float', class extends Number {
  2291. constructor(value) {
  2292. if (value && value.__float__) {
  2293. value = value.__float__();
  2294. } else if (Number(value) !== value) {
  2295. value = NaN;
  2296. }
  2297. super(value);
  2298. }
  2299. });
  2300. this.registerType('builtins.long', class extends Number {
  2301. constructor(value) {
  2302. if (value && value.__int__) {
  2303. value = value.__int__();
  2304. } else if (!Number.isInteger(value)) {
  2305. value = NaN;
  2306. }
  2307. super(value);
  2308. }
  2309. });
  2310. this.registerType('builtins.str', class extends String {
  2311. constructor(value) {
  2312. if (value && value.__str__) {
  2313. value = value.__str__();
  2314. } else if (typeof value !== 'string') {
  2315. value = JSON.stringify(value);
  2316. }
  2317. super(value);
  2318. }
  2319. });
  2320. this.registerType('builtins.complex', class {
  2321. constructor(real, imaginary) {
  2322. this.real = real;
  2323. this.imag = imaginary;
  2324. }
  2325. });
  2326. this.registerType('builtins.NoneType', class {});
  2327. this.registerType('builtins.object', class {
  2328. static __new__(cls, ...args) {
  2329. return execution.invoke(cls, args);
  2330. }
  2331. });
  2332. this.registerType('builtins.tuple', class extends Array {
  2333. constructor(items) {
  2334. super(items ? items.length : 0);
  2335. if (items) {
  2336. for (let i = 0; i < items.length; i++) {
  2337. this[i] = items[i];
  2338. }
  2339. }
  2340. }
  2341. });
  2342. this.registerType('builtins.staticmethod', class {});
  2343. this.registerType('builtins.Warning', class {});
  2344. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2345. this.registerType('builtins.BaseException', class {});
  2346. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2347. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2348. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2349. this.registerFunction('builtins.print', () => {});
  2350. this.registerFunction('builtins.unicode');
  2351. builtins.Ellipsis = new builtins.ellipsis();
  2352. this.registerType('typing._Final', class {});
  2353. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2354. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2355. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2356. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2357. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2358. this.registerType('typing._CallableType', class {});
  2359. this.registerFunction('typing.cast');
  2360. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2361. typing.Callable = Reflect.construct(typing._CallableType, []);
  2362. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2363. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2364. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2365. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2366. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2367. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2368. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2369. this.registerType('enum.Enum', class {});
  2370. this.registerFunction('operator.add');
  2371. this.registerFunction('operator.eq');
  2372. this.registerFunction('operator.ge');
  2373. this.registerFunction('operator.getitem');
  2374. this.registerFunction('operator.gt');
  2375. this.registerFunction('operator.mul');
  2376. this.registerFunction('operator.mod');
  2377. this.registerFunction('operator.le');
  2378. this.registerFunction('operator.lt');
  2379. this.registerFunction('operator.ne');
  2380. this.registerFunction('operator.floordiv');
  2381. this.registerFunction('operator.sub');
  2382. this.registerFunction('sys.path.append', () => {});
  2383. this.registerFunction('sys.path.insert', () => {});
  2384. this.registerType('argparse.Namespace', class {
  2385. constructor(args) {
  2386. this.args = args;
  2387. }
  2388. });
  2389. this.registerType('catboost._catboost._CatBoost', class {
  2390. _deserialize_model(/* serialized_model_str */) {
  2391. }
  2392. });
  2393. this.registerType('catboost.core._CatBoostBase', class {
  2394. constructor() {
  2395. this._object = new catboost._catboost._CatBoost();
  2396. }
  2397. __setstate__(state) {
  2398. for (const [key, value] of state) {
  2399. if (key === '__model') {
  2400. this._load_from_string(value);
  2401. continue;
  2402. }
  2403. this[key] = value;
  2404. }
  2405. }
  2406. _load_from_string(dump_model_str) {
  2407. this._deserialize_model(dump_model_str);
  2408. }
  2409. _deserialize_model(dump_model_str) {
  2410. this._object._deserialize_model(dump_model_str);
  2411. }
  2412. });
  2413. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2414. load_model(/* blob */) {
  2415. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2416. // this._load_from_string(blob);
  2417. }
  2418. });
  2419. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2420. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2421. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2422. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2423. catboost.CatBoost = catboost.core.CatBoost;
  2424. this.registerType('collections.deque', class extends Array {
  2425. constructor(iterable) {
  2426. super();
  2427. if (Array.isArray(iterable)) {
  2428. for (const value of iterable) {
  2429. this.push(value);
  2430. }
  2431. }
  2432. }
  2433. });
  2434. this.registerType('collections.OrderedDict', class extends dict {});
  2435. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2436. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2437. this.registerType('cuml.internals.array.CumlArray', class {});
  2438. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2439. this.registerType('cuml.raft.common.handle.Handle', class {
  2440. __setstate__(state) {
  2441. this._handle = state;
  2442. }
  2443. });
  2444. this.registerType('cuml.svm.svr.SVR', class {});
  2445. this.registerType('datetime.date', class {});
  2446. this.registerType('datetime.datetime', class extends datetime.date {});
  2447. this.registerType('datetime.timedelta', class {});
  2448. this.registerType('datetime.tzinfo', class {});
  2449. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2450. this.registerType('dnnlib.tflib.network.Network', class {});
  2451. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2452. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2453. constructor(dict) {
  2454. Object.assign(this, dict);
  2455. }
  2456. });
  2457. this.registerType('haiku._src.data_structures.frozendict', class {
  2458. constructor(obj) {
  2459. Object.assign(this, obj);
  2460. }
  2461. });
  2462. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2463. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2464. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2465. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2466. this.registerType('io.BytesIO', class {
  2467. constructor(buf, mode) {
  2468. this.mode = mode || 'r';
  2469. this._buf = this.mode === 'w' ? null : buf;
  2470. this._point = 0;
  2471. }
  2472. seek(offset) {
  2473. this._point = offset;
  2474. }
  2475. read(size) {
  2476. const start = this._point;
  2477. this._point = size === undefined ? this._buf.length : start + size;
  2478. return this._buf.subarray(start, this._point);
  2479. }
  2480. write(data) {
  2481. const src = this._buf || new Uint8Array();
  2482. this._point = src.length + data.length;
  2483. this._buf = new Uint8Array(this._point);
  2484. this._buf.set(src, 0);
  2485. this._buf.set(data, src.length);
  2486. }
  2487. });
  2488. this.registerType('io.StringIO', class {
  2489. constructor() {
  2490. this._buf = [];
  2491. }
  2492. write(text) {
  2493. this._buf.push(text);
  2494. }
  2495. toString() {
  2496. return this._buf.join('');
  2497. }
  2498. });
  2499. this.registerType('numpy.dtype', class {
  2500. constructor(obj, align, copy) {
  2501. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2502. this.byteorder = obj.substring(0, 1);
  2503. obj = obj.substring(1);
  2504. } else {
  2505. this.byteorder = '=';
  2506. }
  2507. switch (obj) {
  2508. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2509. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2510. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2511. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2512. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2513. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2514. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2515. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2516. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2517. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2518. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2519. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2520. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2521. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2522. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2523. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2524. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2525. default:
  2526. if (obj.startsWith('V')) {
  2527. this.itemsize = parseInt(obj.substring(1), 10);
  2528. this.kind = 'V';
  2529. } else if (obj.startsWith('O')) {
  2530. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2531. this.kind = 'O';
  2532. } else if (obj.startsWith('S')) {
  2533. this.itemsize = parseInt(obj.substring(1), 10);
  2534. this.kind = 'S';
  2535. } else if (obj.startsWith('U')) { // Unicode string
  2536. this.kind = 'U';
  2537. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2538. } else if (obj.startsWith('T')) {
  2539. this.kind = 'T';
  2540. this.itemsize = parseInt(obj.substring(1), 10);
  2541. } else {
  2542. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2543. }
  2544. break;
  2545. }
  2546. if (align) {
  2547. this.align = align;
  2548. }
  2549. if (copy) {
  2550. this.copy = copy;
  2551. }
  2552. }
  2553. get str() {
  2554. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2555. }
  2556. get name() {
  2557. switch (this.kind) {
  2558. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2559. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2560. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2561. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2562. case 'M': return 'datetime64';
  2563. case 'b': return 'bool';
  2564. default: return this.__name__;
  2565. }
  2566. }
  2567. __setstate__(state) {
  2568. switch (state.length) {
  2569. case 8:
  2570. [
  2571. this.version, this.byteorder, this.subarray, this.names,
  2572. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2573. ] = state;
  2574. break;
  2575. case 9:
  2576. [
  2577. this.version, this.byteorder, this.subarray, this.names,
  2578. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2579. this.metadata
  2580. ] = state;
  2581. break;
  2582. default:
  2583. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2584. }
  2585. }
  2586. get __name__() {
  2587. switch (this.kind) {
  2588. case 'b':
  2589. switch (this.itemsize) {
  2590. case 1: return 'boolean';
  2591. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2592. }
  2593. case 'i':
  2594. switch (this.itemsize) {
  2595. case 1: return 'int8';
  2596. case 2: return 'int16';
  2597. case 4: return 'int32';
  2598. case 8: return 'int64';
  2599. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2600. }
  2601. case 'u':
  2602. switch (this.itemsize) {
  2603. case 1: return 'uint8';
  2604. case 2: return 'uint16';
  2605. case 4: return 'uint32';
  2606. case 8: return 'uint64';
  2607. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2608. }
  2609. case 'f':
  2610. switch (this.itemsize) {
  2611. case 1: return 'float8e5m2';
  2612. case 2: return 'float16';
  2613. case 4: return 'float32';
  2614. case 8: return 'float64';
  2615. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2616. }
  2617. case 'c':
  2618. switch (this.itemsize) {
  2619. case 8: return 'complex64';
  2620. case 16: return 'complex128';
  2621. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2622. }
  2623. case 'S':
  2624. case 'T':
  2625. return 'string';
  2626. case 'U':
  2627. return 'string';
  2628. case 'M':
  2629. return 'datetime';
  2630. case 'O':
  2631. return 'object';
  2632. case 'V':
  2633. return 'void';
  2634. default:
  2635. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2636. }
  2637. }
  2638. });
  2639. this.registerType('numpy.generic', class {});
  2640. this.registerType('numpy.inexact', class {});
  2641. this.registerType('numpy.bool_', class extends numpy.generic {});
  2642. this.registerType('numpy.number', class extends numpy.generic {});
  2643. this.registerType('numpy.integer', class extends numpy.number {});
  2644. this.registerType('numpy.floating', class extends numpy.inexact {});
  2645. this.registerType('numpy.float16', class extends numpy.floating {});
  2646. this.registerType('numpy.float32', class extends numpy.floating {});
  2647. this.registerType('numpy.float64', class extends numpy.floating {});
  2648. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2649. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2650. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2651. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2652. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2653. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2654. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2655. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2656. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2657. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2658. this.registerType('numpy.datetime64', class extends numpy.generic {});
  2659. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2660. constructor() {
  2661. super('|T16');
  2662. }
  2663. });
  2664. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2665. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2666. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2667. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2668. this.registerType('gensim.models.fasttext.FastText', class {});
  2669. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2670. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2671. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2672. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2673. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2674. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2675. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2676. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2677. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2678. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2679. this.registerFunction('gensim.models.phrases.original_scorer');
  2680. this.registerType('gensim.models.phrases.Phraser', class {});
  2681. this.registerType('gensim.models.phrases.Phrases', class {});
  2682. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2683. this.registerType('gensim.models.word2vec.Vocab', class {});
  2684. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2685. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2686. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2687. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2688. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2689. throw new builtins.AttributeError('This method should be called on a class object.');
  2690. });
  2691. this.registerFunction('gensim.utils.identity');
  2692. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2693. constructor(obj) {
  2694. Object.assign(this, obj);
  2695. }
  2696. });
  2697. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2698. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2699. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2700. __read__(unpickler) {
  2701. if (this.dtype.__name__ === 'object') {
  2702. return unpickler.load();
  2703. }
  2704. if (this.numpy_array_alignment_bytes) {
  2705. const [size] = unpickler.read(1);
  2706. unpickler.read(size);
  2707. }
  2708. if (this.order === 'F') {
  2709. throw new python.Error('Fortran order not implemented.');
  2710. }
  2711. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2712. this.data = unpickler.read(size);
  2713. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2714. }
  2715. });
  2716. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2717. __setstate__(state) {
  2718. this.subclass = state.get('subclass');
  2719. this.filename = state.get('state');
  2720. this.allow_mmap = state.get('allow_mmap');
  2721. }
  2722. __read__(/* unpickler */) {
  2723. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2724. }
  2725. });
  2726. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2727. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2728. this.registerType('keras.engine.sequential.Sequential', class {});
  2729. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2730. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2731. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2732. this.registerType('lasagne.layers.input.InputLayer', class {});
  2733. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2734. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2735. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2736. this.registerType('lightgbm.basic.Booster', class {
  2737. constructor() {
  2738. this.average_output = false;
  2739. this.models = [];
  2740. this.loaded_parameter = '';
  2741. }
  2742. __setstate__(state) {
  2743. const model_str = state.get('_handle', state.get('handle', null));
  2744. if (model_str) {
  2745. this.LoadModelFromString(model_str);
  2746. return;
  2747. }
  2748. for (const [key, value] of state) {
  2749. this[key] = value;
  2750. }
  2751. }
  2752. LoadModelFromString(model_str) {
  2753. const lines = model_str.split('\n');
  2754. const signature = lines.shift() || '?';
  2755. if (signature.trim() !== 'tree') {
  2756. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2757. }
  2758. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2759. const key_vals = new Map();
  2760. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2761. const cur_line = lines.shift().trim();
  2762. if (cur_line.length > 0) {
  2763. const strs = cur_line.split('=');
  2764. if (strs.length === 1) {
  2765. key_vals.set(strs[0], '');
  2766. } else if (strs.length === 2) {
  2767. key_vals.set(strs[0], strs[1]);
  2768. } else if (strs.length > 2) {
  2769. if (strs[0] === "feature_names") {
  2770. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2771. } else if (strs[0] === 'monotone_constraints') {
  2772. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2773. } else {
  2774. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2775. }
  2776. }
  2777. }
  2778. }
  2779. const atoi = (key, value) => {
  2780. if (key_vals.has(key)) {
  2781. return parseInt(key_vals.get(key), 10);
  2782. }
  2783. if (value !== undefined) {
  2784. return value;
  2785. }
  2786. throw new python.Error(`Model file does not specify ${key}.`);
  2787. };
  2788. const list = (key, size) => {
  2789. if (key_vals.has(key)) {
  2790. const value = key_vals.get(key).split(' ');
  2791. if (value.length !== size) {
  2792. throw new python.Error(`Wrong size of ${key}.`);
  2793. }
  2794. return value;
  2795. }
  2796. throw new python.Error(`Model file does not contain ${key}.`);
  2797. };
  2798. this.version = key_vals.get('version') || '';
  2799. this.num_class = atoi('num_class');
  2800. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2801. this.label_index = atoi('label_index');
  2802. this.max_feature_idx = atoi('max_feature_idx');
  2803. if (key_vals.has('average_output')) {
  2804. this.average_output = true;
  2805. }
  2806. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2807. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2808. if (key_vals.has('monotone_constraints')) {
  2809. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2810. }
  2811. if (key_vals.has('objective')) {
  2812. this.objective = key_vals.get('objective');
  2813. }
  2814. let tree = null;
  2815. while (lines.length > 0) {
  2816. const text = lines.shift();
  2817. const line = text.trim();
  2818. if (line.length === 0) {
  2819. continue;
  2820. }
  2821. if (line.startsWith('Tree=')) {
  2822. tree = { index: parseInt(line.split('=').pop(), 10) };
  2823. this.models.push(tree);
  2824. continue;
  2825. }
  2826. if (line === 'end of trees') {
  2827. break;
  2828. }
  2829. const param = line.split('=');
  2830. if (param.length !== 2) {
  2831. throw new python.Error(`Invalid property '${line}'.`);
  2832. }
  2833. const name = param[0].trim();
  2834. const value = param[1].trim();
  2835. tree[name] = value;
  2836. }
  2837. const ss = [];
  2838. let is_inparameter = false;
  2839. while (lines.length > 0) {
  2840. const text = lines.shift();
  2841. const line = text.trim();
  2842. if (line === 'parameters:') {
  2843. is_inparameter = true;
  2844. continue;
  2845. } else if (line === 'end of parameters') {
  2846. break;
  2847. } else if (is_inparameter) {
  2848. ss.push(line);
  2849. }
  2850. }
  2851. if (ss.length > 0) {
  2852. this.loaded_parameter = ss.join('\n');
  2853. }
  2854. }
  2855. });
  2856. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2857. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  2858. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  2859. this.registerFunction('megengine.functional.nn.relu', () => {});
  2860. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  2861. this.registerFunction('megengine.functional.tensor.arange', () => {});
  2862. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  2863. this.registerFunction('megengine.functional.tensor.concat', () => {});
  2864. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  2865. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  2866. this.registerFunction('megengine.functional.tensor.full', () => {});
  2867. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  2868. this.registerFunction('megengine.functional.tensor.split', () => {});
  2869. this.registerFunction('megengine.functional.tensor.stack', () => {});
  2870. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  2871. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  2872. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  2873. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  2874. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  2875. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  2876. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  2877. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  2878. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  2879. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  2880. this.registerType('megengine.distributed.group.Group', class {});
  2881. this.registerType('megengine.module.activation.ReLU', class {});
  2882. this.registerType('megengine.module.activation.Softmax', class {});
  2883. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  2884. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  2885. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  2886. this.registerType('megengine.module.conv.Conv2d', class {});
  2887. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  2888. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  2889. this.registerType('megengine.module.dropout.Dropout', class {});
  2890. this.registerType('megengine.module.identity.Identity', class {});
  2891. this.registerType('megengine.module.linear.Linear', class {});
  2892. this.registerType('megengine.module.module.Module', class {});
  2893. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  2894. this.registerType('megengine.module.normalization.GroupNorm', class {});
  2895. this.registerType('megengine.module.normalization.LayerNorm', class {});
  2896. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  2897. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  2898. this.registerType('megengine.module.qat.concat.Concat', class {});
  2899. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  2900. this.registerType('megengine.module.sequential.Sequential', class {});
  2901. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  2902. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  2903. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  2904. this.registerType('megengine.quantization.utils.QParams', class {});
  2905. this.registerType('megengine.quantization.utils.QuantMode', class {});
  2906. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  2907. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  2908. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  2909. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  2910. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  2911. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  2912. this.registerType('megengine.traced_module.expr.Apply', class {});
  2913. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  2914. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  2915. this.registerType('megengine.traced_module.expr.Constant', class {});
  2916. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  2917. this.registerType('megengine.traced_module.expr.Input', class {});
  2918. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  2919. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  2920. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  2921. this.registerType('megengine.traced_module.node.TensorNode', class {});
  2922. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  2923. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  2924. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  2925. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  2926. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  2927. this.registerType('megengine.tensor.Parameter', class {
  2928. constructor(data, dtype, device) {
  2929. this.data = data;
  2930. this.dtype = dtype;
  2931. this.device = device;
  2932. }
  2933. });
  2934. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  2935. toString() {
  2936. let content = '';
  2937. for (const child of this.children_defs) {
  2938. content += `${child},`;
  2939. }
  2940. if (typeof this.type === "string") {
  2941. return `${this.type.split(".").slice(-1)}(${content})`;
  2942. }
  2943. return `${this.type.__name__}(${content})`;
  2944. }
  2945. });
  2946. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  2947. toString() {
  2948. let content = '';
  2949. if (this.const_val === null) {
  2950. content += '[';
  2951. } else {
  2952. content += this.const_val;
  2953. }
  2954. for (const t of Object.values(this.type)) {
  2955. content += t.__name__;
  2956. }
  2957. content += ']';
  2958. return content;
  2959. }
  2960. });
  2961. this.registerType('megengine.tensor.Tensor', class {
  2962. constructor(data, dtype, device) {
  2963. this.data = data;
  2964. this.dtype = dtype;
  2965. this.device = device;
  2966. }
  2967. });
  2968. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  2969. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  2970. this.name = name;
  2971. this.cname = cname;
  2972. this.np_dtype = np_dtype;
  2973. this.qmin = qmin;
  2974. this.qmax = qmax;
  2975. this.is_signed = is_signed;
  2976. }
  2977. });
  2978. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  2979. this.registerType('nolearn.lasagne.base.Layers', class {});
  2980. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  2981. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  2982. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  2983. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  2984. this.registerType('numpy.ndarray', class {
  2985. constructor(shape, dtype, buffer, offset, strides, order) {
  2986. this.shape = shape;
  2987. this.dtype = dtype;
  2988. this.data = buffer === undefined ? null : buffer;
  2989. this.offset = offset === undefined ? 0 : offset;
  2990. this._strides = strides === undefined ? null : strides;
  2991. this.order = order === undefined ? null : order;
  2992. this.flags = {};
  2993. this._read();
  2994. }
  2995. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  2996. return new cls(shape, dtype, buffer, offset, strides, order);
  2997. }
  2998. __setstate__(state) {
  2999. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3000. this._read();
  3001. }
  3002. flatten() {
  3003. const size = this.shape.reduce((a, b) => a * b, 1);
  3004. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3005. value.flags = this.flags;
  3006. return value;
  3007. }
  3008. tobytes() {
  3009. return this.data;
  3010. }
  3011. tolist() {
  3012. if (this.shape.length < 0 || this.shape.length > 1) {
  3013. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3014. }
  3015. const size = this.shape.reduce((a, b) => a * b, 1);
  3016. const list = new Array(size);
  3017. switch (this.dtype.kind) {
  3018. case 'U': {
  3019. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3020. const itemsize = this.dtype.itemsize >> 2;
  3021. let offset = 0;
  3022. for (let i = 0; i < size; i++) {
  3023. const buffer = data.subarray(offset, offset + itemsize);
  3024. const index = buffer.indexOf(0);
  3025. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3026. offset += itemsize;
  3027. }
  3028. return list;
  3029. }
  3030. case 'S': {
  3031. const data = this.data;
  3032. const itemsize = this.dtype.itemsize;
  3033. const decoder = new TextDecoder('utf-8');
  3034. let offset = 0;
  3035. for (let i = 0; i < size; i++) {
  3036. const buffer = data.subarray(offset, offset + itemsize);
  3037. const index = buffer.indexOf(0);
  3038. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3039. offset += itemsize;
  3040. }
  3041. return list;
  3042. }
  3043. case 'V': {
  3044. const data = this.data;
  3045. const itemsize = this.dtype.itemsize;
  3046. let offset = 0;
  3047. for (let i = 0; i < size; i++) {
  3048. list[i] = data.slice(offset, offset + itemsize);
  3049. offset += itemsize;
  3050. }
  3051. return list;
  3052. }
  3053. case 'T': {
  3054. return this.data;
  3055. }
  3056. case 'O': {
  3057. return this.data;
  3058. }
  3059. default: {
  3060. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3061. }
  3062. }
  3063. }
  3064. get itemsize() {
  3065. return this.dtype.itemsize;
  3066. }
  3067. get size() {
  3068. return (this.shape || []).reduce((a, b) => a * b, 1);
  3069. }
  3070. get strides() {
  3071. if (!this._strides) {
  3072. const shape = this.shape;
  3073. const strides = new Array(shape.length);
  3074. let stride = this.itemsize;
  3075. for (let i = shape.length - 1; i >= 0; i--) {
  3076. strides[i] = stride;
  3077. stride *= shape[i];
  3078. }
  3079. return strides;
  3080. }
  3081. return this._strides;
  3082. }
  3083. _read() {
  3084. if (this.data) {
  3085. const length = this.dtype.itemsize * this.size;
  3086. if (typeof this.data === 'string') {
  3087. this.data = this._unescape(this.data, length);
  3088. if (this.data.length !== length) {
  3089. throw new python.Error('Invalid string array data size.');
  3090. }
  3091. } else if (this.data.length !== length) {
  3092. // throw new python.Error('Invalid array data size.');
  3093. }
  3094. }
  3095. }
  3096. _unescape(token, size) {
  3097. const length = token.length;
  3098. const a = new Uint8Array(length);
  3099. if (size && size === length) {
  3100. for (let p = 0; p < size; p++) {
  3101. a[p] = token.charCodeAt(p);
  3102. }
  3103. return a;
  3104. }
  3105. let i = 0;
  3106. let o = 0;
  3107. while (i < length) {
  3108. let c = token.charCodeAt(i++);
  3109. if (c !== 0x5C || i >= length) {
  3110. a[o++] = c;
  3111. } else {
  3112. c = token.charCodeAt(i++);
  3113. switch (c) {
  3114. case 0x27: a[o++] = 0x27; break; // '
  3115. case 0x5C: a[o++] = 0x5C; break; // \\
  3116. case 0x22: a[o++] = 0x22; break; // "
  3117. case 0x72: a[o++] = 0x0D; break; // \r
  3118. case 0x6E: a[o++] = 0x0A; break; // \n
  3119. case 0x74: a[o++] = 0x09; break; // \t
  3120. case 0x62: a[o++] = 0x08; break; // \b
  3121. case 0x58: // x
  3122. case 0x78: { // X
  3123. const xsi = i - 1;
  3124. const xso = o;
  3125. for (let xi = 0; xi < 2; xi++) {
  3126. if (i >= length) {
  3127. i = xsi;
  3128. o = xso;
  3129. a[o] = 0x5c;
  3130. break;
  3131. }
  3132. let c = token.charCodeAt(i++);
  3133. if (c >= 65 && c <= 70) {
  3134. c -= 55;
  3135. } else if (c >= 97 && c <= 102) {
  3136. c -= 87;
  3137. } else if (c >= 48 && c <= 57) {
  3138. c -= 48;
  3139. } else {
  3140. c = -1;
  3141. }
  3142. if (c === -1) {
  3143. i = xsi;
  3144. o = xso;
  3145. a[o] = 0x5c;
  3146. break;
  3147. }
  3148. a[o] = a[o] << 4 | c;
  3149. }
  3150. o++;
  3151. break;
  3152. }
  3153. default:
  3154. if (c < 48 || c > 57) { // 0-9
  3155. a[o++] = 0x5c;
  3156. a[o++] = c;
  3157. } else {
  3158. i--;
  3159. const osi = i;
  3160. const oso = o;
  3161. for (let oi = 0; oi < 3; oi++) {
  3162. if (i >= length) {
  3163. i = osi;
  3164. o = oso;
  3165. a[o] = 0x5c;
  3166. break;
  3167. }
  3168. const od = token.charCodeAt(i++);
  3169. if (od < 48 || od > 57) {
  3170. i = osi;
  3171. o = oso;
  3172. a[o] = 0x5c;
  3173. break;
  3174. }
  3175. a[o] = a[o] << 3 | od - 48;
  3176. }
  3177. o++;
  3178. }
  3179. break;
  3180. }
  3181. }
  3182. }
  3183. return a.slice(0, o);
  3184. }
  3185. });
  3186. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3187. static __new__(/* subtype, data, dtype, copy */) {
  3188. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3189. }
  3190. });
  3191. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3192. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3193. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3194. super(data.shape, data.dtype, data.data);
  3195. }
  3196. });
  3197. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  3198. });
  3199. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3200. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {});
  3201. this.registerType('pandas.core.arrays.integer.IntegerArray', class {});
  3202. this.registerType('pandas.core.frame.DataFrame', class {});
  3203. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3204. return new cls(d);
  3205. });
  3206. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3207. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3208. this.registerType('pandas.core.indexes.base.Index', class {});
  3209. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3210. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3211. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3212. this.registerType('pandas.core.index.Int64Index', class {});
  3213. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3214. });
  3215. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3216. });
  3217. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3218. return pandas.core.internals.blocks.NumpyBlock;
  3219. });
  3220. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3221. return values;
  3222. });
  3223. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3224. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3225. return new klass(values, ndim, placement, refs);
  3226. });
  3227. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3228. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3229. this.registerType('pandas.core.series.Series', class {});
  3230. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked');
  3231. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3232. values = execution.invoke('pandas.core.internals.blocks.maybe_coerce_values', [values]);
  3233. // if not isinstance(placement, BlockPlacement):
  3234. // placement = BlockPlacement(placement)
  3235. return execution.invoke('pandas.core.internals.blocks.new_block', [values, placement, ndim]);
  3236. });
  3237. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3238. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3239. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3240. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3241. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3242. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3243. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3244. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3245. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3246. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3247. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3248. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3249. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3250. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3251. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3252. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3253. this.registerType('pathlib.Path', class {});
  3254. this.registerType('pathlib.PosixPath', class {});
  3255. this.registerType('pathlib.WindowsPath', class {});
  3256. this.registerType('shap._serializable.Serializable', class {});
  3257. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3258. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3259. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3260. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3261. this.registerType('sklearn._loss.link.BaseLink', class {});
  3262. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3263. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3264. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3265. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3266. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3267. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3268. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3269. this.registerType('sklearn._loss.link.Interval', class {});
  3270. this.registerType('sklearn._loss.link.LogitLink', class {});
  3271. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3272. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3273. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3274. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3275. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3276. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3277. this.registerType('sklearn.base.BaseEstimator', class {});
  3278. this.registerType('sklearn.base.TransformerMixin', class {});
  3279. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3280. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3281. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3282. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3283. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3284. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3285. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3286. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3287. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3288. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3289. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3290. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3291. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3292. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3293. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3294. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3295. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3296. this.registerType('sklearn.decomposition.PCA', class {});
  3297. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3298. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3299. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3300. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3301. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3302. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3303. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3304. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3305. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3306. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3307. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3308. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3309. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3310. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3311. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3312. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3313. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3314. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3315. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3316. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3317. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3318. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3319. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3320. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3321. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3322. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3323. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3324. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3325. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3326. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3327. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3328. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3329. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3330. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3331. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3332. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3333. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3334. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3335. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3336. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3337. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3338. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3339. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3340. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3341. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3342. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3343. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3344. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3345. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3346. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3347. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3348. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3349. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3350. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3351. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3352. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3353. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3354. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3355. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3356. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3357. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3358. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3359. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3360. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3361. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3362. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3363. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3364. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3365. this.registerType('sklearn.impute.SimpleImputer', class {});
  3366. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3367. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3368. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3369. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3370. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3371. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3372. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3373. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3374. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3375. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3376. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3377. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3378. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3379. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3380. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3381. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3382. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3383. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3384. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3385. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3386. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3387. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3388. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3389. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3390. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3391. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3392. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3393. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3394. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3395. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3396. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3397. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3398. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3399. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3400. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3401. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3402. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3403. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3404. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3405. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3406. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3407. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3408. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3409. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3410. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3411. this.registerType('sklearn.model_selection._split.KFold', class {});
  3412. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3413. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3414. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3415. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3416. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3417. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3418. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3419. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3420. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3421. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3422. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3423. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3424. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3425. return obj.__new__(obj);
  3426. });
  3427. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3428. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3429. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3430. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3431. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3432. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3433. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3434. return obj.__new__(obj);
  3435. });
  3436. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3437. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3438. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3439. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3440. return obj.__new__(obj);
  3441. });
  3442. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3443. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3444. return obj.__new__(obj);
  3445. });
  3446. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3447. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3448. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3449. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3450. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3451. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3452. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3453. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3454. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3455. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3456. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3457. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3458. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3459. this.registerType('sklearn.pipeline.Pipeline', class {});
  3460. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3461. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3462. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3463. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3464. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3465. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3466. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3467. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3468. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3469. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3470. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3471. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3472. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3473. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3474. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3475. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3476. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3477. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3478. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3479. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3480. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3481. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3482. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3483. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3484. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3485. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3486. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3487. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3488. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3489. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3490. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3491. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3492. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3493. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3494. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3495. this.registerType('sklearn.svm._classes.SVC', class {});
  3496. this.registerType('sklearn.svm._classes.SVR', class {});
  3497. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3498. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3499. this.registerType('sklearn.svm.classes.SVC', class {});
  3500. this.registerType('sklearn.svm.classes.SVR', class {});
  3501. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3502. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3503. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3504. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3505. this.registerType('sklearn.tree._tree.Tree', class {
  3506. constructor(n_features, n_classes, n_outputs) {
  3507. this.n_features = n_features;
  3508. this.n_classes = n_classes;
  3509. this.n_outputs = n_outputs;
  3510. }
  3511. __setstate__(state) {
  3512. this.max_depth = state.get('max_depth');
  3513. this.node_count = state.get('node_count');
  3514. this.nodes = state.get('nodes');
  3515. this.values = state.get('values');
  3516. }
  3517. });
  3518. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3519. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3520. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3521. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3522. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3523. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3524. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3525. this.registerType('pickle.Unpickler', class {
  3526. constructor(data) {
  3527. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3528. this.persistent_load = () => {
  3529. throw new python.Error('Unsupported persistent id.');
  3530. };
  3531. }
  3532. load() {
  3533. const reader = this._reader;
  3534. const marker = [];
  3535. let stack = [];
  3536. const memo = {};
  3537. let size = 0;
  3538. while (reader.position < reader.length) {
  3539. const opcode = reader.byte();
  3540. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3541. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3542. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3543. switch (opcode) {
  3544. case 128: { // PROTO
  3545. const version = reader.byte();
  3546. if (version > 5) {
  3547. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3548. }
  3549. break;
  3550. }
  3551. case 99: { // GLOBAL 'c'
  3552. const module = reader.line();
  3553. const name = reader.line();
  3554. stack.push(this.find_class(module, name));
  3555. break;
  3556. }
  3557. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3558. const name = stack.pop();
  3559. const module = stack.pop();
  3560. stack.push(this.find_class(module, name));
  3561. break;
  3562. }
  3563. case 111: { // OBJ 'o'
  3564. const args = stack;
  3565. const cls = args.pop();
  3566. stack = marker.pop();
  3567. const obj = this._instantiate(cls, args);
  3568. stack.push(obj);
  3569. break;
  3570. }
  3571. case 112 : { // PUT 'p'
  3572. const index = parseInt(reader.line(), 10);
  3573. memo[index] = stack[stack.length - 1];
  3574. size++;
  3575. break;
  3576. }
  3577. case 103: { // GET 'g'
  3578. const index = parseInt(reader.line(), 10);
  3579. stack.push(memo[index]);
  3580. break;
  3581. }
  3582. case 48: // POP '0'
  3583. stack.pop();
  3584. break;
  3585. case 49: // POP_MARK '1'
  3586. stack = marker.pop();
  3587. break;
  3588. case 50: // DUP '2'
  3589. stack.push(stack[stack.length - 1]);
  3590. break;
  3591. case 80: // PERSID 'P'
  3592. stack.push(this.persistent_load(reader.line()));
  3593. break;
  3594. case 81: // BINPERSID 'Q'
  3595. stack.push(this.persistent_load(stack.pop()));
  3596. break;
  3597. case 82: { // REDUCE 'R'
  3598. const args = stack.pop();
  3599. const func = stack.pop();
  3600. stack.push(this._reduce(func, args));
  3601. break;
  3602. }
  3603. case 129: { // NEWOBJ
  3604. const args = stack.pop();
  3605. const cls = stack.pop();
  3606. const obj = this._newobj(cls, args);
  3607. stack.push(obj);
  3608. break;
  3609. }
  3610. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3611. const kwargs = stack.pop();
  3612. const args = stack.pop();
  3613. const cls = stack.pop();
  3614. if (Object.entries(kwargs).length > 0) {
  3615. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3616. }
  3617. const obj = this._newobj(cls, args);
  3618. stack.push(obj);
  3619. break;
  3620. }
  3621. case 104: // BINGET 'h'
  3622. stack.push(memo[reader.byte()]);
  3623. break;
  3624. case 105: { // INST 'i'
  3625. const module = reader.line();
  3626. const name = reader.line();
  3627. const args = stack;
  3628. const cls = `${module}.${name}`;
  3629. stack = marker.pop();
  3630. // cls = this.find_class(module, name)
  3631. const obj = this._instantiate(cls, args);
  3632. stack.push(obj);
  3633. break;
  3634. }
  3635. case 106: // LONG_BINGET 'j'
  3636. stack.push(memo[reader.uint32()]);
  3637. break;
  3638. case 113: // BINPUT 'q'
  3639. memo[reader.byte()] = stack[stack.length - 1];
  3640. size++;
  3641. break;
  3642. case 114: // LONG_BINPUT 'r'
  3643. memo[reader.uint32()] = stack[stack.length - 1];
  3644. size++;
  3645. break;
  3646. case 74: // BININT 'J'
  3647. stack.push(reader.int32());
  3648. break;
  3649. case 75: // BININT1 'K'
  3650. stack.push(reader.byte());
  3651. break;
  3652. case 76: // LONG 'L'
  3653. stack.push(parseInt(reader.line(), 10));
  3654. break;
  3655. case 77: // BININT2 'M'
  3656. stack.push(reader.uint16());
  3657. break;
  3658. case 66: // BINBYTES 'B' (Protocol 3)
  3659. stack.push(reader.read(reader.int32()));
  3660. break;
  3661. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3662. stack.push(reader.read(reader.byte()));
  3663. break;
  3664. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3665. stack.push(reader.read(reader.int64().toNumber()));
  3666. break;
  3667. case 70: // FLOAT 'F'
  3668. stack.push(parseFloat(reader.line()));
  3669. break;
  3670. case 71: // BINFLOAT 'G'
  3671. stack.push(reader.float64());
  3672. break;
  3673. case 73: { // INT 'I'
  3674. const value = reader.line();
  3675. if (value === '01') {
  3676. stack.push(true);
  3677. } else if (value === '00') {
  3678. stack.push(false);
  3679. } else {
  3680. stack.push(parseInt(value, 10));
  3681. }
  3682. break;
  3683. }
  3684. case 93: // EMPTY_LIST ']'
  3685. stack.push(new builtins.list());
  3686. break;
  3687. case 41: // EMPTY_TUPLE ')'
  3688. stack.push([]);
  3689. break;
  3690. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3691. stack.push([]);
  3692. break;
  3693. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3694. const items = stack;
  3695. stack = marker.pop();
  3696. const obj = stack[stack.length - 1];
  3697. for (let i = 0; i < items.length; i++) {
  3698. obj.push(items[i]);
  3699. }
  3700. break;
  3701. }
  3702. case 145: { // FROZENSET '\x91' (Protocol 4)
  3703. const items = stack;
  3704. stack = marker.pop();
  3705. stack.push(items);
  3706. break;
  3707. }
  3708. case 100: { // DICT 'd'
  3709. const items = stack;
  3710. stack = marker.pop();
  3711. const dict = new builtins.dict();
  3712. for (let i = 0; i < items.length; i += 2) {
  3713. dict.__setitem__(items[i], items[i + 1]);
  3714. }
  3715. stack.push(dict);
  3716. break;
  3717. }
  3718. case 108: { // LIST 'l'
  3719. const items = stack;
  3720. stack = marker.pop();
  3721. stack.push(items);
  3722. break;
  3723. }
  3724. case 116: { // TUPLE 't'
  3725. const items = stack;
  3726. stack = marker.pop();
  3727. stack.push(items);
  3728. break;
  3729. }
  3730. case 133: { // TUPLE1 // '\x85'
  3731. stack.push([stack.pop()]);
  3732. break;
  3733. }
  3734. case 134: { // TUPLE2 '\x86'
  3735. const b = stack.pop();
  3736. const a = stack.pop();
  3737. stack.push([a, b]);
  3738. break;
  3739. }
  3740. case 135: { // TUPLE3 '\x87'
  3741. const c = stack.pop();
  3742. const b = stack.pop();
  3743. const a = stack.pop();
  3744. stack.push([a, b, c]);
  3745. break;
  3746. }
  3747. case 115: { // SETITEM 's'
  3748. const value = stack.pop();
  3749. const key = stack.pop();
  3750. const obj = stack[stack.length - 1];
  3751. if (obj.__setitem__) {
  3752. obj.__setitem__(key, value);
  3753. } else {
  3754. obj[key] = value;
  3755. }
  3756. break;
  3757. }
  3758. case 117: { // SETITEMS 'u'
  3759. const items = stack;
  3760. stack = marker.pop();
  3761. const obj = stack[stack.length - 1];
  3762. if (obj.__setitem__) {
  3763. for (let i = 0; i < items.length; i += 2) {
  3764. obj.__setitem__(items[i], items[i + 1]);
  3765. }
  3766. } else {
  3767. for (let i = 0; i < items.length; i += 2) {
  3768. obj[items[i]] = items[i + 1];
  3769. }
  3770. }
  3771. break;
  3772. }
  3773. case 125: // EMPTY_DICT '}'
  3774. stack.push(new builtins.dict());
  3775. break;
  3776. case 97: { // APPEND 'a'
  3777. const append = stack.pop();
  3778. stack[stack.length - 1].push(append);
  3779. break;
  3780. }
  3781. case 101: { // APPENDS 'e'
  3782. const appends = stack;
  3783. stack = marker.pop();
  3784. const list = stack[stack.length - 1];
  3785. list.push(...appends);
  3786. break;
  3787. }
  3788. case 83: { // STRING 'S'
  3789. const str = reader.line();
  3790. stack.push(str.substr(1, str.length - 2));
  3791. break;
  3792. }
  3793. case 84: // BINSTRING 'T'
  3794. stack.push(reader.string(reader.uint32()));
  3795. break;
  3796. case 85 : // SHORT_BINSTRING 'U'
  3797. stack.push(reader.string(reader.byte()));
  3798. break;
  3799. case 86: // UNICODE 'V'
  3800. stack.push(reader.line());
  3801. break;
  3802. case 88: // BINUNICODE 'X
  3803. stack.push(reader.string(reader.uint32(), 'utf-8'));
  3804. break;
  3805. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  3806. stack.push(reader.string(reader.byte(), 'utf-8'));
  3807. break;
  3808. case 98: { // BUILD 'b'
  3809. const state = stack.pop();
  3810. let obj = stack.pop();
  3811. if (obj.__setstate__) {
  3812. if (obj.__setstate__.__call__) {
  3813. obj.__setstate__.__call__([obj, state]);
  3814. } else {
  3815. obj.__setstate__(state);
  3816. }
  3817. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  3818. obj.__state__ = state;
  3819. } else if (obj instanceof Map && state instanceof Map) {
  3820. for (const [key, value] of state) {
  3821. obj.set(key, value);
  3822. }
  3823. } else if (obj instanceof Map) {
  3824. for (const key in state) {
  3825. obj.set(key, state[key]);
  3826. }
  3827. } else if (state instanceof Map) {
  3828. for (const [key, value] of state) {
  3829. obj[key] = value;
  3830. }
  3831. } else {
  3832. Object.assign(obj, state);
  3833. }
  3834. if (obj.__read__) {
  3835. obj = obj.__read__(this);
  3836. }
  3837. stack.push(obj);
  3838. break;
  3839. }
  3840. case 40: // MARK '('
  3841. marker.push(stack);
  3842. stack = [];
  3843. break;
  3844. case 136: // NEWTRUE '\x88'
  3845. stack.push(true);
  3846. break;
  3847. case 137: // NEWFALSE '\x89'
  3848. stack.push(false);
  3849. break;
  3850. case 138: { // LONG1 '\x8a'
  3851. const data = reader.read(reader.byte());
  3852. let number = 0;
  3853. switch (data.length) {
  3854. case 0: number = 0; break;
  3855. /* eslint-disable prefer-destructuring */
  3856. case 1: number = data[0]; break;
  3857. /* eslint-enable prefer-destructuring */
  3858. case 2: number = data[1] << 8 | data[0]; break;
  3859. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  3860. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  3861. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  3862. default: number = Array.prototype.slice.call(data, 0); break;
  3863. }
  3864. stack.push(number);
  3865. break;
  3866. }
  3867. case 139: // LONG4 '\x8b'
  3868. // decode LONG4
  3869. stack.push(reader.read(reader.uint32()));
  3870. break;
  3871. case 148: // MEMOIZE '\x94' (Protocol 4)
  3872. memo[size++] = stack[stack.length - 1];
  3873. break;
  3874. case 149: // FRAME '\x95' (Protocol 4)
  3875. reader.read(8);
  3876. break;
  3877. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  3878. stack.push(reader.read(reader.int64().toNumber()));
  3879. break;
  3880. }
  3881. case 78: // NONE 'N'
  3882. stack.push(null);
  3883. break;
  3884. case 46: // STOP '.'
  3885. return stack.pop();
  3886. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  3887. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  3888. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  3889. default:
  3890. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  3891. }
  3892. }
  3893. throw new python.Error('Unexpected end of file.');
  3894. }
  3895. find_class(module, name) {
  3896. execution.__import__(module);
  3897. return execution.resolve(`${module}.${name}`);
  3898. }
  3899. _instantiate(cls, args) {
  3900. return execution.invoke(cls, args);
  3901. }
  3902. _newobj(cls, args) {
  3903. // cls.__new__(cls, args)
  3904. return execution.invoke(cls, args);
  3905. }
  3906. _reduce(func, args) {
  3907. return execution.invoke(func, args);
  3908. }
  3909. read(size) {
  3910. return this._reader.read(size);
  3911. }
  3912. stream(size) {
  3913. return this._reader.stream(size);
  3914. }
  3915. });
  3916. this.registerType('random.Random', class {});
  3917. this.registerType('re.Pattern', class {
  3918. constructor(pattern, flags) {
  3919. this.pattern = pattern;
  3920. this.flags = flags;
  3921. }
  3922. });
  3923. this.registerType('spacy._ml.PrecomputableAffine', class {
  3924. __setstate__(state) {
  3925. Object.assign(this, new pickle.Unpickler(state).load());
  3926. }
  3927. });
  3928. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  3929. __setstate__(state) {
  3930. Object.assign(this, new pickle.Unpickler(state).load());
  3931. }
  3932. });
  3933. this.registerType('theano.compile.function_module._constructor_Function', class {});
  3934. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  3935. this.registerType('theano.compile.function_module.Function', class {});
  3936. this.registerType('theano.compile.function_module.Supervisor', class {});
  3937. this.registerType('theano.compile.io.In', class {});
  3938. this.registerType('theano.compile.io.SymbolicOutput', class {});
  3939. this.registerType('theano.compile.mode.Mode', class {});
  3940. this.registerType('theano.compile.ops.OutputGuard', class {});
  3941. this.registerType('theano.compile.ops.Shape', class {});
  3942. this.registerType('theano.compile.ops.Shape_i', class {});
  3943. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  3944. this.registerType('theano.gof.fg.FunctionGraph', class {});
  3945. this.registerType('theano.gof.graph.Apply', class {});
  3946. this.registerType('theano.gof.link.Container', class {});
  3947. this.registerType('theano.gof.opt._metadict', class {});
  3948. this.registerType('theano.gof.opt.ChangeTracker', class {});
  3949. this.registerType('theano.gof.opt.MergeFeature', class {});
  3950. this.registerType('theano.gof.optdb.Query', class {});
  3951. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  3952. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  3953. this.registerType('theano.gof.utils.scratchpad', class {});
  3954. this.registerType('theano.misc.ordered_set.Link', class {});
  3955. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  3956. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  3957. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  3958. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  3959. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  3960. this.registerType('theano.scalar.basic.Abs', class {});
  3961. this.registerType('theano.scalar.basic.Add', class {});
  3962. this.registerType('theano.scalar.basic.Cast', class {});
  3963. this.registerType('theano.scalar.basic.Composite', class {});
  3964. this.registerType('theano.scalar.basic.EQ', class {});
  3965. this.registerType('theano.scalar.basic.GE', class {});
  3966. this.registerType('theano.scalar.basic.Identity', class {});
  3967. this.registerType('theano.scalar.basic.IntDiv', class {});
  3968. this.registerType('theano.scalar.basic.Inv', class {});
  3969. this.registerType('theano.scalar.basic.LE', class {});
  3970. this.registerType('theano.scalar.basic.LT', class {});
  3971. this.registerType('theano.scalar.basic.Mul', class {});
  3972. this.registerType('theano.scalar.basic.Neg', class {});
  3973. this.registerType('theano.scalar.basic.Pow', class {});
  3974. this.registerType('theano.scalar.basic.Scalar', class {});
  3975. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  3976. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  3977. this.registerType('theano.scalar.basic.Second', class {});
  3978. this.registerType('theano.scalar.basic.Sgn', class {});
  3979. this.registerType('theano.scalar.basic.specific_out', class {});
  3980. this.registerType('theano.scalar.basic.Sub', class {});
  3981. this.registerType('theano.scalar.basic.Switch', class {});
  3982. this.registerType('theano.scalar.basic.Tanh', class {});
  3983. this.registerType('theano.scalar.basic.transfer_type', class {});
  3984. this.registerType('theano.scalar.basic.TrueDiv', class {});
  3985. this.registerType('theano.tensor.basic.Alloc', class {});
  3986. this.registerType('theano.tensor.basic.Dot', class {});
  3987. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  3988. this.registerType('theano.tensor.basic.Reshape', class {});
  3989. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  3990. this.registerType('theano.tensor.blas.Dot22', class {});
  3991. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  3992. this.registerType('theano.tensor.blas.Gemm', class {});
  3993. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  3994. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  3995. this.registerType('theano.tensor.elemwise.Sum', class {});
  3996. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  3997. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  3998. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  3999. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4000. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4001. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4002. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4003. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4004. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4005. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4006. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4007. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4008. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4009. this.registerType('theano.tensor.opt.MakeVector', class {});
  4010. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4011. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4012. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4013. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4014. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4015. this.registerType('theano.tensor.type.TensorType', class {});
  4016. this.registerType('theano.tensor.var.TensorConstant', class {});
  4017. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4018. this.registerType('theano.tensor.var.TensorVariable', class {});
  4019. this.registerType('thinc.describe.Biases', class {});
  4020. this.registerType('thinc.describe.Dimension', class {});
  4021. this.registerType('thinc.describe.Gradient', class {});
  4022. this.registerType('thinc.describe.Weights', class {});
  4023. this.registerType('thinc.describe.Synapses', class {});
  4024. this.registerType('thinc.neural._classes.affine.Affine', class {
  4025. __setstate__(state) {
  4026. Object.assign(this, new pickle.Unpickler(state).load());
  4027. }
  4028. });
  4029. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4030. __setstate__(state) {
  4031. Object.assign(this, new pickle.Unpickler(state).load());
  4032. }
  4033. });
  4034. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4035. __setstate__(state) {
  4036. Object.assign(this, new pickle.Unpickler(state).load());
  4037. }
  4038. });
  4039. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4040. __setstate__(state) {
  4041. Object.assign(this, new pickle.Unpickler(state).load());
  4042. }
  4043. });
  4044. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4045. __setstate__(state) {
  4046. Object.assign(this, new pickle.Unpickler(state).load());
  4047. }
  4048. });
  4049. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4050. __setstate__(state) {
  4051. Object.assign(this, new pickle.Unpickler(state).load());
  4052. }
  4053. });
  4054. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4055. __setstate__(state) {
  4056. Object.assign(this, new pickle.Unpickler(state).load());
  4057. }
  4058. });
  4059. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4060. __setstate__(state) {
  4061. Object.assign(this, new pickle.Unpickler(state).load());
  4062. }
  4063. });
  4064. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4065. __setstate__(state) {
  4066. Object.assign(this, new pickle.Unpickler(state).load());
  4067. }
  4068. });
  4069. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4070. __setstate__(state) {
  4071. Object.assign(this, new pickle.Unpickler(state).load());
  4072. }
  4073. });
  4074. this.registerType('thinc.neural.mem.Memory', class {
  4075. });
  4076. this.registerType('thinc.neural.ops.NumpyOps', class {
  4077. });
  4078. this.registerType('__main__.BYOLState', class {
  4079. constructor(dict) {
  4080. Object.assign(this, dict);
  4081. }
  4082. });
  4083. const types = this.register('types');
  4084. this.registerType('types.GenericAlias', class {});
  4085. this.registerType('types.SimpleNamespace', class {});
  4086. this.registerFunction('types.resolve_bases', (bases) => {
  4087. return bases;
  4088. });
  4089. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4090. if (kwds) {
  4091. kwds = new builtins.dict(kwds);
  4092. } else {
  4093. kwds = new builtins.dict();
  4094. }
  4095. let meta = null;
  4096. if (kwds.__contains__('metaclass')) {
  4097. meta = kwds.pop('metaclass');
  4098. } else if (bases && bases.length > 0) {
  4099. meta = builtins.type(bases[0]);
  4100. } else {
  4101. meta = builtins.type;
  4102. }
  4103. if (meta instanceof builtins.type) {
  4104. meta = types._calculate_meta(meta, bases);
  4105. }
  4106. let ns = null;
  4107. if (builtins.hasattr(meta, '__prepare__')) {
  4108. // ns = meta.__prepare__(name, bases, **kwds)
  4109. } else {
  4110. ns = new builtins.dict();
  4111. }
  4112. return [meta, ns, kwds];
  4113. });
  4114. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4115. const winner = meta;
  4116. return winner;
  4117. });
  4118. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4119. const resolved_bases = types.resolve_bases(bases);
  4120. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4121. if (exec_body) {
  4122. exec_body(ns);
  4123. }
  4124. return new meta(name, resolved_bases, ns);
  4125. });
  4126. types.ObjectType = builtins.object;
  4127. types.ModuleType = builtins.module;
  4128. types.MethodType = builtins.method;
  4129. types.FunctionType = builtins.function;
  4130. types.TypeType = builtins.type;
  4131. types.CodeType = builtins.code;
  4132. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4133. this.registerType('xgboost.core.Booster', class {});
  4134. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4135. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4136. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4137. return execution.invoke('builtins.bytearray', [obj, encoding]);
  4138. });
  4139. this.registerType('builtins.bytearray', class extends Uint8Array {
  4140. constructor(source, encoding /*, errors */) {
  4141. source = builtins.bytes.__encode__(source, encoding);
  4142. super(Number.isInteger(source) ? source : source.length);
  4143. if (Array.isArray(source)) {
  4144. for (let i = 0; i < source.length; i++) {
  4145. this[i] = source;
  4146. }
  4147. } else if (source instanceof Uint8Array) {
  4148. this.set(source, 0);
  4149. } else if (typeof source === 'string') {
  4150. for (let i = 0; i < source.length; i++) {
  4151. this[i] = source.charCodeAt(i);
  4152. }
  4153. }
  4154. }
  4155. static __encode__(source, encoding) {
  4156. if (source === undefined) {
  4157. return 0;
  4158. }
  4159. if (Number.isInteger(source)) {
  4160. return source;
  4161. }
  4162. if (Array.isArray(source) || source instanceof Uint8Array) {
  4163. return source;
  4164. }
  4165. if (typeof source === 'string') {
  4166. switch (encoding) {
  4167. case 'latin1':
  4168. case 'latin-1':
  4169. return source;
  4170. case 'utf8':
  4171. case 'utf-8':
  4172. return new TextEncoder('utf-8').encode(source);
  4173. case undefined:
  4174. throw new python.Error('Unsupported string argument without an encoding.');
  4175. default:
  4176. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4177. }
  4178. }
  4179. throw new python.Error('Unsupported source.');
  4180. }
  4181. });
  4182. this.registerType('builtins.bytes', class extends Uint8Array {
  4183. constructor(source, encoding /*, errors */) {
  4184. source = builtins.bytes.__encode__(source, encoding);
  4185. super(Number.isInteger(source) ? source : source.length);
  4186. if (Array.isArray(source)) {
  4187. for (let i = 0; i < source.length; i++) {
  4188. this[i] = source;
  4189. }
  4190. } else if (source instanceof Uint8Array) {
  4191. this.set(source, 0);
  4192. } else if (typeof source === 'string') {
  4193. for (let i = 0; i < source.length; i++) {
  4194. this[i] = source.charCodeAt(i);
  4195. }
  4196. }
  4197. }
  4198. static __encode__(source, encoding) {
  4199. if (source === undefined) {
  4200. return 0;
  4201. }
  4202. if (Number.isInteger(source)) {
  4203. return source;
  4204. }
  4205. if (Array.isArray(source) || source instanceof Uint8Array) {
  4206. return source;
  4207. }
  4208. if (typeof source === 'string') {
  4209. switch (encoding) {
  4210. case 'latin1':
  4211. case 'latin-1':
  4212. return source;
  4213. case 'utf8':
  4214. case 'utf-8':
  4215. return new TextEncoder('utf-8').encode(source);
  4216. case undefined:
  4217. throw new python.Error('Unsupported string argument without an encoding.');
  4218. default:
  4219. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4220. }
  4221. }
  4222. throw new python.Error('Unsupported source.');
  4223. }
  4224. });
  4225. this.registerType('builtins.frozenset', class extends Set {
  4226. constructor(iterable) {
  4227. super();
  4228. if (iterable) {
  4229. for (const item of iterable) {
  4230. this.add(item);
  4231. }
  4232. }
  4233. }
  4234. });
  4235. this.registerFunction('builtins.exec');
  4236. this.registerFunction('builtins.issubclass', (obj, type) => {
  4237. const name = `${type.__module__}.${type.__name__}`;
  4238. if (obj.__module__ && obj.__name__) {
  4239. if (name === `${obj.__module__}.${obj.__name__}`) {
  4240. return true;
  4241. }
  4242. }
  4243. if (obj.__bases__) {
  4244. for (const base of obj.__bases__) {
  4245. if (builtins.issubclass(base, type)) {
  4246. return true;
  4247. }
  4248. }
  4249. }
  4250. return false;
  4251. });
  4252. this.registerFunction('builtins.isinstance', (obj, type) => {
  4253. return obj.__class__ ? builtins.issubclass(obj.__class__, type) : false;
  4254. });
  4255. this.registerFunction('builtins.hasattr', (obj, name) => {
  4256. if (obj instanceof Map && obj.__contains__) {
  4257. return obj.__contains__(name);
  4258. }
  4259. return Object.prototype.hasOwnProperty.call(obj, name);
  4260. });
  4261. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4262. if (obj && obj.__getattr__) {
  4263. return obj.__getattr__(name);
  4264. }
  4265. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4266. return obj[name];
  4267. }
  4268. return defaultValue;
  4269. });
  4270. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4271. obj[name] = value;
  4272. });
  4273. this.registerType('builtins.set', class extends Set {});
  4274. this.registerType('builtins.slice', class {
  4275. constructor(start, stop, step) {
  4276. this.start = start;
  4277. this.stop = stop;
  4278. this.step = step;
  4279. }
  4280. });
  4281. this.registerFunction('builtins.hash');
  4282. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4283. return name;
  4284. });
  4285. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4286. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4287. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4288. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4289. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4290. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4291. cell.cell_contents = value;
  4292. }
  4293. return cell;
  4294. });
  4295. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4296. // globals["__builtins__"] = __builtins__
  4297. return new types.FunctionType(code, globals, name, argdefs, closure);
  4298. });
  4299. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4300. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4301. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4302. if (class_tracker_id) {
  4303. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4304. }
  4305. return class_def;
  4306. });
  4307. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4308. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4309. const kwds = { 'metaclass': type_constructor };
  4310. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4311. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4312. });
  4313. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4314. return new builtins.cell();
  4315. });
  4316. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4317. [state] = state;
  4318. let registry = null;
  4319. for (const [attrname, attr] of state.items()) {
  4320. if (attrname === '_abc_impl') {
  4321. registry = attr;
  4322. } else {
  4323. builtins.setattr(obj, attrname, attr);
  4324. }
  4325. }
  4326. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4327. obj.__firstlineno__ = state.get('__firstlineno__');
  4328. }
  4329. if (registry) {
  4330. for (const subclass of registry) {
  4331. obj.register(subclass);
  4332. }
  4333. }
  4334. return obj;
  4335. });
  4336. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4337. const [, slotstate] = state;
  4338. [state] = state;
  4339. // obj.__dict__.update(state)
  4340. /* const obj_globals = */ slotstate.pop('__globals__');
  4341. const obj_closure = slotstate.pop('__closure__');
  4342. slotstate.pop('_cloudpickle_submodules');
  4343. if (obj.__globals__) {
  4344. // obj.__globals__.update(obj_globals);
  4345. // obj.__globals__.__builtins__ = __builtins__;
  4346. }
  4347. if (obj_closure) {
  4348. // let value = null;
  4349. for (let i = 0; i < obj_closure.length; i++) {
  4350. // const cell = obj_closure[i];
  4351. try {
  4352. // value = cell.cell_contents;
  4353. } catch {
  4354. // cell is empty
  4355. }
  4356. // obj.__closure__[i].cell_contents = value;
  4357. }
  4358. }
  4359. for (const [k, v] of slotstate.items()) {
  4360. builtins.setattr(obj, k, v);
  4361. }
  4362. });
  4363. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4364. execution.__import__(name);
  4365. return sys.modules.get(name);
  4366. });
  4367. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4368. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4369. const ray = this.register('ray');
  4370. this.register('ray.cloudpickle.cloudpickle');
  4371. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4372. this.registerType('collections.Counter', class {});
  4373. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4374. return {};
  4375. });
  4376. this.registerFunction('copy.deepcopy');
  4377. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4378. // copyreg._reconstructor in Python 3
  4379. if (base === '__builtin__.object' || base === builtins.object) {
  4380. return self.invoke(cls, []);
  4381. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4382. const obj = self.invoke(cls, []);
  4383. for (let i = 0; i < state.length; i++) {
  4384. obj[i] = state[i];
  4385. }
  4386. return obj;
  4387. }
  4388. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4389. });
  4390. this.registerFunction('copy.deepcopy', (/* x */) => {
  4391. throw new python.Error('Unsupported copy.deepcopy().');
  4392. });
  4393. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4394. const array = f(...args);
  4395. if (array.__setstate__) {
  4396. array.__setstate__(state);
  4397. }
  4398. if (npdict) {
  4399. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4400. }
  4401. return array;
  4402. });
  4403. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4404. return function() {
  4405. };
  4406. });
  4407. this.registerFunction('dill._dill._create_code', (args) => {
  4408. return self.invoke('types.CodeType', [args]);
  4409. });
  4410. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4411. return function() {
  4412. };
  4413. });
  4414. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4415. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4416. if (obj) {
  4417. return obj;
  4418. }
  4419. return undefined;
  4420. });
  4421. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4422. const [name, bases, dict] = args;
  4423. const type = class extends bases[0] {};
  4424. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4425. return self.registerType(identifier, Object.assign(type, dict));
  4426. });
  4427. this.registerFunction('dill._dill._eval_repr');
  4428. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4429. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4430. return self[name];
  4431. }
  4432. return undefined;
  4433. });
  4434. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4435. try {
  4436. if (import_name.startsWith('__runtime__.')) {
  4437. return execution.module(import_name);
  4438. } else if (import_name.indexOf('.') === -1) {
  4439. return execution.__import__(import_name);
  4440. }
  4441. return execution.resolve(import_name);
  4442. } catch (error) {
  4443. if (safe) {
  4444. return null;
  4445. }
  4446. throw error;
  4447. }
  4448. });
  4449. this.registerFunction('dill._dill._load_type', (name) => {
  4450. const _dill = self.register('dill._dill');
  4451. if (!_dill._reverse_typemap) {
  4452. _dill._reverse_typemap = new Map();
  4453. for (const name of ['__builtin__', 'types']) {
  4454. const module = self.register(name);
  4455. for (const [name, obj] of Object.entries(module)) {
  4456. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4457. _dill._reverse_typemap.set(name, obj);
  4458. }
  4459. }
  4460. }
  4461. _dill._reverse_typemap.set('PartialType', functools.partial);
  4462. _dill._reverse_typemap.set('CellType', builtins.cell);
  4463. }
  4464. if (!_dill._reverse_typemap.has(name)) {
  4465. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4466. }
  4467. return _dill._reverse_typemap.get(name);
  4468. });
  4469. this.registerFunction('dill._dill.loads');
  4470. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4471. const np_value = fun(...args);
  4472. np_value.__setstate__(arr_state);
  4473. const jnp_value = jax.device_put(np_value);
  4474. jnp_value.aval = jnp_value.aval.update(aval_state);
  4475. return jnp_value;
  4476. });
  4477. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4478. this.registerFunction('jax.device_put', (x) => {
  4479. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4480. return new jax.Array(aval, x.data);
  4481. });
  4482. this.registerType('jax._src.core.AbstractValue', class {});
  4483. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4484. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4485. constructor(shape, dtype, weak_type) {
  4486. super();
  4487. this.shape = shape;
  4488. this.dtype = dtype;
  4489. this.weak_type = weak_type || false;
  4490. }
  4491. update(dict) {
  4492. const shape = dict.get('shape') || this.shape;
  4493. const dtype = dict.get('dtype') || this.dtype;
  4494. const weak_type = dict.get('weak_type') || this.weak_type;
  4495. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4496. }
  4497. });
  4498. this.registerType('jax.Array', class {
  4499. constructor(aval, data) {
  4500. this.aval = aval;
  4501. this.data = data;
  4502. }
  4503. get dtype() {
  4504. return this.aval.dtype;
  4505. }
  4506. get shape() {
  4507. return this.aval.shape;
  4508. }
  4509. tobytes() {
  4510. return this.data;
  4511. }
  4512. });
  4513. jax.numpy.ndarray = jax.Array;
  4514. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4515. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4516. });
  4517. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4518. this.registerFunction('lasagne.nonlinearities.rectify');
  4519. this.registerFunction('lasagne.nonlinearities.softmax');
  4520. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4521. this.registerFunction('lasagne.updates.nesterov_momentum');
  4522. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4523. const BinaryReader = class {
  4524. constructor(buffer, ext_hook) {
  4525. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4526. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4527. this._buffer = buffer;
  4528. this._position = 0;
  4529. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4530. this._ext_hook = ext_hook;
  4531. }
  4532. value() {
  4533. const c = this._view.getUint8(this.skip(1));
  4534. if (c >= 0xe0) {
  4535. return c - 0x100;
  4536. }
  4537. if (c < 0xC0) {
  4538. if (c < 0x80) {
  4539. return c;
  4540. }
  4541. if (c < 0x90) {
  4542. return this.map(c - 0x80);
  4543. }
  4544. if (c < 0xa0) {
  4545. return this.array(c - 0x90);
  4546. }
  4547. return this.string(c - 0xa0);
  4548. }
  4549. switch (c) {
  4550. case 0xC0: return null;
  4551. case 0xC2: return false;
  4552. case 0xC3: return true;
  4553. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4554. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4555. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4556. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4557. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4558. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4559. case 0xCA: return this._view.getFloat32(this.skip(4));
  4560. case 0xCB: return this._view.getFloat64(this.skip(8));
  4561. case 0xCC: return this._view.getUint8(this.skip(1));
  4562. case 0xCD: return this._view.getUint16(this.skip(2));
  4563. case 0xCE: return this._view.getUint32(this.skip(4));
  4564. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4565. case 0xD0: return this._view.getInt8(this.skip(1));
  4566. case 0xD1: return this._view.getInt16(this.skip(2));
  4567. case 0xD2: return this._view.getInt32(this.skip(4));
  4568. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4569. case 0xD4: return this.extension(1);
  4570. case 0xD5: return this.extension(2);
  4571. case 0xD6: return this.extension(4);
  4572. case 0xD7: return this.extension(8);
  4573. case 0xD8: return this.extension(16);
  4574. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4575. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4576. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4577. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4578. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4579. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4580. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4581. default: throw new python.Error(`Invalid code '${c}'.`);
  4582. }
  4583. }
  4584. map(size) {
  4585. const map = {};
  4586. for (let i = 0; i < size; i++) {
  4587. const key = this.value();
  4588. const value = this.value();
  4589. map[key] = value;
  4590. }
  4591. return map;
  4592. }
  4593. array(size) {
  4594. const array = new Array(size);
  4595. for (let i = 0; i < size; i++) {
  4596. array[i] = this.value();
  4597. }
  4598. return array;
  4599. }
  4600. extension(size) {
  4601. const code = this._view.getUint8(this.skip(1));
  4602. const data = this.read(size);
  4603. return this._ext_hook(code, data);
  4604. }
  4605. skip(offset) {
  4606. const position = this._position;
  4607. this._position += offset;
  4608. if (this._position > this._buffer.length) {
  4609. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4610. }
  4611. return position;
  4612. }
  4613. read(size) {
  4614. const data = this._buffer.subarray(this._position, this._position + size);
  4615. this._position += size;
  4616. return data;
  4617. }
  4618. string(size) {
  4619. const buffer = this.read(size);
  4620. this._decoder = this._decoder || new TextDecoder('utf8');
  4621. return this._decoder.decode(buffer);
  4622. }
  4623. };
  4624. return new BinaryReader(packed, ext_hook).value();
  4625. });
  4626. this.registerFunction('nolearn.lasagne.base.objective');
  4627. this.registerFunction('numpy.core._DType_reconstruct');
  4628. this.registerFunction('numpy.core._ufunc_reconstruct');
  4629. this.registerFunction('numpy.core.numeric._frombuffer', (/* buf, dtype, shape, order */) => {
  4630. return {};
  4631. });
  4632. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4633. return numpy.ndarray.__new__(subtype, shape, dtype);
  4634. });
  4635. this.registerFunction('numpy._core.numeric._frombuffer');
  4636. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4637. return new numpy.dtypes.StringDType();
  4638. });
  4639. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4640. let data = rawData;
  4641. if (typeof rawData === 'string' || rawData instanceof String) {
  4642. data = new Uint8Array(rawData.length);
  4643. for (let i = 0; i < rawData.length; i++) {
  4644. data[i] = rawData.charCodeAt(i);
  4645. }
  4646. }
  4647. switch (dtype.kind) {
  4648. case 'b': {
  4649. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4650. switch (dtype.itemsize) {
  4651. case 1: return view.getInt8(0) ? true : false;
  4652. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  4653. }
  4654. }
  4655. case 'f': {
  4656. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4657. switch (dtype.itemsize) {
  4658. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  4659. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  4660. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  4661. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  4662. }
  4663. }
  4664. case 'i': {
  4665. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4666. switch (dtype.itemsize) {
  4667. case 1: return view.getInt8(0);
  4668. case 2: return view.getInt16(0, dtype.byteorder === '<');
  4669. case 4: return view.getInt32(0, dtype.byteorder === '<');
  4670. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  4671. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  4672. }
  4673. }
  4674. case 'u': {
  4675. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4676. switch (dtype.itemsize) {
  4677. case 1: return view.getUint8(0);
  4678. case 2: return view.getUint16(0, dtype.byteorder === '<');
  4679. case 4: return view.getUint32(0, dtype.byteorder === '<');
  4680. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  4681. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  4682. }
  4683. }
  4684. case 'U': {
  4685. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4686. const list = [];
  4687. for (let i = 0; i < dtype.itemsize; i += 4) {
  4688. list.push(String.fromCodePoint(view.getUint32(i, true)));
  4689. }
  4690. return list.join('');
  4691. }
  4692. default: {
  4693. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  4694. }
  4695. }
  4696. });
  4697. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  4698. this.registerFunction('numpy.core._multiarray_umath.fmin');
  4699. this.registerFunction('numpy.core._multiarray_umath.fmax');
  4700. this.registerFunction('numpy.core._multiarray_umath.greater');
  4701. this.registerFunction('numpy.core._multiarray_umath.less');
  4702. this.registerFunction('numpy.core._multiarray_umath.log');
  4703. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  4704. let data = rawData;
  4705. if (typeof rawData === 'string') {
  4706. data = new Uint8Array(rawData.length);
  4707. for (let i = 0; i < rawData.length; i++) {
  4708. data[i] = rawData.charCodeAt(i);
  4709. }
  4710. }
  4711. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4712. switch (dtype.__name__) {
  4713. case 'uint8':
  4714. return dataView.getUint8(0);
  4715. case 'float32':
  4716. return dataView.getFloat32(0, true);
  4717. case 'float64':
  4718. return dataView.getFloat64(0, true);
  4719. case 'int8':
  4720. return dataView.getInt8(0, true);
  4721. case 'int16':
  4722. return dataView.getInt16(0, true);
  4723. case 'int32':
  4724. return dataView.getInt32(0, true);
  4725. case 'int64':
  4726. return dataView.getBigInt64(0, true);
  4727. default:
  4728. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  4729. }
  4730. });
  4731. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  4732. this.register('numpy._core.multiarray', numpy.core.multiarray);
  4733. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  4734. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  4735. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  4736. this.registerFunction('numpy.load', (file) => {
  4737. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  4738. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  4739. if (!file.read(6).every((v, i) => v === signature[i])) {
  4740. throw new python.Error('Invalid signature.');
  4741. }
  4742. const version = file.read(2);
  4743. const [major, minor] = version;
  4744. if (major > 3) {
  4745. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  4746. }
  4747. const buffer = new Uint8Array([0, 0, 0, 0]);
  4748. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  4749. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  4750. let header = file.read(header_length);
  4751. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  4752. header = decoder.decode(header);
  4753. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',']').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  4754. if (!header.descr || header.descr.length < 2) {
  4755. throw new python.Error("Missing property 'descr'.");
  4756. }
  4757. if (!header.shape) {
  4758. throw new python.Error("Missing property 'shape'.");
  4759. }
  4760. const shape = header.shape;
  4761. const dtype = self.invoke('numpy.dtype', [header.descr.substring(1)]);
  4762. dtype.byteorder = header.descr.substring(0, 1);
  4763. let data = null;
  4764. switch (dtype.byteorder) {
  4765. case '|': {
  4766. data = file.read();
  4767. if (dtype.kind === 'O') {
  4768. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  4769. return unpickler.load();
  4770. }
  4771. break;
  4772. }
  4773. case '>':
  4774. case '<': {
  4775. if (header.descr.length !== 3 && header.descr[1] !== 'U' && header.descr.substring(1) !== 'c16') {
  4776. throw new python.Error(`Unsupported data type '${header.descr}'.`);
  4777. }
  4778. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  4779. data = file.read(dtype.itemsize * count);
  4780. break;
  4781. }
  4782. default: {
  4783. throw new python.Error(`Unsupported data type '${header.descr}'.`);
  4784. }
  4785. }
  4786. if (header.fortran_order) {
  4787. data = null;
  4788. }
  4789. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  4790. });
  4791. this.registerFunction('numpy.save', (file, arr) => {
  4792. const descr = arr.dtype.str;
  4793. if (descr[0] !== '<' && descr[0] !== '>') {
  4794. throw new python.Error(`Unsupported byte order '${descr}'.`);
  4795. }
  4796. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  4797. throw new python.Error(`Unsupported data type '${descr}'.`);
  4798. }
  4799. let shape = '';
  4800. switch (arr.shape.length) {
  4801. case 0: shape = '()'; break;
  4802. case 1: shape = `(${arr.shape[0]},)`; break;
  4803. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  4804. }
  4805. const properties = [
  4806. `'descr': '${descr}'`,
  4807. "'fortran_order': False",
  4808. `'shape': ${shape}`
  4809. ];
  4810. let header = `{ ${properties.join(', ')} }`;
  4811. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  4812. const encoder = new TextEncoder('ascii');
  4813. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  4814. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  4815. file.write(encoder.encode(header));
  4816. file.write(arr.tobytes());
  4817. });
  4818. this.registerFunction('numpy.amin');
  4819. this.registerFunction('numpy.amax');
  4820. this.registerFunction('numpy.std');
  4821. this.registerFunction('numpy.asarray', (a, dtype) => {
  4822. const encode = (context, data, dim) => {
  4823. const size = context.shape[dim];
  4824. const littleendian = context.littleendian;
  4825. if (dim === context.shape.length - 1) {
  4826. for (let i = 0; i < size; i++) {
  4827. switch (context.dtype) {
  4828. case 'f2':
  4829. context.view.setFloat16(context.position, data[i], littleendian);
  4830. break;
  4831. case 'f4':
  4832. context.view.setFloat32(context.position, data[i], littleendian);
  4833. break;
  4834. case 'f8':
  4835. context.view.setFloat64(context.position, data[i], littleendian);
  4836. break;
  4837. case 'i1':
  4838. context.view.setInt8(context.position, data[i], littleendian);
  4839. break;
  4840. case 'i2':
  4841. context.view.setInt16(context.position, data[i], littleendian);
  4842. break;
  4843. case 'i4':
  4844. context.view.setInt32(context.position, data[i], littleendian);
  4845. break;
  4846. case 'i8':
  4847. context.view.setBigInt64(context.position, data[i], littleendian);
  4848. break;
  4849. case 'u1':
  4850. context.view.setUint8(context.position, data[i], littleendian);
  4851. break;
  4852. case 'u2':
  4853. context.view.setUint16(context.position, data[i], littleendian);
  4854. break;
  4855. case 'u4':
  4856. context.view.setUint32(context.position, data[i], littleendian);
  4857. break;
  4858. case 'u8':
  4859. context.view.setBigUint64(context.position, data[i], littleendian);
  4860. break;
  4861. case 'c8':
  4862. context.view.setComplex64(context.position, data[i], littleendian);
  4863. break;
  4864. case 'c16':
  4865. context.view.setComplex128(context.position, data[i], littleendian);
  4866. break;
  4867. case 'b1':
  4868. context.view.setInt8(context.position, data[i] ? 1 : 0);
  4869. break;
  4870. default:
  4871. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  4872. }
  4873. context.position += context.itemsize;
  4874. }
  4875. } else {
  4876. for (let j = 0; j < size; j++) {
  4877. encode(context, data[j], dim + 1);
  4878. }
  4879. }
  4880. };
  4881. const array_size = (value) => {
  4882. if (value.every((item) => Array.isArray(item))) {
  4883. const dims = value.map((item) => array_size(item));
  4884. const [dim] = dims;
  4885. for (let i = 1; i < dims.length; i++) {
  4886. if (dim.length === dims[i].length) {
  4887. if (!dims[i].every((value, i) => value === dim[i])) {
  4888. throw new python.Error('Invalid array shape.');
  4889. }
  4890. }
  4891. }
  4892. return [value.length].concat(dim);
  4893. }
  4894. return [value.length];
  4895. };
  4896. const shape = Array.isArray(a) ? array_size(a) : [];
  4897. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  4898. const context = {
  4899. position: 0,
  4900. itemsize: dtype.itemsize,
  4901. dtype: dtype.str.substring(1),
  4902. littleendian: dtype.str[0],
  4903. shape,
  4904. data: new Uint8Array(size)
  4905. };
  4906. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  4907. encode(context, a, 0);
  4908. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  4909. });
  4910. this.registerFunction('numpy.max');
  4911. this.registerFunction('numpy.mean');
  4912. this.registerFunction('numpy.min');
  4913. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  4914. const data = self.invoke(baseclass, [baseshape, basetype]);
  4915. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  4916. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  4917. return self.invoke(subtype, [data, mask, basetype]);
  4918. });
  4919. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  4920. return {};
  4921. });
  4922. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  4923. return {};
  4924. });
  4925. this.registerType('numpy.random.bit_generator.BitGenerator', class {});
  4926. this.registerType('numpy.random.bit_generator.SeedSequence', class {});
  4927. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence');
  4928. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  4929. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  4930. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  4931. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  4932. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  4933. numpy.random._pickle.BitGenerators = {
  4934. 'MT19937': numpy.random._mt19937.MT19937,
  4935. 'PCG64': numpy.random._pcg64.PCG64,
  4936. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  4937. 'Philox': numpy.random._philox.Philox,
  4938. 'SFC64': numpy.random._sfc64.SFC64,
  4939. };
  4940. this.registerType('numpy.random._generator.Generator', class {
  4941. constructor(bit_generator) {
  4942. this.bit_generator = bit_generator;
  4943. }
  4944. });
  4945. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator_name) => {
  4946. bit_generator_name = bit_generator_name || 'MT19937';
  4947. const bit_generator = numpy.random._pickle.BitGenerators[bit_generator_name];
  4948. if (bit_generator) {
  4949. return new bit_generator();
  4950. }
  4951. throw new python.Error(`Unknown bit generator '${bit_generator_name}'.`);
  4952. });
  4953. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  4954. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  4955. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  4956. });
  4957. this.registerFunction('numpy.reshape');
  4958. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  4959. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  4960. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  4961. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  4962. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  4963. this.registerFunction('sklearn.metrics._classification.f1_score');
  4964. this.registerFunction('sklearn.metrics._classification.log_loss');
  4965. this.registerFunction('sklearn.metrics._classification.precision_score');
  4966. this.registerFunction('sklearn.metrics._classification.recall_score');
  4967. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  4968. return obj.__new__(obj);
  4969. });
  4970. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  4971. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  4972. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  4973. this.registerFunction('sklearn.metrics._regression.r2_score');
  4974. sklearn.metrics.regression = sklearn.metrics._regression;
  4975. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  4976. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  4977. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  4978. this.registerFunction('re._compile', (pattern, flags) => {
  4979. return self.invoke('re.Pattern', [pattern, flags]);
  4980. });
  4981. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  4982. return function() {
  4983. return self.invoke(`types.${args[0]}`, args);
  4984. };
  4985. });
  4986. this.registerFunction('theano.scalar.basic.same_out');
  4987. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  4988. this.registerFunction('theano.scalar.basic.upcast_out');
  4989. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  4990. this.registerFunction('theano.tensor.nnet.conv2d');
  4991. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  4992. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  4993. this.registerType('torch.nn.modules.module.Module', class {
  4994. constructor() {
  4995. this._modules = execution.invoke('collections.OrderedDict', []);
  4996. this._parameters = execution.invoke('collections.OrderedDict', []);
  4997. this._buffers = execution.invoke('collections.OrderedDict', []);
  4998. }
  4999. __setattr__(name, value) {
  5000. if (value instanceof torch.nn.modules.module.Module) {
  5001. this._modules.set(name, value);
  5002. } else {
  5003. this[name] = value;
  5004. }
  5005. }
  5006. __getattr__(name) {
  5007. if (this._modules.has(name)) {
  5008. return this._modules.get(name);
  5009. }
  5010. return this[name];
  5011. }
  5012. __delattr__(name) {
  5013. if (this._modules.has(name)) {
  5014. this._modules.delete(name);
  5015. }
  5016. }
  5017. children() {
  5018. return this._modules.values();
  5019. }
  5020. named_modules(memo, prefix, remove_duplicate) {
  5021. memo = memo || new Set();
  5022. prefix = prefix || '';
  5023. const modules = new builtins.dict();
  5024. if (!memo.has(this)) {
  5025. if (remove_duplicate) {
  5026. memo.add(this);
  5027. }
  5028. modules.set(prefix, this);
  5029. for (const [name, module] of this._modules.items()) {
  5030. if (module) {
  5031. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5032. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5033. modules.set(k, v);
  5034. }
  5035. }
  5036. }
  5037. }
  5038. return modules;
  5039. }
  5040. named_children() {
  5041. return this._modules;
  5042. }
  5043. parameters() {
  5044. return this._parameters.values();
  5045. }
  5046. named_parameters(recurse) {
  5047. if (recurse) {
  5048. throw new python.Error('Named parameters with recurse not implemented.');
  5049. }
  5050. return this._parameters;
  5051. }
  5052. buffers() {
  5053. return this._buffers.values();
  5054. }
  5055. named_buffers(recurse) {
  5056. if (recurse) {
  5057. throw new python.Error('Named parameters with recurse not implemented.');
  5058. }
  5059. return this._buffers;
  5060. }
  5061. _get_name() {
  5062. return this.__class__.__name__;
  5063. }
  5064. });
  5065. torch.nn.Module = torch.nn.modules.module.Module;
  5066. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5067. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5068. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5069. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5070. this.registerType('torch._C.OperatorRegistry', class {
  5071. constructor() {
  5072. this.to_register = [];
  5073. this.operators = new Map();
  5074. }
  5075. registerPendingOperators() {
  5076. for (const op of this.to_register) {
  5077. const sym = op.schema().name;
  5078. if (!this.operators.has(sym)) {
  5079. this.operators.set(sym, []);
  5080. }
  5081. this.operators.get(sym).push(op);
  5082. }
  5083. this.to_register = [];
  5084. }
  5085. registerOperator(op) {
  5086. this.to_register.push(op);
  5087. }
  5088. getOperators(name) {
  5089. this.registerPendingOperators();
  5090. if (this.operators.has(name)) {
  5091. return this.operators.get(name);
  5092. }
  5093. return [];
  5094. }
  5095. });
  5096. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  5097. return torch._C.getRegistry().getOperators(name);
  5098. });
  5099. this.registerType('torch._C.Operator', class {
  5100. constructor(schema) {
  5101. this._schema = schema;
  5102. }
  5103. schema() {
  5104. return this._schema;
  5105. }
  5106. getOperation(/* node */) {
  5107. return null;
  5108. }
  5109. aliasAnalysisKind() {
  5110. const schemaRef = this.schema();
  5111. const alias_analysis = schemaRef.aliasAnalysis();
  5112. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  5113. return alias_analysis;
  5114. }
  5115. });
  5116. this.registerFunction('torch._C.getRegistry', () => {
  5117. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  5118. return torch._C.r;
  5119. });
  5120. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  5121. const operations = torch._C.getAllOperatorsFor(op_name);
  5122. for (const op of operations) {
  5123. if (op.schema().overload_name === overload_name) {
  5124. return op.schema();
  5125. }
  5126. }
  5127. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  5128. });
  5129. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  5130. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  5131. });
  5132. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  5133. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  5134. if (sortedOps.length === 0) {
  5135. return [null, null];
  5136. }
  5137. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  5138. return [{}, overload_names];
  5139. });
  5140. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  5141. const operations = torch._C.getAllOperatorsFor(op_name);
  5142. for (const op of operations) {
  5143. if (op.schema().overload_name === overload_name) {
  5144. return [{}, {}, null];
  5145. }
  5146. }
  5147. return null;
  5148. });
  5149. this.registerType('torch._C.MatchedSchema', class {
  5150. constructor(inputs, return_types, return_field_names, schema_name) {
  5151. this.inputs = inputs;
  5152. this.return_types = return_types;
  5153. this.register_field_names = return_field_names;
  5154. this.schema_name = schema_name;
  5155. }
  5156. });
  5157. this.registerType('torch._C.Self', class {
  5158. });
  5159. this.registerFunction('torch._C.toValues', (g, nvs) => {
  5160. return nvs.map((v) => v.value(g));
  5161. });
  5162. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  5163. constructor(classType) {
  5164. super();
  5165. this._classType = classType;
  5166. }
  5167. makeSugared(v) {
  5168. v.setType(this._classType);
  5169. return new torch._C.SimpleValue(v);
  5170. }
  5171. getClassType() {
  5172. return this._classType;
  5173. }
  5174. });
  5175. this.registerType('torch._C.Function', class {
  5176. isGraphFunction() {
  5177. return false;
  5178. }
  5179. name() {
  5180. return this.qualname().name();
  5181. }
  5182. });
  5183. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  5184. constructor(qualname, schema) {
  5185. super();
  5186. this._name = qualname;
  5187. this._schema = schema;
  5188. }
  5189. qualname() {
  5190. return this._name;
  5191. }
  5192. getSchema() {
  5193. return this._schema;
  5194. }
  5195. ensure_defined() {
  5196. }
  5197. });
  5198. this.registerType('torch._C.DeadCodeEliminator', class {
  5199. constructor(graph, sideEffectPolicy) {
  5200. this._graph = graph;
  5201. this._sideEffectPolicy = sideEffectPolicy;
  5202. this._useAliasDb = true;
  5203. this._aliasDb = null;
  5204. this._memo = new Map();
  5205. this._marked = new Set();
  5206. this._liveValues = new Set();
  5207. this._deleteCallback = () => {};
  5208. }
  5209. run(block, recurse) {
  5210. this.eliminateDeadForkInputs(block, recurse);
  5211. this.mark(block.return_node());
  5212. this.mark(block);
  5213. this._deleteCallback(this._liveValues);
  5214. this.sweep(block, recurse);
  5215. }
  5216. setDeleteCallback(deleteCallback) {
  5217. this._deleteCallback = deleteCallback;
  5218. }
  5219. eliminateDeadForkInputs(block, recurse) {
  5220. for (const node of block.nodes()) {
  5221. if (recurse) {
  5222. for (const sb of node.blocks()) {
  5223. this.eliminateDeadForkInputs(sb, recurse);
  5224. }
  5225. }
  5226. if (node.kind() !== 'prim::fork') {
  5227. continue;
  5228. }
  5229. const g = node.g("Subgraph");
  5230. for (let i = 0; i < g.inputs().length; i++) {
  5231. if (!g.inputs()[i].hasUses()) {
  5232. g.eraseInput(i);
  5233. node.removeInput(i);
  5234. }
  5235. }
  5236. }
  5237. }
  5238. markReturnNode(node) {
  5239. if (this._marked.has(node)) {
  5240. return false;
  5241. }
  5242. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  5243. const outerNode = node.owningBlock().owningNode();
  5244. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  5245. return this.mark(node);
  5246. }
  5247. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  5248. const loop = new torch._C.LoopView(outerNode);
  5249. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  5250. if (outerNode.kind() === 'onnx::Loop') {
  5251. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  5252. continue;
  5253. }
  5254. const innerInput = loop.bodyCarriedInputs()[i];
  5255. const innerOutput = loop.bodyCarriedOutputs()[i];
  5256. const outerOutput = loop.carriedOutputs()[i];
  5257. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  5258. this._liveValues.add(innerOutput);
  5259. }
  5260. }
  5261. this._liveValues.add(loop.nextCond());
  5262. } else {
  5263. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  5264. for (let i = 0; i < outerNode.outputs().length; i++) {
  5265. const innerOutput = node.inputs()[i];
  5266. const outerOutput = outerNode.outputs()[i];
  5267. if (!this._liveValues.has(outerOutput)) {
  5268. this._liveValues.add(innerOutput);
  5269. }
  5270. }
  5271. }
  5272. this._marked.add(node);
  5273. return true;
  5274. }
  5275. markLoop(node) {
  5276. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  5277. let marked = false;
  5278. let anyMarked = false;
  5279. do {
  5280. marked = this.mark(node.blocks()[0]);
  5281. anyMarked = anyMarked || marked;
  5282. } while (marked);
  5283. return anyMarked;
  5284. }
  5285. mark(...args) {
  5286. if (args.length === 1 && args[0] instanceof torch.Block) {
  5287. const [block] = args;
  5288. let anyMarked = false;
  5289. for (const node of block.nodes()) {
  5290. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  5291. const marked = this.mark(node);
  5292. anyMarked = anyMarked || marked;
  5293. }
  5294. }
  5295. const marked = this.markReturnNode(block.return_node());
  5296. anyMarked = anyMarked || marked;
  5297. for (const node of block.nodes()) {
  5298. if (node.kind() === 'prim::Loop') {
  5299. const marked = this.markLoop(node);
  5300. anyMarked = anyMarked || marked;
  5301. } else {
  5302. for (const subBlock of node.blocks()) {
  5303. const marked = this.mark(subBlock);
  5304. anyMarked = anyMarked || marked;
  5305. }
  5306. }
  5307. const marked = this.markIfLive(node);
  5308. anyMarked = anyMarked || marked;
  5309. }
  5310. return anyMarked;
  5311. }
  5312. if (args.length === 1 && args[0] instanceof torch.Node) {
  5313. const [node] = args;
  5314. if (this._marked.has(node)) {
  5315. return false;
  5316. }
  5317. this._marked.add(node);
  5318. let curNode = node;
  5319. while (curNode && curNode.owningBlock()) {
  5320. this.mark(curNode);
  5321. curNode = curNode.owningBlock().owningNode();
  5322. }
  5323. for (const input of node.inputs()) {
  5324. if (!this._liveValues.has(input)) {
  5325. this._liveValues.add(input);
  5326. }
  5327. }
  5328. return true;
  5329. }
  5330. throw new python.Error('Not implemented.');
  5331. }
  5332. markIfLive(node) {
  5333. for (const output of node.outputs()) {
  5334. if (this._liveValues.has(output)) {
  5335. return this.mark(node);
  5336. }
  5337. }
  5338. if (this._useAliasDb) {
  5339. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  5340. return this.mark(node);
  5341. }
  5342. }
  5343. return false;
  5344. }
  5345. sweep(block, recurse) {
  5346. const nodes = Array.from(block.nodes()).reverse();
  5347. for (const node of nodes) {
  5348. this.removeDeadBlockOutputs(node);
  5349. this.removeDeadLoopOutputs(node);
  5350. if (recurse) {
  5351. for (const block of node.blocks()) {
  5352. this.sweep(block, true);
  5353. }
  5354. }
  5355. if (!this._marked.has(node) && !node.hasUses()) {
  5356. node.destroy();
  5357. }
  5358. }
  5359. }
  5360. hasUntrackedMutation(node) {
  5361. if (!this._useAliasDb) {
  5362. if (node.kind() === 'prim::SetAttr') {
  5363. return true;
  5364. }
  5365. const schema = node.maybeSchema();
  5366. return schema && schema.is_mutable();
  5367. }
  5368. return this.getOrCreateAliasDb().writesToWildcard(node);
  5369. }
  5370. hasSideEffects(node) {
  5371. const it = this._memo.get(node);
  5372. if (it) {
  5373. return it;
  5374. }
  5375. const has_side_effects = node.hasSideEffects() ||
  5376. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  5377. this.hasUntrackedMutation(node);
  5378. this._memo.set(node, has_side_effects);
  5379. return has_side_effects;
  5380. }
  5381. removeDeadBlockOutputs(node) {
  5382. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  5383. return;
  5384. }
  5385. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  5386. const i = i_1 - 1;
  5387. if (!node.outputs()[i].hasUses()) {
  5388. node.eraseOutput(i);
  5389. for (const b of node.blocks()) {
  5390. b.eraseOutput(i);
  5391. }
  5392. }
  5393. }
  5394. }
  5395. removeDeadLoopOutputs() {
  5396. }
  5397. getOrCreateAliasDb() {
  5398. if (!this._aliasDb) {
  5399. this._aliasDb = new torch._C.AliasDb(this._graph);
  5400. }
  5401. return this._aliasDb;
  5402. }
  5403. });
  5404. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  5405. if (args.length === 1 && args[0] instanceof torch.Graph) {
  5406. const [graph] = args;
  5407. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  5408. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  5409. worker.run(graph.block(), /*recurse=*/true);
  5410. } else {
  5411. throw new python.Error('Not implemented.');
  5412. }
  5413. });
  5414. this.registerFunction('torch._C.removeTupleNodes', () => {
  5415. });
  5416. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  5417. if (args.length === 1 && args[0] instanceof torch.Graph) {
  5418. const [graph] = args;
  5419. torch._C.LowerSimpleTuples(graph.block());
  5420. torch._C.EliminateDeadCode(graph);
  5421. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  5422. const [block] = args;
  5423. for (const n of block.nodes()) {
  5424. torch._C.removeTupleNodes(n, false);
  5425. for (const b of n.blocks()) {
  5426. torch._C.LowerSimpleTuples(b);
  5427. }
  5428. }
  5429. } else {
  5430. throw new python.Error('Not implemented.');
  5431. }
  5432. });
  5433. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  5434. torch._C.AT_ASSERT(lhs !== null);
  5435. torch._C.AT_ASSERT(rhs !== null);
  5436. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  5437. return false;
  5438. }
  5439. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  5440. return true;
  5441. }
  5442. const lnames = lhs.attributeNames();
  5443. const rnames = rhs.attributeNames();
  5444. lnames.sort();
  5445. rnames.sort();
  5446. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  5447. return false;
  5448. }
  5449. for (const name of lnames) {
  5450. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  5451. return false;
  5452. }
  5453. const kind = lhs.kindOf(name);
  5454. switch (kind) {
  5455. case 'i':
  5456. case 'f':
  5457. case 's':
  5458. case 't': {
  5459. if (lhs[kind](name) !== rhs[kind](name)) {
  5460. return false;
  5461. }
  5462. break;
  5463. }
  5464. case 'ival': {
  5465. if (lhs[kind](name) !== rhs[kind](name)) {
  5466. return false;
  5467. }
  5468. break;
  5469. }
  5470. default: {
  5471. throw new python.Error('Not implemented.');
  5472. }
  5473. }
  5474. }
  5475. return true;
  5476. });
  5477. this.registerFunction('torch._C.get_hash', (...args) => {
  5478. let hash = 0;
  5479. for (const value of args) {
  5480. if (typeof value === 'number') {
  5481. hash += (value | 0);
  5482. } else if (typeof value === 'string') {
  5483. hash += (value.length | 0);
  5484. } else if (Array.isArray(value)) {
  5485. for (const item of value) {
  5486. hash += torch._C.get_hash(item);
  5487. }
  5488. }
  5489. }
  5490. return hash;
  5491. });
  5492. this.registerFunction('torch._C.HashNode', (k) => {
  5493. torch._C.AT_ASSERT(k !== null);
  5494. let constant_hash = 0;
  5495. if (k.kind() === 'prim::Constant') {
  5496. const type = k.output().type();
  5497. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  5498. constant_hash = k.i('value');
  5499. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  5500. constant_hash = k.f('value');
  5501. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  5502. constant_hash = k.c('value');
  5503. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  5504. constant_hash = k.i('value');
  5505. }
  5506. }
  5507. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  5508. });
  5509. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  5510. if (lhs === null && rhs === null) {
  5511. return true;
  5512. }
  5513. if (lhs === null || rhs === null) {
  5514. return false;
  5515. }
  5516. if (lhs.kind() !== rhs.kind()) {
  5517. return false;
  5518. }
  5519. const lhs_outputs = lhs.outputs();
  5520. const rhs_outputs = rhs.outputs();
  5521. if (lhs_outputs.length !== rhs_outputs.length) {
  5522. return false;
  5523. }
  5524. for (let i = 0; i < lhs_outputs.length; i++) {
  5525. const lt = lhs_outputs[i].type();
  5526. const rt = rhs_outputs[i].type();
  5527. if (!lt.equals(rt)) {
  5528. return false;
  5529. }
  5530. }
  5531. const lhs_inputs = lhs.inputs();
  5532. const rhs_inputs = rhs.inputs();
  5533. if (lhs_inputs.length !== rhs_inputs.length) {
  5534. return false;
  5535. }
  5536. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  5537. return false;
  5538. }
  5539. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  5540. return false;
  5541. }
  5542. if (lhs.blocks().length !== rhs.blocks().length) {
  5543. return false;
  5544. }
  5545. for (let i = 0; i < lhs.blocks().length; i++) {
  5546. if (lhs.blocks()[i] !== rhs.blocks()[i]) {
  5547. return false;
  5548. }
  5549. }
  5550. return true;
  5551. });
  5552. this.registerType('torch._C.NodeSet', class {
  5553. constructor() {
  5554. this._nodes = new Map();
  5555. }
  5556. insert(n) {
  5557. const key = torch._C.HashNode(n);
  5558. if (this._nodes.has(key)) {
  5559. this._nodes.get(key).push(n);
  5560. } else {
  5561. this._nodes.set(key, [n]);
  5562. }
  5563. }
  5564. get(n) {
  5565. const key = torch._C.HashNode(n);
  5566. if (this._nodes.has(key)) {
  5567. const nodes = this._nodes.get(key);
  5568. for (const node of nodes) {
  5569. if (torch._C.EqualNode(node, n)) {
  5570. return node;
  5571. }
  5572. }
  5573. }
  5574. return null;
  5575. }
  5576. has(n) {
  5577. return this.get(n) !== null;
  5578. }
  5579. });
  5580. this.registerFunction('torch._C.isinstance', (stack, types) => {
  5581. const ty = torch._C.pop(stack).type();
  5582. for (const candidate of types) {
  5583. if (ty.isSubtypeOf(candidate)) {
  5584. torch._C.push(stack, true);
  5585. return;
  5586. }
  5587. }
  5588. torch._C.push(stack, false);
  5589. });
  5590. this.registerType('torch._C.Tuple', class {
  5591. constructor(elements) {
  5592. this._elements = elements;
  5593. }
  5594. static create(elements) {
  5595. return new torch._C.Tuple(elements);
  5596. }
  5597. elements() {
  5598. return this._elements;
  5599. }
  5600. });
  5601. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  5602. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  5603. switch (num_inputs) {
  5604. case 0: {
  5605. stack.push(new torch._C.IValue(torch._C.Tuple.create([])));
  5606. break;
  5607. }
  5608. case 1: {
  5609. const tuple = torch._C.Tuple.create([stack.pop()]);
  5610. stack.push(new torch._C.IValue(tuple));
  5611. break;
  5612. }
  5613. case 2: {
  5614. const tuple = torch._C.Tuple.create([stack[stack.length - 2], stack[stack.length - 1]]);
  5615. stack.pop();
  5616. stack.pop();
  5617. stack.push(new torch._C.IValue(tuple));
  5618. break;
  5619. }
  5620. case 3: {
  5621. throw new python.Error('Not implemented.');
  5622. /* auto tuple = c10::ivalue::Tuple::create(
  5623. std::move(stack[stack.size() - 3]),
  5624. std::move(stack[stack.size() - 2]),
  5625. std::move(stack[stack.size() - 1]));
  5626. stack.pop_back();
  5627. stack.pop_back();
  5628. stack.back() = std::move(tuple);
  5629. break; */
  5630. }
  5631. default: {
  5632. throw new python.Error('Not implemented.');
  5633. /* std::vector<IValue> elems{
  5634. std::make_move_iterator(stack.end() - num_inputs),
  5635. std::make_move_iterator(stack.end())};
  5636. drop(stack, num_inputs - 1);
  5637. stack.back() = c10::ivalue::Tuple::create(std::move(elems));
  5638. break; */
  5639. }
  5640. }
  5641. });
  5642. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  5643. let stack = [];
  5644. for (const input of n.inputs()) {
  5645. const ival = torch._C.toIValue(input);
  5646. if (ival) {
  5647. stack.push(ival);
  5648. } else {
  5649. return null;
  5650. }
  5651. }
  5652. switch (n.kind()) {
  5653. case 'prim::ListUnpack': {
  5654. if (stack.back().toList().size() !== n.outputs().size()) {
  5655. return null;
  5656. }
  5657. torch._C.listUnpack(stack, n.outputs().length);
  5658. break;
  5659. }
  5660. case 'prim::TupleConstruct': {
  5661. const tt = n.output().type().expect(torch.TupleType);
  5662. if (tt.name()) {
  5663. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  5664. } else {
  5665. torch._C.tupleConstruct(stack, n.inputs().length);
  5666. }
  5667. break;
  5668. }
  5669. case 'prim::ListConstruct': {
  5670. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  5671. break;
  5672. }
  5673. case 'prim::DictConstruct': {
  5674. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  5675. break;
  5676. }
  5677. case 'prim::CreateObject': {
  5678. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  5679. break;
  5680. }
  5681. case 'prim::GetAttr': {
  5682. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  5683. torch._C.push(stack, attr);
  5684. break;
  5685. }
  5686. case 'prim::isinstance': {
  5687. torch._C.isinstance(stack, n.tys('types'));
  5688. break;
  5689. }
  5690. default: {
  5691. const maybe_schema = n.maybeSchema();
  5692. if (maybe_schema && maybe_schema.is_vararg) {
  5693. return null;
  5694. }
  5695. // try
  5696. // {
  5697. // const op = n.getOperation();
  5698. // op(stack);
  5699. const [module, name] = n.kind().split('::');
  5700. const obj = torch.ops[module];
  5701. if (!obj) {
  5702. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  5703. }
  5704. const fn = torch.ops[module][name];
  5705. if (!fn) {
  5706. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  5707. }
  5708. const args = stack.map((v) => v.value);
  5709. const result = fn(...args);
  5710. stack = result === undefined ? [] : [new torch._C.IValue(result)];
  5711. // } catch {
  5712. // stack = [];
  5713. // return null;
  5714. // }
  5715. break;
  5716. }
  5717. }
  5718. for (const v of stack) {
  5719. if (v.isTensor()) {
  5720. const t = v.toTensor();
  5721. if (t.defined() && t.requires_grad()) {
  5722. return null;
  5723. }
  5724. }
  5725. if (ignore_custom_classes) {
  5726. if (v.isCustomClass()) {
  5727. return null;
  5728. }
  5729. }
  5730. if (v.isCustomClass()) {
  5731. if (v.toObject().is_weak_compilation_ref()) {
  5732. continue;
  5733. }
  5734. if (!db) {
  5735. continue;
  5736. }
  5737. const n_non_const = n;
  5738. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  5739. continue;
  5740. }
  5741. const obj = v.toObject();
  5742. obj.unsafe_make_weak_compilation_ref();
  5743. }
  5744. if (v.isObject()) {
  5745. if (!v.toObject().is_weak_compilation_ref()) {
  5746. return null;
  5747. }
  5748. }
  5749. }
  5750. return stack;
  5751. });
  5752. this.registerType('torch._C.ConstantPropagator', class {
  5753. constructor(graph, aliasing_types, ignore_custom_classes) {
  5754. this._made_change = false;
  5755. this._graph = graph;
  5756. this._aliasing_types = aliasing_types;
  5757. this._ignore_custom_classes = ignore_custom_classes;
  5758. }
  5759. static NoAliasDb(graph) {
  5760. return new torch._C.ConstantPropagator(graph, false, false);
  5761. }
  5762. run() {
  5763. this.ConstantPropagation(this._graph.block());
  5764. return this._made_change;
  5765. }
  5766. propagateNode(n) {
  5767. let outputs = [];
  5768. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  5769. if (outputs_opt) {
  5770. outputs = outputs_opt;
  5771. } else {
  5772. return;
  5773. }
  5774. const graph = n.owningGraph();
  5775. const guard = new torch._C.WithInsertPoint(n);
  5776. for (let i = 0; i < outputs.length; i++) {
  5777. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  5778. if (new_output) {
  5779. this._made_change = true;
  5780. if (outputs[i].isNone()) {
  5781. new_output.setType(n.outputs()[i].type());
  5782. }
  5783. n.outputs()[i].replaceAllUsesWith(new_output);
  5784. }
  5785. }
  5786. guard.dispose();
  5787. }
  5788. removeLoopNode(n) {
  5789. const loop_input_offset = 2;
  5790. for (let i = 0; i < n.outputs().length; i++) {
  5791. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  5792. }
  5793. this._made_change = true;
  5794. n.destroy();
  5795. }
  5796. loopWillNotRun(node) {
  5797. const [trip_count, start_cond] = node.inputs();
  5798. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  5799. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  5800. const loop_might_run = cond_val && iter_len > 0;
  5801. return !loop_might_run;
  5802. }
  5803. inlineIfBody(body) {
  5804. const n = body.owningNode();
  5805. for (const body_node of body.nodes()) {
  5806. body_node.moveBefore(n);
  5807. }
  5808. for (let i = 0; i < n.outputs().length; i++) {
  5809. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  5810. }
  5811. n.destroy();
  5812. }
  5813. inlineIf(n) {
  5814. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  5815. torch._C.AT_ASSERT(input_bool !== null);
  5816. const block_index = input_bool ? 0 : 1;
  5817. this.ConstantPropagation(n.blocks()[block_index]);
  5818. this.inlineIfBody(n.blocks()[block_index]);
  5819. this._made_change = true;
  5820. }
  5821. replaceAndRemoveIfOutput(n, i, replacement) {
  5822. n.outputs()[i].replaceAllUsesWith(replacement);
  5823. n.eraseOutput(i);
  5824. n.blocks()[0].eraseOutput(i);
  5825. n.blocks()[1].eraseOutput(i);
  5826. }
  5827. removeExtraIfOutputs(n) {
  5828. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  5829. const [true_block, false_block] = n.blocks();
  5830. const graph = n.owningGraph();
  5831. const initial_outputs = true_block.outputs().length;
  5832. const guard = new torch._C.WithInsertPoint(n);
  5833. for (let i = 0; i < true_block.outputs().length;) {
  5834. const t_out = true_block.outputs()[i];
  5835. const f_out = false_block.outputs()[i];
  5836. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  5837. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  5838. continue;
  5839. }
  5840. const maybe_const = torch._C.toIValue(t_out);
  5841. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  5842. const new_const = graph.insertConstant(maybe_const);
  5843. this.replaceAndRemoveIfOutput(n, i, new_const);
  5844. continue;
  5845. }
  5846. i++;
  5847. }
  5848. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  5849. guard.dispose();
  5850. }
  5851. removeExtraLoopOutputs(node) {
  5852. const initial_outputs = node.outputs().length;
  5853. const [loop_body] = node.blocks();
  5854. const loop_input_offset = 2;
  5855. const loop_body_offset = 1;
  5856. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  5857. const i = i_1 - 1;
  5858. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  5859. const node_input = node.inputs()[loop_input_offset + i];
  5860. node.outputs().at(i).replaceAllUsesWith(node_input);
  5861. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  5862. node.eraseOutput(i);
  5863. node.removeInput(loop_input_offset + i);
  5864. loop_body.eraseInput(loop_body_offset + i);
  5865. loop_body.eraseOutput(loop_body_offset + i);
  5866. }
  5867. }
  5868. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  5869. }
  5870. noMutableValues(values) {
  5871. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  5872. }
  5873. getOrCreateAliasDb() {
  5874. if (!this._aliasDb) {
  5875. this._aliasDb = new torch._C.AliasDb(this._graph);
  5876. }
  5877. return this._aliasDb;
  5878. }
  5879. supportedNode(n) {
  5880. torch._C.skip_list = torch._C.skip_list || new Set([
  5881. 'prim::If',
  5882. 'prim::Loop',
  5883. 'prim::Closure',
  5884. 'prim::Constant',
  5885. 'prim::AutogradZero',
  5886. 'prim::Uninitialized',
  5887. 'prim::Guard',
  5888. 'prim::profile',
  5889. 'prim::profile_ivalue',
  5890. 'prim::unchecked_unwrap_optional',
  5891. 'prim::awaitable',
  5892. 'aten::dequantize'
  5893. ]);
  5894. let no_mutation = false;
  5895. if (this._aliasing_types) {
  5896. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  5897. } else {
  5898. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  5899. }
  5900. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  5901. }
  5902. ConstantPropagation(...args) {
  5903. if (args[0] instanceof torch.Graph) {
  5904. throw new python.Error('Not implemented.');
  5905. } else if (args[0] instanceof torch.Block) {
  5906. const [block] = args;
  5907. for (const n of block.nodes()) {
  5908. this.ConstantPropagation(n);
  5909. }
  5910. } else if (args[0] instanceof torch.Node) {
  5911. const [n] = args;
  5912. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  5913. if (n.kind() === 'prim::If') {
  5914. if (constant_inputs) {
  5915. this.inlineIf(n);
  5916. } else {
  5917. this.ConstantPropagation(n.blocks());
  5918. this.removeExtraIfOutputs(n);
  5919. }
  5920. } else if (n.kind() === 'prim::Loop') {
  5921. if (this.loopWillNotRun(n)) {
  5922. this.removeLoopNode(n);
  5923. } else {
  5924. this.ConstantPropagation(n.blocks());
  5925. this.removeExtraLoopOutputs(n);
  5926. }
  5927. } else if (constant_inputs && this.supportedNode(n)) {
  5928. this.propagateNode(n);
  5929. } else {
  5930. this.ConstantPropagation(n.blocks()); // not implemented
  5931. }
  5932. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  5933. const [blocks] = args;
  5934. for (const block of blocks) {
  5935. this.ConstantPropagation(block);
  5936. }
  5937. } else {
  5938. throw new python.Error('Not implemented.');
  5939. }
  5940. }
  5941. });
  5942. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  5943. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  5944. const made_change = cp.run();
  5945. if (made_change) {
  5946. torch._C.EliminateDeadCode(graph);
  5947. }
  5948. return made_change;
  5949. });
  5950. this.registerType('torch._C.MutableTypePtrHelper', class {
  5951. constructor(mutable_type_cache) {
  5952. this._mutable_type_cache = mutable_type_cache;
  5953. }
  5954. mapTypeToAliasTypeSet(type) {
  5955. if (this._mutable_type_cache) {
  5956. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  5957. if (result) {
  5958. return result;
  5959. }
  5960. }
  5961. return this.mapTypeToAliasTypeSetImpl(type);
  5962. }
  5963. mapTypeToAliasTypeSetImpl(type) {
  5964. if (type instanceof torch.ListType ||
  5965. type instanceof torch.DictType ||
  5966. type instanceof torch.ClassType ||
  5967. type instanceof torch.TensorType) {
  5968. return [torch._C.unshapedType(type)];
  5969. }
  5970. if (type instanceof torch.UnionType) {
  5971. const mutable_types = [];
  5972. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  5973. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  5974. if (maybe_inner_types) {
  5975. mutable_types.push(...maybe_inner_types);
  5976. }
  5977. }
  5978. if (mutable_types.length === 0) {
  5979. return null;
  5980. }
  5981. return mutable_types;
  5982. }
  5983. if (type instanceof torch.OptionalType) {
  5984. const inner = type.getElementType();
  5985. return this.mapTypeToAliasTypeSet(inner);
  5986. }
  5987. if (type instanceof torch.AnyType) {
  5988. return [torch._C.AliasTypeSet([type])];
  5989. }
  5990. if (type instanceof torch.FutureType) {
  5991. throw new python.Error('Not implemented.');
  5992. /* if (auto maybe_mut_types = mapTypeToAliasTypeSet(type.castRaw<FutureType>()->getElementType())) {
  5993. return {AliasTypeSet{FutureType::create(*toSingleType(*maybe_mut_types))}};
  5994. }
  5995. return null; */
  5996. }
  5997. if (type instanceof torch.AwaitType) {
  5998. throw new python.Error('Not implemented.');
  5999. /*
  6000. if (auto maybe_mut_types = mapTypeToAliasTypeSet(
  6001. type->castRaw<AwaitType>()->getElementType())) {
  6002. return {
  6003. AliasTypeSet{AwaitType::create(*toSingleType(*maybe_mut_types))}};
  6004. }
  6005. return null; */
  6006. }
  6007. if (type instanceof torch.TupleType) {
  6008. const mutable_types = [];
  6009. for (const inner of type.elements()) {
  6010. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  6011. if (maybe_inner_types) {
  6012. mutable_types.push(...maybe_inner_types);
  6013. }
  6014. }
  6015. if (mutable_types.length === 0) {
  6016. return null;
  6017. }
  6018. return [[torch.TupleType.create(mutable_types)]];
  6019. }
  6020. return null;
  6021. }
  6022. });
  6023. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  6024. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  6025. type instanceof torch.ClassType || type instanceof torch.DictType) {
  6026. return true;
  6027. }
  6028. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  6029. if (mutable_type_cache) {
  6030. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  6031. }
  6032. return helper.mapTypeToAliasTypeSet(type) !== null;
  6033. });
  6034. this.registerType('torch._C.AliasDb', class {
  6035. constructor() {
  6036. this._writeIndex = new Map();
  6037. }
  6038. static isMutableType(...args) {
  6039. if (args[0] instanceof torch.Type) {
  6040. const [type] = args;
  6041. return torch._C.isMutableTypeImpl(type, null);
  6042. }
  6043. if (args[0] instanceof torch.Value) {
  6044. const [value] = args;
  6045. return torch._C.AliasDb.isMutableType(value.type());
  6046. }
  6047. throw new python.Error('Not implemented.');
  6048. }
  6049. writesToAlias(/* n, vs */) {
  6050. /*
  6051. const writtenTo = this.getWrites(n);
  6052. if (writtenTo.length === 0) {
  6053. return false;
  6054. }
  6055. MemoryLocations locs;
  6056. for (const v of vs) {
  6057. const it = elementMap_.find(v);
  6058. if (it != elementMap_.end()) {
  6059. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  6060. if (writtenTo.intersects(vlocs)) {
  6061. return true;
  6062. }
  6063. }
  6064. }
  6065. */
  6066. return false;
  6067. }
  6068. writesToWildcard(n) {
  6069. if (!this._writeIndex.has(n)) {
  6070. return false;
  6071. }
  6072. const writes = this._writeIndex.get(n);
  6073. for (const pr of this._wildcardIndex) {
  6074. const [, wildcardElement] = pr;
  6075. if (writes.test(wildcardElement.index)) {
  6076. return true;
  6077. }
  6078. }
  6079. return false;
  6080. }
  6081. safeToChangeAliasingRelationship(a, b) {
  6082. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  6083. return false;
  6084. }
  6085. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  6086. }
  6087. });
  6088. this.registerFunction('torch._C.hasWriters', () => {
  6089. });
  6090. this.registerFunction('torch._C.escapesScope', () => {
  6091. });
  6092. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  6093. if (!cond) {
  6094. throw new python.Error('Assertion failed.');
  6095. }
  6096. });
  6097. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  6098. if (!cond) {
  6099. throw new python.Error('Assertion failed.');
  6100. }
  6101. });
  6102. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  6103. if (!cond) {
  6104. throw new python.Error('Assertion failed.');
  6105. }
  6106. });
  6107. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  6108. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  6109. for (let next_node = it.next(); next_node !== null;) {
  6110. const node = next_node;
  6111. next_node = it.next();
  6112. if (node.kind() === 'prim::EmptyListLiteral') {
  6113. if (node.hasUses()) {
  6114. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  6115. }
  6116. const li = graph.createList(torch.TensorType.get(), []);
  6117. li.insertBefore(node);
  6118. node.replaceAllUsesWith(li);
  6119. }
  6120. node.destroy();
  6121. }
  6122. });
  6123. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  6124. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6125. const [graph] = args;
  6126. const aliasDb = new torch._C.AliasDb(graph);
  6127. const constants = new torch._C.NodeSet();
  6128. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  6129. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  6130. const [block, constants, aliasDb] = args;
  6131. for (const node of block.nodes()) {
  6132. if (node.blocks().length > 0) {
  6133. for (const block of node.blocks()) {
  6134. torch._C.ConstantPooling(block, constants, aliasDb);
  6135. }
  6136. continue;
  6137. }
  6138. if (node.kind() !== 'prim::Constant') {
  6139. continue;
  6140. }
  6141. if (constants.has(node)) {
  6142. const existing = constants.get(node);
  6143. const old_ivalue = torch._C.toIValue(existing.output());
  6144. const new_ivalue = torch._C.toIValue(node.output());
  6145. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  6146. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  6147. continue;
  6148. }
  6149. node.replaceAllUsesWith(existing);
  6150. node.destroy();
  6151. continue;
  6152. } else {
  6153. constants.insert(node);
  6154. }
  6155. const [first_node] = node.owningGraph().block().nodes();
  6156. if (node !== first_node) {
  6157. node.moveBefore(first_node);
  6158. }
  6159. }
  6160. } else {
  6161. throw new python.Error('Not implemented.');
  6162. }
  6163. });
  6164. this.registerFunction('torch._C.handleBlock', () =>{
  6165. //
  6166. });
  6167. this.registerFunction('torch._C.autocastEnabled', () => {
  6168. return true;
  6169. });
  6170. this.registerFunction('torch._C.Autocast', (graph) => {
  6171. if (torch._C.autocastEnabled()) {
  6172. const init = null;
  6173. /* AutocastContext init = {
  6174. at::autocast::is_autocast_enabled(at::kCUDA),
  6175. at::autocast::is_autocast_enabled(at::kCPU),
  6176. at::autocast::get_autocast_dtype(at::kCUDA),
  6177. at::autocast::get_autocast_dtype(at::kCPU)}; */
  6178. torch._C.handleBlock(graph.block(), init);
  6179. }
  6180. });
  6181. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  6182. disable_autocast = disable_autocast || false;
  6183. torch._C.Inline(graph);
  6184. // torch._C.PeepholeOptimize(graph, true);
  6185. torch._C.ConstantPropagationImmutableTypes(graph);
  6186. if (!disable_autocast) {
  6187. torch._C.Autocast(graph);
  6188. }
  6189. torch._C.ConstantPooling(graph);
  6190. });
  6191. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  6192. constructor(name, graph, function_creator, executor_execution_mode) {
  6193. super();
  6194. this._name = name;
  6195. this._graph = graph;
  6196. this._executor_execution_mode = executor_execution_mode || null;
  6197. this._function_creator = function_creator;
  6198. this._force_no_amp = false;
  6199. }
  6200. isGraphFunction() {
  6201. return true;
  6202. }
  6203. qualname() {
  6204. return this._name;
  6205. }
  6206. graph() {
  6207. return this._graph;
  6208. }
  6209. optimized_graph() {
  6210. const graph_ref = this._graph.copy();
  6211. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  6212. return graph_ref;
  6213. }
  6214. ensure_defined() {
  6215. if (this._function_creator) {
  6216. const creator = this._function_creator;
  6217. this._function_creator = () => {
  6218. throw new python.Error('Recursive method call.');
  6219. };
  6220. creator(this);
  6221. this._function_creator = null;
  6222. }
  6223. this.check_single_output();
  6224. }
  6225. check_single_output() {
  6226. if (this.graph().outputs().length !== 1) {
  6227. throw new python.Error('Graph must have a single output.');
  6228. }
  6229. }
  6230. getSchema() {
  6231. this._schema = this._schema || this.defaultSchemaFor(this);
  6232. return this._schema;
  6233. }
  6234. setSchema(schema) {
  6235. this._schema = schema;
  6236. }
  6237. num_inputs() {
  6238. return this.graph().inputs().length;
  6239. }
  6240. unshapedType(type) {
  6241. if (type.isSubtypeOf(torch.TensorType.get())) {
  6242. return torch.TensorType.get();
  6243. }
  6244. throw new python.Error('Not implemented.');
  6245. /*
  6246. at::ArrayRef<TypePtr> contained = type->containedTypes();
  6247. if (contained.empty()) {
  6248. return type;
  6249. }
  6250. return type->withContained(fmap(type->containedTypes(), unshapedType));
  6251. */
  6252. }
  6253. defaultSchemaFor(fn) {
  6254. const args = [];
  6255. const returns = [];
  6256. const g = fn.graph();
  6257. const num_inputs = fn.num_inputs();
  6258. for (let i = 0; i < num_inputs; i++) {
  6259. const v = g.inputs()[i];
  6260. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  6261. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  6262. args.push(argument);
  6263. }
  6264. const num_outputs = g.outputs().length;
  6265. for (let i = 0; i < num_outputs; i++) {
  6266. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  6267. returns.push(argument);
  6268. }
  6269. return new torch.FunctionSchema(fn.name(), '', args, returns);
  6270. }
  6271. });
  6272. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  6273. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  6274. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  6275. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  6276. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  6277. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  6278. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  6279. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  6280. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  6281. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  6282. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  6283. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  6284. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  6285. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  6286. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  6287. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  6288. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  6289. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  6290. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  6291. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  6292. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  6293. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  6294. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  6295. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  6296. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  6297. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  6298. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  6299. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  6300. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  6301. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  6302. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  6303. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  6304. this.registerType('torch.autograd.variable.Variable', class {});
  6305. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  6306. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  6307. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  6308. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  6309. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  6310. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  6311. this.registerType('torch.distributed.remote_device._remote_device', class {});
  6312. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  6313. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  6314. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  6315. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  6316. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  6317. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  6318. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  6319. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  6320. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  6321. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  6322. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  6323. this.registerType('torch.distributions.beta.Beta', class {});
  6324. this.registerType('torch.distributions.binomial.Binomial', class {});
  6325. this.registerType('torch.distributions.categorical.Categorical', class {});
  6326. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  6327. this.registerType('torch.distributions.constraints._Real', class {});
  6328. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  6329. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  6330. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  6331. this.registerType('torch.distributions.normal.Normal', class {});
  6332. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  6333. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  6334. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  6335. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  6336. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  6337. this.registerType('torch.distributions.uniform.Uniform', class {});
  6338. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  6339. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  6340. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  6341. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  6342. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  6343. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  6344. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  6345. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  6346. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  6347. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  6348. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  6349. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  6350. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  6351. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  6352. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  6353. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  6354. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  6355. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  6356. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  6357. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  6358. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  6359. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  6360. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  6361. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  6362. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  6363. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  6364. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  6365. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  6366. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  6367. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  6368. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  6369. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  6370. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  6371. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  6372. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  6373. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  6374. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  6375. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  6376. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  6377. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  6378. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  6379. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  6380. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  6381. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  6382. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6383. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6384. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6385. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  6386. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  6387. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  6388. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  6389. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  6390. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  6391. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  6392. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  6393. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  6394. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  6395. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  6396. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  6397. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  6398. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  6399. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  6400. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  6401. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  6402. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  6403. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  6404. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  6405. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  6406. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  6407. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  6408. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  6409. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  6410. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  6411. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  6412. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  6413. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  6414. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  6415. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  6416. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  6417. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  6418. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  6419. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  6420. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  6421. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  6422. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  6423. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  6424. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  6425. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  6426. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  6427. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  6428. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  6429. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  6430. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  6431. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  6432. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  6433. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6434. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  6435. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6436. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  6437. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  6438. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  6439. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  6440. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  6441. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  6442. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  6443. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  6444. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  6445. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  6446. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6447. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  6448. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  6449. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  6450. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  6451. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  6452. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  6453. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  6454. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  6455. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  6456. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  6457. this.registerType('torch.nn.modules.module.PatchForward', class {});
  6458. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  6459. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  6460. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  6461. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  6462. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  6463. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  6464. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  6465. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  6466. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  6467. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  6468. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  6469. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  6470. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  6471. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  6472. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  6473. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  6474. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  6475. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  6476. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  6477. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  6478. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  6479. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  6480. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  6481. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  6482. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  6483. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  6484. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  6485. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  6486. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  6487. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  6488. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  6489. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  6490. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  6491. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  6492. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  6493. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  6494. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  6495. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  6496. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  6497. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  6498. this.registerType('torch.nn.modules.rnn.GRU', class {});
  6499. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  6500. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  6501. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  6502. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  6503. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  6504. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  6505. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  6506. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  6507. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  6508. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  6509. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  6510. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  6511. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  6512. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  6513. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  6514. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  6515. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  6516. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  6517. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  6518. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  6519. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  6520. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  6521. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  6522. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  6523. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  6524. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  6525. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  6526. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  6527. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  6528. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  6529. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  6530. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  6531. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  6532. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  6533. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  6534. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  6535. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  6536. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  6537. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  6538. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  6539. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  6540. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  6541. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  6542. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  6543. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  6544. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  6545. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  6546. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  6547. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  6548. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  6549. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  6550. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  6551. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  6552. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  6553. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  6554. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  6555. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  6556. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  6557. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  6558. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  6559. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  6560. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  6561. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  6562. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  6563. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  6564. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  6565. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  6566. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  6567. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  6568. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  6569. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  6570. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  6571. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  6572. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  6573. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  6574. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  6575. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  6576. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  6577. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  6578. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  6579. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  6580. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  6581. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  6582. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  6583. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  6584. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  6585. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  6586. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  6587. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  6588. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  6589. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  6590. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  6591. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  6592. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  6593. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  6594. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  6595. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  6596. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  6597. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  6598. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  6599. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  6600. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  6601. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  6602. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  6603. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  6604. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  6605. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  6606. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  6607. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  6608. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  6609. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  6610. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  6611. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  6612. this.registerType('torch.optim.optimizer.Optimizer', class {});
  6613. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  6614. this.registerType('torch.optim.adamw.AdamW', class {});
  6615. this.registerType('torch.optim.adagrad.Adagrad', class {});
  6616. this.registerType('torch.optim.adadelta.Adadelta', class {});
  6617. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  6618. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  6619. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  6620. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  6621. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  6622. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  6623. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  6624. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  6625. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  6626. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  6627. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  6628. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  6629. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  6630. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  6631. this.registerType('torch.optim.sgd.SGD', class {});
  6632. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  6633. this.registerType('torch.optim.swa_utils.SWALR', class {});
  6634. torch.optim.RAdam = torch.optim.radam.RAdam;
  6635. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  6636. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  6637. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  6638. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  6639. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  6640. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  6641. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  6642. this.registerFunction('torch.quantization.observer._with_args');
  6643. this.registerType('torch.quantization.qconfig.QConfig', class {});
  6644. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  6645. this.registerType('torch.quantization.stubs.QuantStub', class {});
  6646. this.registerType('torch.utils._pytree.LeafSpec', class {});
  6647. this.registerType('torch.utils._pytree.TreeSpec', class {});
  6648. this.registerFunction('torch.utils._pytree.tree_map');
  6649. this.registerFunction('torch.utils.checkpoint.checkpoint');
  6650. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  6651. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  6652. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  6653. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  6654. this.registerType('torch.utils.data.dataset.Subset', class {});
  6655. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  6656. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  6657. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  6658. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  6659. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  6660. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  6661. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  6662. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  6663. create_symintnode(/* sym, hint, source */) {
  6664. return new torch.SymInt();
  6665. }
  6666. });
  6667. this.registerType('torch.fx.proxy.TracerBase', class {
  6668. constructor() {
  6669. this.traced_func_name = 'forward';
  6670. }
  6671. });
  6672. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  6673. trace(root /*, concrete_args */) {
  6674. let fn = null;
  6675. if (root instanceof torch.nn.Module) {
  6676. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  6677. this.root = root;
  6678. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  6679. this.root_module_name = root._get_name();
  6680. this.submodule_paths = new builtins.dict(root.named_modules());
  6681. } else {
  6682. this.root = new torch.nn.Module();
  6683. fn = root;
  6684. }
  6685. const tracer_cls = builtins.getattr(this, '__class__', null);
  6686. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  6687. if (builtins.hasattr(this, '__code__')) {
  6688. const code = fn.__code__;
  6689. this.graph._co_fields = {
  6690. co_name: code.co_name,
  6691. co_filename: code.co_filename,
  6692. co_firstlineno: code.co_firstlineno,
  6693. };
  6694. }
  6695. return this.graph;
  6696. }
  6697. is_leaf_module(m /*, module_qualified_name */) {
  6698. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  6699. }
  6700. });
  6701. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  6702. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  6703. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  6704. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  6705. return new graph_module_cls(...args);
  6706. });
  6707. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  6708. let tracer_cls = body.get('_tracer_cls');
  6709. if (!tracer_cls) {
  6710. tracer_cls = torch.fx._symbolic_trace.Tracer;
  6711. }
  6712. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  6713. const cls_tracer = tracer_cls;
  6714. const KeepModules = class extends cls_tracer {
  6715. is_leaf_module() {
  6716. return true;
  6717. }
  6718. };
  6719. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  6720. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  6721. const graph = new KeepModules().trace(com, tracer_extras);
  6722. graph._tracer_cls = tracer_cls;
  6723. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  6724. for (const [k, v] of body.items()) {
  6725. if (!builtins.hasattr(gm, k)) {
  6726. builtins.setattr(gm, k, v);
  6727. }
  6728. }
  6729. return gm;
  6730. });
  6731. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  6732. globals = { ...globals };
  6733. const context = new python.Execution.Context(globals, null);
  6734. execution.exec(src, context);
  6735. const forward_fn = globals.forward;
  6736. delete globals.forward;
  6737. return forward_fn;
  6738. });
  6739. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  6740. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  6741. let fn_src = null;
  6742. if (body.has('_code')) {
  6743. fn_src = body.get('_code');
  6744. } else if (body.has('code')) {
  6745. fn_src = body.get('code');
  6746. } else {
  6747. fn_src = body._code || body.code;
  6748. }
  6749. const forward = execution.invoke('torch.fx.graph_module._forward_from_src', [import_block + fn_src, {}]);
  6750. return execution.invoke('torch.fx.graph_module._deserialize_graph_module', [forward, body]);
  6751. });
  6752. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  6753. const forward = importer.import_module(generated_module_name).forward;
  6754. return execution.invoke('torch.fx.graph_module._deserialize_graph_module', [forward, body]);
  6755. });
  6756. this.registerType('torch.fx.graph.CodeGen', class {});
  6757. this.registerType('torch.fx.graph._Namespace', class {
  6758. constructor() {
  6759. this._obj_to_name = new Map();
  6760. this._unassociated_names = new Set();
  6761. this._used_names = new Set();
  6762. this._base_count = {};
  6763. }
  6764. create_name(candidate, obj) {
  6765. if (obj && this._obj_to_name.has(obj)) {
  6766. return self._obj_to_name.get(obj);
  6767. }
  6768. candidate = candidate || '_unnamed';
  6769. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  6770. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  6771. const match = candidate.match(/(.*)_(\d+)$"/);
  6772. let base = candidate;
  6773. let num = null;
  6774. if (match) {
  6775. [, base] = match;
  6776. num = parseInt(match[2], 10);
  6777. }
  6778. candidate = num ? `${base}_${num}` : base;
  6779. if (!num) {
  6780. num = this._base_count[base] || 0;
  6781. }
  6782. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  6783. num += 1;
  6784. candidate = `${base}_${num}`;
  6785. }
  6786. this._used_names.add(candidate);
  6787. this._base_count[base] = num;
  6788. if (obj) {
  6789. this._obj_to_name[obj] = candidate;
  6790. } else {
  6791. this._unassociated_names.add(candidate);
  6792. }
  6793. return candidate;
  6794. }
  6795. _is_illegal_name(/* name, obj */) {
  6796. /*
  6797. if name in keyword.kwlist:
  6798. return True
  6799. if name in builtins.__dict__:
  6800. return obj is not builtins.__dict__[name]
  6801. if name in _custom_builtins:
  6802. return obj is not _custom_builtins[name].obj
  6803. */
  6804. return false;
  6805. }
  6806. associate_name_with_obj() {
  6807. }
  6808. });
  6809. this.registerType('torch.fx.node.Node', class {
  6810. constructor(graph, name, op, target, args, kwargs, return_type) {
  6811. this.graph = graph;
  6812. this.name = name;
  6813. this.op = op;
  6814. this.target = target;
  6815. this._input_nodes = new builtins.dict();
  6816. this.__update_args_kwargs(args, kwargs);
  6817. this.users = new builtins.dict();
  6818. this.type = return_type;
  6819. this._prev = this;
  6820. this._next = this;
  6821. this._erased = false;
  6822. this._repr_fn = null;
  6823. this.meta = new builtins.dict();
  6824. }
  6825. get args() {
  6826. return this._args;
  6827. }
  6828. get kwargs() {
  6829. return this._kwargs;
  6830. }
  6831. get next() {
  6832. return this._next;
  6833. }
  6834. prepend(x) {
  6835. x._remove_from_list();
  6836. const p = this._prev;
  6837. [p._next, x._prev] = [x, p];
  6838. [x._next, this._prev] = [this, x];
  6839. }
  6840. _remove_from_list() {
  6841. const [p, n] = [this._prev, this._next];
  6842. [p._next, n._prev] = [n, p];
  6843. }
  6844. __update_args_kwargs(new_args, new_kwargs) {
  6845. const update_users_and_input_nodes = (n) => {
  6846. if (n instanceof torch.fx.node.Node) {
  6847. this._input_nodes.setdefault(n);
  6848. n.users.setdefault(this);
  6849. }
  6850. return n;
  6851. };
  6852. const map_aggregate = (a, fn) => {
  6853. if (a instanceof builtins.tuple) {
  6854. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  6855. if (!builtins.hasattr(a, '_fields')) {
  6856. return t;
  6857. }
  6858. throw new python.Error('Not implemented.');
  6859. // return type(a)(*t);
  6860. } else if (Array.isArray(a)) {
  6861. return a.map((elem) => map_aggregate(elem, fn));
  6862. } else if (a instanceof builtins.dict) {
  6863. const rv = new builtins.dict();
  6864. for (const [k, v] of a) {
  6865. rv.__setitem__(k, map_aggregate(v, fn));
  6866. }
  6867. return rv;
  6868. } else if (a instanceof builtins.slice) {
  6869. throw new python.Error('Not implemented.');
  6870. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  6871. }
  6872. return fn(a);
  6873. };
  6874. for (const old_use of this._input_nodes.keys()) {
  6875. old_use.users.pop(this);
  6876. }
  6877. // object.__setattr__(self, "_input_nodes", {})
  6878. this._input_nodes = new builtins.dict();
  6879. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  6880. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  6881. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  6882. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  6883. }
  6884. });
  6885. torch.fx.Node = torch.fx.node.Node;
  6886. torch.fx.graph.Node = torch.fx.node.Node;
  6887. this.registerType('torch.fx.graph.Graph', class {
  6888. constructor(owning_module, tracer_cls, tracer_extras) {
  6889. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  6890. this._used_names = new Map();
  6891. this._len = 0;
  6892. this._graph_namespace = new torch.fx.graph._Namespace();
  6893. this._owning_module = owning_module;
  6894. this._tracer_cls = tracer_cls;
  6895. this._tracer_extras = tracer_extras;
  6896. // this._codegen = CodeGen()
  6897. // this._co_fields = {}
  6898. }
  6899. get nodes() {
  6900. const array = new Array(this._len);
  6901. let node = this._root.next;
  6902. for (let i = 0; node !== this._root; i++) {
  6903. array[i] = node;
  6904. node = node.next;
  6905. }
  6906. return array;
  6907. }
  6908. placeholder(name, type_expr /*, default_value */) {
  6909. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  6910. const kwargs = new builtins.dict();
  6911. return this.create_node('placeholder', name, args, kwargs, type_expr);
  6912. }
  6913. create_node(op, target, args, kwargs, name, type_expr) {
  6914. args = args || new builtins.tuple();
  6915. kwargs = kwargs || new builtins.dict();
  6916. const candidate = name || this._target_to_str(target);
  6917. name = this._graph_namespace.create_name(candidate, null);
  6918. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  6919. this._graph_namespace.associate_name_with_obj(name, n);
  6920. this._insert(n);
  6921. this._len += 1;
  6922. return n;
  6923. }
  6924. _insert(n) {
  6925. this._root.prepend(n);
  6926. }
  6927. output(result, type_expr) {
  6928. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  6929. }
  6930. _target_to_str(target) {
  6931. if (typeof target === 'string') {
  6932. if (target.startsWith('__') && target.endswith('__')) {
  6933. target = target.substring(2, target.length - 2);
  6934. }
  6935. } else {
  6936. target = target.__name__;
  6937. }
  6938. return this._snake_case(target);
  6939. }
  6940. _snake_case(s) {
  6941. const chars = [];
  6942. let prev_lower = false;
  6943. for (const c of s) {
  6944. const x = c.toLowerCase();
  6945. if (prev_lower && x !== c) {
  6946. chars.push('_');
  6947. } else {
  6948. prev_lower = true;
  6949. }
  6950. chars.push(x);
  6951. }
  6952. return chars.join('');
  6953. }
  6954. });
  6955. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  6956. constructor(body) {
  6957. super();
  6958. for (const [k, v] of body.items()) {
  6959. builtins.setattr(this, k, v);
  6960. }
  6961. }
  6962. });
  6963. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  6964. constructor(root, graph, class_name) {
  6965. super();
  6966. this.__class__.__name__ = class_name || 'GraphModule';
  6967. this.graph = graph;
  6968. }
  6969. });
  6970. torch.fx.Graph = torch.fx.graph.Graph;
  6971. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  6972. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  6973. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  6974. return fn_or_name;
  6975. });
  6976. this.registerFunction('torchvision.datasets.folder.default_loader');
  6977. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  6978. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  6979. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  6980. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  6981. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  6982. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  6983. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  6984. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  6985. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  6986. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  6987. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  6988. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  6989. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  6990. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  6991. this.registerType('torchvision.ops.misc.Permute', class {});
  6992. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  6993. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  6994. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  6995. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  6996. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  6997. this.registerType('torchvision.models._api.Weights', class {});
  6998. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  6999. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  7000. this.registerType('torchvision.models.convnext.CNBlock', class {});
  7001. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  7002. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  7003. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  7004. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  7005. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  7006. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  7007. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  7008. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  7009. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  7010. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  7011. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  7012. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  7013. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  7014. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  7015. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  7016. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  7017. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  7018. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  7019. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  7020. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  7021. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  7022. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  7023. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  7024. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  7025. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  7026. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  7027. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  7028. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  7029. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  7030. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  7031. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  7032. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  7033. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  7034. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  7035. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  7036. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  7037. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  7038. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  7039. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  7040. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  7041. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  7042. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  7043. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  7044. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  7045. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  7046. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  7047. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  7048. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  7049. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  7050. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  7051. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  7052. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  7053. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  7054. this.registerType('torchvision.models.googlenet.Inception', class {});
  7055. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  7056. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  7057. this.registerType('torchvision.models.inception.Inception3', class {});
  7058. this.registerType('torchvision.models.inception.InceptionAux', class {});
  7059. this.registerType('torchvision.models.inception.InceptionA', class {});
  7060. this.registerType('torchvision.models.inception.InceptionB', class {});
  7061. this.registerType('torchvision.models.inception.InceptionC', class {});
  7062. this.registerType('torchvision.models.inception.InceptionD', class {});
  7063. this.registerType('torchvision.models.inception.InceptionE', class {});
  7064. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  7065. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  7066. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  7067. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  7068. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  7069. this.registerType('torchvision.models.maxvit.MBConv', class {});
  7070. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  7071. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  7072. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  7073. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  7074. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  7075. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  7076. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  7077. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  7078. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  7079. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  7080. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  7081. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  7082. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  7083. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  7084. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  7085. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  7086. this.registerType('torchvision.models.regnet.RegNet', class {});
  7087. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  7088. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  7089. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  7090. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  7091. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  7092. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  7093. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  7094. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  7095. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  7096. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  7097. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  7098. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  7099. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  7100. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  7101. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  7102. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  7103. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  7104. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  7105. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  7106. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  7107. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  7108. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  7109. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  7110. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  7111. this.registerType('torchvision.models.squeezenet.Fire', class {});
  7112. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  7113. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  7114. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  7115. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  7116. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  7117. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  7118. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  7119. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  7120. this.registerType('torchvision.models.resnet.ResNet', class {});
  7121. this.registerType('torchvision.models.vgg.VGG', class {});
  7122. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  7123. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  7124. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  7125. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  7126. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  7127. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  7128. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  7129. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  7130. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  7131. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  7132. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  7133. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  7134. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  7135. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  7136. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  7137. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  7138. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  7139. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  7140. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  7141. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  7142. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  7143. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  7144. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  7145. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  7146. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  7147. this.registerType('torchvision.transforms.transforms.Compose', class {});
  7148. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  7149. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  7150. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  7151. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  7152. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  7153. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  7154. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  7155. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  7156. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  7157. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  7158. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  7159. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  7160. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  7161. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  7162. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  7163. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  7164. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  7165. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  7166. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  7167. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  7168. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  7169. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  7170. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  7171. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  7172. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  7173. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  7174. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  7175. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  7176. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  7177. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  7178. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  7179. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  7180. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  7181. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  7182. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  7183. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  7184. this.registerFunction('torchvision.ops.boxes.box_iou');
  7185. this.registerFunction('builtins.annotate', (type, value) => {
  7186. if (type === builtins.int) {
  7187. return Number.isInteger(value) ? value : NaN;
  7188. }
  7189. if (type === builtins.float) {
  7190. return typeof value === 'number' ? value : NaN;
  7191. }
  7192. if (type === builtins.number) {
  7193. // if (pytorch.Utility.isTensor(value)) {
  7194. // value.resize_([]);
  7195. // }
  7196. }
  7197. return value;
  7198. });
  7199. this.registerFunction('builtins.uninitialized', (/* type */) => {
  7200. return undefined;
  7201. });
  7202. this.registerFunction('ops.prim.unchecked_cast', (type, value) => {
  7203. return value;
  7204. });
  7205. this.registerFunction('ops.prim.data', (tensor) => {
  7206. return tensor;
  7207. });
  7208. this.registerFunction('ops.prim.device', (tensor) => {
  7209. return tensor.device;
  7210. });
  7211. this.registerFunction('ops.prim.dtype', (tensor) => {
  7212. return tensor.dtype.scalar_type();
  7213. });
  7214. this.registerFunction('ops.prim.is_quantized', (tensor) => {
  7215. return tensor.is_quantized;
  7216. });
  7217. this.registerFunction('ops.prim.is_cuda', (/* tensor */) => {
  7218. return false;
  7219. });
  7220. this.registerFunction('ops.prim.is_nested', (tensor) => {
  7221. return tensor.is_nested;
  7222. });
  7223. this.registerFunction('ops.prim.is_sparse', (tensor) => {
  7224. return tensor.is_sparse;
  7225. });
  7226. this.registerFunction('ops.prim.unchecked_unwrap_optional', (value) => {
  7227. return value;
  7228. });
  7229. this.registerFunction('ops.prim.NumToTensor', (value) => {
  7230. const tensor = self.invoke('torch.Tensor', []);
  7231. tensor.value = value;
  7232. return tensor;
  7233. });
  7234. this.registerFunction('ops.prim.min', (...args) => {
  7235. if (Array.isArray(args[0])) {
  7236. return Math.min.apply(null, args[0]);
  7237. }
  7238. return Math.min.apply(null, args);
  7239. });
  7240. this.registerFunction('ops.prim.max', (...args) => {
  7241. if (Array.isArray(args[0])) {
  7242. return Math.max.apply(null, args[0]);
  7243. }
  7244. return Math.max.apply(null, args);
  7245. });
  7246. this.registerFunction('ops.prim.shape', (tensor) => {
  7247. return tensor && tensor.size ? tensor.size() : undefined;
  7248. });
  7249. this.registerFunction('ops.quantized.conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7250. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7251. params.weight = weight;
  7252. params.bias = bias;
  7253. params.stride = stride;
  7254. params.padding = padding;
  7255. params.dilation = dilation;
  7256. params.groups = groups;
  7257. return params;
  7258. });
  7259. this.registerFunction('ops.quantized.conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7260. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7261. params.weight = weight;
  7262. params.bias = bias;
  7263. params.stride = stride;
  7264. params.padding = padding;
  7265. params.dilation = dilation;
  7266. params.groups = groups;
  7267. return params;
  7268. });
  7269. this.registerFunction('ops.quantized.conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7270. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7271. params.weight = weight;
  7272. params.bias = bias;
  7273. params.stride = stride;
  7274. params.padding = padding;
  7275. params.dilation = dilation;
  7276. params.groups = groups;
  7277. return params;
  7278. });
  7279. this.registerFunction('ops.quantized.conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  7280. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  7281. params.weight = weight;
  7282. params.bias = bias;
  7283. params.stride = stride;
  7284. params.padding = padding;
  7285. params.dilation = dilation;
  7286. params.groups = groups;
  7287. return params;
  7288. });
  7289. this.registerFunction('ops.quantized.conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  7290. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7291. params.weight = weight;
  7292. params.bias = bias;
  7293. params.stride = stride;
  7294. params.padding = padding;
  7295. params.output_padding = output_padding;
  7296. params.dilation = dilation;
  7297. params.groups = groups;
  7298. return params;
  7299. });
  7300. this.registerFunction('ops.quantized.conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  7301. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  7302. params.weight = weight;
  7303. params.bias = bias;
  7304. params.stride = stride;
  7305. params.padding = padding;
  7306. params.output_padding = output_padding;
  7307. params.dilation = dilation;
  7308. params.groups = groups;
  7309. return params;
  7310. });
  7311. this.registerFunction('ops.quantized.linear_prepack', (weight, bias) => {
  7312. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  7313. params.weight = weight;
  7314. params.bias = bias;
  7315. return params;
  7316. });
  7317. this.registerFunction('ops.prim.RaiseException', (message) => {
  7318. throw new python.Error(message);
  7319. });
  7320. this.registerFunction('builtins.range', (start, stop, step) => {
  7321. if (stop === undefined && step === undefined) {
  7322. if (Number.isInteger(start)) {
  7323. return Array(start).keys();
  7324. }
  7325. if (isNaN(start)) {
  7326. return [];
  7327. }
  7328. }
  7329. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  7330. });
  7331. builtins.xrange = builtins.range;
  7332. this.registerFunction('torch._C._nn.gelu');
  7333. this.registerFunction('torch._C._nn.avg_pool2d');
  7334. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  7335. this.registerFunction('torch._C._nn.softplus');
  7336. this.registerFunction('torch._native_multi_head_attention');
  7337. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  7338. if (layout === torch.sparse_coo) {
  7339. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  7340. }
  7341. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  7342. });
  7343. this.registerFunction('torch._utils._rebuild_wrapper_subclass');
  7344. this.registerFunction('torch.from_numpy', (obj) => {
  7345. const dtypes = new Map([
  7346. ['<f2', torch.float16],
  7347. ['<f4', torch.float32],
  7348. ['<f8', torch.float64],
  7349. ['<i2', torch.int16],
  7350. ['<i4', torch.int32],
  7351. ['<i8', torch.int64],
  7352. ]);
  7353. if (!dtypes.has(obj.dtype.str)) {
  7354. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  7355. }
  7356. const dtype = dtypes.get(obj.dtype.str);
  7357. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  7358. const storage = execution.invoke('torch.storage.TypedStorage', [obj.size, dtype]);
  7359. storage._set_cdata(obj.data);
  7360. const tensor = execution.invoke('torch.Tensor', []);
  7361. tensor.__setstate__([storage, 0, obj.shape, strides]);
  7362. return tensor;
  7363. });
  7364. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  7365. const tensor = execution.invoke('torch.from_numpy', [data]);
  7366. // tensor = tensor.to(dtype, device)
  7367. tensor.requires_grad = requires_grad;
  7368. return tensor;
  7369. });
  7370. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  7371. const tensor = self.invoke('torch.Tensor', []);
  7372. tensor._layout = torch.sparse_coo;
  7373. tensor._indices = indices;
  7374. tensor._values = values;
  7375. tensor._shape = size;
  7376. return tensor;
  7377. });
  7378. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  7379. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  7380. });
  7381. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  7382. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  7383. const [, storage_type, , ,size] = storage;
  7384. storage = new storage_type(size);
  7385. }
  7386. const name = `${storage.__class__.__module__}.${storage.__class__.__name__.replace('Storage', 'Tensor')}`;
  7387. const tensor = self.invoke(name, []);
  7388. tensor.__setstate__([storage, storage_offset, size, stride]);
  7389. return tensor;
  7390. });
  7391. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks) => {
  7392. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, storage_offset, size, stride]);
  7393. tensor.requires_grad = requires_grad;
  7394. tensor.backward_hooks = backward_hooks;
  7395. return tensor;
  7396. });
  7397. this.registerFunction('torch._utils._rebuild_tensor_v3');
  7398. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  7399. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  7400. param.backward_hooks = backward_hooks;
  7401. return param;
  7402. });
  7403. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  7404. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  7405. param.backward_hooks = backward_hooks;
  7406. torch._utils._set_obj_state(param, state);
  7407. return param;
  7408. });
  7409. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  7410. const _set_obj_state = (obj, state) => {
  7411. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  7412. if (dict_state) {
  7413. for (const [k, v] of Object.entries(dict_state)) {
  7414. builtins.setattr(obj, k, v);
  7415. }
  7416. }
  7417. if (slots_state) {
  7418. for (const [k, v] of Object.entries(slots_state)) {
  7419. builtins.setattr(obj, k, v);
  7420. }
  7421. }
  7422. };
  7423. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  7424. param._backward_hooks = backward_hooks;
  7425. _set_obj_state(param, state);
  7426. return param;
  7427. });
  7428. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  7429. const tensor = execution.invoke('torch._utils._rebuild_tensor_v2', [storage, storage_offset, size, stride, requires_grad, backward_hooks]);
  7430. tensor.quantizer_params = quantizer_params;
  7431. return tensor;
  7432. });
  7433. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  7434. let dict_state = state;
  7435. let slots_state = null;
  7436. if (state instanceof self.builtins.tuple) {
  7437. if (state.length !== 2) {
  7438. throw new python.Error(`Invalid serialized state: '${state}'.`);
  7439. }
  7440. [dict_state, slots_state] = state;
  7441. }
  7442. if (dict_state) {
  7443. for (const [name, value] of Object.entries(dict_state)) {
  7444. builtins.setattr(obj, name, value);
  7445. }
  7446. }
  7447. if (slots_state) {
  7448. for (const [name, value] of Object.entries(slots_state)) {
  7449. builtins.setattr(obj, name, value);
  7450. }
  7451. }
  7452. return obj;
  7453. });
  7454. this.registerFunction('torch._set_item', (dict, key, value) => {
  7455. dict[key] = value;
  7456. });
  7457. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  7458. let ret = func(...args);
  7459. if (ret.__class__ !== new_type) {
  7460. // ret = ret.as_subclass(new_type);
  7461. }
  7462. const setstate = execution.invoke('builtins.getattr', [ret.__class__, '__setstate__', torch.Tensor.__setstate__]);
  7463. if (setstate === torch.Tensor.__setstate__) {
  7464. ret = execution.invoke('torch._utils._set_obj_state', [ret, state]);
  7465. } else {
  7466. ret.__setstate__(state);
  7467. }
  7468. return ret;
  7469. });
  7470. this.registerFunction('ops.aten.is_scripting', () => {
  7471. return true;
  7472. });
  7473. this.registerFunction('ops.aten.__and__', (left, right) => {
  7474. return left && right;
  7475. });
  7476. this.registerFunction('ops.aten.__contains__', (dict, key) => {
  7477. return builtins.hasattr(dict, key);
  7478. });
  7479. this.registerFunction('torch.__derive_index', (index, start, step) => {
  7480. return start + index * step;
  7481. });
  7482. this.registerFunction('ops.aten.__is__', (left, right) => {
  7483. return left === right;
  7484. });
  7485. this.registerFunction('ops.aten.__isnot__', (left, right) => {
  7486. return left !== right;
  7487. });
  7488. this.registerFunction('ops.aten.__not__', (value) => {
  7489. if (Number.isInteger(value)) {
  7490. value = Boolean(value);
  7491. }
  7492. if (typeof value === 'boolean') {
  7493. return !value;
  7494. }
  7495. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  7496. });
  7497. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  7498. if (step === 0) {
  7499. throw new python.Error('range() arg 3 must not be zero');
  7500. }
  7501. if (step > 0 && lo < hi) {
  7502. return 1 + (hi - 1 - lo) / step;
  7503. } else if (step < 0 && lo > hi) {
  7504. return 1 + (lo - 1 - hi) / (0 - step);
  7505. }
  7506. return 0;
  7507. });
  7508. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  7509. this.registerFunction('ops.aten._unwrap_optional', (value) => {
  7510. return value;
  7511. });
  7512. this.registerFunction('torch.get_default_dtype', () => {
  7513. torch._default_type = torch._default_type || torch.float32;
  7514. return torch._default_type;
  7515. });
  7516. this.registerFunction('torch.set_default_dtype', (value) => {
  7517. torch._default_type = value;
  7518. });
  7519. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  7520. return value || torch.get_default_dtype();
  7521. });
  7522. this.registerFunction('torch.empty_strided', (size, stride, dtype /*, layout, device, pin_memory, requires_grad */) => {
  7523. const shape = size;
  7524. dtype = torch._prims_common.dtype_or_default(dtype);
  7525. size = shape.reduce((a, b) => a * b, 1);
  7526. const storage = execution.invoke('torch.storage.TypedStorage', [size, dtype]);
  7527. const tensor = execution.invoke('torch.Tensor', []);
  7528. tensor.__setstate__([storage, 0, shape, stride]);
  7529. return tensor;
  7530. });
  7531. this.registerFunction('ops.aten.add', (left, right) => {
  7532. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7533. return left + right;
  7534. }
  7535. if (Array.isArray(left) && Array.isArray(right)) {
  7536. return left.concat(right);
  7537. }
  7538. if (typeof left === 'string' && typeof right === 'string') {
  7539. return left + right;
  7540. }
  7541. throw new python.Error('Unsupported ops.aten.add expression type.');
  7542. });
  7543. this.registerFunction('torch.all', (input) => {
  7544. if (Array.isArray(input) && input.length === 0) {
  7545. return true;
  7546. }
  7547. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  7548. });
  7549. this.registerFunction('torch.append', (list, value) => {
  7550. list.push(value);
  7551. return value;
  7552. });
  7553. this.registerFunction('torch.clear', (value) => {
  7554. if (value instanceof torch.Value) {
  7555. throw new python.Error('Invalid value.');
  7556. }
  7557. if (Object(value) === value) {
  7558. for (const key of Object.keys(value)) {
  7559. delete value[key];
  7560. }
  7561. }
  7562. });
  7563. this.registerFunction('ops.aten..cosine_similarity');
  7564. this.registerFunction('ops.aten..extend', (list, value) => {
  7565. list.push(...value);
  7566. });
  7567. this.registerFunction('ops.aten..insert', (list, index, value) => {
  7568. list.splice(index, 0, value);
  7569. return value;
  7570. });
  7571. this.registerFunction('ops.aten..replace', (value, oldvalue, newvalue /*, max */) => {
  7572. return value.replace(oldvalue, newvalue);
  7573. });
  7574. this.registerFunction('torch.dict', (args) => {
  7575. const obj = {};
  7576. if (args) {
  7577. if (Array.isArray(args)) {
  7578. for (const [key, value] of args) {
  7579. obj[key] = value;
  7580. }
  7581. } else {
  7582. throw new python.Error("'torch.dict' arguments not supported.");
  7583. }
  7584. }
  7585. return obj;
  7586. });
  7587. this.registerFunction('ops.aten..dim', (tensor) => {
  7588. if (tensor && tensor.size) {
  7589. const size = tensor.size();
  7590. if (size) {
  7591. return size.length;
  7592. }
  7593. }
  7594. return NaN;
  7595. });
  7596. this.registerFunction('ops.aten..numel', (tensor) => {
  7597. if (tensor && tensor.size) {
  7598. const size = tensor.size();
  7599. if (size) {
  7600. return size.reduce((a, b) => a * b, 1);
  7601. }
  7602. }
  7603. return NaN;
  7604. });
  7605. this.registerFunction('ops.aten.eq', (left, right) => {
  7606. if (typeof left === 'string' && typeof right === 'string') {
  7607. return left === right;
  7608. }
  7609. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7610. if (isNaN(left) && isNaN(right)) {
  7611. return true;
  7612. }
  7613. return left === right;
  7614. }
  7615. if (left === undefined || right === undefined) {
  7616. return true;
  7617. }
  7618. if (Array.isArray(left) && Array.isArray(right)) {
  7619. return left.length === right.length && left.every((item, index) => item === right[index]);
  7620. }
  7621. throw new python.Error("Unsupported 'torch.eq' expression type.");
  7622. });
  7623. this.registerFunction('ops.aten.floor', (value) => {
  7624. return Math.floor(value);
  7625. });
  7626. this.registerFunction('ops.aten.ceil', (value) => {
  7627. return Math.ceil(value);
  7628. });
  7629. this.registerFunction('ops.aten.floordiv', (left, right) => {
  7630. return Math.floor(left / right);
  7631. });
  7632. this.registerFunction('ops.aten..format', (...args) => {
  7633. const list = args.shift().split(/({}D?)/);
  7634. return list.map((text) => {
  7635. if (text === '{}' || text === '{}D') {
  7636. const arg = args.shift();
  7637. if (Array.isArray(arg)) {
  7638. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  7639. }
  7640. return arg ? arg.toString() : '?';
  7641. }
  7642. return text;
  7643. }).join('');
  7644. });
  7645. this.registerFunction('ops.aten.strip', (self, chars) => {
  7646. chars = chars || '\\n\\t\\f\\v';
  7647. const regex = new RegExp(`[${chars}]`, 'g');
  7648. return self.replace(regex, '');
  7649. });
  7650. this.registerFunction('ops.aten.gt', (left, right) => {
  7651. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7652. if (!isNaN(left) && !isNaN(right)) {
  7653. return left > right;
  7654. }
  7655. }
  7656. if (isNaN(left) && !isNaN(right)) {
  7657. return true;
  7658. }
  7659. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  7660. });
  7661. this.registerFunction('ops.aten.ge', (left, right) => {
  7662. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7663. if (!isNaN(left) && !isNaN(right)) {
  7664. return left > right;
  7665. }
  7666. }
  7667. if (isNaN(left) && !isNaN(right)) {
  7668. return true;
  7669. }
  7670. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  7671. });
  7672. this.registerFunction('ops.aten.is_floating_point', (tensor) => {
  7673. const type = tensor.dtype.scalar_type();
  7674. return (type === 5 || type === 6 || type === 7);
  7675. });
  7676. this.registerFunction('ops.aten.is_grad_enabled', () => {
  7677. return false;
  7678. });
  7679. this.registerFunction('ops.aten.is_autocast_enabled', () => {
  7680. return false;
  7681. });
  7682. this.registerFunction('ops.aten.isfinite');
  7683. this.registerFunction('ops.aten.set_grad_enabled', (/* value */) => {
  7684. });
  7685. this.registerFunction('torch.serialization._get_layout', (name) => {
  7686. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  7687. return value instanceof torch.layout ? value : null;
  7688. });
  7689. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  7690. return torch.load(b);
  7691. });
  7692. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  7693. return data;
  7694. });
  7695. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  7696. return data;
  7697. });
  7698. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  7699. return data;
  7700. });
  7701. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  7702. return data;
  7703. });
  7704. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  7705. return self.builtins.CONSTANTS[`c${data}`];
  7706. });
  7707. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  7708. return value;
  7709. });
  7710. this.registerFunction('ops.aten..keys', (dict) => {
  7711. return Object.keys(dict);
  7712. });
  7713. this.registerFunction('ops.aten..len', (value) => {
  7714. if (Array.isArray(value)) {
  7715. return value.length;
  7716. }
  7717. if (value && value.shape && value.__len__) {
  7718. return value.__len__();
  7719. }
  7720. return NaN;
  7721. });
  7722. this.registerFunction('ops.aten..le', (left, right) => {
  7723. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7724. if (isNaN(left) || isNaN(right)) {
  7725. return false;
  7726. }
  7727. return left <= right;
  7728. }
  7729. if (left === undefined || right === undefined) {
  7730. return true;
  7731. }
  7732. throw new python.Error("Unsupported 'torch.le' expression type.");
  7733. });
  7734. this.registerFunction('ops.aten..list', (args) => {
  7735. return args;
  7736. });
  7737. this.registerFunction('ops.aten..list_with_default', (size /*, defaults */) => {
  7738. return size;
  7739. });
  7740. this.registerType('torch.PyTorchFileReader', class {
  7741. constructor(entries) {
  7742. let prefix = 0;
  7743. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  7744. for (let set = new Set(); set && paths.length > 0;) {
  7745. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  7746. set = set.size > 1 || set.keys().next().value === null ? null : set;
  7747. prefix += set ? set.keys().next().value.length + 1 : 0;
  7748. }
  7749. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  7750. this._version = 0;
  7751. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  7752. if (stream) {
  7753. const decoder = new TextDecoder('utf-8');
  7754. const buffer = stream.peek();
  7755. const text = decoder.decode(buffer);
  7756. this._version = Number(text.split('\n').shift().trim());
  7757. }
  7758. }
  7759. has_record(name) {
  7760. return this._records.has(name);
  7761. }
  7762. get_record(name) {
  7763. return this._records.get(name);
  7764. }
  7765. get_all_records() {
  7766. return Array.from(this._records.keys());
  7767. }
  7768. version() {
  7769. return this._version;
  7770. }
  7771. });
  7772. this.registerFunction('torch.load', (f) => {
  7773. const legacy_load = (entries) => {
  7774. const deserialized_objects = {};
  7775. if (entries.has('storages')) {
  7776. const data = entries.get('storages');
  7777. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  7778. const num_storages = unpickler.load();
  7779. for (let i = 0; i < num_storages; i++) {
  7780. const args = unpickler.load();
  7781. const [key, , storage_type] = args;
  7782. const obj = storage_type._new_with_file(unpickler);
  7783. deserialized_objects[key] = obj;
  7784. }
  7785. /*
  7786. let storage_views = unpickler.load();
  7787. for target_cdata, root_cdata, offset, size in storage_views:
  7788. root = deserialized_objects[root_cdata]
  7789. deserialized_objects[target_cdata] = root[offset:offset + size]
  7790. */
  7791. }
  7792. if (entries.has('tensors')) {
  7793. const data = entries.get('tensors');
  7794. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  7795. const num_tensors = unpickler.load();
  7796. const int32 = (unpickler) => {
  7797. const buffer = unpickler.read(4);
  7798. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  7799. };
  7800. const int64 = (unpickler) => {
  7801. const buffer = unpickler.read(8);
  7802. if (buffer[6] !== 0 && buffer[7] !== 0) {
  7803. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  7804. }
  7805. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  7806. };
  7807. for (let i = 0; i < num_tensors; i++) {
  7808. const args = unpickler.load();
  7809. const [key, storage_id] = args;
  7810. const storage = deserialized_objects[storage_id];
  7811. const ndim = int32(unpickler);
  7812. unpickler.read(4);
  7813. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  7814. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  7815. const storage_offset = int64(unpickler);
  7816. const tensor = execution.invoke('torch._utils._rebuild_tensor', [storage, storage_offset, shape, stride]);
  7817. deserialized_objects[key] = tensor;
  7818. }
  7819. }
  7820. const data = entries.get('pickle');
  7821. const unpickler = execution.invoke('pickle.Unpickler', [data]);
  7822. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  7823. return unpickler.load();
  7824. };
  7825. const _legacy_load = () => {
  7826. const unpickler = execution.invoke('pickle.Unpickler', [f]);
  7827. unpickler.load(); // magic_number
  7828. const protocol_version = unpickler.load();
  7829. if (protocol_version !== 1001) {
  7830. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  7831. }
  7832. const sys_info = unpickler.load();
  7833. if (sys_info.get('protocol_version') !== 1001) {
  7834. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  7835. }
  7836. if (sys_info.get('little_endian') === false) {
  7837. throw new python.Error("Unsupported big-endian storage data.");
  7838. }
  7839. const module_source_map = new Map();
  7840. const deserialized_objects = new Map();
  7841. unpickler.persistent_load = (saved_id) => {
  7842. switch (saved_id[0]) {
  7843. case 'module': {
  7844. const [, module, ,source] = saved_id;
  7845. module_source_map.set(module, source);
  7846. return saved_id[1];
  7847. }
  7848. case 'storage': {
  7849. const [, storage_type, key, , size, view_metadata] = saved_id;
  7850. if (!deserialized_objects.has(key)) {
  7851. const obj = new storage_type(size);
  7852. deserialized_objects.set(key, obj);
  7853. }
  7854. if (view_metadata) {
  7855. const view_key = view_metadata.shift();
  7856. view_metadata.shift(); // view_offset
  7857. view_metadata.shift(); // view_size
  7858. if (!deserialized_objects.has(view_key)) {
  7859. const view = null; // storage.slice(view_offset, view_offset + view_size);
  7860. deserialized_objects.set(view_key, view);
  7861. }
  7862. return deserialized_objects.get(view_key);
  7863. }
  7864. return deserialized_objects.get(key);
  7865. }
  7866. default: {
  7867. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  7868. }
  7869. }
  7870. };
  7871. const obj = unpickler.load();
  7872. const deserialized_storage_keys = unpickler.load();
  7873. for (const deserialized_storage_key of deserialized_storage_keys) {
  7874. const storage = deserialized_objects.get(deserialized_storage_key);
  7875. storage._set_from_file(unpickler);
  7876. }
  7877. if (!obj) {
  7878. throw new python.Error('File format is not PyTorch.');
  7879. }
  7880. if (obj === 'None') {
  7881. throw new python.Error("File contains 'None' root object.");
  7882. }
  7883. return obj;
  7884. };
  7885. const _load = (entries) => {
  7886. if (f.has('constant.pkl')) {
  7887. throw python.Error("TorchScript 'torch.load' not supported.");
  7888. }
  7889. const loaded_storages = new Map();
  7890. const persistent_load = (saved_id) => {
  7891. switch (saved_id[0]) {
  7892. case 'storage': {
  7893. const [, storage_type, key, , numel] = saved_id;
  7894. if (!loaded_storages.has(key)) {
  7895. const storage = new storage_type(numel);
  7896. const name = `data/${key}`;
  7897. const stream = entries.get(name);
  7898. storage._set_cdata(stream);
  7899. loaded_storages.set(key, storage);
  7900. }
  7901. return loaded_storages.get(key);
  7902. }
  7903. default: {
  7904. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  7905. }
  7906. }
  7907. };
  7908. const data_file = entries.get('data.pkl');
  7909. const unpickler = execution.invoke('pickle.Unpickler', [data_file]);
  7910. unpickler.persistent_load = persistent_load;
  7911. const result = unpickler.load();
  7912. return result;
  7913. };
  7914. if (f instanceof Map) {
  7915. const reader = new torch.PyTorchFileReader(f);
  7916. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  7917. f = new Map(records);
  7918. if (f.has('pickle')) {
  7919. return legacy_load(f);
  7920. }
  7921. if (f.has('data.pkl')) {
  7922. return _load(f);
  7923. }
  7924. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  7925. }
  7926. return _legacy_load(f);
  7927. });
  7928. this.registerFunction('ops.aten.log10', (value) => {
  7929. return Math.log10(value);
  7930. });
  7931. this.registerFunction('ops.aten.device', (type, index) => {
  7932. return new torch.device(type, index);
  7933. });
  7934. this.registerFunction('ops.aten.lt', (left, right) => {
  7935. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7936. return left < right;
  7937. }
  7938. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  7939. });
  7940. this.registerFunction('ops.aten.mul', (left, right) => {
  7941. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7942. return left * right;
  7943. }
  7944. if (isNaN(left) || isNaN(right)) {
  7945. return NaN;
  7946. }
  7947. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7948. return left.map((value) => value * right);
  7949. }
  7950. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  7951. });
  7952. this.registerFunction('ops.aten.div', (left, right) => {
  7953. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7954. return left / right;
  7955. }
  7956. if (isNaN(left) || isNaN(right)) {
  7957. return NaN;
  7958. }
  7959. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  7960. });
  7961. this.registerFunction('torch.round', (value) => {
  7962. if (typeof value === 'number' || value instanceof Number) {
  7963. return Math.round(value);
  7964. }
  7965. if (isNaN(value)) {
  7966. return value;
  7967. }
  7968. throw new python.Error("Unsupported 'torch.round' expression type.");
  7969. });
  7970. this.registerFunction('ops.aten.remainder', (left, right) => {
  7971. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7972. return left % right;
  7973. }
  7974. if (isNaN(left) || isNaN(right)) {
  7975. return NaN;
  7976. }
  7977. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  7978. });
  7979. this.registerFunction('ops.aten.ne', (left, right) => {
  7980. if (typeof left === 'boolean' && typeof right === 'boolean') {
  7981. return left !== right;
  7982. }
  7983. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  7984. if (isNaN(left) || isNaN(right)) {
  7985. return false;
  7986. }
  7987. return left !== right;
  7988. }
  7989. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  7990. return false;
  7991. }
  7992. if (typeof left === 'string' && typeof right === 'string') {
  7993. return left !== right;
  7994. }
  7995. if (left === undefined || right === undefined) {
  7996. return true;
  7997. }
  7998. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  7999. });
  8000. this.registerFunction('ops.aten.neg', (value) => {
  8001. if (typeof value === 'number') {
  8002. return -value;
  8003. }
  8004. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  8005. });
  8006. this.registerFunction('ops.aten.pow', (left, right) => {
  8007. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8008. return Math.pow(left, right);
  8009. }
  8010. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  8011. });
  8012. this.registerFunction('torch.q_scale', (/* tensor */) => {
  8013. return -1;
  8014. });
  8015. this.registerFunction('torch.t', (tensor) => {
  8016. return tensor;
  8017. });
  8018. this.registerFunction('ops.aten.size', (tensor, dim) => {
  8019. if (tensor && tensor.size) {
  8020. const size = tensor.size();
  8021. if (Array.isArray(size)) {
  8022. if (dim === undefined) {
  8023. return size;
  8024. }
  8025. if (Number.isInteger(dim)) {
  8026. if (dim >= 0 && dim < size.length) {
  8027. return size[dim];
  8028. }
  8029. if (dim < 0 && -dim < size.length) {
  8030. return size[size.length + dim];
  8031. }
  8032. }
  8033. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  8034. }
  8035. }
  8036. if (Number.isInteger(dim)) {
  8037. return NaN;
  8038. }
  8039. return [];
  8040. });
  8041. this.registerFunction('ops.aten.sqrt', (x) => {
  8042. return Math.sqrt(x);
  8043. });
  8044. this.registerFunction('ops.aten.slice', (l, start, end, step) => {
  8045. if (!Array.isArray(l)) {
  8046. throw new python.Error('Slicing expected array');
  8047. }
  8048. step = step || 1;
  8049. if (step !== 1) {
  8050. throw new python.Error('Slicing only supports step=1');
  8051. }
  8052. start = Math.max(0, start >= 0 ? start : l.length + start);
  8053. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  8054. return l.slice(start, end);
  8055. });
  8056. this.registerFunction('ops.aten.sub', (left, right) => {
  8057. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  8058. return left - right;
  8059. }
  8060. throw new python.Error("Unsupported 'torch.sub' expression type.");
  8061. });
  8062. this.registerFunction('torch.sym_int');
  8063. this.registerFunction('torch.sym_ite');
  8064. this.registerFunction('torch.sym_max');
  8065. this.registerFunction('torch.sym_min');
  8066. this.registerFunction('torch.sym_not');
  8067. this.registerFunction('torch.sym_sqrt');
  8068. this.registerFunction('torch.sym_sqrt');
  8069. this.registerFunction('torch.functional.einsum');
  8070. this.registerFunction('torch.functional.norm');
  8071. this.registerFunction('torch.functional.split');
  8072. this.registerFunction('torch.nn.init.constant_');
  8073. this.registerFunction('torch.nn.init.normal_');
  8074. this.registerFunction('torch.nn.init.xavier_uniform_');
  8075. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  8076. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  8077. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  8078. this.registerFunction('torch.nn.functional.cross_entropy');
  8079. this.registerFunction('torch.nn.functional.elu');
  8080. this.registerFunction('torch.nn.functional.gelu');
  8081. this.registerFunction('torch.nn.functional.hardsigmoid');
  8082. this.registerFunction('torch.nn.functional.hardswish');
  8083. this.registerFunction('torch.nn.functional.hardtanh');
  8084. this.registerFunction('torch.nn.functional.interpolate');
  8085. this.registerFunction('torch.nn.functional.leaky_relu');
  8086. this.registerFunction('torch.nn.functional.l1_loss');
  8087. this.registerFunction('torch.nn.functional.linear');
  8088. this.registerFunction('torch.nn.functional.log_softmax');
  8089. this.registerFunction('torch.nn.functional._max_pool2d');
  8090. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  8091. this.registerFunction('torch.nn.functional.mse_loss');
  8092. this.registerFunction('torch.nn.functional.pad');
  8093. this.registerFunction('torch.nn.functional.relu');
  8094. this.registerFunction('torch.nn.functional.relu6');
  8095. this.registerFunction('torch.nn.functional.sigmoid');
  8096. this.registerFunction('torch.nn.functional.silu');
  8097. this.registerFunction('torch.nn.functional.softmax');
  8098. this.registerFunction('torch.nn.functional.tanh');
  8099. this.registerFunction('torch.values', (dict) => {
  8100. return Object.values(dict);
  8101. });
  8102. this.registerFunction('torch.warn', () => {
  8103. });
  8104. this.registerType('torch._ops.OperatorBase', class {
  8105. constructor() {
  8106. this.functorch_table = {};
  8107. }
  8108. });
  8109. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  8110. constructor(name, cacheable) {
  8111. super();
  8112. this._name = name;
  8113. this.__name__ = name;
  8114. // _higher_order_ops[name] = this;
  8115. this._ns = 'higher_order';
  8116. this.__module__ = 'torch.ops.higher_order';
  8117. this._cacheable = cacheable;
  8118. }
  8119. });
  8120. this.registerType('torch.Type', class {
  8121. constructor(kind, annotation_str) {
  8122. this._kind = kind;
  8123. if (annotation_str) {
  8124. this._annotation_str = annotation_str;
  8125. }
  8126. }
  8127. static get(kind, annotation_str) {
  8128. return new torch.Type(kind, annotation_str);
  8129. }
  8130. kind() {
  8131. return this._kind;
  8132. }
  8133. get annotation_str() {
  8134. return this._annotation_str;
  8135. }
  8136. equals(rhs) {
  8137. return this.kind() === rhs.kind();
  8138. }
  8139. isSubtypeOf(rhs) {
  8140. if (rhs.kind() === 'AnyType' || this === rhs) {
  8141. return true;
  8142. }
  8143. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  8144. return this.isSubtypeOf(rhs.getElementType());
  8145. }
  8146. if (rhs instanceof torch.UnionType) {
  8147. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  8148. }
  8149. if (rhs instanceof torch._C.DynamicType) {
  8150. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  8151. }
  8152. return this.equals(rhs);
  8153. }
  8154. containedTypes() {
  8155. return [];
  8156. }
  8157. withContained(contained_types) {
  8158. const current_contained = this.containedTypes();
  8159. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  8160. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  8161. return this;
  8162. }
  8163. return this.createWithContained(contained_types);
  8164. }
  8165. createWithContained(/* createWithContained */) {
  8166. throw new python.Error('Not implemented.');
  8167. }
  8168. isUnionType() {
  8169. return false;
  8170. }
  8171. hasFreeVariables() {
  8172. return false;
  8173. }
  8174. is_module() {
  8175. return false;
  8176. }
  8177. expect(type) {
  8178. torch._C.AT_ASSERT(this instanceof type);
  8179. return this;
  8180. }
  8181. str() {
  8182. if (this instanceof torch._C.VarType && this._annotation_str) {
  8183. return this._annotation_str;
  8184. } else if (this._kind === 'ScalarTypeType') {
  8185. return 'ScalarType';
  8186. } else if (this._kind === 'QSchemeType') {
  8187. return 'QScheme';
  8188. } else if (this._kind) {
  8189. return this._kind;
  8190. }
  8191. throw new python.Error(`Not implemented '${this.kind()}'.`);
  8192. }
  8193. __str__() {
  8194. return this.str();
  8195. }
  8196. toString() {
  8197. return this.__str__();
  8198. }
  8199. });
  8200. this.registerType('torch.ClassType', class extends torch.Type {
  8201. constructor(qualified_name, cu, is_module) {
  8202. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  8203. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  8204. this._is_module = is_module;
  8205. this._attributes = [];
  8206. this._attributeTypes = [];
  8207. this._methods = [];
  8208. this._staticmethods = new Map();
  8209. this._forward_hooks = [];
  8210. this._forward_pre_hooks = [];
  8211. this._properties = [];
  8212. this._constants = new Map();
  8213. }
  8214. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  8215. return new torch.ClassType(qualifiedName, cu, is_module);
  8216. }
  8217. qualified_name() {
  8218. return this.annotation_str;
  8219. }
  8220. name() {
  8221. return this._name;
  8222. }
  8223. is_module() {
  8224. return this._is_module;
  8225. }
  8226. is_parameter(slot) {
  8227. return this._attributes[slot].is_parameter === true;
  8228. }
  8229. is_buffer(slot) {
  8230. return this._attributes[slot].is_buffer === true;
  8231. }
  8232. addMethod(method) {
  8233. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  8234. this._methods.push(method);
  8235. }
  8236. findMethod(name) {
  8237. for (const method of this._methods) {
  8238. if (name === method.name()) {
  8239. return method;
  8240. }
  8241. }
  8242. return null;
  8243. }
  8244. getMethod(name) {
  8245. const method = this.findMethod(name);
  8246. if (!method) {
  8247. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  8248. }
  8249. return method;
  8250. }
  8251. methods() {
  8252. return this._methods;
  8253. }
  8254. addStaticMethod(func) {
  8255. this._staticmethods.set(func.name, func);
  8256. }
  8257. findStaticMethod(name) {
  8258. return this._staticmethods.get(name);
  8259. }
  8260. findHook(name) {
  8261. let hook = this.findForwardHook(name);
  8262. if (hook === null) {
  8263. hook = this.findForwardPreHook(name);
  8264. }
  8265. return hook;
  8266. }
  8267. findForwardHook(name) {
  8268. for (const hook of this._forward_hooks) {
  8269. if (name === hook.name()) {
  8270. return hook;
  8271. }
  8272. }
  8273. return null;
  8274. }
  8275. findForwardPreHook(name) {
  8276. for (const pre_hook of this._forward_pre_hooks) {
  8277. if (name === pre_hook.name()) {
  8278. return pre_hook;
  8279. }
  8280. }
  8281. return null;
  8282. }
  8283. numAttributes() {
  8284. return this._attributes.length;
  8285. }
  8286. addAttribute(name, type, is_parameter, is_buffer) {
  8287. is_parameter = is_parameter || false;
  8288. is_buffer = is_buffer || false;
  8289. const slot = this._attributes.length;
  8290. this._attributes.push({ name, type, is_parameter, is_buffer });
  8291. this._attributeTypes.push(type);
  8292. return slot;
  8293. }
  8294. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  8295. is_parameter = is_parameter || false;
  8296. is_buffer = is_buffer || false;
  8297. const slot_idx = this.findAttributeSlot(name);
  8298. if (slot_idx === null) {
  8299. return this.addAttribute(name, ty, is_parameter, is_buffer);
  8300. }
  8301. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  8302. // const TypePtr& atype = getAttribute(*slot_idx);
  8303. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  8304. return slot_idx;
  8305. }
  8306. findAttributeSlot(name) {
  8307. for (let pos = 0; pos < this._attributes.length; pos++) {
  8308. if (name === this._attributes[pos].name) {
  8309. return pos;
  8310. }
  8311. }
  8312. return null;
  8313. }
  8314. findAttribute(name) {
  8315. const slot = this.findAttributeSlot(name);
  8316. if (slot !== null) {
  8317. return this._attributes[slot].type;
  8318. }
  8319. return null;
  8320. }
  8321. hasAttribute(name) {
  8322. return this._attributes.find((attr) => attr.name === name);
  8323. }
  8324. getAttribute(arg) {
  8325. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  8326. return this._attributes[slot].type;
  8327. }
  8328. getAttributeName(slot) {
  8329. return this._attributes[slot].name;
  8330. }
  8331. addConstant(name, value) {
  8332. this._constants.set(name, value);
  8333. }
  8334. hasConstant(/* name */) {
  8335. }
  8336. getProperty(name) {
  8337. for (const prop of this._properties) {
  8338. if (name === prop.name) {
  8339. return prop;
  8340. }
  8341. }
  8342. return null;
  8343. }
  8344. containedTypes() {
  8345. return this._attributeTypes;
  8346. }
  8347. createWithContained(contained_types) {
  8348. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  8349. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  8350. for (let i = 0; i < this._attributes.length; i++) {
  8351. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  8352. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  8353. }
  8354. for (const method of this.methods()) {
  8355. ptr.addMethod(method);
  8356. }
  8357. return ptr;
  8358. }
  8359. str() {
  8360. return this.qualified_name();
  8361. }
  8362. });
  8363. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  8364. if (args.length === 1) {
  8365. const [to_flatten] = args;
  8366. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  8367. const to_fill = [];
  8368. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  8369. to_flatten.splice(0, to_flatten.length);
  8370. to_flatten.push(...to_fill);
  8371. } else if (args.length === 2) {
  8372. const [reference, to_fill] = args;
  8373. for (const type of reference) {
  8374. torch._C.flattenUnion(type, to_fill);
  8375. }
  8376. torch._C.filterDuplicateSubtypes(to_fill);
  8377. torch._C.sortUnion(to_fill);
  8378. } else {
  8379. throw new python.Error('Not implemented.');
  8380. }
  8381. });
  8382. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  8383. if (type instanceof torch.UnionType) {
  8384. for (const inner of type.containedTypes()) {
  8385. torch._C.flattenUnion(inner, to_fill);
  8386. }
  8387. } else if (type instanceof torch.OptionalType) {
  8388. const inner = type.getElementType();
  8389. torch._C.flattenUnion(inner, to_fill);
  8390. to_fill.push(torch.NoneType.get());
  8391. } else if (type instanceof torch.NumberType) {
  8392. to_fill.push(torch.IntType.get());
  8393. to_fill.push(torch.FloatType.get());
  8394. to_fill.push(torch.ComplexType.get());
  8395. } else {
  8396. to_fill.push(type);
  8397. }
  8398. });
  8399. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  8400. if (types.length === 0) {
  8401. // return;
  8402. }
  8403. /*
  8404. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  8405. // We don't want nested Optionals. Also, prematurely unifying to
  8406. // `Optional` could prevent us from coalescing other types
  8407. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  8408. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  8409. return null;
  8410. } else {
  8411. return unifyTypes(t1, t2, default_to_union=false);
  8412. }
  8413. };
  8414. size_t end_idx = types->size()-1;
  8415. for (size_t i = types->size()-1; i > 0; --i) {
  8416. for (size_t j = std::min(i-1, end_idx); ; --j) {
  8417. std::optional<TypePtr> unified;
  8418. unified = get_supertype((*types)[i], (*types)[j]);
  8419. if (unified) {
  8420. (*types)[j] = *unified;
  8421. (*types)[i] = (*types)[end_idx];
  8422. --end_idx;
  8423. break;
  8424. }
  8425. if (j == 0) {
  8426. break;
  8427. }
  8428. }
  8429. }
  8430. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  8431. */
  8432. });
  8433. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  8434. /*
  8435. std::sort(types->begin(), types->end(),
  8436. [](const TypePtr& a, const TypePtr& b) -> bool {
  8437. if (a->kind() != b->kind()) {
  8438. return a->kind() < b->kind();
  8439. }
  8440. return a->str() < b->str();
  8441. });
  8442. */
  8443. });
  8444. this.registerType('torch.UnionType', class extends torch.Type {
  8445. constructor(reference, kind) {
  8446. super(kind || 'UnionType');
  8447. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  8448. this._types = [];
  8449. torch._C.standardizeVectorForUnion(reference, this._types);
  8450. if (this._types.length === 1) {
  8451. throw new python.Error('Invalid union type reference.');
  8452. }
  8453. this._can_hold_none = false;
  8454. this._has_free_variables = false;
  8455. for (const type of this._types) {
  8456. if (type instanceof torch.NoneType) {
  8457. this._can_hold_none = true;
  8458. }
  8459. if (type.hasFreeVariables()) {
  8460. this._has_free_variables = true;
  8461. }
  8462. }
  8463. }
  8464. static create(reference) {
  8465. const union_type = new torch.UnionType(reference);
  8466. /*
  8467. bool int_found = false;
  8468. bool float_found = false;
  8469. bool complex_found = false;
  8470. bool nonetype_found = false;
  8471. const update_is_opt_flags = [&](const TypePtr& t) {
  8472. if (t == IntType::get()) {
  8473. int_found = true;
  8474. } else if (t == FloatType::get()) {
  8475. float_found = true;
  8476. } else if (t == ComplexType::get()) {
  8477. complex_found = true;
  8478. } else if (t == NoneType::get()) {
  8479. nonetype_found = true;
  8480. }
  8481. };
  8482. for (const auto& t : union_type->containedTypes()) {
  8483. update_is_opt_flags(t);
  8484. }
  8485. bool numbertype_found = int_found && float_found && complex_found;
  8486. if (nonetype_found) {
  8487. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  8488. return OptionalType::create(NumberType::get());
  8489. }
  8490. if (union_type->containedTypes().size() == 2) {
  8491. const not_none = union_type->containedTypes()[0] != NoneType::get()
  8492. ? union_type->containedTypes()[0]
  8493. : union_type->containedTypes()[1];
  8494. return OptionalType::create(not_none);
  8495. }
  8496. }
  8497. */
  8498. return union_type;
  8499. }
  8500. containedTypes() {
  8501. return this._types;
  8502. }
  8503. isUnionType() {
  8504. return true;
  8505. }
  8506. hasFreeVariables() {
  8507. return this._has_free_variables;
  8508. }
  8509. equals(rhs) {
  8510. if (rhs instanceof torch.UnionType) {
  8511. if (rhs.containedTypes().length !== this.containedTypes().length) {
  8512. return false;
  8513. }
  8514. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  8515. } else if (rhs instanceof torch.OptionalType) {
  8516. if (rhs.getElementType() === torch.NumberType.get()) {
  8517. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  8518. }
  8519. const optional_lhs = this.toOptional();
  8520. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  8521. } else if (rhs instanceof torch.NumberType) {
  8522. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  8523. }
  8524. return false;
  8525. }
  8526. isSubtypeOf(rhs) {
  8527. const rhs_types = [];
  8528. if (rhs instanceof torch.UnionType) {
  8529. if (this.containedTypes() === rhs.containedTypes()) {
  8530. return true;
  8531. }
  8532. for (const typePtr of rhs.containedTypes()) {
  8533. rhs_types.push(typePtr);
  8534. }
  8535. } else if (rhs instanceof torch.OptionalType) {
  8536. rhs_types.push(torch.NoneType.get());
  8537. if (rhs.getElementType() === torch.NumberType.get()) {
  8538. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  8539. rhs_types.push(...number_types);
  8540. } else {
  8541. rhs_types.push(rhs.getElementType());
  8542. }
  8543. } else if (rhs instanceof torch.NumberType) {
  8544. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  8545. rhs_types.push(...number_types);
  8546. } else {
  8547. rhs_types.push(rhs);
  8548. }
  8549. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  8550. }
  8551. });
  8552. this.registerType('torch.OptionalType', class extends torch.UnionType {
  8553. constructor(contained) {
  8554. super([contained, torch.NoneType.get()], 'OptionalType');
  8555. let is_numbertype = false;
  8556. if (contained instanceof torch.UnionType) {
  8557. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  8558. }
  8559. if (super.containedTypes().length === 2) {
  8560. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  8561. } else if (contained === torch.NumberType.get() || is_numbertype) {
  8562. this._contained = torch.NumberType.get();
  8563. this._types.splice(0, this._types.length);
  8564. this._types.push(torch.NumberType.get());
  8565. this._types.push(torch.NoneType.get());
  8566. } else {
  8567. const to_subtract = [torch.NoneType.get()];
  8568. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  8569. this._contained = torch.UnionType.create([without_none]);
  8570. }
  8571. this._has_free_variables = contained.hasFreeVariables();
  8572. }
  8573. static create(elem) {
  8574. return new torch.OptionalType(elem);
  8575. }
  8576. getElementType() {
  8577. return this._contained;
  8578. }
  8579. equals(rhs) {
  8580. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  8581. }
  8582. isSubtypeOf(rhs) {
  8583. if (rhs instanceof torch.OptionalType) {
  8584. return this.getElementType().isSubtypeOf(rhs.getElementType());
  8585. } else if (rhs instanceof torch.UnionType) {
  8586. throw new python.Error('Not implemented.');
  8587. }
  8588. // return super.isSubtypeOf(rhs);
  8589. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  8590. }
  8591. containedTypes() {
  8592. return [this._contained];
  8593. }
  8594. createWithContained(contained_types) {
  8595. torch._C.AT_ASSERT(contained_types.length === 1);
  8596. return torch.OptionalType.create(contained_types[0]);
  8597. }
  8598. subtractTypeSetFrom(to_subtract, from) {
  8599. const types = [];
  8600. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  8601. for (const t of from) {
  8602. if (!should_subtract(t)) {
  8603. types.push(t);
  8604. }
  8605. }
  8606. if (types.length === 0) {
  8607. return null;
  8608. } else if (types.length === 1) {
  8609. return types[0];
  8610. }
  8611. return torch.UnionType.create(types);
  8612. }
  8613. str() {
  8614. return `${this.getElementType().str()}?`;
  8615. }
  8616. __str__() {
  8617. return `Optional[${this.getElementType().__str__()}]`;
  8618. }
  8619. });
  8620. this.registerType('torch.ListType', class extends torch.Type {
  8621. constructor(elem) {
  8622. super('ListType');
  8623. this._elem = elem;
  8624. }
  8625. static create(elem) {
  8626. return new torch.ListType(elem);
  8627. }
  8628. getElementType() {
  8629. return this._elem;
  8630. }
  8631. equals(rhs) {
  8632. if (rhs instanceof torch.ListType) {
  8633. return this.getElementType().equals(rhs.getElementType());
  8634. }
  8635. return false;
  8636. }
  8637. isSubtypeOf(rhs) {
  8638. if (super.isSubtypeOf(rhs)) {
  8639. return true;
  8640. }
  8641. if (rhs.kind() === 'AnyListType') {
  8642. return true;
  8643. }
  8644. return false;
  8645. }
  8646. containedTypes() {
  8647. return [this._elem];
  8648. }
  8649. createWithContained(contained_types) {
  8650. return new torch.ListType(contained_types[0]);
  8651. }
  8652. hasFreeVariables() {
  8653. return this.getElementType().hasFreeVariables();
  8654. }
  8655. str() {
  8656. return `${this.getElementType().str()}[]`;
  8657. }
  8658. __str__() {
  8659. return `List[${this.getElementType().__str__()}]`;
  8660. }
  8661. });
  8662. this.registerType('torch.FutureType', class extends torch.Type {
  8663. constructor(elem) {
  8664. super('FutureType');
  8665. this._elem = elem;
  8666. }
  8667. static get(elem) {
  8668. return new torch.FutureType(elem);
  8669. }
  8670. getElementType() {
  8671. return this._elem;
  8672. }
  8673. containedTypes() {
  8674. throw new python.Error('Not implemented.');
  8675. }
  8676. str() {
  8677. return `Future(${this.getElementType().str()})`;
  8678. }
  8679. __str__() {
  8680. return `Future[${this.getElementType().__str__()}]`;
  8681. }
  8682. });
  8683. this.registerType('torch.RRefType', class extends torch.Type {
  8684. constructor(elem) {
  8685. super('RRefType');
  8686. this._elem = elem;
  8687. }
  8688. get(elem) {
  8689. return new torch.RRefType(elem);
  8690. }
  8691. getElementType() {
  8692. return this._elem;
  8693. }
  8694. containedTypes() {
  8695. throw new python.Error('Not implemented.');
  8696. }
  8697. str() {
  8698. return `RRef(${this.getElementType().str()})`;
  8699. }
  8700. __str__() {
  8701. return `RRef[${this.getElementType().__str__()}]`;
  8702. }
  8703. });
  8704. this.registerType('torch.AwaitType', class extends torch.Type {
  8705. constructor(elem) {
  8706. super('AwaitType');
  8707. this._elem = elem;
  8708. }
  8709. static get(elem) {
  8710. return new torch.AwaitType(elem);
  8711. }
  8712. getElementType() {
  8713. return this._elem;
  8714. }
  8715. containedTypes() {
  8716. throw new python.Error('Not implemented.');
  8717. }
  8718. str() {
  8719. return `Await(${this.getElementType().str()})`;
  8720. }
  8721. __str__() {
  8722. return `Await[${this.getElementType().__str__()}]`;
  8723. }
  8724. });
  8725. this.registerType('torch.TupleType', class extends torch.Type {
  8726. constructor(elements, annotation_str, schema) {
  8727. super('TupleType', annotation_str);
  8728. this._elements = elements;
  8729. this._has_free_variables = elements.some((v) => {
  8730. if (!v) {
  8731. throw new python.Error('Can not create tuple with None type');
  8732. }
  8733. return v.hasFreeVariables();
  8734. });
  8735. this._schema = schema;
  8736. }
  8737. static create(elements) {
  8738. return new torch.TupleType(elements, null, null);
  8739. }
  8740. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  8741. const args = [];
  8742. for (let i = 0; i < field_names.length; i++) {
  8743. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  8744. args.push(arg);
  8745. }
  8746. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  8747. return new torch.TupleType(field_types, qualified_name, schema);
  8748. }
  8749. elements() {
  8750. return this._elements;
  8751. }
  8752. name() {
  8753. return this.annotation_str;
  8754. }
  8755. containedTypes() {
  8756. return this._elements;
  8757. }
  8758. createWithContained(createWithContained) {
  8759. return new torch.TupleType(createWithContained, this.name(), this.schema());
  8760. }
  8761. hasFreeVariables() {
  8762. return this._has_free_variables;
  8763. }
  8764. schema() {
  8765. return this._schema;
  8766. }
  8767. str() {
  8768. if (this._schema) {
  8769. return `NamedTuple(...)`;
  8770. }
  8771. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  8772. }
  8773. __str__() {
  8774. if (this.annotation_str) {
  8775. return this.annotation_str;
  8776. }
  8777. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  8778. }
  8779. });
  8780. this.registerType('torch.AnyType', class extends torch.Type {
  8781. constructor() {
  8782. super('AnyType');
  8783. }
  8784. static get() {
  8785. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  8786. return torch.AnyType.value;
  8787. }
  8788. str() {
  8789. return 'Any';
  8790. }
  8791. __str__() {
  8792. return 'Any';
  8793. }
  8794. });
  8795. this.registerType('torch.NoneType', class extends torch.Type {
  8796. constructor() {
  8797. super('NoneType');
  8798. }
  8799. static get() {
  8800. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  8801. return torch.NoneType.value;
  8802. }
  8803. equals(rhs) {
  8804. return this.kind() === rhs.kind();
  8805. }
  8806. isSubtypeOf(rhs) {
  8807. if (rhs.kind() === 'OptionalType') {
  8808. return true;
  8809. }
  8810. return super.isSubtypeOf(rhs);
  8811. }
  8812. str() {
  8813. return 'NoneType';
  8814. }
  8815. __str__() {
  8816. return 'NoneType';
  8817. }
  8818. });
  8819. this.registerType('torch.TensorType', class extends torch.Type {
  8820. constructor() {
  8821. super('TensorType');
  8822. this._is_inferred = false;
  8823. }
  8824. static get() {
  8825. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  8826. return torch.TensorType.value;
  8827. }
  8828. equals(rhs) {
  8829. return this.kind() === rhs.kind();
  8830. }
  8831. isInferredType() {
  8832. return this._is_inferred;
  8833. }
  8834. str() {
  8835. return 'Tensor';
  8836. }
  8837. __str__() {
  8838. return 'Tensor';
  8839. }
  8840. });
  8841. this.registerType('torch.NumberType', class extends torch.Type {
  8842. constructor() {
  8843. super('NumberType');
  8844. }
  8845. static get() {
  8846. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  8847. return torch.NumberType.value;
  8848. }
  8849. str() {
  8850. return 'Scalar';
  8851. }
  8852. __str__() {
  8853. return 'number';
  8854. }
  8855. });
  8856. this.registerType('torch.BoolType', class extends torch.Type {
  8857. constructor() {
  8858. super('BoolType');
  8859. }
  8860. static get() {
  8861. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  8862. return torch.BoolType.value;
  8863. }
  8864. equals(rhs) {
  8865. return this.kind() === rhs.kind();
  8866. }
  8867. str() {
  8868. return 'bool';
  8869. }
  8870. __str__() {
  8871. return 'bool';
  8872. }
  8873. });
  8874. this.registerType('torch.IntType', class extends torch.Type {
  8875. constructor() {
  8876. super('IntType');
  8877. }
  8878. static get() {
  8879. torch.IntType.value = torch.IntType.value || new torch.IntType();
  8880. return torch.IntType.value;
  8881. }
  8882. equals(rhs) {
  8883. return this.kind() === rhs.kind();
  8884. }
  8885. isSubtypeOf(rhs) {
  8886. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  8887. }
  8888. str() {
  8889. return 'int';
  8890. }
  8891. __str__() {
  8892. return 'int';
  8893. }
  8894. });
  8895. this.registerType('torch.SymIntType', class extends torch.Type {
  8896. constructor() {
  8897. super('SymIntType');
  8898. }
  8899. static get() {
  8900. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  8901. return torch.SymIntType.value;
  8902. }
  8903. equals(rhs) {
  8904. return this.kind() === rhs.kind();
  8905. }
  8906. str() {
  8907. return 'SymInt';
  8908. }
  8909. __str__() {
  8910. return 'int';
  8911. }
  8912. });
  8913. this.registerType('torch.FloatType', class extends torch.Type {
  8914. constructor() {
  8915. super('FloatType');
  8916. }
  8917. static get() {
  8918. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  8919. return torch.FloatType.value;
  8920. }
  8921. equals(rhs) {
  8922. return this.kind() === rhs.kind();
  8923. }
  8924. isSubtypeOf(rhs) {
  8925. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  8926. }
  8927. str() {
  8928. return 'float';
  8929. }
  8930. __str__() {
  8931. return 'float';
  8932. }
  8933. });
  8934. this.registerType('torch.StringType', class extends torch.Type {
  8935. constructor() {
  8936. super('StringType');
  8937. }
  8938. static get() {
  8939. torch.StringType.value = torch.StringType.value || new torch.StringType();
  8940. return torch.StringType.value;
  8941. }
  8942. equals(rhs) {
  8943. return this.kind() === rhs.kind();
  8944. }
  8945. str() {
  8946. return 'str';
  8947. }
  8948. __str__() {
  8949. return 'str';
  8950. }
  8951. });
  8952. this.registerType('torch.ComplexType', class extends torch.Type {
  8953. constructor() {
  8954. super('ComplexType');
  8955. }
  8956. static get() {
  8957. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  8958. return torch.ComplexType.value;
  8959. }
  8960. equals(rhs) {
  8961. return this.kind() === rhs.kind();
  8962. }
  8963. isSubtypeOf(rhs) {
  8964. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  8965. }
  8966. str() {
  8967. return 'complex';
  8968. }
  8969. __str__() {
  8970. return 'complex';
  8971. }
  8972. });
  8973. this.registerType('torch.DictType', class extends torch.Type {
  8974. constructor(key, value) {
  8975. super('DictType');
  8976. this.types = [key, value];
  8977. }
  8978. static create(key, value) {
  8979. let kind = key.kind();
  8980. if (key instanceof torch._C.DynamicType) {
  8981. kind = key.dynamicKind();
  8982. }
  8983. switch (kind) {
  8984. case 'AnyType':
  8985. case 'IntType':
  8986. case 'BoolType':
  8987. case 'FloatType':
  8988. case 'ComplexType':
  8989. case 'StringType':
  8990. case 'TensorType':
  8991. case 'DeviceObjType':
  8992. return new torch.DictType(key, value);
  8993. default:
  8994. throw new python.Error(`Invalid dict key type '${kind}'.`);
  8995. }
  8996. }
  8997. createWithContained(contained_types) {
  8998. if (contained_types.length !== 2) {
  8999. throw new python.Error('Expected 2 contained types.');
  9000. }
  9001. return torch.DictType.create(contained_types[0], contained_types[1]);
  9002. }
  9003. getKeyType() {
  9004. return this.types[0];
  9005. }
  9006. getValueType() {
  9007. return this.types[1];
  9008. }
  9009. hasFreeVariables() {
  9010. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  9011. }
  9012. containedTypes() {
  9013. return this.types;
  9014. }
  9015. equals(rhs) {
  9016. if (rhs instanceof torch.DictType) {
  9017. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  9018. }
  9019. return false;
  9020. }
  9021. str() {
  9022. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  9023. }
  9024. __str__() {
  9025. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  9026. }
  9027. });
  9028. this.registerType('torch.DeviceObjType', class extends torch.Type {
  9029. constructor() {
  9030. super('DeviceObjType');
  9031. }
  9032. static get() {
  9033. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  9034. return torch.DeviceObjType.value;
  9035. }
  9036. str() {
  9037. return 'Device';
  9038. }
  9039. __str__() {
  9040. return 'Device';
  9041. }
  9042. });
  9043. this.registerType('torch.StreamObjType', class extends torch.Type {
  9044. constructor() {
  9045. super('StreamObjType');
  9046. }
  9047. str() {
  9048. return 'Stream';
  9049. }
  9050. __str__() {
  9051. return 'Stream';
  9052. }
  9053. });
  9054. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  9055. constructor() {
  9056. super('GeneratorType');
  9057. }
  9058. static get() {
  9059. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  9060. return torch._C._GeneratorType.value;
  9061. }
  9062. str() {
  9063. return 'Generator';
  9064. }
  9065. __str__() {
  9066. return 'Generator';
  9067. }
  9068. });
  9069. this.registerType('torch.InterfaceType', class extends torch.Type {
  9070. constructor() {
  9071. super('InterfaceType');
  9072. }
  9073. });
  9074. this.registerType('torch._C.DynamicType', class extends torch.Type {
  9075. constructor() {
  9076. super('DynamicType');
  9077. }
  9078. });
  9079. this.registerType('torch._C.FunctionType', class extends torch.Type {
  9080. constructor(func) {
  9081. super('FunctionType');
  9082. this._func = func;
  9083. }
  9084. static create(func) {
  9085. return new torch._C.FunctionType(func);
  9086. }
  9087. function() {
  9088. return this._func;
  9089. }
  9090. });
  9091. this.registerType('torch._C.VarType', class extends torch.Type {
  9092. constructor(name) {
  9093. super('VarType', name);
  9094. }
  9095. static create(name) {
  9096. return new torch._C.VarType(name);
  9097. }
  9098. name() {
  9099. return this._annotation_str;
  9100. }
  9101. hasFreeVariables() {
  9102. return true;
  9103. }
  9104. });
  9105. this.registerType('torch._C.AliasInfo', class {
  9106. constructor() {
  9107. this.is_write = false;
  9108. this.before_set = [];
  9109. this.after_set = [];
  9110. this.containedTypes = [];
  9111. }
  9112. addBeforeSet(value) {
  9113. this.before_set.push(value);
  9114. }
  9115. addAfterSet(value) {
  9116. this.after_set.push(value);
  9117. }
  9118. addContainedType(alias_info) {
  9119. this.containedTypes.push(alias_info);
  9120. }
  9121. str() {
  9122. const list = ['('];
  9123. list.push(this.before_set.join('|'));
  9124. if (this.after_set.length > 0) {
  9125. list.push(' -> ');
  9126. list.push(this.after_set.join('|'));
  9127. }
  9128. if (this.is_write) {
  9129. list.push('!');
  9130. }
  9131. list.push(')');
  9132. return list.join('');
  9133. }
  9134. });
  9135. this.registerType('torch._C.Lexer', class {
  9136. constructor(buffer) {
  9137. this.buffer = buffer;
  9138. this.position = 0;
  9139. this.value = '';
  9140. this.next();
  9141. }
  9142. eat(kind) {
  9143. if (this.kind !== kind) {
  9144. return null;
  9145. }
  9146. const value = this.value;
  9147. this.next();
  9148. return value;
  9149. }
  9150. expect(kind) {
  9151. if (this.kind !== kind) {
  9152. throw new python.Error(`Unexpected '${this.kind}' instead of '${kind}'.`);
  9153. }
  9154. const value = this.value;
  9155. this.next();
  9156. return value;
  9157. }
  9158. whitespace(count) {
  9159. if (this.kind !== ' ') {
  9160. if (count > this.value.length) {
  9161. throw new python.Error();
  9162. }
  9163. return false;
  9164. }
  9165. this.next();
  9166. return true;
  9167. }
  9168. next() {
  9169. this.position += this.value.length;
  9170. let i = this.position;
  9171. if (i >= this.buffer.length) {
  9172. this.kind = '\0';
  9173. this.value = '';
  9174. } else if (this.buffer[i] === ' ') {
  9175. while (this.buffer[i] === ' ') {
  9176. i += 1;
  9177. }
  9178. this.kind = ' ';
  9179. this.value = this.buffer.slice(this.position, i);
  9180. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  9181. this.kind = '...';
  9182. this.value = '...';
  9183. } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  9184. this.kind = '[]';
  9185. this.value = '[]';
  9186. } 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] === '|') {
  9187. this.kind = this.buffer[i];
  9188. this.value = this.buffer[i];
  9189. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  9190. i += 1;
  9191. 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] === '_')) {
  9192. i += 1;
  9193. }
  9194. this.kind = 'id';
  9195. this.value = this.buffer.slice(this.position, i);
  9196. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  9197. this.kind = '->';
  9198. this.value = '->';
  9199. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  9200. i += 1;
  9201. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  9202. i += 1;
  9203. }
  9204. this.kind = '#';
  9205. this.value = this.buffer.slice(this.position, i);
  9206. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  9207. const quote = this.buffer[i];
  9208. i += 1;
  9209. while (i < this.buffer.length && this.buffer[i] !== quote) {
  9210. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  9211. }
  9212. i += 1;
  9213. this.kind = 'string';
  9214. this.value = this.buffer.slice(this.position, i);
  9215. } else {
  9216. throw new python.Error(`Unsupported token at '${this.position}'.`);
  9217. }
  9218. }
  9219. });
  9220. this.registerType('torch._C.SchemaTypeParser', class {
  9221. constructor(L, complete_tensor_types, allow_typevars) {
  9222. this.L = L;
  9223. this.complete_tensor_types = complete_tensor_types;
  9224. this._allow_typevars = allow_typevars;
  9225. }
  9226. parseType() {
  9227. const r = this.parseFakeAndRealType();
  9228. return { first: r[0], second: r[2] };
  9229. }
  9230. parseBaseType() {
  9231. const L = this.L;
  9232. const value = L.value;
  9233. L.next();
  9234. switch (value) {
  9235. case 'Tensor': return torch.TensorType.get();
  9236. case 'bool': return torch.BoolType.get();
  9237. case 'int': return torch.IntType.get();
  9238. case 'float': return torch.FloatType.get();
  9239. case 'complex': return torch.ComplexType.get();
  9240. case 'str': return torch.StringType.get();
  9241. case 'SymInt': return torch.SymIntType.get();
  9242. case 'Scalar': return torch.NumberType.get();
  9243. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  9244. case 'Device': return torch.DeviceObjType.get();
  9245. case 'Layout': return torch.Type.get('Layout');
  9246. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  9247. case 'Generator': return torch._C._GeneratorType.get();
  9248. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(value);
  9249. case 'Any': return torch.AnyType.get();
  9250. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  9251. case 'Dimname': return torch.StringType.get();
  9252. case 'QScheme': return torch.Type.get('QSchemeType');
  9253. case 'Stream': return torch.StreamObjType.get();
  9254. case 'Storage': return torch.Type.get('Storage');
  9255. case 'AnyClassType': return torch.Type.get('AnyClassType');
  9256. case 'NoneType': return torch.NoneType.get();
  9257. default: throw new python.Error(`Unsupported type '${value}'.`);
  9258. }
  9259. }
  9260. parseFakeAndRealType() {
  9261. const L = this.L;
  9262. let fake_value = null;
  9263. let real_value = null;
  9264. let alias_info = null;
  9265. if (L.eat('(')) {
  9266. const types = [];
  9267. L.whitespace(0);
  9268. while (!L.eat(')')) {
  9269. const r = this.parseType();
  9270. types.push(r.first);
  9271. if (alias_info && r.second) {
  9272. alias_info.addContainedType(r.second);
  9273. }
  9274. L.whitespace(0);
  9275. L.eat(',');
  9276. L.whitespace(0);
  9277. }
  9278. real_value = torch.TupleType.create(types);
  9279. fake_value = real_value;
  9280. } else if (L.value === 'Future') {
  9281. L.next();
  9282. L.expect('(');
  9283. const p = this.parseType();
  9284. const subtype = p.first;
  9285. // const subalias = p.second;
  9286. L.expect(')');
  9287. real_value = torch.FutureType.get(subtype);
  9288. fake_value = real_value;
  9289. } else if (L.value === 'Await') {
  9290. L.next();
  9291. L.expect('(');
  9292. const p = this.parseType();
  9293. const subtype = p.first;
  9294. // const subalias = p.second;
  9295. L.expect(')');
  9296. real_value = torch.AwaitType.get(subtype);
  9297. fake_value = real_value;
  9298. } else if (L.value === 'RRef') {
  9299. L.next();
  9300. L.expect('(');
  9301. const p = this.parseType();
  9302. const subtype = p.first;
  9303. // const subalias = p.second;
  9304. L.expect(')');
  9305. real_value = torch.RRefType.get(subtype);
  9306. fake_value = real_value;
  9307. } else if (L.value === 'Tensor') {
  9308. L.next();
  9309. real_value = torch.TensorType.get();
  9310. fake_value = real_value;
  9311. alias_info = this.parseAliasAnnotation();
  9312. } else if (L.value === 'Dict') {
  9313. L.next();
  9314. L.expect('(');
  9315. const key_type = this.parseType().first;
  9316. L.expect(',');
  9317. L.whitespace(0);
  9318. const value_type = this.parseType().first;
  9319. L.expect(')');
  9320. alias_info = this.parseAliasAnnotation();
  9321. real_value = torch.DictType.create(key_type, value_type);
  9322. fake_value = real_value;
  9323. } else if (L.eat('Union')) {
  9324. L.next();
  9325. L.expect('(');
  9326. const types = [];
  9327. types.push(this.parseType().first);
  9328. while (L.cur().kind !== ')') {
  9329. L.expect(',');
  9330. types.push(this.parseType().first);
  9331. }
  9332. L.expect(')');
  9333. alias_info = this.parseAliasAnnotation();
  9334. real_value = new torch.UnionType(types);
  9335. fake_value = real_value;
  9336. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  9337. fake_value = real_value = parseRefinedTensor();
  9338. alias_info = parseAliasAnnotation(); */
  9339. } else if (L.value === '__torch__') {
  9340. L.next();
  9341. L.expect('.');
  9342. const torch_tok = L.expect('id');
  9343. if (torch_tok !== 'torch') {
  9344. throw new python.Error('Expected classes namespace.');
  9345. }
  9346. L.expect('.');
  9347. const classes_tok = L.expect('id');
  9348. if (classes_tok !== 'classes') {
  9349. throw new python.Error('Expected classes namespace.');
  9350. }
  9351. L.expect('.');
  9352. const ns_tok = L.expect('id');
  9353. L.expect('.');
  9354. const class_tok = L.expect('id');
  9355. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok}.${class_tok}`);
  9356. fake_value = real_value;
  9357. if (!fake_value) {
  9358. throw new python.Error(`Unknown custom class type '${ns_tok}.${class_tok}'.`);
  9359. }
  9360. } else {
  9361. real_value = this.parseBaseType();
  9362. fake_value = real_value;
  9363. if (real_value.kind() === 'ScalarTypeType' ||
  9364. real_value.kind() === 'MemoryFormat' ||
  9365. real_value.kind() === 'Layout' ||
  9366. real_value.kind() === 'SymIntType') {
  9367. fake_value = torch.IntType.get();
  9368. }
  9369. alias_info = this.parseAliasAnnotation();
  9370. }
  9371. while (true) {
  9372. if (L.kind === '[]') {
  9373. L.expect('[]');
  9374. fake_value = torch.ListType.create(fake_value);
  9375. real_value = torch.ListType.create(real_value);
  9376. let container = this.parseAliasAnnotation();
  9377. if (alias_info) {
  9378. if (!container) {
  9379. container = new torch._C.AliasInfo();
  9380. container.is_write = alias_info.is_write;
  9381. }
  9382. container.addContainedType(alias_info);
  9383. }
  9384. alias_info = container;
  9385. } else if (L.eat('?')) {
  9386. fake_value = torch.OptionalType.create(fake_value);
  9387. real_value = torch.OptionalType.create(real_value);
  9388. } else {
  9389. break;
  9390. }
  9391. }
  9392. return [fake_value, real_value, alias_info];
  9393. }
  9394. parseAliasAnnotation() {
  9395. const L = this.L;
  9396. let alias_info = null;
  9397. if (L.eat('(')) {
  9398. alias_info = new torch._C.AliasInfo();
  9399. do {
  9400. alias_info.addBeforeSet(L.value);
  9401. L.next();
  9402. if (L.eat('!')) {
  9403. alias_info.is_write = true;
  9404. }
  9405. L.whitespace(0);
  9406. }
  9407. while (L.eat('|'));
  9408. if (L.eat('->')) {
  9409. L.whitespace(0);
  9410. do {
  9411. alias_info.addAfterSet(L.value);
  9412. L.next();
  9413. L.whitespace(0);
  9414. }
  9415. while (L.eat('|'));
  9416. }
  9417. L.expect(')');
  9418. }
  9419. return alias_info;
  9420. }
  9421. });
  9422. this.registerType('torch.Argument', class {
  9423. constructor(...args) {
  9424. // torch/aten/src/ATen/core/function_schema.h
  9425. this.N = null;
  9426. this.default_value = null;
  9427. this.kwarg_only = false;
  9428. this.alias_info = null;
  9429. if (args.length === 2) {
  9430. [this.name, this.type] = args;
  9431. this.real_type = this.type;
  9432. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  9433. [this.name, this.type, this.real_type] = args;
  9434. } else if (args.length === 6) {
  9435. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  9436. } else if (args.length === 7) {
  9437. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  9438. } else {
  9439. throw new python.Error('Invalid arguments.');
  9440. }
  9441. const is_alias = this.alias_info && this.alias_info.is_write;
  9442. this.is_out = this.kwarg_only && is_alias;
  9443. }
  9444. has_default_value() {
  9445. return this.default_value !== undefined;
  9446. }
  9447. is_inferred_type() {
  9448. if (this.type instanceof torch.TensorType) {
  9449. return this.type.isInferredType();
  9450. }
  9451. return false;
  9452. }
  9453. static parse(L, is_return, kwarg_only) {
  9454. const type_parser = new torch._C.SchemaTypeParser(L);
  9455. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  9456. L.whitespace(0);
  9457. let N = null;
  9458. if (L.eat('[')) {
  9459. fake_type = torch.ListType.create(fake_type);
  9460. real_type = torch.ListType.create(real_type);
  9461. if (L.kind === '#') {
  9462. N = Number(L.value);
  9463. L.next();
  9464. }
  9465. L.expect(']');
  9466. let container = type_parser.parseAliasAnnotation();
  9467. if (alias_info) {
  9468. if (!container) {
  9469. container = new torch._C.AliasInfo();
  9470. container.is_write = alias_info.is_write;
  9471. }
  9472. container.addContainedType(alias_info);
  9473. }
  9474. alias_info = container;
  9475. if (L.eat('?')) {
  9476. fake_type = torch.OptionalType.create(fake_type);
  9477. real_type = torch.OptionalType.create(real_type);
  9478. }
  9479. }
  9480. let name = null;
  9481. /* eslint-disable no-undef-init */
  9482. let default_value = undefined;
  9483. /* eslint-enable no-undef-init */
  9484. if (is_return) {
  9485. L.whitespace(0);
  9486. kwarg_only = false;
  9487. if (L.kind === 'id') {
  9488. name = L.expect('id');
  9489. }
  9490. } else {
  9491. L.whitespace(1);
  9492. name = L.expect('id');
  9493. L.whitespace(0);
  9494. if (L.eat('=')) {
  9495. L.whitespace(0);
  9496. default_value = torch.Argument._parse_value(L);
  9497. }
  9498. }
  9499. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  9500. }
  9501. static _parse_value(L) {
  9502. /* eslint-disable no-undef-init */
  9503. let value = undefined;
  9504. /* eslint-enable no-undef-init */
  9505. if (L.kind === 'id') {
  9506. if (L.value === 'True' || L.value === 'False') {
  9507. value = L.value === 'True';
  9508. } else if (L.value === 'None') {
  9509. value = null;
  9510. } else if (L.value === 'Mean' || L.value === 'contiguous_format' || L.value === 'long') {
  9511. value = L.value;
  9512. } else if (typeof L.value === 'string') {
  9513. value = L.value;
  9514. } else if (typeof L.value === 'number') {
  9515. value = L.value;
  9516. } else {
  9517. throw new python.Error(`Unsupported default value '${L.value}'.`);
  9518. }
  9519. } else if (L.kind === '#') {
  9520. value = Number(L.value);
  9521. } else if (L.kind === 'string') {
  9522. value = L.value.slice(1, -1);
  9523. } else if (L.kind === '[]') {
  9524. value = [];
  9525. } else if (L.eat('[')) {
  9526. value = [];
  9527. if (!L.eat(']')) {
  9528. while (true) {
  9529. L.whitespace(0);
  9530. value.push(torch.Argument._parse_value(L));
  9531. L.whitespace(0);
  9532. if (!L.eat(',')) {
  9533. break;
  9534. }
  9535. }
  9536. L.expect(']');
  9537. }
  9538. return value;
  9539. } else {
  9540. throw new python.Error(`Unsupported default value '${L.kind}'.`);
  9541. }
  9542. L.next();
  9543. return value;
  9544. }
  9545. str() {
  9546. const list = [];
  9547. const type = this.real_type;
  9548. const is_opt = type instanceof torch.OptionalType;
  9549. const unopt_type = is_opt ? type.getElementType() : type;
  9550. if (unopt_type instanceof torch.ListType) {
  9551. list.push(unopt_type.getElementType().str());
  9552. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  9553. list.push(this.alias_info.containedTypes[0].str());
  9554. }
  9555. list.push(this.N === null ? `[]` : `[${this.N}]`);
  9556. } else {
  9557. list.push(unopt_type.str());
  9558. }
  9559. if (this.alias_info && this.alias_info.before_set.length > 0) {
  9560. list.push(this.alias_info.str());
  9561. }
  9562. if (is_opt) {
  9563. list.push('?');
  9564. }
  9565. if (this.name) {
  9566. list.push(' ');
  9567. list.push(this.name);
  9568. }
  9569. if (this.default_value !== undefined) {
  9570. const value = this.default_value;
  9571. if (value === null) {
  9572. list.push('=None');
  9573. } else if (typeof value === 'boolean') {
  9574. list.push('=');
  9575. list.push(value ? 'True' : 'False');
  9576. } else if (typeof value === 'string') {
  9577. list.push(`="${value}"`);
  9578. } else if (typeof value === 'number') {
  9579. list.push(`=${value}`);
  9580. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  9581. list.push(`.`);
  9582. }
  9583. } else if (Array.isArray(value)) {
  9584. list.push(`=[${value.join(', ')}]`);
  9585. }
  9586. }
  9587. return list.join('');
  9588. }
  9589. });
  9590. this.registerType('torch._C.SchemaParser', class {
  9591. constructor(str, allow_typevars) {
  9592. this.L = new torch._C.Lexer(str);
  9593. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  9594. }
  9595. parseName() {
  9596. const L = this.L;
  9597. let name = L.expect('id').text();
  9598. if (L.nextIf(':')) {
  9599. L.expect(':');
  9600. name = `${name}::${L.expect('ident').text()}`;
  9601. }
  9602. let overload_name = '';
  9603. if (L.nextIf('.')) {
  9604. overload_name = L.expect('ident').text();
  9605. }
  9606. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  9607. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  9608. return new torch._C.OperatorName(name, overload_name);
  9609. }
  9610. parseDeclaration() {
  9611. const L = this.L;
  9612. const name = this.parseName();
  9613. if (L.cur().kind !== '(') {
  9614. return name;
  9615. }
  9616. throw new python.Error('Not implemented.');
  9617. }
  9618. parseExactlyOneDeclaration() {
  9619. // const L = this.L;
  9620. const result = this.parseDeclaration();
  9621. // L.nextIf(TK_NEWLINE);
  9622. // L.expect(TK_EOF);
  9623. return result;
  9624. }
  9625. parseArgument() {
  9626. throw new python.Error('Not implemented.');
  9627. }
  9628. });
  9629. this.registerType('torch.FunctionSchema', class {
  9630. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  9631. const index = name.indexOf('(');
  9632. if (index === -1) {
  9633. this._name = name;
  9634. this._overload_name = overload_name || '';
  9635. this._arguments = args || [];
  9636. this._returns = returns || [];
  9637. this._is_vararg = is_vararg || false;
  9638. this._is_varret = is_varret || false;
  9639. } else {
  9640. const value = name.substring(0, index).trim();
  9641. const dot = value.indexOf('.');
  9642. if (dot === -1) {
  9643. this._name = value;
  9644. this._overload_name = '';
  9645. } else {
  9646. this._name = value.substring(0, dot);
  9647. this._overload_name = value.substring(dot + 1, value.length);
  9648. }
  9649. this._buffer = name.substring(index, name.length);
  9650. }
  9651. }
  9652. static parse(schema) {
  9653. return new torch.FunctionSchema(schema);
  9654. }
  9655. get name() {
  9656. return this._name;
  9657. }
  9658. get overload_name() {
  9659. return this._overload_name;
  9660. }
  9661. get arguments() {
  9662. this._parse();
  9663. return this._arguments;
  9664. }
  9665. get returns() {
  9666. this._parse();
  9667. return this._returns;
  9668. }
  9669. get is_vararg() {
  9670. this._parse();
  9671. return this._is_vararg;
  9672. }
  9673. get is_varret() {
  9674. this._parse();
  9675. return this._is_varret;
  9676. }
  9677. _parse() {
  9678. if (this._buffer) {
  9679. const L = new torch._C.Lexer(this._buffer);
  9680. this._arguments = [];
  9681. this._is_vararg = false;
  9682. this._kwarg_only = false;
  9683. L.expect('(');
  9684. if (!L.eat(')')) {
  9685. while (true) {
  9686. L.whitespace(0);
  9687. if (this._is_vararg) {
  9688. throw new python.Error();
  9689. }
  9690. if (L.eat('*')) {
  9691. this._kwarg_only = true;
  9692. } else if (L.eat('...')) {
  9693. this._is_vararg = true;
  9694. } else {
  9695. const argument = torch.Argument.parse(L, false, this._kwarg_only);
  9696. this._arguments.push(argument);
  9697. }
  9698. L.whitespace(0);
  9699. if (!L.eat(',')) {
  9700. break;
  9701. }
  9702. }
  9703. L.expect(')');
  9704. }
  9705. L.whitespace(0);
  9706. L.expect('->');
  9707. L.whitespace(0);
  9708. this._returns = [];
  9709. this._is_varret = false;
  9710. if (L.eat('...')) {
  9711. this._is_varret = true;
  9712. } else if (L.eat('(')) {
  9713. L.whitespace(0);
  9714. if (!L.eat(')')) {
  9715. while (true) {
  9716. L.whitespace(0);
  9717. if (this._is_varret) {
  9718. throw new python.Error();
  9719. }
  9720. if (L.eat('...')) {
  9721. this._is_varret = true;
  9722. } else {
  9723. const argument = torch.Argument.parse(L, true, false);
  9724. this._returns.push(argument);
  9725. }
  9726. L.whitespace(0);
  9727. if (!L.eat(',')) {
  9728. break;
  9729. }
  9730. }
  9731. L.expect(')');
  9732. }
  9733. L.whitespace(0);
  9734. } else {
  9735. this._returns.push(torch.Argument.parse(L, true, false));
  9736. }
  9737. delete this._buffer;
  9738. }
  9739. }
  9740. __str__() {
  9741. const list = [this.name];
  9742. const overload_name = this.overload_name;
  9743. if (overload_name !== '' && overload_name !== 'default') {
  9744. list.push(`.${this.overload_name}`);
  9745. }
  9746. list.push('(');
  9747. let first = true;
  9748. let kwarg_only = false;
  9749. for (const argument of this.arguments) {
  9750. if (!first) {
  9751. list.push(', ');
  9752. }
  9753. if (argument.kwarg_only && !kwarg_only) {
  9754. list.push('*, ');
  9755. kwarg_only = true;
  9756. }
  9757. first = false;
  9758. list.push(argument.str());
  9759. }
  9760. if (this.is_vararg) {
  9761. if (!first) {
  9762. list.push(', ');
  9763. }
  9764. first = true;
  9765. list.push('...');
  9766. }
  9767. list.push(') -> ');
  9768. const returns = this.returns;
  9769. const braces = !this.is_varret &&
  9770. (returns.length !== 1 ||
  9771. returns[0].name ||
  9772. returns[0].real_type instanceof torch.TupleType ||
  9773. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  9774. if (braces) {
  9775. list.push('(');
  9776. }
  9777. first = true;
  9778. for (const argument of this.returns) {
  9779. if (!first) {
  9780. list.push(', ');
  9781. }
  9782. first = false;
  9783. list.push(argument.str());
  9784. }
  9785. if (this.is_varret) {
  9786. if (!first) {
  9787. list.push(', ');
  9788. }
  9789. first = true;
  9790. list.push('...');
  9791. }
  9792. if (braces) {
  9793. list.push(')');
  9794. }
  9795. return list.join('');
  9796. }
  9797. aliasAnalysis() {
  9798. return this._alias_kind || 'CONSERVATIVE';
  9799. }
  9800. setAliasAnalysis(v) {
  9801. this._alias_kind = v;
  9802. }
  9803. hasAnyAliasInfo() {
  9804. for (const arg of this.arguments) {
  9805. if (arg.alias_info !== null) {
  9806. return true;
  9807. }
  9808. }
  9809. for (const ret of this.returns) {
  9810. if (ret.alias_info !== null) {
  9811. return true;
  9812. }
  9813. }
  9814. return false;
  9815. }
  9816. });
  9817. this.registerType('torch._C.SchemaInfo', class {
  9818. constructor(schema) {
  9819. this._schema = schema;
  9820. this._alias_maps_current = false;
  9821. this._has_init = false;
  9822. }
  9823. is_nondeterministic() {
  9824. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  9825. //
  9826. }
  9827. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  9828. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  9829. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  9830. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  9831. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  9832. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  9833. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  9834. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  9835. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  9836. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  9837. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  9838. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  9839. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  9840. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  9841. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  9842. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  9843. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  9844. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  9845. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  9846. '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',
  9847. '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',
  9848. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  9849. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  9850. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  9851. ]);
  9852. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  9853. return true;
  9854. }
  9855. /*
  9856. const auto& op = c10::Dispatcher::singleton().findOp(
  9857. c10::OperatorName(schema_.name(), schema_.overload_name()));
  9858. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  9859. */
  9860. return false;
  9861. }
  9862. });
  9863. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  9864. return new Map();
  9865. });
  9866. this.registerFunction('torch._C.string_to_type_lut', () => {
  9867. if (!torch._C.string_to_type_lut.basePythonTypes) {
  9868. const map = new Map();
  9869. map.set('Tensor', torch.TensorType.get());
  9870. map.set('int', torch.IntType.get());
  9871. map.set('float', torch.FloatType.get());
  9872. map.set('bool', torch.BoolType.get());
  9873. map.set('complex', torch.ComplexType.get());
  9874. map.set('str', torch.StringType.get());
  9875. map.set('Device', torch.DeviceObjType.get());
  9876. map.set('number', torch.NumberType.get());
  9877. map.set('None', torch.NoneType.get());
  9878. map.set('NoneType', torch.NoneType.get());
  9879. map.set('Any', torch.AnyType.get());
  9880. map.set('list', torch.Type.get('AnyListType'));
  9881. map.set('tuple', torch.Type.get('AnyTupleType'));
  9882. torch._C.string_to_type_lut.basePythonTypes = map;
  9883. }
  9884. return torch._C.string_to_type_lut.basePythonTypes;
  9885. });
  9886. this.registerType('torch._C.ScriptTypeParser', class {
  9887. constructor(resolver) {
  9888. this._resolver = resolver;
  9889. }
  9890. parseSchemaFromDef(def, skip_self) {
  9891. const name = def.name;
  9892. const args = this.parseArgsFromDecl(def, skip_self);
  9893. const returns = this.parseReturnFromDecl(def);
  9894. return new torch.FunctionSchema(name, '', args, returns, false, false);
  9895. }
  9896. parseArgsFromDecl(decl, skip_self) {
  9897. const retval = [];
  9898. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  9899. throw new python.Error('Unsupported function argument.');
  9900. }
  9901. const params = decl.args.args.slice();
  9902. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  9903. const start = skip_self ? 1 : 0;
  9904. for (let i = start; i < params.length; i++) {
  9905. const decl_arg = params[i];
  9906. const N = null;
  9907. const default_value = undefined;
  9908. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  9909. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  9910. retval.push(arg);
  9911. }
  9912. return retval;
  9913. }
  9914. parseReturnFromDecl(decl) {
  9915. if (!decl.returns) {
  9916. return [];
  9917. }
  9918. if (this.parseBroadcastList(decl.returns)) {
  9919. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  9920. }
  9921. const parsed_type = this.parseTypeFromExpr(decl.returns);
  9922. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  9923. }
  9924. parseTypeFromExpr(expr) {
  9925. if (this._resolver) {
  9926. if (expr instanceof ast.Name) {
  9927. const type = this._resolver.resolveType(expr.id);
  9928. if (type) {
  9929. return type;
  9930. }
  9931. }
  9932. }
  9933. return this.parseTypeFromExprImpl(expr);
  9934. }
  9935. parseTypeFromExprImpl(expr) {
  9936. if (expr instanceof ast.Subscript) {
  9937. const value_name = this.parseBaseTypeName(expr.value);
  9938. if (!value_name) {
  9939. throw new python.Error('Subscripted type must be a type identifier.');
  9940. }
  9941. return this.subscriptToType(value_name, expr);
  9942. }
  9943. const name = this.parseBaseTypeName(expr);
  9944. if (name) {
  9945. const itr = torch._C.string_to_type_lut().get(name);
  9946. if (itr) {
  9947. return itr;
  9948. }
  9949. if (this._resolver) {
  9950. const typePtr = this._resolver.resolveType(name, expr);
  9951. if (typePtr) {
  9952. return typePtr;
  9953. }
  9954. }
  9955. }
  9956. throw new python.Error(`Unknown type name '${name}'.`);
  9957. }
  9958. parseBaseTypeName(expr) {
  9959. if (expr instanceof ast.Name) {
  9960. return expr.id;
  9961. } else if (expr instanceof ast.Constant && expr.value === null) {
  9962. return 'None';
  9963. } else if (expr instanceof ast.Attribute) {
  9964. const name = expr.attr;
  9965. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  9966. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  9967. return name;
  9968. }
  9969. return torch._C.collectQualname(expr);
  9970. }
  9971. throw new python.Error('Unsupported type.');
  9972. }
  9973. parseBroadcastList(/* expr */) {
  9974. return null;
  9975. }
  9976. parseType(str) {
  9977. const expr = ast.parse(str);
  9978. return this.parseTypeFromExpr(expr.body[0].value);
  9979. }
  9980. subscriptToType(typeName, subscript) {
  9981. if (typeName === 'Tuple' || typeName === 'tuple') {
  9982. /*
  9983. if (subscript.slice.elts.length === 1 && subscript.slice.elts[0].kind() === TK_TUPLE_LITERAL) {
  9984. const tup_literal = null; // TupleLiteral(subscript.subscript_exprs()[0]);
  9985. if (!tup_literal.inputs().empty()) {
  9986. throw new python.Error('Tuple literal in Tuple type annotation must not have any elements.');
  9987. }
  9988. return torch.TupleType.create({});
  9989. }
  9990. */
  9991. const subscript_expr_types = [];
  9992. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  9993. for (const expr of elts) {
  9994. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  9995. }
  9996. return torch.TupleType.create(subscript_expr_types);
  9997. } else if (typeName === 'List' || typeName === 'list') {
  9998. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  9999. throw new python.Error('List type must have exactly one element type.');
  10000. }
  10001. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  10002. return torch.ListType.create(elem_type);
  10003. } else if (typeName === 'Optional') {
  10004. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  10005. throw new python.Error('Optional type must have exactly one element type.');
  10006. }
  10007. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  10008. return torch.OptionalType.create(elem_type);
  10009. } else if (typeName === 'Union') {
  10010. const subscript_expr_types = [];
  10011. for (const expr of subscript.slice.elts) {
  10012. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  10013. }
  10014. return torch.UnionType.create(subscript_expr_types);
  10015. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  10016. if (subscript.slice.elts.length !== 1) {
  10017. throw new python.Error('Future type must have exactly one element type.');
  10018. }
  10019. const elem_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10020. return torch.FutureType.create(elem_type);
  10021. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  10022. if (subscript.slice.elts.length !== 1) {
  10023. throw new python.Error('Await type must have exactly one element type.');
  10024. }
  10025. const elem_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10026. return torch.AwaitType.create(elem_type);
  10027. } else if (typeName === 'RRef') {
  10028. if (subscript.slice.elts.length !== 1) {
  10029. throw new python.Error('RRef type must have exactly one element type.');
  10030. }
  10031. const elem_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10032. return torch.RRefType.create(elem_type);
  10033. } else if (typeName === 'Dict' || typeName === 'dict') {
  10034. if (subscript.slice.elts.length !== 2) {
  10035. throw new python.Error('Dict type must have exactly two element types.');
  10036. }
  10037. const key_type = this.parseTypeFromExprImpl(subscript.slice.elts[0]);
  10038. const value_type = this.parseTypeFromExprImpl(subscript.slice.elts[1]);
  10039. return torch.DictType.create(key_type, value_type);
  10040. }
  10041. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  10042. }
  10043. });
  10044. this.registerFunction('torch._C.isTorch', (expr) => {
  10045. return expr instanceof ast.Name && expr.id === 'torch';
  10046. });
  10047. this.registerFunction('torch._C.collectQualname', (select) => {
  10048. const base = select.value;
  10049. if (base instanceof ast.Name) {
  10050. return `${base.id}.${select.attr}`;
  10051. }
  10052. const basename = torch._C.collectQualname(base);
  10053. return `${basename}.${select.attr}`;
  10054. });
  10055. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  10056. constructor(overloadpacket, op, op_dk, schema, tags) {
  10057. super();
  10058. this._op = op;
  10059. this._op_dk = op_dk;
  10060. this._schema = schema;
  10061. this._overloadpacket = overloadpacket;
  10062. this._tags = tags;
  10063. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  10064. this._name = this._schema.name;
  10065. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  10066. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  10067. this.__module__ = overloadpacket.__module__;
  10068. op.__module__ = overloadpacket.__module__;
  10069. this.__qualname__ = self._name;
  10070. this.__annotations__ = {};
  10071. // this._defined_in_python = this.__qualname__ in torch.library._defs
  10072. let is_write = null;
  10073. for (const a of this._schema.arguments) {
  10074. if (a.alias_info) {
  10075. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  10076. }
  10077. }
  10078. this.is_view = is_write !== null && !is_write;
  10079. }
  10080. get name() {
  10081. return this._name;
  10082. }
  10083. });
  10084. this.registerType('torch._ops.OpOverloadPacket', class {
  10085. constructor(qualified_op_name, op_name, op, overload_names) {
  10086. this._qualified_op_name = qualified_op_name;
  10087. this.__name__ = op_name;
  10088. this._op = op;
  10089. this._overload_names = overload_names;
  10090. this._dir = [];
  10091. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  10092. }
  10093. get _schemas() {
  10094. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  10095. }
  10096. __getattr__(key) {
  10097. key = key === 'default' ? '' : key;
  10098. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  10099. const [op_, op_dk_, tags] = op_dk_tags;
  10100. const schema = torch._C._get_schema(this._qualified_op_name, key);
  10101. const overload = this._has_script_object_arg(schema) ?
  10102. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  10103. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  10104. builtins.setattr(self, key, overload);
  10105. this._dir.push(key);
  10106. return overload;
  10107. }
  10108. _has_script_object_arg(/* schema */) {
  10109. return false;
  10110. // return any(isinstance(arg.type, torch.ClassType) for arg in schema.arguments)
  10111. }
  10112. });
  10113. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  10114. constructor(name) {
  10115. super(`torch.ops.${name}`);
  10116. this.name = name;
  10117. this._dir = [];
  10118. }
  10119. __getattr__(op_name) {
  10120. const namespace_name = this.name;
  10121. const qualified_op_name = `${namespace_name}::${op_name}`;
  10122. const module_name = `${this.__module__}.${namespace_name}`;
  10123. let op = null;
  10124. let overload_names = null;
  10125. try {
  10126. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  10127. } catch {
  10128. // continue regardless of error
  10129. }
  10130. if (!op) {
  10131. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  10132. }
  10133. op.__module__ = module_name;
  10134. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  10135. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  10136. builtins.setattr(this, op_name, opoverloadpacket);
  10137. this._dir.push(op_name);
  10138. return opoverloadpacket;
  10139. }
  10140. _get_packet(qualname, op_module) {
  10141. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  10142. if (op) {
  10143. // torch.jit._builtins._register_builtin(op, qualname);
  10144. }
  10145. op.__module__ = op_module;
  10146. return [op, overload_names];
  10147. }
  10148. });
  10149. this.registerType('torch._C.graph_node_list', class {
  10150. constructor(head) {
  10151. this.head = head;
  10152. }
  10153. front() {
  10154. return this.head.next;
  10155. }
  10156. end() {
  10157. return this.head.prev;
  10158. }
  10159. [Symbol.iterator]() {
  10160. let current = this.head.next;
  10161. const prev = this.head.prev;
  10162. return {
  10163. next() {
  10164. if (current !== prev) {
  10165. const value = current;
  10166. current = current.next;
  10167. return { value, done: false };
  10168. }
  10169. return { done: true };
  10170. }
  10171. };
  10172. }
  10173. });
  10174. this.registerType('torch.Graph', class {
  10175. constructor() {
  10176. this._next_unique = 0;
  10177. this._unique_names = new Map();
  10178. this._name_base_suffix = new Map();
  10179. this.all_nodes = new Set();
  10180. this.all_values = new Set();
  10181. this.all_blocks = new Set();
  10182. this._block = new torch.Block(this, null);
  10183. this._insert_before = this.return_node();
  10184. }
  10185. insert(opname, args, kwargs, range) {
  10186. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  10187. }
  10188. create(kind, ...args) {
  10189. let inputs = null;
  10190. let num_outputs = 1;
  10191. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  10192. [inputs, num_outputs] = args;
  10193. } else if (args.length === 1) {
  10194. if (typeof args[0] === 'number') {
  10195. [num_outputs] = args;
  10196. } else if (Array.isArray(args[0])) {
  10197. [inputs] = args;
  10198. }
  10199. }
  10200. const n = new torch.Node(this, kind);
  10201. if (inputs) {
  10202. for (const i of inputs) {
  10203. n.addInput(i);
  10204. }
  10205. }
  10206. for (let i = 0; i < num_outputs; i++) {
  10207. n.addOutput();
  10208. }
  10209. return n;
  10210. }
  10211. createClone(n, value_map, copy_blocks) {
  10212. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  10213. const r = n.allocNewInstance(this);
  10214. for (const o of n.outputs()) {
  10215. r.addOutput().copyMetadata(o);
  10216. }
  10217. r.cloneFrom(n);
  10218. for (const i of n.inputs()) {
  10219. r.addInput(value_map(i));
  10220. }
  10221. if (copy_blocks) {
  10222. for (const b of n.blocks()) {
  10223. r.addBlock().cloneFrom(b, value_map);
  10224. }
  10225. }
  10226. return r;
  10227. }
  10228. createNone() {
  10229. const n = this.create('prim::Constant');
  10230. n.output().setType(torch.NoneType.get());
  10231. return n;
  10232. }
  10233. createUninitialized(typ) {
  10234. const n = this.create('prim::Uninitialized');
  10235. n.output().setType(typ);
  10236. return n;
  10237. }
  10238. createList(contained_type, values) {
  10239. const n = this.create('prim::ListConstruct', values);
  10240. for (const v of values) {
  10241. if (!v.type().isSubtypeOf(contained_type)) {
  10242. throw new python.Error('Invalid list item.');
  10243. }
  10244. }
  10245. n.output().setType(torch.ListType.create(contained_type));
  10246. return n;
  10247. }
  10248. createListUnpack(v, size) {
  10249. const list_type = v.type().expect(torch.ListType);
  10250. const elem_type = list_type.getElementType();
  10251. const n = this.create('prim::ListUnpack', [v], 0);
  10252. for (let i = 0; i < size; i++) {
  10253. n.addOutput().setType(elem_type);
  10254. }
  10255. return n;
  10256. }
  10257. createTuple(values, tuple_type) {
  10258. if (!tuple_type) {
  10259. const types = values.map((v) => v.type());
  10260. tuple_type = torch.TupleType.create(types);
  10261. }
  10262. const n = this.create('prim::TupleConstruct', values);
  10263. n.output().setType(tuple_type);
  10264. return n;
  10265. }
  10266. createTupleUnpack(v) {
  10267. const tt = v.type().expect(torch.TupleType);
  10268. const n = this.create('prim::TupleUnpack', [v], 0);
  10269. for (const element of tt.elements()) {
  10270. n.addOutput().setType(element);
  10271. }
  10272. return n;
  10273. }
  10274. createTupleIndex(tup, idx, output_type) {
  10275. const n = this.create('prim::TupleIndex', [tup, idx]);
  10276. n.output().setType(output_type);
  10277. return n;
  10278. }
  10279. createTupleSlice(tup, beg, step_size, num_values) {
  10280. const new_vals = [];
  10281. const tt = tup.type().expect(torch.TupleType);
  10282. let i = beg;
  10283. for (let j = 0; j < num_values; j++) {
  10284. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  10285. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  10286. new_vals.push(tupleIndex.output());
  10287. i += step_size;
  10288. }
  10289. const n = this.createTuple(new_vals);
  10290. return n;
  10291. }
  10292. createDict(key_type, value_type, keys, values) {
  10293. if (keys.length !== values.length) {
  10294. throw new python.Error('Invalid dictionary size.');
  10295. }
  10296. const n = this.create('prim::DictConstruct');
  10297. const length = keys.length;
  10298. for (let i = 0; i < length; i++) {
  10299. if (!keys[i].type().isSubtypeOf(key_type)) {
  10300. throw new python.Error('Invalid key.');
  10301. }
  10302. if (!values[i].type().isSubtypeOf(value_type)) {
  10303. throw new python.Error('Invalid value.');
  10304. }
  10305. n.addInput(keys[i]);
  10306. n.addInput(values[i]);
  10307. }
  10308. n.output().setType(torch.DictType.create(key_type, value_type));
  10309. return n;
  10310. }
  10311. createObject(type) {
  10312. const node = this.create('prim::CreateObject');
  10313. node.output().setType(type);
  10314. return node;
  10315. }
  10316. createIsInstance(v, types) {
  10317. const n = this.create('prim::isinstance', [v], 1);
  10318. n.tys_('types', types);
  10319. n.output().setType(torch.BoolType.get());
  10320. return n;
  10321. }
  10322. createSetAttr(obj, field, newValue) {
  10323. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  10324. n.s_('name', field);
  10325. return n;
  10326. }
  10327. createGetAttr(obj, field) {
  10328. const n = this.create('prim::GetAttr', [obj]);
  10329. n.s_('name', field);
  10330. const classType = obj.type();
  10331. const outputType = classType.getAttribute(field);
  10332. n.output().setType(outputType);
  10333. n.output().setDebugName(/^[0-9]+$/.test(field) ? `_${field}` : field);
  10334. return n;
  10335. }
  10336. createLoad(name, type) {
  10337. const n = this.create('prim::Load', [], 1);
  10338. n.s_('name', name);
  10339. n.output().setType(type);
  10340. return n;
  10341. }
  10342. createStore(name, v) {
  10343. const n = this.create('prim::Store', [v], 0);
  10344. n.s_('name', name);
  10345. return n;
  10346. }
  10347. inputs() {
  10348. return this._block.inputs();
  10349. }
  10350. outputs() {
  10351. return this._block.outputs();
  10352. }
  10353. nodes() {
  10354. return this._block.nodes();
  10355. }
  10356. param_node() {
  10357. return this._block.param_node();
  10358. }
  10359. return_node() {
  10360. return this._block.return_node();
  10361. }
  10362. block() {
  10363. return this._block;
  10364. }
  10365. addInput(name) {
  10366. return this._block.addInput(name);
  10367. }
  10368. insertNode(node) {
  10369. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  10370. return node.insertBefore(this._insert_before);
  10371. }
  10372. insertConstant(val, loc, scope) {
  10373. return torch._C.insertConstant(this, val, loc, scope);
  10374. }
  10375. insertMethodCall(method_name, matched) {
  10376. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  10377. .s_('name', method_name)
  10378. .output().setType(matched.return_types[0]);
  10379. return result;
  10380. }
  10381. insertUncheckedCast(v, type) {
  10382. const n = this.create('prim::unchecked_cast', [v]);
  10383. this.insertNode(n);
  10384. n.output().setType(type);
  10385. return n.output();
  10386. }
  10387. insertToList(v, type) {
  10388. let dim = 0;
  10389. let ptr = type;
  10390. while (ptr instanceof torch.ListType) {
  10391. ptr = ptr.getElementType();
  10392. dim += 1;
  10393. }
  10394. let elem_ty = 0;
  10395. if (ptr instanceof torch.IntType) {
  10396. elem_ty = 0;
  10397. } else if (ptr instanceof torch.FloatType) {
  10398. elem_ty = 1;
  10399. } else if (ptr instanceof torch.BoolType) {
  10400. elem_ty = 2;
  10401. } else if (ptr instanceof torch.ComplexType) {
  10402. elem_ty = 3;
  10403. } else {
  10404. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  10405. }
  10406. const dim_val = this.insertConstant(dim);
  10407. const elem_ty_val = this.insertConstant(elem_ty);
  10408. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  10409. n.output().setType(type);
  10410. return n.output();
  10411. }
  10412. insertFunctionCall(callee, matched) {
  10413. const func_name = callee.name();
  10414. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  10415. const inputs = [fn_constant, ...matched.inputs];
  10416. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  10417. return result;
  10418. }
  10419. insertPoint() {
  10420. return this._insert_before;
  10421. }
  10422. setInsertPoint(node) {
  10423. if (node instanceof torch.Block) {
  10424. node = node.return_node();
  10425. }
  10426. this._insert_before = node;
  10427. }
  10428. freeNode(n) {
  10429. this.all_nodes.delete(n);
  10430. }
  10431. freeValue(v) {
  10432. v.setDebugName('');
  10433. this.all_values.delete(v);
  10434. }
  10435. freeBlock(b) {
  10436. this.all_blocks.delete(b);
  10437. }
  10438. copy() {
  10439. const new_g = new torch.Graph();
  10440. new_g.cloneFrom(this);
  10441. return new_g;
  10442. }
  10443. cloneFrom(src) {
  10444. const env = (v) => {
  10445. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  10446. };
  10447. this.block().cloneFrom(src.block(), env);
  10448. }
  10449. set_op_version(version) {
  10450. this._op_version = version;
  10451. }
  10452. get_op_version() {
  10453. return this._op_version;
  10454. }
  10455. print(out, print_source_locations) {
  10456. out.write('graph(');
  10457. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  10458. out.write('):\n');
  10459. const groups = [];
  10460. for (const node of this.nodes()) {
  10461. node.print(out, 1, groups, print_source_locations);
  10462. }
  10463. out.write(' return (');
  10464. torch._C.printValueRefs(out, this.outputs());
  10465. out.write(')\n');
  10466. for (let i = 0; i < groups.length; i++) {
  10467. const fg = groups[i];
  10468. out.write('with ');
  10469. out.write(fg.kind());
  10470. out.write(`_${i} = `);
  10471. out.write(fg.g('Subgraph'));
  10472. }
  10473. return out;
  10474. }
  10475. toString() {
  10476. const out = new io.StringIO();
  10477. this.print(out, true);
  10478. return out.toString();
  10479. }
  10480. });
  10481. this.registerType('torch.Block', class {
  10482. constructor(graph, node) {
  10483. this._graph = graph;
  10484. this._input = graph.create('prim::Param', 0);
  10485. this._output = graph.create('prim::Return', 0);
  10486. this._owning_node = node;
  10487. this._input.next = this._output;
  10488. this._input.prev = this._output;
  10489. this._output.next = this._input;
  10490. this._output.prev = this._input;
  10491. this._graph.all_blocks.add(this);
  10492. this._output._owning_block = this;
  10493. // output_.topo_position_ = kUpperBound;
  10494. this._input._owning_block = this;
  10495. // input_.topo_position_ = kLowerBound;
  10496. }
  10497. inputs() {
  10498. return this._input.outputs();
  10499. }
  10500. outputs() {
  10501. return this._output.inputs();
  10502. }
  10503. nodes() {
  10504. return new torch._C.graph_node_list(this._input);
  10505. }
  10506. return_node() {
  10507. return this._output;
  10508. }
  10509. param_node() {
  10510. return this._input;
  10511. }
  10512. owningNode() {
  10513. return this._owning_node;
  10514. }
  10515. owningGraph() {
  10516. return this._graph;
  10517. }
  10518. addInput(name) {
  10519. const value = this._input.addOutput();
  10520. value.setDebugName(name || '');
  10521. return value;
  10522. }
  10523. registerOutput(value) {
  10524. this._output.addInput(value);
  10525. return this.outputs().length - 1;
  10526. }
  10527. appendNode(n) {
  10528. if (n._graph !== this._graph || n.inBlockList()) {
  10529. throw new python.Error('Node not in graph.');
  10530. }
  10531. n.insertBefore(this._output);
  10532. return n;
  10533. }
  10534. cloneFrom(src, value_map) {
  10535. const local_map = new Map();
  10536. const env = (v) => {
  10537. if (local_map.has(v)) {
  10538. return local_map.get(v);
  10539. }
  10540. return value_map(v);
  10541. };
  10542. const graph = this.owningGraph();
  10543. for (const input of src.inputs()) {
  10544. local_map.set(input, this.addInput().copyMetadata(input));
  10545. }
  10546. for (const node of src.nodes()) {
  10547. const new_node = this.appendNode(graph.createClone(node, env));
  10548. for (let i = 0; i < node.outputs().length; i++) {
  10549. const oo = node.outputs()[i];
  10550. const no = new_node.outputs()[i];
  10551. local_map.set(oo, no);
  10552. no.copyMetadata(oo);
  10553. }
  10554. }
  10555. for (const output of src.outputs()) {
  10556. this.registerOutput(env(output));
  10557. }
  10558. }
  10559. eraseOutput(i) {
  10560. this._output.removeInput(i);
  10561. }
  10562. destroy() {
  10563. this._output.removeAllInputs();
  10564. for (const n of this.nodes()) {
  10565. n.destroy();
  10566. }
  10567. this._output.destroy();
  10568. this._input.destroy();
  10569. this._graph.freeBlock(this);
  10570. }
  10571. });
  10572. this.registerType('torch.Node', class {
  10573. constructor(graph, kind) {
  10574. this._kind = kind;
  10575. this._graph = graph;
  10576. this._owning_block = null;
  10577. this._values = new Map();
  10578. this._inputs = [];
  10579. this._outputs = [];
  10580. this._blocks = [];
  10581. this._graph.all_nodes.add(this);
  10582. this._prev = null;
  10583. this._next = null;
  10584. this._source_range = null;
  10585. this._op = null;
  10586. }
  10587. owningGraph() {
  10588. return this._graph;
  10589. }
  10590. owningBlock() {
  10591. return this._owning_block;
  10592. }
  10593. kind() {
  10594. return this._kind;
  10595. }
  10596. schema() {
  10597. if (this._op) {
  10598. return this._op.schema();
  10599. }
  10600. // Node::schema() throws while torch.Node.schema() does not.
  10601. const op = this.maybeOperator();
  10602. if (op) {
  10603. return op.schema();
  10604. }
  10605. return null;
  10606. // return this.getOperator().schema();
  10607. }
  10608. hasNamedInput(name) {
  10609. for (const argument of this.schema().arguments) {
  10610. if (argument.name === name) {
  10611. return true;
  10612. }
  10613. }
  10614. return false;
  10615. }
  10616. matches(schema) {
  10617. if (torch._C.isBlockListedSchema(schema)) {
  10618. return false;
  10619. }
  10620. if (this.kind() !== schema.name) {
  10621. return false;
  10622. }
  10623. const actuals = this.inputs();
  10624. const formals = schema.arguments;
  10625. if (actuals.length < formals.length) {
  10626. return false;
  10627. }
  10628. const type_env = new Map();
  10629. for (let i = 0; i < formals.length; i++) {
  10630. let formal = formals[i].type;
  10631. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  10632. if (!matched_type.success()) {
  10633. return false;
  10634. }
  10635. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  10636. if (resolved) {
  10637. formal = resolved;
  10638. }
  10639. if (!actuals[i].type().isSubtypeOf(formal)) {
  10640. return false;
  10641. }
  10642. }
  10643. if (!schema.is_vararg && actuals.length !== formals.length) {
  10644. return false;
  10645. }
  10646. return true;
  10647. }
  10648. mustBeNone() {
  10649. return this._kind === 'prim::AutogradZero' ||
  10650. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  10651. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  10652. }
  10653. maybeSchema() {
  10654. const op = this.maybeOperator();
  10655. if (op) {
  10656. return op.schema();
  10657. }
  10658. return null;
  10659. }
  10660. maybeOperator() {
  10661. if (!this._op) {
  10662. const candidates = torch._C.getAllOperatorsFor(this.kind());
  10663. for (const candidate of candidates) {
  10664. if (this.matches(candidate.schema())) {
  10665. this._op = candidate;
  10666. break;
  10667. }
  10668. }
  10669. }
  10670. return this._op;
  10671. }
  10672. getOperator() {
  10673. const maybe = this.maybeOperator();
  10674. if (maybe) {
  10675. return maybe;
  10676. }
  10677. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  10678. }
  10679. getOperation() {
  10680. return this.getOperator().getOperation(this);
  10681. }
  10682. isNondeterministic() {
  10683. const schema = this.maybeSchema();
  10684. if (!this.kind().startsWith('aten::')) {
  10685. return false;
  10686. }
  10687. if (!schema) {
  10688. return false;
  10689. }
  10690. const schema_info = new torch._C.SchemaInfo(schema);
  10691. if (this.hasNamedInput('train')) {
  10692. throw new python.Error('Not Implemented.');
  10693. // const value = constant_as<bool>(this.namedInput("train"));
  10694. // if (value) {
  10695. // schema_info.addArgumentValue('train', value);
  10696. // }
  10697. }
  10698. return schema_info.is_nondeterministic();
  10699. }
  10700. hasSideEffects() {
  10701. switch (this._kind) {
  10702. case 'prim::PythonOp':
  10703. case 'prim::IgnoredPythonOp':
  10704. case 'prim::Print':
  10705. case 'prim::RaiseException':
  10706. case 'aten::warn':
  10707. case 'aten::save':
  10708. case 'aten::manual_seed':
  10709. case 'prim::AddStatValue':
  10710. case 'prim::TimePoint':
  10711. case 'prim::CallFunction':
  10712. case 'prim::CallMethod':
  10713. case 'prim::BailoutTemplate':
  10714. case 'prim::BailOut':
  10715. case 'prim::rpc_async':
  10716. case 'prim::rpc_sync':
  10717. case 'prim::rpc_remote':
  10718. case 'aten::wait':
  10719. case 'cuda::set_stream':
  10720. case 'cuda::_set_device':
  10721. case 'cuda::_current_device':
  10722. case 'cuda::synchronize':
  10723. case 'prim::Enter':
  10724. case 'prim::Exit':
  10725. return true;
  10726. default:
  10727. break;
  10728. }
  10729. const op = this.maybeOperator();
  10730. if (!op) {
  10731. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  10732. return false;
  10733. }
  10734. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  10735. torch._C.TORCH_INTERNAL_ASSERT(
  10736. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  10737. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  10738. op.aliasAnalysisKind() === 'CONSERVATIVE');
  10739. }
  10740. switch (op.aliasAnalysisKind()) {
  10741. case 'PURE_FUNCTION':
  10742. case 'FROM_SCHEMA':
  10743. case 'INTERNAL_SPECIAL_CASE':
  10744. return false;
  10745. case 'CONSERVATIVE':
  10746. return true;
  10747. default:
  10748. break;
  10749. }
  10750. torch._C.TORCH_INTERNAL_ASSERT(false);
  10751. return false;
  10752. }
  10753. inputs() {
  10754. return this._inputs;
  10755. }
  10756. outputs() {
  10757. return this._outputs;
  10758. }
  10759. input(i) {
  10760. if (i === undefined) {
  10761. torch._C.AT_ASSERT(this._inputs.length === 1);
  10762. return this._inputs[0];
  10763. }
  10764. return this._inputs[i];
  10765. }
  10766. output(i) {
  10767. if (i === undefined) {
  10768. torch._C.AT_ASSERT(this._outputs.length === 1);
  10769. return this._outputs[0];
  10770. }
  10771. return this._outputs[i];
  10772. }
  10773. hasUses() {
  10774. for (const o of this.outputs()) {
  10775. if (o.uses().length > 0) {
  10776. return true;
  10777. }
  10778. }
  10779. return false;
  10780. }
  10781. blocks() {
  10782. return this._blocks;
  10783. }
  10784. insertInput(i, value) {
  10785. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  10786. this._op = null;
  10787. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  10788. const use = this.findUseForInput(use_itr);
  10789. use.offset += 1;
  10790. }
  10791. this._inputs.splice(i, 0, value);
  10792. value._uses.push(new torch.Use(this, i));
  10793. return value;
  10794. }
  10795. addInput(value) {
  10796. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  10797. this._op = null;
  10798. const use = new torch.Use(this, this._inputs.length);
  10799. value.uses().push(use);
  10800. this._inputs.push(value);
  10801. return value;
  10802. }
  10803. addOutput() {
  10804. const value = new torch.Value(this, this._outputs.length);
  10805. this._outputs.push(value);
  10806. return value;
  10807. }
  10808. addBlock() {
  10809. this._op = null;
  10810. this._blocks.push(new torch.Block(this.owningGraph(), this));
  10811. return this._blocks[this._blocks.length - 1];
  10812. }
  10813. get prev() {
  10814. return this._prev;
  10815. }
  10816. set prev(value) {
  10817. this._prev = value;
  10818. }
  10819. get next() {
  10820. return this._next;
  10821. }
  10822. set next(value) {
  10823. this._next = value;
  10824. }
  10825. insertBefore(n) {
  10826. if (!n.inBlockList()) {
  10827. throw new python.Error('Node not in block.');
  10828. }
  10829. this.insertAfter(n.prev);
  10830. return this;
  10831. }
  10832. insertAfter(n) {
  10833. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  10834. torch._C.AT_ASSERT(n.owningBlock());
  10835. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  10836. this._owning_block = n.owningBlock();
  10837. const next = n.next;
  10838. n.next = this;
  10839. this.prev = n;
  10840. this.next = next;
  10841. next.prev = this;
  10842. // this.assignTopoPosition();
  10843. return this;
  10844. }
  10845. allocNewInstance(g) {
  10846. return new torch.Node(g, this.kind());
  10847. }
  10848. cloneFrom(s) {
  10849. this._source_range = s._source_range;
  10850. if (s._scope && !s._scope.isBlank()) {
  10851. this._scope = s._scope;
  10852. }
  10853. this.copyAttributes(s);
  10854. this._callstack = s._callstack;
  10855. }
  10856. copyAttributes(rhs) {
  10857. this._values = new Map(rhs._values);
  10858. return this;
  10859. }
  10860. dropInput(i) {
  10861. torch._C.AT_ASSERT(i < this._inputs.length);
  10862. const input_node = this._inputs[i];
  10863. const use_it = this.findUseForInput(i);
  10864. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  10865. this._inputs[i] = null;
  10866. return input_node;
  10867. }
  10868. eraseOutput(i) {
  10869. torch._C.AT_ASSERT(i < this._outputs.length);
  10870. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  10871. this._op = null;
  10872. const n = this._outputs[i];
  10873. this._outputs.splice(i, 1);
  10874. this.owningGraph().freeValue(n);
  10875. for (let j = i; j < this._outputs.length; j++) {
  10876. this._outputs[j]._offset--;
  10877. }
  10878. }
  10879. eraseBlock(i) {
  10880. this._op = null;
  10881. const n = this._blocks[i];
  10882. this._blocks.splice(i, 1);
  10883. n.destroy();
  10884. }
  10885. findUseForInput(i) {
  10886. const input_uses = this._inputs[i]._uses;
  10887. for (const use_it of input_uses) {
  10888. if (use_it.user === this && use_it.offset === i) {
  10889. return use_it;
  10890. }
  10891. }
  10892. throw new python.Error('Input use not found.');
  10893. }
  10894. moveBefore(n) {
  10895. this.removeFromList();
  10896. this.insertBefore(n);
  10897. }
  10898. removeInput(i) {
  10899. this._op = null;
  10900. this.dropInput(i);
  10901. for (let j = i + 1; j < this._inputs.length; j++) {
  10902. const it = this.findUseForInput(j);
  10903. it.offset--;
  10904. }
  10905. this._inputs.splice(i, 1);
  10906. }
  10907. removeAllInputs() {
  10908. this._op = null;
  10909. for (let i = 0; i < this._inputs.length; i++) {
  10910. this.dropInput(i);
  10911. }
  10912. this._inputs = [];
  10913. }
  10914. inBlockList() {
  10915. return this.next !== null;
  10916. }
  10917. removeFromList() {
  10918. this._owning_block = null;
  10919. const next = this.next;
  10920. const prev = this.prev;
  10921. prev.next = next;
  10922. next.prev = prev;
  10923. this.next = null;
  10924. this.prev = null;
  10925. }
  10926. destroy() {
  10927. while (this.outputs().length > 0) {
  10928. this.eraseOutput(this.outputs().length - 1);
  10929. }
  10930. while (this.blocks().length > 0) {
  10931. this.eraseBlock(this.blocks().length - 1);
  10932. }
  10933. this.removeAllInputs();
  10934. if (this.inBlockList()) {
  10935. this.removeFromList();
  10936. }
  10937. this._graph.freeNode(this);
  10938. }
  10939. replaceAllUsesWith(n) {
  10940. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  10941. const nOutputs = this.outputs().length;
  10942. for (let i = 0; i < nOutputs; i++) {
  10943. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  10944. }
  10945. }
  10946. s_(name, value) {
  10947. this._values.set(name, [value, 's']);
  10948. return this;
  10949. }
  10950. s(name) {
  10951. return this._values.get(name)[0];
  10952. }
  10953. ss_(name, value) {
  10954. this._values.set(name, [value, 'ss']);
  10955. return this;
  10956. }
  10957. ss(name) {
  10958. return this._values.get(name)[0];
  10959. }
  10960. i_(name, value) {
  10961. this._values.set(name, [value, 'i']);
  10962. return this;
  10963. }
  10964. i(name) {
  10965. return this._values.get(name)[0];
  10966. }
  10967. f_(name, value) {
  10968. this._values.set(name, [value, 'f']);
  10969. return this;
  10970. }
  10971. f(name) {
  10972. return this._values.get(name)[0];
  10973. }
  10974. t_(name, value) {
  10975. this._values.set(name, [value, 't']);
  10976. return this;
  10977. }
  10978. t(name) {
  10979. return this._values.get(name)[0];
  10980. }
  10981. tys_(name, value) {
  10982. this._values.set(name, [value, 'tys']);
  10983. return this;
  10984. }
  10985. tys(name) {
  10986. return this._values.get(name)[0];
  10987. }
  10988. ival_(name, value) {
  10989. this._values.set(name, [value, 'ival']);
  10990. return this;
  10991. }
  10992. ival(name) {
  10993. return this._values.get(name)[0];
  10994. }
  10995. hasAttribute(name) {
  10996. return this._values.has(name);
  10997. }
  10998. hasAttributes() {
  10999. return this._values.size > 0;
  11000. }
  11001. attributeNames() {
  11002. return Array.from(this._values.keys());
  11003. }
  11004. kindOf(name) {
  11005. return this._values.get(name)[1];
  11006. }
  11007. setSourceRange(r) {
  11008. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  11009. this._source_range = r;
  11010. return this;
  11011. }
  11012. sourceRange() {
  11013. return this._source_range || new torch._C.SourceRange();
  11014. }
  11015. print_attributes(out, ignore_subgraph) {
  11016. ignore_subgraph = ignore_subgraph || false;
  11017. out.write('[');
  11018. const names = this.attributeNames();
  11019. for (let i = 0; i < names.length; i++) {
  11020. const name = names[i];
  11021. if (ignore_subgraph && name === 'Subgraph') {
  11022. continue;
  11023. }
  11024. if (i > 0) {
  11025. out.write(', ');
  11026. }
  11027. out.write(`${name}=`);
  11028. this.printAttrValue(out, name);
  11029. }
  11030. out.write(']');
  11031. }
  11032. printTypeList(out, items) {
  11033. out.write('[');
  11034. for (let i = 0; i < items.length; i++) {
  11035. const item = items[i];
  11036. if (i++ > 0) {
  11037. out.write(', ');
  11038. }
  11039. out.write(item.str());
  11040. }
  11041. out.write(']');
  11042. }
  11043. printAttrValue(out, name) {
  11044. const kind = this.kindOf(name);
  11045. switch (kind) {
  11046. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  11047. case 'ss': case 'ival': case 'ty':
  11048. out.write(this[kind](name));
  11049. break;
  11050. case 's':
  11051. out.write(`"${this.s(name)}"`);
  11052. break;
  11053. case 't':
  11054. out.write(`"{}"`);
  11055. break;
  11056. case 'ts': out.write('[<Tensors>]'); break;
  11057. case 'g': out.write('[<Graph>]'); break;
  11058. case 'gs': out.write('[<Graphs>]'); break;
  11059. case 'tys': this.printTypeList(out, this.tys(name)); break;
  11060. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  11061. }
  11062. }
  11063. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  11064. print_source_locations = print_source_locations === false ? false : true;
  11065. print_attributes = print_attributes === false ? false : true;
  11066. print_scopes = print_scopes === false ? false : true;
  11067. print_body = print_body === false ? false : true;
  11068. const outs = this.outputs();
  11069. torch._C.indent(out, level);
  11070. torch._C.const_value_list_with_types(out, outs, ', ');
  11071. out.write(' = ');
  11072. if (this.kind() === 'prim::PythonOp') {
  11073. throw new python.Error('Not implemented.');
  11074. } else if (this.hasAttribute('Subgraph') && groups) {
  11075. throw new python.Error('Not implemented.');
  11076. } else {
  11077. out.write(this.kind());
  11078. if (print_attributes && this.hasAttributes()) {
  11079. this.print_attributes(out);
  11080. }
  11081. }
  11082. out.write('(');
  11083. torch._C.printValueRefs(out, this.inputs());
  11084. out.write(')');
  11085. if (print_scopes) {
  11086. //
  11087. }
  11088. if (print_source_locations) {
  11089. let r = this.sourceRange();
  11090. if (r.source()) {
  11091. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  11092. if (orig) {
  11093. r = orig;
  11094. }
  11095. }
  11096. const file_line_col = r.file_line_col();
  11097. if (file_line_col !== null) {
  11098. const [filename, line, col] = file_line_col;
  11099. out.write(` # ${filename}:${line}:${col}`);
  11100. }
  11101. }
  11102. if (!print_body) {
  11103. return out;
  11104. }
  11105. out.write('\n');
  11106. for (let i = 0; i < this.blocks().length; i++) {
  11107. const b = this.blocks()[i];
  11108. torch._C.indent(out, level + 1);
  11109. out.write(`block${i}(`);
  11110. torch._C.const_value_list_with_types(out, b.inputs());
  11111. out.write('):\n');
  11112. for (const nested of b.nodes()) {
  11113. nested.print(out, level + 2, groups);
  11114. }
  11115. torch._C.indent(out, level + 2);
  11116. out.write('-> (');
  11117. torch._C.printValueRefs(out, b.outputs());
  11118. out.write(')\n');
  11119. }
  11120. return out;
  11121. }
  11122. toString() {
  11123. const out = new io.StringIO();
  11124. this.print(out, 0, true);
  11125. return out.toString();
  11126. }
  11127. });
  11128. this.registerType('torch.Value', class {
  11129. constructor(node, offset) {
  11130. this._node = node;
  11131. this._offset = offset;
  11132. this._unique = node._graph._next_unique++;
  11133. this._uses = [];
  11134. this._node._graph.all_values.add(this);
  11135. }
  11136. unique() {
  11137. return this._unique;
  11138. }
  11139. node() {
  11140. return this._node;
  11141. }
  11142. owningGraph() {
  11143. return this._node.owningGraph();
  11144. }
  11145. uses() {
  11146. return this._uses;
  11147. }
  11148. hasUses() {
  11149. return this._uses.length > 0;
  11150. }
  11151. hasDebugName() {
  11152. return this._unique_name;
  11153. }
  11154. setDebugName(name) {
  11155. // if (!isValidName(name)) {
  11156. // throw std::runtime_error("Invalid name: '" + name + "'");
  11157. // }
  11158. const names = this.node().owningGraph()._unique_names;
  11159. if (this.hasDebugName()) {
  11160. names.delete(this._unique_name);
  11161. this._unique_name = '';
  11162. }
  11163. if (!name) {
  11164. return this;
  11165. }
  11166. const old_owner_of_name = names.get(name);
  11167. if (old_owner_of_name) {
  11168. let suffix = 1;
  11169. let name_base = name;
  11170. const last_dot_pos = name.lastIndexOf('.');
  11171. if (last_dot_pos !== -1) {
  11172. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  11173. suffix = Number(name.substring(last_dot_pos + 1));
  11174. name_base = name.substring(0, last_dot_pos);
  11175. }
  11176. }
  11177. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  11178. if (names_suffixes.has(name_base)) {
  11179. suffix = Math.max(suffix, names_suffixes.get(name_base));
  11180. }
  11181. let replacement_name = null;
  11182. do {
  11183. replacement_name = `${name_base}.${suffix++}`;
  11184. } while (names.has(replacement_name));
  11185. names_suffixes.set(name_base, suffix);
  11186. old_owner_of_name.setDebugName(replacement_name);
  11187. }
  11188. names.set(name, this);
  11189. this._unique_name = name;
  11190. return this;
  11191. }
  11192. debugName() {
  11193. if (this.hasDebugName()) {
  11194. return this._unique_name;
  11195. }
  11196. return this.unique().toString();
  11197. }
  11198. type() {
  11199. return this._type;
  11200. }
  11201. setType(type) {
  11202. // torch._C.AT_ASSERT(type instanceof torch.Type);
  11203. if (type instanceof torch._C.DynamicType) {
  11204. type = type.fallback();
  11205. }
  11206. this._type = type;
  11207. for (const use of this._uses) {
  11208. use.user._op = null;
  11209. }
  11210. return this;
  11211. }
  11212. set value(value) { // remove
  11213. if (value instanceof torch.Value) {
  11214. throw new python.Error('Value cannot be a value.');
  11215. }
  11216. this._value = value;
  11217. }
  11218. get value() { // remove
  11219. return this._value;
  11220. }
  11221. replaceFirstUseWith(newValue) {
  11222. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  11223. const [u] = this.uses();
  11224. u.user._inputs[u.offset] = newValue;
  11225. newValue._uses.push(u);
  11226. this._uses.shift();
  11227. }
  11228. replaceAllUsesWith(newValue) {
  11229. while (this.uses().length > 0) {
  11230. this.replaceFirstUseWith(newValue);
  11231. }
  11232. }
  11233. copyMetadata(from) {
  11234. this.setType(from.type());
  11235. if (from.hasDebugName()) {
  11236. this.setDebugName(from.debugName());
  11237. }
  11238. return this;
  11239. }
  11240. toString() {
  11241. return `${this.debugName()} : ${this.type().toString()}`;
  11242. }
  11243. });
  11244. this.registerType('torch.Use', class {
  11245. constructor(user, offset) {
  11246. this.user = user;
  11247. this.offset = offset;
  11248. }
  11249. });
  11250. this.registerType('torch._C.IValue', class {
  11251. constructor(value, tag) {
  11252. this.value = value;
  11253. if (tag) {
  11254. this.tag = tag;
  11255. } else if (value === undefined) {
  11256. this.tag = 'None';
  11257. this.value = 'None';
  11258. } else if (typeof value === 'boolean') {
  11259. this.tag = 'Bool';
  11260. } else if (typeof value === 'string') {
  11261. this.tag = 'String';
  11262. } else if (value instanceof torch.Tensor) {
  11263. this.tag = 'Tensor';
  11264. } else if (value instanceof torch.ScriptObject) {
  11265. this.tag = 'Object';
  11266. } else if (Array.isArray(value)) {
  11267. this.tag = 'GenericList';
  11268. } else if (value instanceof torch._C.Tuple) {
  11269. this.tag = 'Tuple';
  11270. } else if (value instanceof torch.device) {
  11271. this.tag = 'Device';
  11272. } else if (Number.isInteger(value)) {
  11273. this.tag = 'Int';
  11274. } else if (typeof value === 'number') {
  11275. this.tag = 'Double';
  11276. } else {
  11277. throw new python.Error('Unsupported type.');
  11278. }
  11279. }
  11280. isNone() {
  11281. return this.tag === 'None';
  11282. }
  11283. isBool() {
  11284. return this.tag === 'Bool';
  11285. }
  11286. toBool() {
  11287. return this.value;
  11288. }
  11289. isObject() {
  11290. return this.tag === 'Object';
  11291. }
  11292. toObject() {
  11293. return this.value;
  11294. }
  11295. isTensor() {
  11296. return this.tag === 'Tensor';
  11297. }
  11298. toTensor() {
  11299. return this.value;
  11300. }
  11301. isDouble() {
  11302. return this.tag === 'Double';
  11303. }
  11304. toDouble() {
  11305. return this.value;
  11306. }
  11307. isComplexDouble() {
  11308. return this.tag === 'ComplexDouble';
  11309. }
  11310. isInt() {
  11311. return this.tag === 'Int';
  11312. }
  11313. toInt() {
  11314. if (this.isInt()) {
  11315. return this.value;
  11316. } else if (this.isSymInt()) {
  11317. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  11318. }
  11319. throw new python.Error('Expected int.');
  11320. }
  11321. isString() {
  11322. return this.tag === 'String';
  11323. }
  11324. toStringRef() {
  11325. return this.value;
  11326. }
  11327. isList() {
  11328. return this.tag === 'GenericList';
  11329. }
  11330. toList() {
  11331. return this.value;
  11332. }
  11333. isDevice() {
  11334. return this.tag === 'Device';
  11335. }
  11336. toDevice() {
  11337. return this.value;
  11338. }
  11339. isGenerator() {
  11340. return this.tag === 'Generator';
  11341. }
  11342. isStream() {
  11343. return this.tag === 'Stream';
  11344. }
  11345. isEnum() {
  11346. return this.tag === 'Enum';
  11347. }
  11348. isTuple() {
  11349. return this.tag === 'Tuple';
  11350. }
  11351. toTupleRef() {
  11352. return this.value;
  11353. }
  11354. isCustomClass() {
  11355. return torch._C.isCustomClass(this);
  11356. }
  11357. equals(rhs) {
  11358. const lhs = this;
  11359. switch (lhs.tag) {
  11360. case 'None': return rhs.isNone();
  11361. case 'Bool': return rhs.isBool() && lhs.toBool() === rhs.toBool();
  11362. case 'Int': return rhs.isInt() && lhs.toInt() === rhs.toInt();
  11363. case 'Double': return rhs.isDouble() && lhs.toDouble() === rhs.toDouble();
  11364. case 'String': return rhs.isString() && lhs.toString() === rhs.toString();
  11365. case 'Tensor': return rhs.isTensor() && lhs.toTensor() === rhs.toTensor();
  11366. case 'Object': return rhs.isObject() && lhs.toObject() === rhs.toObject();
  11367. case 'Device': return rhs.isObject() && lhs.toDevice() === rhs.toDevice();
  11368. case 'GenericList': {
  11369. if (rhs.isList()) {
  11370. const a = lhs.toList();
  11371. const b = rhs.toList();
  11372. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  11373. }
  11374. return false;
  11375. }
  11376. default: throw new python.Error(`IValue.equals() not implemented for '${lhs.tag}.`);
  11377. }
  11378. }
  11379. is(rhs) {
  11380. const lhs = this;
  11381. return lhs.equals(rhs);
  11382. }
  11383. type() {
  11384. switch (this.tag) {
  11385. case 'Int': return torch.IntType.get();
  11386. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  11387. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  11388. }
  11389. }
  11390. });
  11391. this.registerFunction('torch._C.indent', (out, level) => {
  11392. for (let i = 0; i < level; i++) {
  11393. out.write(' ');
  11394. }
  11395. return out;
  11396. });
  11397. this.registerFunction('torch._C.printValueRef', (out, n) => {
  11398. out.write(`%${n.debugName()}`);
  11399. });
  11400. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  11401. for (let i = 0; i < nodes.length; i++) {
  11402. const n = nodes[i];
  11403. if (i > 0) {
  11404. out.write(', ');
  11405. }
  11406. torch._C.printValueRef(out, n);
  11407. }
  11408. return out;
  11409. });
  11410. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  11411. for (let i = 0; i < values.length; i++) {
  11412. const n = values[i];
  11413. if (i > 0) {
  11414. out.write(delim);
  11415. }
  11416. torch._C.printValueRef(out, n);
  11417. out.write(' : ');
  11418. out.write(n.type().str());
  11419. }
  11420. });
  11421. this.register('torch.jit._script');
  11422. this.register('torch.jit._trace');
  11423. this.registerType('torch._C.Parser', class {
  11424. constructor(source) {
  11425. this.L = source;
  11426. }
  11427. parse() {
  11428. const p = ast.parse(this.L.text_str(), this.L.filename());
  11429. return p;
  11430. }
  11431. parseExp() {
  11432. const expr = ast.parse(this.L.text_str());
  11433. return expr.body[0].value;
  11434. }
  11435. });
  11436. this.registerType('torch._C.Source', class {
  11437. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  11438. if (text_view instanceof Uint8Array) {
  11439. const decoder = new TextDecoder('utf-8');
  11440. this._text_view = decoder.decode(text_view);
  11441. } else if (typeof text_view === 'string') {
  11442. this._text_view = text_view;
  11443. } else {
  11444. throw new python.Error('Invalid text view.');
  11445. }
  11446. this._filename = filename;
  11447. this._starting_line_no = starting_line_no;
  11448. this._gen_ranges = gen_ranges;
  11449. }
  11450. text_str() {
  11451. return this._text_view;
  11452. }
  11453. filename() {
  11454. return this._filename;
  11455. }
  11456. findSourceRangeThatGenerated(range) {
  11457. if (!this._gen_ranges) {
  11458. return null;
  11459. }
  11460. return this._gen_ranges.findSourceRangeThatGenerated(range);
  11461. }
  11462. });
  11463. this.registerType('torch._C.SourceRange', class {
  11464. constructor(node) {
  11465. this._node = node;
  11466. }
  11467. source() {
  11468. return null;
  11469. }
  11470. file_line_col() {
  11471. return null;
  11472. }
  11473. toString() {
  11474. const n = this._node;
  11475. return n ? `${n.filename}:${n.lineno}:${n.col_offset}` : '';
  11476. }
  11477. });
  11478. this.registerType('torch._C.QualifiedName', class {
  11479. constructor(...args) {
  11480. let name = null;
  11481. if (args.length === 1 && typeof args[0] === 'string') {
  11482. [name] = args;
  11483. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  11484. name = args[0].join('.');
  11485. } else {
  11486. name = `${args[0].qualifiedName()}.${args[1]}`;
  11487. }
  11488. const index = name.lastIndexOf('.');
  11489. this._qualifiedName = name;
  11490. this._prefix = index === -1 ? '' : name.substring(0, index);
  11491. this._name = index === -1 ? name : name.substring(index + 1);
  11492. }
  11493. qualifiedName() {
  11494. return this._qualifiedName; // "foo.bar.baz"
  11495. }
  11496. prefix() {
  11497. return this._prefix; // "foo.bar"
  11498. }
  11499. name() {
  11500. return this._name; // "baz"
  11501. }
  11502. atoms() {
  11503. return this._qualifiedName.split('.');
  11504. }
  11505. });
  11506. this.registerType('torch._C.Resolver', class {
  11507. resolveValue() {
  11508. throw new python.Error('Not implemented.');
  11509. }
  11510. resolveType() {
  11511. throw new python.Error('Not implemented.');
  11512. }
  11513. });
  11514. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  11515. torch._C.customClasses = torch._C.customClasses || new Map();
  11516. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  11517. const name = class_type.name().qualifiedName();
  11518. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  11519. torch._C.customClasses.set(name, class_type);
  11520. });
  11521. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  11522. torch._C.customClasses = torch._C.customClasses || new Map();
  11523. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  11524. return ret;
  11525. });
  11526. this.registerFunction('torch._C.isCustomClass', (v) => {
  11527. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  11528. });
  11529. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  11530. constructor(cu, constant_table, source_loader, version) {
  11531. super();
  11532. this._cu = cu;
  11533. this._constant_table = constant_table;
  11534. this._source_loader = source_loader;
  11535. this._version = version;
  11536. this._loaded_sources = new Set();
  11537. ast.AST.prototype.range = function() {
  11538. this._range = this._range || new torch._C.SourceRange(this);
  11539. return this._range;
  11540. };
  11541. this._to_be_defined = new Map();
  11542. this._env = new Map([
  11543. ['torch', new torch._C.BuiltinModule('aten', version)],
  11544. ['ops', new torch._C.OpsValue(version)],
  11545. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  11546. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  11547. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  11548. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  11549. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  11550. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  11551. ]);
  11552. }
  11553. loadType(name) {
  11554. const type_parser = new torch._C.ScriptTypeParser(this);
  11555. return type_parser.parseType(name.qualifiedName());
  11556. }
  11557. resolveType(name) {
  11558. name = new torch._C.QualifiedName(name);
  11559. return this.findNamedType(name);
  11560. }
  11561. resolveValue(name, m, loc) {
  11562. if (this._env.has(name)) {
  11563. return this._env.get(name);
  11564. }
  11565. const graph = m.graph();
  11566. switch (name) {
  11567. case 'inf': return new torch._C.SimpleValue(graph.insertConstant('std::numeric_limits<double>::infinity()', loc));
  11568. case 'nan': return new torch._C.SimpleValue(graph.insertConstant('std::numeric_limits<double>::quiet_NaN()', loc));
  11569. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  11570. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  11571. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  11572. default: return null;
  11573. }
  11574. }
  11575. findNamedType(name) {
  11576. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  11577. if (custom_class) {
  11578. return custom_class;
  11579. }
  11580. this.parseSourceIfNeeded(name.prefix());
  11581. const key = name.qualifiedName();
  11582. const it = this._to_be_defined.get(key);
  11583. if (it && it instanceof ast.ClassDef) {
  11584. this._to_be_defined.delete(key);
  11585. this.importNamedType(name.prefix(), it);
  11586. }
  11587. return this._cu.get_type(name);
  11588. }
  11589. importNamedType(qualifier, class_def) {
  11590. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  11591. if (class_def.bases.length === 0) {
  11592. this.importClass(qualified_name, class_def, false);
  11593. return;
  11594. }
  11595. const superclass_name = class_def.bases[0].id;
  11596. if (superclass_name === 'Module') {
  11597. this.importClass(qualified_name, class_def, true);
  11598. } else if (superclass_name === 'NamedTuple') {
  11599. this.importNamedTuple(qualified_name, class_def);
  11600. } else if (superclass_name === 'Interface') {
  11601. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  11602. } else if (superclass_name === 'ModuleInterface') {
  11603. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  11604. } else if (superclass_name === 'Enum') {
  11605. // importEnum(qualified_name, class_def);
  11606. } else {
  11607. throw new python.Error('TorchScript does not support class inheritance.');
  11608. }
  11609. }
  11610. importClass(qualified_classname, class_def, is_module) {
  11611. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  11612. return;
  11613. }
  11614. const parameter_names = new Set();
  11615. const buffer_names = new Set();
  11616. const methods = [];
  11617. const method_resolvers = [];
  11618. const attributes = [];
  11619. const constants = [];
  11620. const pre_hook_names = new Set();
  11621. const pre_hook_def_map = new Map();
  11622. const hook_names = new Set();
  11623. const hook_def_map = new Map();
  11624. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  11625. for (const stmt of class_def.body) {
  11626. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  11627. let target = null;
  11628. let annotation = null;
  11629. let value = null;
  11630. if (stmt instanceof ast.Assign) {
  11631. [target] = stmt.targets;
  11632. value = stmt.value;
  11633. } else {
  11634. target = stmt.target;
  11635. annotation = stmt.annotation;
  11636. value = stmt.value;
  11637. }
  11638. if (target instanceof ast.Name) {
  11639. const name = this._cu.execution.identifier(target);
  11640. switch (name) {
  11641. case '__annotations__': {
  11642. continue;
  11643. }
  11644. case '__parameters__': {
  11645. for (const elt of value.elts) {
  11646. parameter_names.add(elt.value);
  11647. }
  11648. break;
  11649. }
  11650. case '__buffers__': {
  11651. for (const elt of value.elts) {
  11652. buffer_names.add(elt.value);
  11653. }
  11654. break;
  11655. }
  11656. case '__forward_pre_hooks__': {
  11657. for (const elt of value.elts) {
  11658. pre_hook_names.add(elt.value);
  11659. }
  11660. break;
  11661. }
  11662. case '__forward_hooks__': {
  11663. for (const elt of value.elts) {
  11664. hook_names.add(elt.value);
  11665. }
  11666. break;
  11667. }
  11668. default: {
  11669. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  11670. if (fixed_up) {
  11671. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  11672. } else if (value) {
  11673. constants.push({ name, value, annotation });
  11674. } else {
  11675. attributes.push({ name, value, annotation });
  11676. }
  11677. break;
  11678. }
  11679. }
  11680. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  11681. const name = target.slice.value;
  11682. attributes.push({ name, value, annotation: stmt.value });
  11683. continue;
  11684. } else {
  11685. throw new python.Error('Unexpected statement kind in module metadata.');
  11686. }
  11687. } else if (stmt instanceof ast.FunctionDef) {
  11688. const def = stmt;
  11689. const def_name = def.name;
  11690. if (pre_hook_names.has(def_name)) {
  11691. pre_hook_def_map.set(def_name, def);
  11692. } else if (hook_names.has(def_name)) {
  11693. hook_def_map.set(def_name, def);
  11694. } else {
  11695. methods.push(def);
  11696. method_resolvers.push(this);
  11697. }
  11698. } else {
  11699. throw new python.Error('Unexpected statement kind in class body.');
  11700. }
  11701. }
  11702. const type_parser = new torch._C.ScriptTypeParser(this);
  11703. for (const assign of attributes) {
  11704. const name = assign.name;
  11705. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  11706. const is_parameter = parameter_names.has(name);
  11707. const is_buffer = buffer_names.has(name);
  11708. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  11709. }
  11710. for (const constant of constants) {
  11711. class_type.addConstant(constant.name, constant.value);
  11712. }
  11713. this._cu.register_type(class_type);
  11714. const self = new torch._C.SimpleSelf(class_type);
  11715. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  11716. }
  11717. importNamedTuple(qualified_name, named_tuple_def) {
  11718. const type_parser = new torch._C.ScriptTypeParser(this);
  11719. const field_names = [];
  11720. const field_types = [];
  11721. const field_defaults = [];
  11722. for (const stmt of named_tuple_def.body) {
  11723. if (stmt instanceof ast.AnnAssign === false) {
  11724. throw new python.Error('Unexpected statement in NamedTuple body.');
  11725. }
  11726. const assign = stmt;
  11727. const target = this._cu.execution.identifier(stmt.target);
  11728. // const annotation = this._cu.execution.type(stmt.annotation);
  11729. const type = type_parser.parseTypeFromExpr(assign.annotation);
  11730. field_names.push(target);
  11731. // field_types.push(annotation);
  11732. field_types.push(type);
  11733. }
  11734. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  11735. this._cu.register_type(tt);
  11736. }
  11737. importFunction(qualifier, def) {
  11738. const definitions = [def];
  11739. const resolvers = [this];
  11740. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  11741. }
  11742. parseSourceIfNeeded(qualifier) {
  11743. if (!qualifier || this._loaded_sources.has(qualifier)) {
  11744. return;
  11745. }
  11746. this._loaded_sources.add(qualifier);
  11747. const src = this._source_loader(qualifier);
  11748. if (!src) {
  11749. return;
  11750. }
  11751. const p = new torch._C.Parser(src);
  11752. const L = p.parse();
  11753. // const p = this._cu.execution.parse(src.filename(), src.text_str(), null);
  11754. this.parsePossibleVersionNumber(p);
  11755. for (const stmt of L.body) {
  11756. if (stmt instanceof ast.ClassDef) {
  11757. const name = `${qualifier}.${stmt.name}`;
  11758. this._to_be_defined.set(name, stmt);
  11759. } else if (stmt instanceof ast.FunctionDef) {
  11760. const name = `${qualifier}.${stmt.name}`;
  11761. this._to_be_defined.set(name, stmt);
  11762. }
  11763. }
  11764. }
  11765. parsePossibleVersionNumber(/* p */) {
  11766. }
  11767. parseImports(/* p */) {
  11768. }
  11769. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  11770. const replacements = new Map([
  11771. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  11772. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  11773. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  11774. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  11775. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  11776. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  11777. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  11778. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  11779. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  11780. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  11781. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  11782. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  11783. ]);
  11784. const mangleRe = /\.___torch_mangle_\d+/g;
  11785. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  11786. if (replacements.has(demangled_classname)) {
  11787. const lhs = assign.target;
  11788. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  11789. return null;
  11790. }
  11791. const type = assign.annotation.id;
  11792. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  11793. if (lhs.id === attr_name && type === expected_type) {
  11794. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  11795. const typename_expr = p.parseExp();
  11796. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  11797. }
  11798. }
  11799. return null;
  11800. }
  11801. LEGACY_import_methods(mod, src) {
  11802. const self = new torch._C.SimpleSelf(mod.type());
  11803. const prefix = mod.type().name();
  11804. const p = new torch._C.Parser(src);
  11805. const L = p.parse();
  11806. this.parsePossibleVersionNumber(L);
  11807. this.parseImports(L);
  11808. const definitions = [];
  11809. const resolvers = [];
  11810. for (const def of L.body) {
  11811. if (def instanceof ast.FunctionDef) {
  11812. definitions.push(def);
  11813. resolvers.push(this);
  11814. }
  11815. }
  11816. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  11817. }
  11818. findFunction(name) {
  11819. this.parseSourceIfNeeded(name.prefix());
  11820. const key = name.qualifiedName();
  11821. const it = this._to_be_defined.get(key);
  11822. if (it && it instanceof ast.FunctionDef) {
  11823. this._to_be_defined.delete(key);
  11824. this.importFunction(name.prefix(), it);
  11825. }
  11826. return this._cu.find_function(name);
  11827. }
  11828. });
  11829. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  11830. constructor(otherResolver, functionTable) {
  11831. super();
  11832. this._otherResolver = otherResolver;
  11833. this._functionTable = functionTable;
  11834. }
  11835. resolveValue(name, m, loc) {
  11836. const it = this._functionTable.get(name);
  11837. if (it) {
  11838. return new torch._C.FunctionValue(it);
  11839. }
  11840. return this._otherResolver.resolveValue(name, m, loc);
  11841. }
  11842. resolveType(name, loc) {
  11843. return this._otherResolver.resolveType(name, loc);
  11844. }
  11845. });
  11846. this.registerType('torch._C.SourceRangeUnpickler', class {
  11847. });
  11848. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  11849. constructor (data) {
  11850. super();
  11851. this.data = data;
  11852. this.deserializer = null;
  11853. this.unpickled_records = null;
  11854. }
  11855. unpickle() {
  11856. if (this.unpickled_records !== null) {
  11857. return;
  11858. }
  11859. /* const unpickler = new pickle.Unpickler(this.data);
  11860. const ivalues = unpickler.load(); */
  11861. this.unpickled_records = [];
  11862. }
  11863. findSourceRangeThatGenerated(/* range */) {
  11864. this.unpickle();
  11865. }
  11866. });
  11867. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  11868. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  11869. });
  11870. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  11871. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  11872. if (!reader.has_record(path)) {
  11873. return null;
  11874. }
  11875. const stream = reader.get_record(path);
  11876. let gen_ranges = null;
  11877. const debug_file = `${path}.debug_pkl`;
  11878. if (reader.has_record(debug_file)) {
  11879. const debug_stream = reader.get_record(debug_file);
  11880. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  11881. }
  11882. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  11883. });
  11884. this.registerType('torch._C.ScriptModuleDeserializer', class {
  11885. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  11886. this._compilation_unit = cu;
  11887. this._reader = reader;
  11888. this._storage_context = storage_context;
  11889. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  11890. this._pickle_dir_prefix = pickle_dir_prefix || '';
  11891. this._tensor_dir_prefix = tensor_dir_prefix || '';
  11892. this._constant_table = [];
  11893. const SourceLoader = (qualifier) => {
  11894. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  11895. };
  11896. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  11897. }
  11898. deserialize() {
  11899. const execution = this._compilation_unit.execution;
  11900. const code_prefix = this._code_prefix;
  11901. for (const name of this._reader.get_all_records()) {
  11902. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  11903. const file = name.substring(code_prefix.length);
  11904. const stream = this._reader.get_record(name);
  11905. const buffer = stream.peek();
  11906. execution.add(file, buffer);
  11907. }
  11908. }
  11909. const torch = execution.import('torch');
  11910. execution.builtins.torch = torch;
  11911. execution.builtins.Tensor = torch.Tensor;
  11912. execution.builtins.ops = torch.ops;
  11913. execution.builtins.inf = torch.inf;
  11914. execution.builtins.CONSTANTS = {};
  11915. execution._resolver = this._source_importer;
  11916. const known_types = [
  11917. { name: '__torch__.torch.classes._nnapi.Compilation', methods: [
  11918. '__init__(__torch__.torch.classes._nnapi.Compilation self) -> NoneType',
  11919. 'init(__torch__.torch.classes._nnapi.Compilation self, Tensor serialized_model_tensor, Tensor[] parameter_buffers) -> NoneType',
  11920. 'init2(__torch__.torch.classes._nnapi.Compilation self, Tensor serialized_model_tensor, Tensor[] parameter_buffers, int compilation_preference, bool relax_f32_to_f16) -> NoneType',
  11921. 'run(__torch__.torch.classes._nnapi.Compilation self, Tensor[] inputs, Tensor[] outputs) -> NoneType'
  11922. ] },
  11923. { name: '__torch__.torch.classes.quantized.Conv2dPackedParamsBase', attributes: 'Tensor weight, Tensor bias, int[] stride, int[] padding, int[] dilation, int groups', methods: ['unpack(__torch__.torch.classes.quantized.Conv2dPackedParamsBase self) -> ((Tensor, Tensor?))'] },
  11924. { name: '__torch__.torch.classes.quantized.Conv3dPackedParamsBase', attributes: 'Tensor weight, Tensor bias, int[] stride, int[] padding, int[] dilation, int groups', methods: ['unpack(__torch__.torch.classes.quantized.Conv3dPackedParamsBase self) -> ((Tensor, Tensor?))'] },
  11925. { name: '__torch__.torch.classes.quantized.LinearPackedParamsBase', attributes: 'Tensor weight, Tensor? bias' },
  11926. { name: '__torch__.torch.classes.rnn.CellParamsBase', attributes: 'str type, Tensor[] tensors, float[] doubles, int[] longs, __torch__.torch.classes.quantized.LinearPackedParamsBase[] packed_params' },
  11927. { name: '__torch__.torch.classes.xnnpack.Conv2dOpContext', attributes: 'Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups, int[] output_min, int[] output_max' },
  11928. { name: '__torch__.torch.classes.xnnpack.LinearOpContext', attributes: 'Tensor weight, Tensor bias, int[] output_min, int[] output_max' },
  11929. { name: '__torch__.torch.classes.xnnpack.TransposeConv2dOpContext', attributes: 'Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int[] dilation, int groups, int[] output_min, int[] output_max' },
  11930. ];
  11931. for (const known_type of known_types) {
  11932. const prefix = new torch._C.QualifiedName(known_type.name);
  11933. const type = torch.ClassType.create(known_type.name, this._compilation_unit, false);
  11934. for (const known_method of known_type.methods || []) {
  11935. const schema = new torch.FunctionSchema(known_method);
  11936. const name = new torch._C.QualifiedName(prefix, schema.name);
  11937. const fn = new torch._C.BuiltinOpFunction(name, schema);
  11938. type.addMethod(fn);
  11939. }
  11940. if (known_type.attributes) {
  11941. const schema = new torch.FunctionSchema(`(${known_type.attributes}) -> ()`);
  11942. for (const arg of schema.arguments) {
  11943. type.addAttribute(arg.name, arg.real_type);
  11944. }
  11945. }
  11946. torch._C.registerCustomClass(type);
  11947. // this._compilation_unit.register_type(type);
  11948. }
  11949. if (this._reader.has_record('model.json')) {
  11950. return this.LEGACY_deserialize();
  11951. }
  11952. const constants = this.readArchive('constants');
  11953. for (let i = 0; i < constants.length; i++) {
  11954. let val = constants[i];
  11955. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  11956. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  11957. const obj = torch.ScriptObject.create(type);
  11958. obj._ivalue = val;
  11959. val = obj;
  11960. }
  11961. execution.builtins.CONSTANTS[`c${i}`] = val;
  11962. this._constant_table.push(val);
  11963. }
  11964. const obj = this.readArchive('data');
  11965. const convertObject = (obj) => {
  11966. if (obj.__class__) {
  11967. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  11968. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  11969. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  11970. for (let i = 0; i < type.numAttributes(); i++) {
  11971. const k = type.getAttributeName(i);
  11972. const t = type.getAttribute(i);
  11973. const v = obj[k];
  11974. if (t instanceof torch.ClassType) {
  11975. module.__setattr__(k, convertObject(v));
  11976. } else {
  11977. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  11978. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  11979. type._attributes[i].type = this._source_importer.resolveType(name);
  11980. }
  11981. module.__setattr__(k, obj[k]);
  11982. }
  11983. }
  11984. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  11985. if (value && value.__class__ === builtins.method) {
  11986. module[key] = value;
  11987. }
  11988. }
  11989. return module;
  11990. }
  11991. throw new python.Error('Module class not found.');
  11992. };
  11993. return convertObject(obj);
  11994. }
  11995. LEGACY_deserialize() {
  11996. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  11997. const execution = this._compilation_unit.execution;
  11998. const caffe2 = execution.proto.caffe2;
  11999. const torch = execution.import('torch');
  12000. const stream = this._reader.get_record('model.json');
  12001. const buffer = stream.peek();
  12002. const decoder = new TextDecoder('utf-8');
  12003. const content = decoder.decode(buffer);
  12004. const obj = JSON.parse(content);
  12005. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  12006. const tensorTypeMap = new Map([
  12007. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  12008. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  12009. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  12010. [caffe2.TensorProto.DataType.INT8, 'Char'],
  12011. [caffe2.TensorProto.DataType.INT32, 'Int'],
  12012. [caffe2.TensorProto.DataType.INT64, 'Long']
  12013. ]);
  12014. const tensor_table = (model.tensors || []).map((constant) => {
  12015. const key = constant.data.key;
  12016. if (!tensorTypeMap.has(constant.data_type)) {
  12017. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  12018. }
  12019. const type = tensorTypeMap.get(constant.data_type);
  12020. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  12021. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  12022. const storage_type = execution.resolve(`torch.${type}Storage`);
  12023. const size = (shape || []).reduce((a, b) => a * b, 1);
  12024. const offset = parseInt(constant.offset, 10) || 0;
  12025. const storage = new storage_type(size);
  12026. const itemsize = storage.dtype.itemsize();
  12027. const stream = this._reader.get_record(key);
  12028. if (stream) {
  12029. const buffer = stream.peek();
  12030. const length = size * itemsize;
  12031. const data = buffer.slice(offset, offset + length);
  12032. storage._set_cdata(data);
  12033. }
  12034. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  12035. tensor.name = key;
  12036. return tensor;
  12037. });
  12038. execution.builtins.CONSTANTS = {};
  12039. for (let i = 0; i < tensor_table.length; i++) {
  12040. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  12041. }
  12042. const attributes = [];
  12043. if (this._reader.has_record('attributes.pkl')) {
  12044. const stream = this._reader.get_record('attributes.pkl');
  12045. const buffer = stream.peek();
  12046. const unpickler = new pickle.Unpickler(buffer);
  12047. const obj = unpickler.load();
  12048. attributes.push(...obj);
  12049. }
  12050. this._LEGACY_moduleStack = ['__torch__'];
  12051. const module_def = model.main_module;
  12052. for (const tensor of tensor_table) {
  12053. this._constant_table.push(tensor);
  12054. }
  12055. return this.LEGACY_convertModule(module_def);
  12056. }
  12057. LEGACY_convertModule(module_def) {
  12058. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  12059. const numPushed = atoms.length;
  12060. for (const atom of atoms) {
  12061. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  12062. this._LEGACY_moduleStack.push(sanitized);
  12063. }
  12064. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  12065. const module = new torch.ScriptModule(qn, this._compilation_unit);
  12066. for (const sub_def of module_def.submodules || []) {
  12067. const submodule = this.LEGACY_convertModule(sub_def);
  12068. module.register_module(sub_def.name, submodule);
  12069. }
  12070. for (const param_def of module_def.parameters || []) {
  12071. const tensor = this._constant_table[Number(param_def.tensor_id)];
  12072. if (param_def.isBuffer) {
  12073. module.register_buffer(param_def.name, tensor);
  12074. } else {
  12075. module.register_parameter(param_def.name, tensor, false);
  12076. }
  12077. }
  12078. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  12079. for (const attr_def of module_def.attributes || []) {
  12080. if (module.hasattr(attr_def.name)) {
  12081. continue;
  12082. }
  12083. throw new python.Error('Not implemented.');
  12084. // IValue ivalue;
  12085. // if (attr_def.id() >= 0) {
  12086. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  12087. // }
  12088. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  12089. }
  12090. if (module_def.torchscript_arena) {
  12091. const key = module_def.torchscript_arena.key;
  12092. const file = key.substring('code/'.length);
  12093. const name = file.replace(/\.py$/, '').split('/').join('.');
  12094. const code = execution.import(name);
  12095. if (code.forward.__class__ === execution.builtins.function) {
  12096. module.forward = code.forward;
  12097. }
  12098. }
  12099. // let gen_ranges = null;
  12100. if (module_def.torchscript_debug_arena) {
  12101. throw new python.Error('Not implemented.');
  12102. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  12103. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  12104. }
  12105. if (module_def.torchscript_arena) {
  12106. const filename = module_def.torchscript_arena.key;
  12107. const stream = this._reader.get_record(filename);
  12108. const data = stream.peek();
  12109. const src = new torch._C.Source(data, filename);
  12110. this._source_importer.LEGACY_import_methods(module, src);
  12111. }
  12112. /*
  12113. if (module_def.has_get_state_attribute_id()) {
  12114. LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  12115. }
  12116. const ClassTypePtr& module_type = module._ivalue()->type();
  12117. for (size_t i = 0, N = module_type->numAttributes(); i < N; ++i) {
  12118. const IValue& v = module._ivalue()->getSlot(i);
  12119. if (module_type->getAttribute(i)->kind() != TypeKind::OptionalType) {
  12120. TORCH_CHECK(!v.isNone(), "The field '", module_type->getAttributeName(i), "' was left unitialized after __setstate__, but expected a ", "value of type '", v.type()->repr_str(), "'");
  12121. }
  12122. }
  12123. */
  12124. for (let i = 0; i < numPushed; i++) {
  12125. this._LEGACY_moduleStack.pop();
  12126. }
  12127. return module;
  12128. }
  12129. readArchive(archive_name) {
  12130. const type_resolver = (qn) => {
  12131. const cls = this._source_importer.loadType(qn);
  12132. return cls;
  12133. };
  12134. const ObjLoaderFunc = (/* type, ivalue */) => {
  12135. };
  12136. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  12137. }
  12138. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  12139. const picklename = `${pickle_prefix + archive_name}.pkl`;
  12140. const stream = stream_reader.get_record(picklename);
  12141. if (!stream) {
  12142. throw new python.Error(`File '${picklename}' is not found.`);
  12143. }
  12144. const buffer = stream.peek();
  12145. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  12146. const read_record = (name) => {
  12147. const stream = stream_reader.get_record(tensor_dir_path + name);
  12148. return stream.length <= 0x40000 ? stream.peek() : stream;
  12149. };
  12150. const execution = this._compilation_unit.execution;
  12151. const pickle = execution.__import__('pickle');
  12152. const Unpickler = class extends pickle.Unpickler {
  12153. find_class(module, name) {
  12154. return super.find_class(module, name);
  12155. }
  12156. };
  12157. const unpickler = new Unpickler(buffer);
  12158. unpickler.persistent_load = (saved_id) => {
  12159. if (saved_id[0] !== 'storage') {
  12160. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  12161. }
  12162. const [, storage_type, key, , size] = saved_id;
  12163. if (storage_context && storage_context.has_storage(key)) {
  12164. return storage_context.get_storage(key);
  12165. }
  12166. const storage = new storage_type(size);
  12167. const storage_ptr = read_record(key);
  12168. storage._set_cdata(storage_ptr);
  12169. if (storage_context) {
  12170. storage_context.add_storage(key);
  12171. }
  12172. return storage;
  12173. };
  12174. return unpickler.load();
  12175. }
  12176. });
  12177. this.registerType('torch._C.WithInsertPoint', class {
  12178. constructor(...args) {
  12179. let n = null;
  12180. if (args.length === 1 && args[0] instanceof torch.Block) {
  12181. const [b] = args;
  12182. n = b.return_node();
  12183. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  12184. [n] = args;
  12185. } else {
  12186. throw new python.Error('Invalid arguments.');
  12187. }
  12188. this._prev = n.owningGraph().insertPoint();
  12189. n.owningGraph().setInsertPoint(n);
  12190. }
  12191. dispose() {
  12192. this._prev.owningGraph().setInsertPoint(this._prev);
  12193. }
  12194. });
  12195. this.registerType('torch._C.Environment', class {
  12196. constructor(method, resolver, b, next) {
  12197. this.method = method;
  12198. this.resolver = resolver;
  12199. this.b = b;
  12200. this.next = next;
  12201. this.value_table = new Map();
  12202. this.type_table = new Map();
  12203. this.error_messages = new Map();
  12204. }
  12205. setVariableTypeError(name, msg) {
  12206. let runner = this;
  12207. while (runner.next) {
  12208. runner = runner.next;
  12209. }
  12210. runner.error_messages.set(name, msg);
  12211. }
  12212. insertLoad(name, type) {
  12213. const g = this.b.owningGraph();
  12214. const load = g.insertNode(g.createLoad(name, type));
  12215. if (torch._C.meaningfulName(name)) {
  12216. load.output().setDebugName(name);
  12217. }
  12218. return new torch._C.SimpleValue(load.output());
  12219. }
  12220. insertStore(name, loc, v, type) {
  12221. const g = this.b.owningGraph();
  12222. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  12223. this.type_table.set(name, type);
  12224. }
  12225. findInThisFrame(name) {
  12226. if (this.value_table.has(name)) {
  12227. return this.value_table.get(name);
  12228. }
  12229. if (this.type_table.has(name)) {
  12230. return this.insertLoad(name, this.type_table.get(name));
  12231. }
  12232. return null;
  12233. }
  12234. findInParentFrame(name) {
  12235. return this.next ? this.next.findInAnyFrame(name) : null;
  12236. }
  12237. setType(name, type) {
  12238. this.type_table.set(name, type);
  12239. }
  12240. findInAnyFrame(name) {
  12241. for (let runner = this; runner; runner = runner.next) {
  12242. const r = runner.findInThisFrame(name);
  12243. if (r) {
  12244. return r;
  12245. }
  12246. }
  12247. return null;
  12248. }
  12249. block() {
  12250. return this.b;
  12251. }
  12252. setVar(loc, name, value) {
  12253. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  12254. }
  12255. setSugaredVar(loc, name, value, annotated_type) {
  12256. let as_simple_value = torch._C.asSimple(value);
  12257. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  12258. as_simple_value.setDebugName(name);
  12259. }
  12260. const parent = this.findInParentFrame(name);
  12261. if (parent) {
  12262. if (annotated_type) {
  12263. throw new python.Error('Type already defined in an outer block.');
  12264. }
  12265. if (!as_simple_value) {
  12266. throw new python.Error('Only reassignments to first-class values are allowed.');
  12267. }
  12268. const simple_parent = torch._C.asSimple(parent);
  12269. if (!simple_parent) {
  12270. throw new python.Error('Only reassignments to first-class values are allowed.');
  12271. }
  12272. const parent_type = torch._C.unshapedType(simple_parent.type());
  12273. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  12274. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  12275. throw new python.Error('Incompatible types.');
  12276. }
  12277. }
  12278. if (as_simple_value) {
  12279. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  12280. throw new python.Error('Invalid type.');
  12281. }
  12282. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  12283. this.insertStore(name, loc, as_simple_value, value_store_type);
  12284. } else {
  12285. this.value_table.set(name, value);
  12286. }
  12287. }
  12288. getSugaredVar(ident, range, required) {
  12289. required = required || true;
  12290. let retval = this.findInAnyFrame(ident);
  12291. if (!retval) {
  12292. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  12293. ['print', new torch._C.PrintValue()],
  12294. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  12295. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  12296. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  12297. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  12298. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  12299. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  12300. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  12301. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  12302. ['range', torch._C.SpecialFormValue.create('prim::range')],
  12303. ]);
  12304. if (torch._C.Environment.globals.has(ident)) {
  12305. retval = torch._C.Environment.globals.get(ident);
  12306. }
  12307. }
  12308. if (!retval) {
  12309. const type = this.resolver.resolveType(ident, range);
  12310. if (type instanceof torch.TupleType) {
  12311. retval = new torch.jit.NamedTupleConstructor(type);
  12312. }
  12313. }
  12314. if (!retval) {
  12315. retval = this.resolver.resolveValue(ident, this.method, range);
  12316. }
  12317. if (!retval) {
  12318. const type = this.resolver.resolveType(ident, range);
  12319. if (type instanceof torch.ClassType) {
  12320. retval = new torch.jit.ClassValue(type);
  12321. }
  12322. }
  12323. if (!retval && required) {
  12324. throw new python.Error(`The name '${ident}' is not defined.`);
  12325. }
  12326. return retval;
  12327. }
  12328. getVar(ident, range) {
  12329. return this.getSugaredVar(ident, range).asValue(range, this.method);
  12330. }
  12331. definedVariables() {
  12332. return Array.from(this.type_table.keys());
  12333. }
  12334. });
  12335. this.registerType('torch._C.Refinement', class {
  12336. constructor(identifier, type) {
  12337. this._identifier = identifier;
  12338. this._type = type;
  12339. }
  12340. identifier() {
  12341. return this._identifier;
  12342. }
  12343. type() {
  12344. return this._type;
  12345. }
  12346. });
  12347. this.registerType('torch._C.RefinementSet', class {
  12348. constructor(...args) {
  12349. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  12350. this._true_refinements = [args[0]];
  12351. this._false_refinements = [];
  12352. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  12353. this._true_refinements = [args[0]];
  12354. this._false_refinements = [args[1]];
  12355. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  12356. [this._true_refinements, this._false_refinements] = args;
  12357. } else {
  12358. throw new python.Error('Not implemented.');
  12359. }
  12360. }
  12361. Not() {
  12362. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  12363. }
  12364. activeRefinements() {
  12365. return this._true_refinements;
  12366. }
  12367. });
  12368. this.registerFunction('torch._C.CondValue', class {
  12369. constructor(...args) {
  12370. if (args.length === 3) {
  12371. [this._value, this._refinements, this._static_if] = args;
  12372. } else if (args.length === 4) {
  12373. const [g, loc, static_value, refinements] = args;
  12374. this._value = g.insertConstant(static_value, loc);
  12375. this._refinements = refinements;
  12376. this._static_if = static_value;
  12377. } else {
  12378. throw new python.Error('Invalid number of arguments.');
  12379. }
  12380. }
  12381. value() {
  12382. return this._value;
  12383. }
  12384. staticIf() {
  12385. return this._static_if;
  12386. }
  12387. refinements() {
  12388. return this._refinements;
  12389. }
  12390. });
  12391. this.registerFunction('torch._C.asSimple', (value) => {
  12392. if (value instanceof torch._C.SimpleValue) {
  12393. return value.getValue();
  12394. }
  12395. return null;
  12396. });
  12397. this.registerFunction('torch._C.meaningfulName', (name) => {
  12398. if (name.length === 0 && name[0] === '$') {
  12399. return false;
  12400. }
  12401. if (name[0] !== '_') {
  12402. return true;
  12403. }
  12404. return !/\d+/.test(name.slice(1));
  12405. });
  12406. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  12407. const key = `${val.value}:${val.tag}`;
  12408. const existing_constant = map.get(key);
  12409. if (existing_constant) {
  12410. return existing_constant;
  12411. }
  12412. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  12413. const new_constant = graph.insertConstant(val, r);
  12414. map.set(key, new_constant);
  12415. guard.dispose();
  12416. return new_constant;
  12417. });
  12418. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  12419. if (schema.overload_name) {
  12420. return `${schema.name}.${schema.overload_name}`;
  12421. }
  12422. return schema.name;
  12423. });
  12424. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  12425. const value_map_func = (v) => value_map.get(v);
  12426. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  12427. for (let i = 0; i < inputs.length; i++) {
  12428. value_map.set(callee.inputs()[i], inputs[i]);
  12429. }
  12430. for (const node of callee.nodes()) {
  12431. const new_node = g.insertNode(g.createClone(node, value_map_func));
  12432. for (let i = 0; i < node.outputs().length; i++) {
  12433. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  12434. }
  12435. }
  12436. const outputs = [];
  12437. for (const output of callee.outputs()) {
  12438. outputs.push(value_map_func(output));
  12439. }
  12440. return outputs;
  12441. });
  12442. this.registerType('TemplateEnv', class {
  12443. });
  12444. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  12445. constructor() {
  12446. this.state = 'UNINITIALIZED';
  12447. this._builtins_by_name = new Map();
  12448. }
  12449. getAllBuiltinFunctionsFor(name) {
  12450. if (this.state === 'UNINITIALIZED') {
  12451. this.loadBuiltinFunctions();
  12452. this.state = 'INITIALIZED';
  12453. }
  12454. if (!this._builtins_by_name.has(name)) {
  12455. return [];
  12456. }
  12457. return this._builtins_by_name.get(name);
  12458. }
  12459. loadBuiltinFunctions() {
  12460. /*
  12461. for (const scalar of ['float', 'int', 'complex']) {
  12462. const env = new torch.C.TemplateEnv();
  12463. env.s('Scalar', scalar);
  12464. this.loadSource(scalar_operators_source.format(env), 'aten');
  12465. }
  12466. for (auto scalar : {'float', 'int'}) {
  12467. const env = new torch.C.TemplateEnv();
  12468. env.s('Scalar', scalar);
  12469. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  12470. }
  12471. using str_pair = std::pair<std::string, std::string>;
  12472. const std::vector<str_pair> name_len = {
  12473. str_pair('single', '1'),
  12474. str_pair('pair', '2'),
  12475. str_pair('triple', '3'),
  12476. str_pair('quadruple', '4'),
  12477. };
  12478. for (const auto scalar : {'float', 'int'}) {
  12479. for (const auto& pair : name_len) {
  12480. const env = new torch.C.TemplateEnv();
  12481. env.s('Scalar', scalar);
  12482. env.s('name', pair.first);
  12483. env.s('Length', pair.second);
  12484. this.loadSource(_ntuple_ops.format(env), 'aten');
  12485. }
  12486. }
  12487. for (auto rhs : {'number', 'Tensor'}) {
  12488. at::jit::TemplateEnv env;
  12489. env.s('Rhs_Type', rhs);
  12490. this.loadSource(floordiv.format(env), 'aten');
  12491. }
  12492. this.loadSource(aten_ops, 'aten');
  12493. this.loadSource(aten_ops_additional, 'aten');
  12494. this.loadSource(tensor_properties, 'prim');
  12495. */
  12496. }
  12497. loadSource(/* source, the_namespace */) {
  12498. }
  12499. });
  12500. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  12501. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  12502. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  12503. });
  12504. this.registerFunction('torch._C.get_operator_version_map', () => {
  12505. return new Map();
  12506. });
  12507. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  12508. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  12509. let arg_type = arg.type;
  12510. if (arg_type instanceof torch._C.DynamicType) {
  12511. arg_type = arg_type.fallback();
  12512. }
  12513. const argument_is_list = arg_type instanceof torch.ListType;
  12514. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  12515. const arg_is_broadcasting_list = arg.N > 0;
  12516. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  12517. });
  12518. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  12519. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  12520. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  12521. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  12522. return true;
  12523. }
  12524. return false;
  12525. });
  12526. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  12527. if (opt_type instanceof torch._C.DynamicType) {
  12528. return torch._C.unwrapOptional(opt_type.fallback());
  12529. }
  12530. if (opt_type instanceof torch.OptionalType) {
  12531. return opt_type.getElementType();
  12532. }
  12533. return opt_type;
  12534. });
  12535. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  12536. const possibleSchemas = [];
  12537. if (version === undefined) {
  12538. return possibleSchemas;
  12539. }
  12540. for (const entry of torch._C.get_operator_version_map()) {
  12541. const old_symbol_name = entry.first;
  12542. const base_name = old_symbol_name.substr(0, old_symbol_name.find('.'));
  12543. if (base_name === name) {
  12544. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  12545. if (possibleUpgrader.has_value()) {
  12546. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  12547. }
  12548. }
  12549. }
  12550. return possibleSchemas;
  12551. });
  12552. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  12553. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  12554. return current_version < latest_update;
  12555. });
  12556. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  12557. const it = torch._C.get_operator_version_map().get(name);
  12558. if (it) {
  12559. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  12560. }
  12561. return true;
  12562. });
  12563. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  12564. if (values.length === 1) {
  12565. return values[0];
  12566. }
  12567. let named_tuple = null;
  12568. if (field_names) {
  12569. const types = values.map((v) => v.type());
  12570. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  12571. }
  12572. return g.insertNode(g.createTuple(values, named_tuple)).output();
  12573. });
  12574. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  12575. const v_type = value.type();
  12576. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  12577. return false;
  12578. }
  12579. const arg_type = torch._C.unwrapOptional(arg.type);
  12580. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  12581. });
  12582. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  12583. const list_type = list_type_;
  12584. if (list_type instanceof torch.ListType === false) {
  12585. return false;
  12586. }
  12587. if (type.isSubtypeOf(list_type_)) {
  12588. return true;
  12589. }
  12590. if (type instanceof torch.TupleType) {
  12591. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  12592. }
  12593. return false;
  12594. });
  12595. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  12596. for (let i = 0; i < kwargs.length; i++) {
  12597. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  12598. return i;
  12599. }
  12600. if (kwargs[i].name() === name) {
  12601. return i;
  12602. }
  12603. }
  12604. return null;
  12605. });
  12606. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  12607. const elem_arg = new torch.Argument('<varargs>', elem_type);
  12608. const list_elements = [];
  12609. for (const named_value of varargs) {
  12610. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  12611. if (!matched_value) {
  12612. return null;
  12613. }
  12614. list_elements.push(matched_value);
  12615. }
  12616. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  12617. });
  12618. this.registerType('torch._C.MatchTypeReturn', class {
  12619. constructor(reason) {
  12620. this._reason = reason;
  12621. }
  12622. static Success() {
  12623. return new torch._C.MatchTypeReturn(null);
  12624. }
  12625. success() {
  12626. return this._reason === null;
  12627. }
  12628. });
  12629. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  12630. if (!formal.hasFreeVariables()) {
  12631. if (formal instanceof torch._C.DynamicType) {
  12632. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  12633. }
  12634. return torch._C.MatchTypeReturn.Success();
  12635. }
  12636. if (formal instanceof torch._C.VarType) {
  12637. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  12638. if (it === null) {
  12639. type_env.set(formal.name(), actual);
  12640. return torch._C.MatchTypeReturn.Success();
  12641. } else if (torch._C.unifyTypes(it, actual)) {
  12642. return torch._C.MatchTypeReturn.Success();
  12643. }
  12644. return new torch._C.MatchTypeReturn('Cannot match var.');
  12645. } else if (formal instanceof torch.ListType) {
  12646. if (actual instanceof torch.ListType) {
  12647. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  12648. if (!innerMatch.success()) {
  12649. return innerMatch;
  12650. }
  12651. return torch._C.MatchTypeReturn.Success();
  12652. } else if (actual instanceof torch.TupleType) {
  12653. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  12654. if (maybe_tuple_unified) {
  12655. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  12656. }
  12657. }
  12658. return new torch._C.MatchTypeReturn('Cannot match list.');
  12659. } else if (formal instanceof torch.TupleType) {
  12660. if (actual instanceof torch.TupleType) {
  12661. if (formal.elements().length !== actual.elements().length) {
  12662. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  12663. }
  12664. for (let i = 0; i < formal.elements().length; i++) {
  12665. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  12666. if (!result.success()) {
  12667. return result;
  12668. }
  12669. }
  12670. return torch._C.MatchTypeReturn.Success();
  12671. }
  12672. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  12673. } else if (formal instanceof torch.FutureType) {
  12674. if (actual instanceof torch.FutureType) {
  12675. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  12676. if (!innerMatch.success()) {
  12677. return innerMatch;
  12678. }
  12679. return torch._C.MatchTypeReturn.Success();
  12680. }
  12681. return new torch._C.MatchTypeReturn('Cannot match future.');
  12682. } else if (formal instanceof torch.AwaitType) {
  12683. if (actual instanceof torch.AwaitType) {
  12684. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  12685. if (!innerMatch.success()) {
  12686. return innerMatch;
  12687. }
  12688. return torch._C.MatchTypeReturn.Success();
  12689. }
  12690. return new torch._C.MatchTypeReturn('Cannot match await.');
  12691. } else if (formal instanceof torch.RRefType) {
  12692. if (actual instanceof torch.RRefType) {
  12693. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  12694. if (!innerMatch.success()) {
  12695. return innerMatch;
  12696. }
  12697. return torch._C.MatchTypeReturn.Success();
  12698. }
  12699. return new torch._C.MatchTypeReturn('Cannot match rref.');
  12700. } else if (formal instanceof torch.OptionalType) {
  12701. if (actual instanceof torch.OptionalType) {
  12702. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  12703. if (!optionedMatch.success()) {
  12704. return optionedMatch;
  12705. }
  12706. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  12707. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  12708. }
  12709. return torch._C.MatchTypeReturn.Success();
  12710. } else if (formal instanceof torch.DictType) {
  12711. if (actual instanceof torch.DictType) {
  12712. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  12713. if (!key_match.success()) {
  12714. return key_match;
  12715. }
  12716. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  12717. if (!value_match.success()) {
  12718. return value_match;
  12719. }
  12720. return torch._C.MatchTypeReturn.Success();
  12721. }
  12722. return new torch._C.MatchTypeReturn('Cannot match dict.');
  12723. }
  12724. throw new python.Error('Unhandled free variable container.');
  12725. });
  12726. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  12727. let value = named_value.value(graph);
  12728. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  12729. const repeated = Array(arg.N).fill(value);
  12730. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  12731. }
  12732. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  12733. if (!matched.success()) {
  12734. if (failure_messages) {
  12735. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  12736. }
  12737. return null;
  12738. }
  12739. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  12740. if (!concrete_type) {
  12741. if (failure_messages) {
  12742. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  12743. }
  12744. return null;
  12745. }
  12746. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  12747. if (!value.type().isSubtypeOf(concrete_type)) {
  12748. if (failure_messages) {
  12749. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  12750. }
  12751. return null;
  12752. }
  12753. return value;
  12754. });
  12755. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  12756. if (concrete_type instanceof torch.OptionalType) {
  12757. const op = concrete_type;
  12758. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  12759. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  12760. }
  12761. }
  12762. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  12763. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  12764. }
  12765. if (value.type() instanceof torch.TupleType) {
  12766. const value_tuple = value.type();
  12767. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  12768. const unpacked = torch._C.createTupleUnpack(value);
  12769. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  12770. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  12771. }
  12772. if (concrete_type instanceof torch.TupleType) {
  12773. const concrete_tuple = concrete_type;
  12774. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  12775. concrete_tuple.elements().length === value_tuple.elements().length) {
  12776. const unpacked = torch._C.createTupleUnpack(value);
  12777. const converted = [];
  12778. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  12779. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  12780. }
  12781. value = graph.insertNode(graph.createTuple(converted)).output();
  12782. }
  12783. }
  12784. }
  12785. if (allow_conversions) {
  12786. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  12787. const value_equals_number = value.type() === torch.NumberType.get();
  12788. const concrete_float = concrete_type === torch.FloatType.get();
  12789. const concrete_complex = concrete_type === torch.ComplexType.get();
  12790. const concrete_int = concrete_type === torch.IntType.get();
  12791. const concrete_number = concrete_type === torch.NumberType.get();
  12792. if (value_isa_tensor) {
  12793. if (concrete_float) {
  12794. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  12795. } else if (concrete_complex) {
  12796. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  12797. } else if (concrete_int) {
  12798. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  12799. } else if (concrete_number) {
  12800. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  12801. }
  12802. } else if (value_equals_number) {
  12803. if (concrete_float) {
  12804. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  12805. } else if (concrete_complex) {
  12806. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  12807. } else if (concrete_int) {
  12808. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  12809. }
  12810. } else if (value.type() === torch.BoolType.get()) {
  12811. if (concrete_float) {
  12812. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  12813. } else if (concrete_int || concrete_number) {
  12814. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  12815. }
  12816. }
  12817. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  12818. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  12819. }
  12820. }
  12821. return value;
  12822. });
  12823. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  12824. if (!type.hasFreeVariables()) {
  12825. if (type instanceof torch._C.DynamicType) {
  12826. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  12827. }
  12828. return type;
  12829. }
  12830. if (type instanceof torch._C.VarType) {
  12831. return type_env.get(type.annotation_str);
  12832. }
  12833. const contained = type.containedTypes();
  12834. if (contained.length === 0) {
  12835. return type;
  12836. }
  12837. const new_contained = [];
  12838. for (const t of contained) {
  12839. const r = torch._C.tryEvalTypeVariables(t, type_env);
  12840. if (!r) {
  12841. return null;
  12842. }
  12843. new_contained.push(r);
  12844. }
  12845. return type.withContained(new_contained);
  12846. });
  12847. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  12848. if (torch._C.isBlockListedSchema(schema)) {
  12849. return null;
  12850. }
  12851. const err = null;
  12852. const type_env = new Map();
  12853. const positional_inputs = [];
  12854. const used_kwarg = kwargs.map(() => false);
  12855. const is_aten = schema.name.startsWith('aten::');
  12856. let used_args = 0;
  12857. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  12858. const arg = schema.arguments[schema_i];
  12859. let actual_named_value = null;
  12860. if (arg.name === 'self' && self) {
  12861. actual_named_value = self;
  12862. self = null;
  12863. } else if (!arg.kwarg_only && used_args < args.length) {
  12864. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  12865. const value = args[used_args].value(graph);
  12866. const actual_type = value.type();
  12867. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  12868. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  12869. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  12870. if (!list) {
  12871. return null;
  12872. }
  12873. used_args = args.length;
  12874. positional_inputs.push(list);
  12875. continue;
  12876. }
  12877. }
  12878. actual_named_value = args[used_args];
  12879. used_args++;
  12880. } else {
  12881. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  12882. if (Number.isInteger(kwarg_idx)) {
  12883. const nv = kwargs[kwarg_idx];
  12884. if (used_kwarg[kwarg_idx]) {
  12885. if (failure_messages) {
  12886. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  12887. }
  12888. return null;
  12889. }
  12890. used_kwarg[kwarg_idx] = true;
  12891. actual_named_value = nv;
  12892. } else if (arg.has_default_value()) {
  12893. actual_named_value = new torch._C.NamedValue(arg.default_value);
  12894. } else {
  12895. if (failure_messages) {
  12896. throw new python.Error(`Argument '${arg.name}' not provided.`);
  12897. }
  12898. return null;
  12899. }
  12900. }
  12901. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  12902. if (!positional) {
  12903. return null;
  12904. }
  12905. positional_inputs.push(positional);
  12906. }
  12907. if (self !== null) {
  12908. if (failure_messages) {
  12909. throw new python.Error('Provided self argument not used in schema.');
  12910. }
  12911. return null;
  12912. }
  12913. if (schema.is_vararg) {
  12914. for (; used_args < args.length; used_args++) {
  12915. positional_inputs.push(args[used_args].value(graph));
  12916. }
  12917. }
  12918. if (used_args < args.length) {
  12919. if (failure_messages) {
  12920. throw new python.Error('Too many positional arguments.');
  12921. }
  12922. return null;
  12923. }
  12924. for (let i = 0; i < kwargs.length; i++) {
  12925. const nv = kwargs[i];
  12926. if (!used_kwarg[i]) {
  12927. if (failure_messages) {
  12928. if (schema.argumentIndexWithName(nv.name())) {
  12929. throw new python.Error('Keyword argument specified twice.');
  12930. } else {
  12931. throw new python.Error('Keyword argument unknown.');
  12932. }
  12933. }
  12934. return null;
  12935. }
  12936. }
  12937. const returns = schema.returns;
  12938. const return_types = returns.map((r) => {
  12939. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  12940. if (!result) {
  12941. throw new python.Error('Unbound type variable.');
  12942. }
  12943. return result;
  12944. });
  12945. const return_has_field_names = returns.every((r) => !r.name);
  12946. let return_field_names = null;
  12947. if (return_has_field_names) {
  12948. return_field_names = returns.map((r) => r.name);
  12949. }
  12950. const schema_name = torch._C.getFullSchemaName(schema);
  12951. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  12952. });
  12953. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  12954. self = self || null;
  12955. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  12956. if (result) {
  12957. return result;
  12958. }
  12959. throw new python.Error(`No matching schema '${schema.name}' found.`);
  12960. });
  12961. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  12962. self = self || null;
  12963. render_errors = render_errors || false;
  12964. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  12965. if (schemas.length === 1) {
  12966. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  12967. }
  12968. for (const allow_conversions of [false, true]) {
  12969. for (let i = 0; i < schemas.length; i++) {
  12970. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  12971. if (matched_schema) {
  12972. return [i, matched_schema];
  12973. }
  12974. }
  12975. }
  12976. if (!render_errors) {
  12977. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  12978. }
  12979. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  12980. });
  12981. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  12982. const variants = torch._C.getAllOperatorsFor(name);
  12983. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  12984. const graph_version = graph.get_op_version();
  12985. const schemas = [];
  12986. const upgrader_schemas = [];
  12987. for (const op of variants) {
  12988. let found_upgrader = false;
  12989. const op_name = torch._C.getFullSchemaName(op.schema());
  12990. if (Number.isInteger(graph_version)) {
  12991. const version_entry = torch._C.get_operator_version_map().get(op_name);
  12992. if (version_entry) {
  12993. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  12994. if (old_schema_entry.has_value()) {
  12995. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  12996. upgrader_schemas.push(old_schema);
  12997. found_upgrader = true;
  12998. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  12999. throw new python.Error('Valid upgrader must be present.');
  13000. }
  13001. }
  13002. }
  13003. if (!found_upgrader) {
  13004. schemas.push(op.schema());
  13005. }
  13006. }
  13007. if (variants.length === 0) {
  13008. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  13009. for (const old_schema_entry of oldSchemas) {
  13010. const old_schema = torch._C.parseSchema(old_schema_entry);
  13011. upgrader_schemas.push(old_schema);
  13012. }
  13013. }
  13014. for (const schema of upgrader_schemas) {
  13015. schemas.push(schema);
  13016. }
  13017. for (const method of builtin_functions) {
  13018. method.ensure_defined();
  13019. schemas.push(method.getSchema());
  13020. }
  13021. if (schemas.length === 0) {
  13022. const user_function_name = name;
  13023. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  13024. }
  13025. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  13026. if (matched[0] < variants.length + upgrader_schemas.length) {
  13027. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  13028. }
  13029. const fn = builtin_functions[matched.first - variants.size()];
  13030. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  13031. });
  13032. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  13033. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  13034. for (const ret of matched_schema.return_types) {
  13035. n.addOutput().setType(ret);
  13036. }
  13037. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  13038. n.getOperation();
  13039. } else {
  13040. n.setHistoricSchemaName(matched_schema.schema_name);
  13041. }
  13042. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  13043. });
  13044. this.registerFunction('torch._C.unshapedType', (type) => {
  13045. if (type.isSubtypeOf(torch.TensorType.get())) {
  13046. return torch.TensorType.get();
  13047. }
  13048. const contained = type.containedTypes();
  13049. if (contained.length === 0) {
  13050. return type;
  13051. }
  13052. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  13053. });
  13054. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  13055. default_to_union = default_to_union || false;
  13056. type_hint = type_hint || null;
  13057. if (t1.isSubtypeOf(t2)) {
  13058. return t2;
  13059. } else if (t2.isSubtypeOf(t1)) {
  13060. return t1;
  13061. }
  13062. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  13063. return t1.merge(t2);
  13064. }
  13065. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  13066. return torch.OptionalType.create(t2);
  13067. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  13068. return torch.OptionalType.create(t1);
  13069. }
  13070. if (t1 instanceof torch.OptionalType) {
  13071. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  13072. if (elem) {
  13073. return torch.OptionalType.create(elem);
  13074. }
  13075. } else if (t2 instanceof torch.OptionalType) {
  13076. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  13077. if (elem) {
  13078. return torch.OptionalType.create(elem);
  13079. }
  13080. }
  13081. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  13082. if (t1.elements().size() !== t2.elements().size()) {
  13083. return null;
  13084. }
  13085. const elements = [];
  13086. for (let i = 0; i < t1.elements().length; i++) {
  13087. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  13088. if (elem) {
  13089. elements.push(elem);
  13090. } else {
  13091. return null;
  13092. }
  13093. }
  13094. return torch.TupleType.create(elements);
  13095. }
  13096. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  13097. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  13098. if (elem) {
  13099. return torch.FutureType.create(elem);
  13100. }
  13101. }
  13102. const t1_unshaped = torch._C.unshapedType(t1);
  13103. const t2_unshaped = torch._C.unshapedType(t2);
  13104. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  13105. return t2_unshaped;
  13106. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  13107. return t1_unshaped;
  13108. }
  13109. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  13110. return type_hint;
  13111. }
  13112. return null;
  13113. });
  13114. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  13115. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  13116. if (default_to_union && !unified) {
  13117. return torch.UnionType.create([t1, t2]);
  13118. }
  13119. return unified;
  13120. });
  13121. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  13122. if (elements.length === 0) {
  13123. return null;
  13124. }
  13125. let [ret_type] = elements;
  13126. for (let i = 1; i < elements.length && ret_type; i++) {
  13127. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  13128. if (!maybe_unified) {
  13129. return null;
  13130. }
  13131. ret_type = maybe_unified;
  13132. }
  13133. return ret_type;
  13134. });
  13135. this.registerFunction('torch._C.insertableTensor', (ten) => {
  13136. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  13137. });
  13138. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  13139. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  13140. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  13141. ivalue.isDevice() || ivalue.isEnum()) {
  13142. return true;
  13143. }
  13144. if (ivalue.isTensor()) {
  13145. return torch._C.insertableTensor(ivalue.toTensor());
  13146. }
  13147. if (ivalue.isList() || ivalue.isTuple()) {
  13148. let elems = [];
  13149. if (ivalue.isTuple()) {
  13150. elems = ivalue.toTupleRef().elements();
  13151. } else {
  13152. elems = ivalue.toListRef();
  13153. }
  13154. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  13155. }
  13156. if (ivalue.isGenericDict()) {
  13157. const dict = ivalue.toGenericDict();
  13158. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  13159. }
  13160. return false;
  13161. });
  13162. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  13163. loc = loc || null;
  13164. scope = scope || null;
  13165. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  13166. if (value !== undefined) {
  13167. return value;
  13168. }
  13169. throw new python.Error('Unsupported value kind.');
  13170. });
  13171. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  13172. if (val instanceof torch._C.IValue) {
  13173. const n = g.create('prim::Constant');
  13174. if (val.isTensor()) {
  13175. const ref = val.toTensor();
  13176. if (!torch._C.insertableTensor(val.toTensor())) {
  13177. n.destroy();
  13178. return null;
  13179. }
  13180. if (!ref.defined()) {
  13181. n.destroy();
  13182. return g.insertNode(g.createNone()).output();
  13183. }
  13184. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  13185. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  13186. n.t_('value', ref);
  13187. } else if (val.isInt()) {
  13188. n.i_('value', val.toInt());
  13189. n.output().setType(torch.IntType.get());
  13190. } else if (val.isDouble()) {
  13191. n.f_('value', val.toDouble());
  13192. n.output().setType(torch.FloatType.get());
  13193. } else if (val.isComplexDouble()) {
  13194. n.c_('value', val.toComplexDouble());
  13195. n.output().setType(torch.ComplexType.get());
  13196. } else if (val.isBool()) {
  13197. n.i_('value', val.toBool());
  13198. n.output().setType(torch.BoolType.get());
  13199. } else if (val.isList()) {
  13200. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  13201. if (fast_path_list || torch._C.insertableIValue(val)) {
  13202. n.ival_('value', val);
  13203. n.output().setType(val.type());
  13204. } else {
  13205. n.destroy();
  13206. return null;
  13207. }
  13208. } else if (val.isString()) {
  13209. n.s_('value', val.toStringRef());
  13210. n.output().setType(torch.StringType.get());
  13211. } else if (val.isDevice()) {
  13212. n.s_('value', val.toDevice().__str__());
  13213. n.output().setType(torch.DeviceObjType.get());
  13214. } else if (val.isGenerator()) {
  13215. n.ival_('value', val.toGenerator());
  13216. n.output().setType(torch._C_._GeneratorType.get());
  13217. } else if (val.isStream()) {
  13218. n.ival_('value', val);
  13219. n.output().setType(torch.StreamObjType.get());
  13220. } else if (val.isNone()) {
  13221. n.output().setType(torch.NoneType.get());
  13222. } else if (val.isTuple()) {
  13223. if (torch._C.insertableIValue(val)) {
  13224. n.ival_('value', val);
  13225. n.output().setType(val.type());
  13226. } else {
  13227. n.destroy();
  13228. return null;
  13229. }
  13230. } else if (val.isObject()) {
  13231. const ref = val.toObjectRef();
  13232. // see: [Constant Object Weak CompilationUnit Reference]
  13233. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  13234. n.ival_('value', val);
  13235. n.output().setType(val.type());
  13236. } else {
  13237. n.destroy();
  13238. return null;
  13239. }
  13240. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  13241. n.ival_('value', val);
  13242. n.output().setType(val.type());
  13243. } else {
  13244. n.destroy();
  13245. return null;
  13246. }
  13247. if (loc) {
  13248. n.setSourceRange(loc);
  13249. }
  13250. if (scope) {
  13251. n.setScope(scope);
  13252. }
  13253. return g.insertNode(n).output();
  13254. }
  13255. const n = g.create('prim::Constant');
  13256. let type = null;
  13257. if (val === null) {
  13258. n.ival_('value', val);
  13259. type = torch.NoneType.get();
  13260. } else if (typeof val === 'string') {
  13261. n.s_('value', val);
  13262. type = torch.StringType.get();
  13263. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  13264. n.ss_('value', val);
  13265. type = torch.ListType.create(torch.StringType.get());
  13266. } else if (typeof val === 'boolean') {
  13267. n.i_('value', val === true ? 1 : 0);
  13268. type = torch.BoolType.get();
  13269. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  13270. n.i_('value', val);
  13271. type = torch.IntType.get();
  13272. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  13273. n.f_('value', val);
  13274. type = torch.FloatType.get();
  13275. } else if (val instanceof torch.Tensor) {
  13276. n.t_('value', val);
  13277. type = torch.TensorType.get();
  13278. } else if (val instanceof torch.ScriptObject) {
  13279. n.ival_('value', val);
  13280. type = val.type();
  13281. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  13282. n.ival_('value', val);
  13283. type = torch.ListType.create(torch.IntType.get());
  13284. } else {
  13285. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  13286. }
  13287. if (type) {
  13288. n.output().setType(type);
  13289. }
  13290. if (loc) {
  13291. n.setSourceRange(loc);
  13292. }
  13293. if (scope) {
  13294. n.setScope(scope);
  13295. }
  13296. return g.insertNode(n).output();
  13297. });
  13298. this.registerFunction('torch._C.toIValue', (v) => {
  13299. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  13300. return null;
  13301. }
  13302. const node = v.node();
  13303. const type = v.type();
  13304. if (type.isSubtypeOf(torch.TensorType.get())) {
  13305. return new torch._C.IValue(node.t('value'), 'Tensor');
  13306. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  13307. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  13308. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  13309. return new torch._C.IValue(node.i('value'), 'Int');
  13310. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  13311. return new torch._C.IValue(node.f('value'), 'Double');
  13312. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'c') {
  13313. return new torch._C.IValue(node.c('value'), 'Complex');
  13314. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  13315. const list = new torch._C.IValue(node.ival('value'));
  13316. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  13317. return list;
  13318. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  13319. const dict = node.ival('value');
  13320. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  13321. return dict;
  13322. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  13323. const tup = node.ival('value');
  13324. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  13325. return tup;
  13326. } else if (type === torch.StringType.get()) {
  13327. const s = new torch._C.IValue(node.s('value'), 'String');
  13328. return s;
  13329. } else if (type === torch.DeviceObjType.get()) {
  13330. const d = new torch.device(node.s('value'));
  13331. return new torch._C.IValue(d);
  13332. } else if (type === torch._C._GeneratorType.get()) {
  13333. throw new python.Error('Not implemented.');
  13334. // const generator = node.ival('value').toGenerator();
  13335. // return generator;
  13336. } else if (type === torch.StreamObjType.get()) {
  13337. throw new python.Error('Not implemented.');
  13338. // const s = node.ival('value').toStream();
  13339. // return s;
  13340. } else if (node.mustBeNone()) {
  13341. return new torch._C.IValue();
  13342. } else if (type.kind() === 'EnumType') {
  13343. const enum_val = node.ival('value');
  13344. return enum_val;
  13345. } else if (type instanceof torch.ClassType && !type.is_module()) {
  13346. const class_val = node.ival('value');
  13347. return new torch._C.IValue(class_val, 'Object');
  13348. }
  13349. throw new python.Error('Unsupported constant literal.');
  13350. });
  13351. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  13352. const ivalue = torch._C.toIValue(v);
  13353. if (ivalue) {
  13354. return ivalue[target]();
  13355. }
  13356. return default_value === undefined ? null : default_value;
  13357. });
  13358. this.registerType('torch._C.NamedValue', class {
  13359. constructor(...args) {
  13360. if (args.length === 1) {
  13361. if (args[0] instanceof torch.Value) {
  13362. [this._value] = args;
  13363. } else {
  13364. [this._ivalue] = args;
  13365. }
  13366. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  13367. [this._loc, this._name, this._value] = args;
  13368. } else {
  13369. throw new python.Error('Invalid argument.');
  13370. }
  13371. }
  13372. name() {
  13373. return this._name;
  13374. }
  13375. value(g) {
  13376. if (!this._value) {
  13377. return torch._C.insertConstant(g, this._ivalue);
  13378. }
  13379. return this._value;
  13380. }
  13381. });
  13382. this.registerType('torch._C.SugaredValue', class {
  13383. kind() {
  13384. throw new python.Error('Not implemented.');
  13385. }
  13386. shouldEmitUnrolled() {
  13387. return this.staticLen() !== null;
  13388. }
  13389. });
  13390. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  13391. constructor(value) {
  13392. super();
  13393. this._value = value;
  13394. }
  13395. kind() {
  13396. return `value of type '${this._value.type().annotation_str}'`;
  13397. }
  13398. asValue(/* range, m */) {
  13399. return this._value;
  13400. }
  13401. getValue() {
  13402. return this._value;
  13403. }
  13404. asTuple(loc, m, size_hint) {
  13405. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  13406. if (this._value.type() instanceof torch.TupleType) {
  13407. const outputs = torch._C.createTupleUnpack(this._value);
  13408. return outputs.map((v) => make_simple_value(v));
  13409. } else if (this._value.type() instanceof torch.ListType) {
  13410. if (!size_hint) {
  13411. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  13412. }
  13413. const graph = this._value.owningGraph();
  13414. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  13415. return unpack.outputs().map((v) => make_simple_value(v));
  13416. } else if (this._value.type().kind() === 'AnyTupleType') {
  13417. throw new python.Error('Provided tuple is not fully defined including its element types.');
  13418. }
  13419. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  13420. }
  13421. attr(loc, m, field) {
  13422. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  13423. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  13424. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  13425. }
  13426. }
  13427. if (this._value.type() instanceof torch.TupleType) {
  13428. throw new python.Error('Not implemented.');
  13429. }
  13430. if (this._value.type() instanceof torch.AwaitType) {
  13431. throw new python.Error('Not implemented.');
  13432. }
  13433. if (this._value.type() instanceof torch.ClassType) {
  13434. const classType = this._value.type();
  13435. if (classType.findMethod(field)) {
  13436. return new torch._C.MethodValue(this.getValue(), [field]);
  13437. }
  13438. if (classType.hasAttribute(field)) {
  13439. const g = m.graph();
  13440. const n = g.insertNode(g.createGetAttr(this._value, field));
  13441. return new torch._C.SimpleValue(n.output());
  13442. }
  13443. const prop = classType.getProperty(field);
  13444. if (prop) {
  13445. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  13446. }
  13447. } else if (this._value.type() instanceof torch.InterfaceType) {
  13448. throw new python.Error('Not implemented.');
  13449. } /* else if (this._value.type() instanceof torch.EnumType) {
  13450. const g = m.graph();
  13451. if (field == 'name') {
  13452. const n = g.insertNode(g.createEnumName(value_));
  13453. return std::make_shared<SimpleValue>(n->output());
  13454. }
  13455. if (field == 'value') {
  13456. const n = g.insertNode(g.createEnumValue(value_));
  13457. return std::make_shared<SimpleValue>(n->output());
  13458. }
  13459. } */
  13460. if (field === 'type') {
  13461. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  13462. if (builtin) {
  13463. return builtin;
  13464. }
  13465. }
  13466. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  13467. if (builtin) {
  13468. return builtin;
  13469. }
  13470. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  13471. return torch._C.SpecialFormValue.create('prim::tolist');
  13472. }
  13473. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  13474. return torch._C.SpecialFormValue.create('aten::index');
  13475. }
  13476. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  13477. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  13478. if (builtin) {
  13479. return builtin;
  13480. }
  13481. }
  13482. throw new python.Error('Object has no attribute or method.');
  13483. }
  13484. setAttr(loc, m, field, newValue) {
  13485. const type = this._value.type();
  13486. if (type instanceof torch.ClassType === false) {
  13487. throw new python.Error('Cannot set attribute on non-class type.');
  13488. }
  13489. const classType = type;
  13490. let expectedType = classType.findAttribute(field);
  13491. if (!expectedType) {
  13492. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  13493. if (isInitializing) {
  13494. if (this.isRecursive(classType, newValue.type())) {
  13495. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  13496. }
  13497. classType.addAttribute(field, newValue.type());
  13498. expectedType = newValue.type();
  13499. const insertPoint = m.graph().insertPoint();
  13500. const topLevelBlock = m.graph().block();
  13501. if (insertPoint.owningBlock() !== topLevelBlock) {
  13502. throw new python.Error('First assignment cannot be in a control-flow block.');
  13503. }
  13504. } else {
  13505. const prop = classType.getProperty(field);
  13506. if (prop && prop.setter) {
  13507. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  13508. return;
  13509. }
  13510. if (prop && !prop.setter) {
  13511. throw new python.Error('Tried to set read-only attribute.');
  13512. }
  13513. throw new python.Error('Tried to set nonexistent attribute.');
  13514. }
  13515. }
  13516. torch._C.AT_ASSERT(expectedType);
  13517. const newType = newValue.type();
  13518. if (!newType.isSubtypeOf(expectedType)) {
  13519. throw new python.Error('Wrong type for attribute assignment.');
  13520. }
  13521. const g = m.graph();
  13522. g.insertNode(g.createSetAttr(this._value, field, newValue));
  13523. }
  13524. getitem(loc, m, idx, type_hint) {
  13525. const val = this.getValue();
  13526. const val_type = val.type();
  13527. const g = m.graph();
  13528. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  13529. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  13530. } else if (val_type instanceof torch.DictType) {
  13531. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  13532. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  13533. 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));
  13534. } else if (val_type instanceof torch.ClassType) {
  13535. const class_type = val_type;
  13536. if (class_type.is_module() && type_hint) {
  13537. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  13538. res.setType(type_hint);
  13539. return new torch._C.SimpleValue(res);
  13540. }
  13541. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  13542. }
  13543. throw new python.Error('Object is not subscriptable.');
  13544. }
  13545. });
  13546. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  13547. constructor(self, method_names) {
  13548. super();
  13549. this._self = self;
  13550. this._method_names = method_names;
  13551. }
  13552. call(loc, f, args, kwargs /*, n_binders */) {
  13553. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  13554. const schemas = [];
  13555. for (const method_name of this._method_names) {
  13556. const type = this._self.type();
  13557. if (type instanceof torch.ClassType) {
  13558. const class_type = type;
  13559. const method = class_type.getMethod(method_name);
  13560. method.ensure_defined();
  13561. schemas.push(method.getSchema());
  13562. } else if (type instanceof torch.InterfaceType) {
  13563. const interface_type = type;
  13564. schemas.push(interface_type.getMethod(method_name));
  13565. } else {
  13566. throw new python.Error('Method constructed that is not a class or interface.');
  13567. }
  13568. }
  13569. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  13570. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  13571. output.node().setSourceRange(loc);
  13572. return new torch._C.SimpleValue(output);
  13573. }
  13574. });
  13575. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  13576. constructor(type) {
  13577. super();
  13578. this._type = type;
  13579. }
  13580. attr(loc, m, field) {
  13581. const hook = this._type.findHook(field);
  13582. if (hook) {
  13583. return new torch._C.FunctionValue(hook);
  13584. }
  13585. if (field !== '__new__') {
  13586. throw new python.Error('Tried to lookup unknown attribute on class.');
  13587. }
  13588. return torch._C.SpecialFormValue.create('prim::CreateObject');
  13589. }
  13590. });
  13591. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  13592. constructor(type) {
  13593. super();
  13594. this._type = type;
  13595. }
  13596. call(loc, m, args, kwargs /*, n_binders */) {
  13597. const g = m.graph();
  13598. const schema = this._type.schema();
  13599. torch._C.TORCH_INTERNAL_ASSERT(schema);
  13600. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  13601. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  13602. self.setType(this._type);
  13603. return new torch._C.SimpleValue(self);
  13604. }
  13605. });
  13606. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  13607. constructor(...args) {
  13608. super();
  13609. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  13610. this._callees = [args[0]];
  13611. } else {
  13612. throw new python.Error('Not implemented.');
  13613. }
  13614. }
  13615. call(loc, f, args, kwargs /*, n_binders */) {
  13616. const schemas = [];
  13617. for (const callee of this._callees) {
  13618. callee.ensure_defined();
  13619. schemas.push(callee.getSchema());
  13620. }
  13621. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  13622. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  13623. output.node().setSourceRange(loc);
  13624. return new torch._C.SimpleValue(output);
  13625. }
  13626. });
  13627. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  13628. });
  13629. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  13630. call(loc, m, args, kwargs /*, n_binders */) {
  13631. const g = m.graph();
  13632. if (kwargs.length > 0) {
  13633. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  13634. }
  13635. const lowered_inputs = torch._C.toValues(m.graph(), args);
  13636. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  13637. return new torch._C.NoneValue();
  13638. }
  13639. });
  13640. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  13641. constructor(form) {
  13642. super();
  13643. this._form = form;
  13644. }
  13645. form() {
  13646. return this._form;
  13647. }
  13648. static create(form) {
  13649. return new torch._C.SpecialFormValue(form);
  13650. }
  13651. });
  13652. this.registerFunction('torch._C.makeMagic', (name, base) => {
  13653. return new torch._C.MagicMethod(name, base);
  13654. });
  13655. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  13656. constructor(symbol, self) {
  13657. super();
  13658. this.symbol = symbol;
  13659. this.self = self;
  13660. }
  13661. call(loc, m, args, kwargs /*, n_binders */) {
  13662. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  13663. }
  13664. static tryCreate(symbol, self) {
  13665. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  13666. if (!self) {
  13667. return new torch._C.BuiltinFunction(symbol, null);
  13668. }
  13669. const index = op.schema().argumentIndexWithName('self');
  13670. if (index) {
  13671. const type_env = new Map();
  13672. const formal_type = op.schema().arguments()[index].type();
  13673. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  13674. if (!matched.success()) {
  13675. continue;
  13676. }
  13677. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  13678. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  13679. continue;
  13680. }
  13681. return new torch._C.BuiltinFunction(symbol, self);
  13682. }
  13683. }
  13684. return null;
  13685. }
  13686. });
  13687. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  13688. constructor(name, version) {
  13689. super();
  13690. this.name = name;
  13691. this.version = version || null;
  13692. }
  13693. attr(loc, m, field) {
  13694. if (field === 'autograd') {
  13695. return new torch._C.BuiltinModule('aten', this.version);
  13696. }
  13697. const sym = `${this.name}::${field}`;
  13698. return new torch._C.BuiltinFunction(sym, null);
  13699. }
  13700. });
  13701. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  13702. constructor(version) {
  13703. super();
  13704. this._version = version;
  13705. }
  13706. attr(loc, m, field) {
  13707. return new torch._C.BuiltinModule(field, this._version);
  13708. }
  13709. });
  13710. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  13711. constructor(constants) {
  13712. super();
  13713. this._constants = constants;
  13714. this.non_holding_object_cache = new Map();
  13715. }
  13716. attr(loc, m, field) {
  13717. const offset = parseInt(field.substring(1), 10);
  13718. if (!Number.isInteger(offset)) {
  13719. throw new python.Error(`Invalid constant identifier '${field}.`);
  13720. }
  13721. if (offset < 0 || offset >= this._constants.length) {
  13722. throw new python.Error('Invalid constant index.');
  13723. }
  13724. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  13725. let value = null;
  13726. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  13727. const obj = ivalue.toObject();
  13728. if (!this.non_holding_object_cache.has(obj)) {
  13729. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  13730. }
  13731. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  13732. } else {
  13733. value = m.graph().insertConstant(this._constants[offset], loc);
  13734. }
  13735. value.setType(torch._C.unshapedType(value.type()));
  13736. return new torch._C.SimpleValue(value);
  13737. }
  13738. });
  13739. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  13740. constructor(type, method) {
  13741. super(method, null);
  13742. this._type = type;
  13743. }
  13744. call(loc, m, args, kwargs, n_binders) {
  13745. if (args.length === 1 && kwargs.length === 0) {
  13746. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  13747. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  13748. const zero = m.graph().insertConstant(0);
  13749. const v = args[0].value(m.graph());
  13750. if (v.type().isSubtypeOf(this._type)) {
  13751. return new torch._C.SimpleValue(v);
  13752. } 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)) {
  13753. const len = len_op.call(loc, m, [v], [], 1);
  13754. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  13755. }
  13756. }
  13757. return super.call(loc, m, args, kwargs, n_binders);
  13758. }
  13759. });
  13760. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  13761. constructor(desugared_name, base) {
  13762. super();
  13763. this._base_value = base;
  13764. this._desugared_name = desugared_name;
  13765. }
  13766. call(loc, m, args, kwargs, n_binders) {
  13767. if (args.length > 0) {
  13768. const self = args[0].value(m.graph());
  13769. if (self.type() instanceof torch.ClassType) {
  13770. return new torch._C.SimpleValue(self)
  13771. .attr(loc, m, this._desugared_name)
  13772. .call(loc, m, args.slice(1), kwargs, n_binders);
  13773. }
  13774. }
  13775. if (!this._base_value) {
  13776. throw new python.Error('Invalid magic method.');
  13777. }
  13778. return this._base_value.call(loc, m, args, kwargs, n_binders);
  13779. }
  13780. });
  13781. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  13782. constructor(loc, m, inputs, static_len) {
  13783. super();
  13784. static_len = static_len || null;
  13785. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  13786. throw new python.Error('Invalid range inputs.');
  13787. }
  13788. const g = m.graph();
  13789. if (inputs.length === 1) {
  13790. [this._end] = inputs;
  13791. this._start = g.insertConstant(0, loc);
  13792. this._step = g.insertConstant(1, loc);
  13793. this._has_only_end = true;
  13794. } else {
  13795. [this._start, this._end] = inputs;
  13796. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  13797. this._has_only_end = false;
  13798. }
  13799. this._static_len = static_len;
  13800. }
  13801. staticLen() {
  13802. return this._static_len;
  13803. }
  13804. iter() {
  13805. return this;
  13806. }
  13807. len(loc, m) {
  13808. if (this._static_len) {
  13809. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  13810. }
  13811. if (this._has_only_end) {
  13812. return this._end;
  13813. }
  13814. const g = m.graph();
  13815. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  13816. }
  13817. getitem(loc, m, idx /*, type_hint */) {
  13818. if (this._has_only_end) {
  13819. return new torch._C.SimpleValue(idx);
  13820. }
  13821. const g = m.graph();
  13822. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  13823. }
  13824. });
  13825. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  13826. });
  13827. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  13828. constructor(name, si) {
  13829. super();
  13830. this._basename = name;
  13831. this._si = si;
  13832. }
  13833. attr(loc, m, name) {
  13834. const fullName = new torch._C.QualifiedName(this._basename, name);
  13835. const serializable_type = this._si.findNamedType(fullName);
  13836. if (serializable_type) {
  13837. if (serializable_type instanceof torch.ClassType) {
  13838. return new torch._C.ClassValue(serializable_type);
  13839. } else if (serializable_type instanceof torch.TupleType) {
  13840. return new torch._C.NamedTupleConstructor(serializable_type);
  13841. } else if (serializable_type instanceof torch.EnumType) {
  13842. return new torch._C.SugaredEnumClass(serializable_type);
  13843. }
  13844. }
  13845. const fn = this._si.findFunction(fullName);
  13846. if (fn) {
  13847. return new torch._C.FunctionValue(fn);
  13848. }
  13849. return new torch._C.ClassNamespaceValue(fullName, this._si);
  13850. }
  13851. });
  13852. this.registerType('torch.package.PackageImporter', class {
  13853. constructor(reader) {
  13854. this.zip_reader = reader;
  13855. }
  13856. load_pickle(module, resource) {
  13857. const name = `${module.replace(/\./, '/')}/${resource}`;
  13858. const stream = this.zip_reader.get_record(name);
  13859. const loaded_reduces = new Map();
  13860. this.storage_context = new torch._C.DeserializationStorageContext();
  13861. const unpickler = new pickle.Unpickler(stream);
  13862. unpickler.persistent_load = (saved_id) => {
  13863. switch (saved_id[0]) {
  13864. case 'storage': {
  13865. const [, storage_type, key, , size] = saved_id;
  13866. if (!this.storage_context.has_storage(key)) {
  13867. const storage = new storage_type(size);
  13868. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  13869. const buffer = stream.peek();
  13870. storage._set_cdata(buffer);
  13871. this.storage_context.add_storage(key, storage);
  13872. }
  13873. return this.storage_context.get_storage(key);
  13874. }
  13875. case 'reduce_package': {
  13876. if (saved_id.length === 2) {
  13877. const [, func, args] = saved_id;
  13878. return execution.invoke(func, args);
  13879. }
  13880. const [, reduce_id, func, args] = saved_id;
  13881. if (!loaded_reduces.has(reduce_id)) {
  13882. const value = execution.invoke(func, [this].concat(args));
  13883. loaded_reduces.set(reduce_id, value);
  13884. }
  13885. return loaded_reduces.get(reduce_id);
  13886. }
  13887. default: {
  13888. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  13889. }
  13890. }
  13891. };
  13892. const obj = unpickler.load();
  13893. this.storage_context = null;
  13894. return obj;
  13895. }
  13896. import_module(name) {
  13897. return execution.import(name);
  13898. }
  13899. });
  13900. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  13901. const cu = new torch.jit.CompilationUnit();
  13902. cu.execution = execution;
  13903. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  13904. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  13905. module.forward = cpp_module.forward; // remove
  13906. return module;
  13907. });
  13908. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  13909. switch (arguments.length) {
  13910. case 4: {
  13911. const [device, extra_files] = args;
  13912. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  13913. return deserializer.deserialize(device, extra_files);
  13914. }
  13915. case 5: {
  13916. const [storage_context, device, ts_id] = args;
  13917. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  13918. return deserializer.deserialize(device, null);
  13919. }
  13920. default: {
  13921. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  13922. }
  13923. }
  13924. });
  13925. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  13926. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  13927. });
  13928. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  13929. if (value instanceof torch.Node) {
  13930. const n = value;
  13931. if (n.kind() === 'prim::CallFunction') {
  13932. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  13933. const function_constant = n.input(0).node();
  13934. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  13935. return torch._C.tryToGraphFunction(fun_type.function());
  13936. }
  13937. if (n.kind() === 'prim::CallMethod') {
  13938. const name = n.s('name');
  13939. const class_type = n.input(0).type();
  13940. if (class_type instanceof torch.ClassType) {
  13941. const fn = class_type.getMethod(name);
  13942. return torch._C.tryToGraphFunction(fn);
  13943. }
  13944. }
  13945. return null;
  13946. } else if (value instanceof torch._C.Function) {
  13947. const fn = value;
  13948. if (!fn.isGraphFunction()) {
  13949. return null;
  13950. }
  13951. return fn;
  13952. }
  13953. throw new python.Error('Not implemented.');
  13954. });
  13955. this.registerType('torch._C.ModuleInstanceInfo', class {
  13956. constructor(module_type, instance_name) {
  13957. this._module_type = module_type;
  13958. this._instance_name = instance_name;
  13959. }
  13960. });
  13961. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  13962. torch._C.TORCH_CHECK(step !== 0);
  13963. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  13964. if (start._ === Number.MAX_SAFE_INTEGER) {
  13965. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  13966. }
  13967. if (stop._ === Number.MAX_SAFE_INTEGER) {
  13968. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  13969. }
  13970. if (start._ < 0) {
  13971. start._ += length;
  13972. if (start._ < 0) {
  13973. start._ = (step < 0) ? -1 : 0;
  13974. }
  13975. } else if (start._ >= length) {
  13976. start._ = (step < 0) ? length - 1 : length;
  13977. }
  13978. if (stop._ < 0) {
  13979. stop._ += length;
  13980. if (stop._ < 0) {
  13981. stop._ = (step < 0) ? -1 : 0;
  13982. }
  13983. } else if (stop._ >= length) {
  13984. stop._ = (step < 0) ? length - 1 : length;
  13985. }
  13986. if (step < 0) {
  13987. if (stop._ < start._) {
  13988. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  13989. }
  13990. } else if (start._ < stop._) {
  13991. return Math.floor((stop._ - start._ - 1) / step + 1);
  13992. }
  13993. return 0;
  13994. });
  13995. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  13996. if (v.node().kind() === 'prim::TupleConstruct') {
  13997. return v.node().inputs();
  13998. }
  13999. const g = v.owningGraph();
  14000. return g.insertNode(g.createTupleUnpack(v)).outputs();
  14001. });
  14002. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  14003. /*
  14004. const new_node_cs = new_node.callstack();
  14005. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  14006. if (!new_cs_entries.has(raw_callstack_ptr)) {
  14007. if (new_node_cs) {
  14008. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  14009. } else {
  14010. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  14011. }
  14012. }
  14013. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  14014. for (const block of new_node.blocks()) {
  14015. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  14016. }
  14017. */
  14018. });
  14019. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  14020. if (arg === undefined || typeof arg === 'boolean') {
  14021. const inline_optimized_graph = arg === undefined ? true : arg;
  14022. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  14023. return torch._C.inlineCallTo(to_replace, callee, graph);
  14024. }
  14025. if (arg instanceof torch.Graph === false) {
  14026. throw new python.Error('Invalid argument.');
  14027. }
  14028. const callee_graph = arg;
  14029. const guard = new torch._C.WithInsertPoint(to_replace);
  14030. const value_map = new Map();
  14031. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  14032. const new_callstack_entries = new Map();
  14033. let module_instance_info = null;
  14034. if (to_replace.kind() === 'prim::CallMethod') {
  14035. const class_type_ptr = to_replace.input(0).type();
  14036. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  14037. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  14038. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  14039. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  14040. } else {
  14041. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  14042. }
  14043. }
  14044. const updated_nodes = new Set();
  14045. for (const kv of value_map) {
  14046. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  14047. if (is_graph_input === -1) {
  14048. continue;
  14049. }
  14050. const new_node = kv[1].node();
  14051. if (updated_nodes.has(new_node)) {
  14052. continue;
  14053. }
  14054. updated_nodes.add(new_node);
  14055. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  14056. }
  14057. const old_outputs = to_replace.outputs();
  14058. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  14059. for (let i = 0; i < old_outputs.length; i++) {
  14060. if (old_outputs[i].hasDebugName()) {
  14061. new_outputs[i].setDebugName(old_outputs[i].debugName());
  14062. }
  14063. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  14064. }
  14065. to_replace.destroy();
  14066. guard.dispose();
  14067. return new_outputs;
  14068. });
  14069. this.registerFunction('torch._C.inlineCalls', (block) => {
  14070. for (const cur of block.nodes()) {
  14071. switch (cur.kind()) {
  14072. case 'prim::CallFunction': {
  14073. const graphFunction = torch._C.tryToGraphFunction(cur);
  14074. if (graphFunction) {
  14075. const function_constant = cur.input(0).node();
  14076. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  14077. cur.removeInput(0);
  14078. let g = null;
  14079. const fallback = function_constant.hasAttribute('fallback');
  14080. if (fallback && graphFunction.get_executor().isOptimized()) {
  14081. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  14082. if (!exec_plans.empty()) {
  14083. g = exec_plans.begin().second.graph;
  14084. torch._C.Inline(g);
  14085. }
  14086. }
  14087. if (g === null) {
  14088. g = graphFunction.optimized_graph();
  14089. }
  14090. torch._C.inlineCallTo(cur, graphFunction, g);
  14091. }
  14092. break;
  14093. }
  14094. case 'prim::CallMethod': {
  14095. const graphFunction = torch._C.tryToGraphFunction(cur);
  14096. if (graphFunction) {
  14097. torch._C.inlineCallTo(cur, graphFunction);
  14098. }
  14099. break;
  14100. }
  14101. default: {
  14102. for (const b of cur.blocks()) {
  14103. torch._C.inlineCalls(b);
  14104. }
  14105. }
  14106. }
  14107. }
  14108. });
  14109. this.registerFunction('torch._C.Inline', (graph) => {
  14110. torch._C.inlineCalls(graph.block());
  14111. });
  14112. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  14113. torch._C.Inline(graph);
  14114. });
  14115. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  14116. const cu = new torch.jit.CompilationUnit();
  14117. cu.execution = execution;
  14118. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  14119. return torch.jit._script.wrap_cpp_module(cpp_module);
  14120. });
  14121. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  14122. const init_fn = (script_module) => {
  14123. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  14124. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  14125. }
  14126. };
  14127. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  14128. });
  14129. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  14130. has_storage(name) {
  14131. return this.has(name);
  14132. }
  14133. get_storage(name) {
  14134. return this.get(name);
  14135. }
  14136. add_storage(name, storage) {
  14137. return this.set(name, storage);
  14138. }
  14139. });
  14140. this.registerType('torch.ScriptFunction', class {
  14141. constructor(name, graph /*, function_creator */) {
  14142. this._name = name;
  14143. this._graph = graph;
  14144. }
  14145. });
  14146. this.registerType('torch.ScriptMethod', class {
  14147. constructor(owner, value) {
  14148. this._owner = owner;
  14149. this._function = value;
  14150. }
  14151. get name() {
  14152. return this._function.name();
  14153. }
  14154. get owner() {
  14155. return this._owner;
  14156. }
  14157. __call__(/* args, kwargs */) {
  14158. throw new python.Error();
  14159. }
  14160. get graph() {
  14161. return this._function.graph();
  14162. }
  14163. get schema() {
  14164. // return this.function().getSchema();
  14165. throw new python.Error();
  14166. }
  14167. get code() {
  14168. throw new python.Error();
  14169. }
  14170. get code_with_constants() {
  14171. throw new python.Error();
  14172. }
  14173. });
  14174. this.registerType('torch.ScriptObject', class {
  14175. constructor(type) {
  14176. this._typ = type;
  14177. this._ivalue = {};
  14178. }
  14179. static create(type) {
  14180. if (type.is_module()) {
  14181. return new torch.ScriptModule(type);
  14182. }
  14183. return new torch.ScriptObject(type);
  14184. }
  14185. type() {
  14186. return this._typ;
  14187. }
  14188. _type() {
  14189. return this._typ; // torch.ClassType
  14190. }
  14191. find_method(basename) {
  14192. for (const fn of this.type().methods()) {
  14193. if (fn.name() === basename) {
  14194. // return Method(_ivalue(), fn);
  14195. return new torch.ScriptMethod(this /* _value() */, fn);
  14196. }
  14197. }
  14198. return null;
  14199. }
  14200. _get_method(name) {
  14201. const method = this.find_method(name);
  14202. if (method) {
  14203. return method;
  14204. }
  14205. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  14206. return null;
  14207. }
  14208. _has_method(name) {
  14209. return this.find_method(name) ? true : false;
  14210. }
  14211. __setattr__(name, value) {
  14212. // if (this._type.hasContant(name))
  14213. this._ivalue[name] = value;
  14214. }
  14215. __getattr__(name) {
  14216. return this._ivalue[name];
  14217. }
  14218. hasattr(name) {
  14219. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  14220. }
  14221. getattr(name) {
  14222. return this.__getattr__(name);
  14223. }
  14224. _properties() {
  14225. throw new python.Error();
  14226. }
  14227. is_weak_compilation_ref() {
  14228. return true; // not implemented
  14229. }
  14230. });
  14231. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  14232. constructor(...args) {
  14233. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  14234. const [class_name, cu, shouldMangle] = args;
  14235. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  14236. } else {
  14237. super(...args);
  14238. }
  14239. }
  14240. get qualified_name() {
  14241. return this.type().qualified_name();
  14242. }
  14243. get code_with_constants() {
  14244. const const_map = {};
  14245. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  14246. return [null, const_map];
  14247. }
  14248. get graph() {
  14249. if (!this._graph) {
  14250. const fn = this._typ.getMethod('forward');
  14251. this._graph = fn.graph();
  14252. }
  14253. return this._graph;
  14254. }
  14255. static create_module_object(class_name, cu, shouldMangle) {
  14256. shouldMangle = shouldMangle || false;
  14257. if (!class_name.prefix()) {
  14258. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  14259. }
  14260. if (shouldMangle && cu.get_class(class_name)) {
  14261. class_name = cu.mangle(class_name);
  14262. }
  14263. const cls = torch.ClassType.create(class_name, cu, true);
  14264. cu.register_type(cls);
  14265. return [cls, cu];
  14266. }
  14267. register_module(name, module) {
  14268. this.type().addOrCheckAttribute(name, module.type());
  14269. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  14270. }
  14271. register_buffer(name, v) {
  14272. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  14273. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  14274. }
  14275. register_parameter(name, v, is_buffer) {
  14276. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  14277. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  14278. }
  14279. register_attribute(name, t, v, is_param, is_buffer) {
  14280. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  14281. // _ivalue()->setAttr(name, v);
  14282. }
  14283. });
  14284. this.registerType('torch.ModuleDict', class {
  14285. constructor(mod) {
  14286. this._module = mod;
  14287. }
  14288. items() {
  14289. const result = new Map();
  14290. const type = this._module.type();
  14291. for (let i = 0; i < type.numAttributes(); i++) {
  14292. const k = type.getAttributeName(i);
  14293. const t = type.getAttribute(i);
  14294. if (t && t.is_module()) {
  14295. result.set(k, this._module.__getattr__(k));
  14296. }
  14297. }
  14298. return result;
  14299. }
  14300. });
  14301. this.registerType('torch.ParameterDict', class {
  14302. constructor(mod) {
  14303. this._module = mod;
  14304. }
  14305. items() {
  14306. const result = new Map();
  14307. const type = this._module.type();
  14308. for (let i = 0; i < type.numAttributes(); i++) {
  14309. if (type.is_parameter(i)) {
  14310. const k = type.getAttributeName(i);
  14311. const v = this._module.__getattr__(k);
  14312. if (v instanceof torch.Tensor) {
  14313. result.set(k, v);
  14314. }
  14315. }
  14316. }
  14317. return result;
  14318. }
  14319. });
  14320. this.registerType('torch.BufferDict', class {
  14321. constructor(mod) {
  14322. this._module = mod;
  14323. }
  14324. items() {
  14325. const result = new Map();
  14326. const type = this._module.type();
  14327. for (let i = 0; i < type.numAttributes(); i++) {
  14328. if (type.is_buffer(i)) {
  14329. const t = type.getAttribute(i);
  14330. if (t.isSubtypeOf(torch.TensorType.get())) {
  14331. const k = type.getAttributeName(i);
  14332. const v = this._module.__getattr__(k);
  14333. result.set(k, v);
  14334. }
  14335. }
  14336. }
  14337. return result;
  14338. }
  14339. });
  14340. this.registerType('torch._C.to_ir', class {
  14341. constructor(def, _resolver, self, method) {
  14342. this.method = method;
  14343. this.graph = method.graph();
  14344. this.resolver = _resolver;
  14345. this.integral_constants = new Map();
  14346. this.fp_constants = new Map();
  14347. this.complex_constants = new Map();
  14348. this.exit_blocks = new Set();
  14349. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  14350. this._loop_status = 'NOT_IN_LOOP';
  14351. this.environment_stack = null;
  14352. this._def_stack = [];
  14353. this._temp_name_count = 0;
  14354. torch._C.AT_ASSERT(this.resolver);
  14355. this.pushFrame(this.graph.block(), true);
  14356. if (self && def && def.args.args.length === 0) {
  14357. throw new python.Error('Method must have a self argument.');
  14358. }
  14359. method.setSchema(this.emitDef(def, self, this.graph.block()));
  14360. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  14361. torch._C.ConvertToSSA(this.graph);
  14362. torch._C.CanonicalizeModifiedLoops(this.graph);
  14363. torch._C.NormalizeOps(this.graph.block());
  14364. torch._C.runCleanupPasses(this.graph);
  14365. }
  14366. pushFrame(b, starts_def) {
  14367. starts_def = starts_def || false;
  14368. if (starts_def) {
  14369. this._def_stack.push({});
  14370. }
  14371. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  14372. }
  14373. popFrame(ends_def) {
  14374. const old_frame = this.environment_stack;
  14375. this.environment_stack = this.environment_stack.next;
  14376. if (ends_def) {
  14377. this._def_stack.pop();
  14378. }
  14379. return old_frame;
  14380. }
  14381. emitDef(def, self, block) {
  14382. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  14383. if (schema.returns.length === 1) {
  14384. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  14385. }
  14386. const args = this.emitFormalArguments(def, self, schema, block);
  14387. this.emitStatements(def.body);
  14388. this.handleMaybeNoReturn(def, block);
  14389. const returns = [this.emitOutput(def, schema, block)];
  14390. return new torch.FunctionSchema(def.name, '', args, returns);
  14391. }
  14392. emitFormalArguments(def, self, schema, block) {
  14393. const args = [];
  14394. const params = def.args.args;
  14395. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  14396. if (schema.arguments.length !== expected_annotation_size) {
  14397. throw new python.Error('Invalid formal arguments.');
  14398. }
  14399. let it = 0;
  14400. if (self) {
  14401. const param = params[it];
  14402. const name = param.arg;
  14403. const new_input = block.addInput().setDebugName(name);
  14404. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  14405. args.push(new torch.Argument(name, new_input.type()));
  14406. it++;
  14407. }
  14408. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  14409. let arg_annotation_idx = 0;
  14410. for (; it < params.length; it++) {
  14411. const param = params[it];
  14412. const name = param.arg;
  14413. const new_input = block.addInput();
  14414. if (torch._C.meaningfulName(name)) {
  14415. new_input.setDebugName(name);
  14416. }
  14417. let arg = schema.arguments[arg_annotation_idx++];
  14418. if (shouldDeriveType) {
  14419. if (schema.arguments.length === 1) {
  14420. throw new python.Error('Invalid schema.');
  14421. }
  14422. const inferredStateType = this.getTypeForSetStateArg(def, self);
  14423. arg = arg.cloneWithType(inferredStateType);
  14424. }
  14425. args.push(arg);
  14426. new_input.setType(arg.type);
  14427. this.environment_stack.setVar(param.range(), name, new_input);
  14428. }
  14429. return args;
  14430. }
  14431. emitOutput(range, schema, block) {
  14432. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  14433. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  14434. block.registerOutput(placeholder_return);
  14435. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  14436. }
  14437. emitStatements(stmts) {
  14438. for (let i = 0; i < stmts.length; i++) {
  14439. const stmt = stmts[i];
  14440. if (stmt instanceof ast.If) {
  14441. this.emitIf(stmt);
  14442. } else if (stmt instanceof ast.While) {
  14443. this.emitWhile(stmt);
  14444. } else if (stmt instanceof ast.For) {
  14445. this.emitFor(stmt);
  14446. } else if (stmt instanceof ast.Assign) {
  14447. this.emitAssignment(stmt);
  14448. } else if (stmt instanceof ast.AnnAssign) {
  14449. this.emitAssignment(stmt);
  14450. } else if (stmt instanceof ast.Expr) {
  14451. this.emitSugaredExpr(stmt.value, 0);
  14452. } else if (stmt instanceof ast.Return) {
  14453. this.emitReturn(stmt);
  14454. } else if (stmt instanceof ast.Pass) {
  14455. // pass
  14456. } else if (stmt instanceof ast.With) {
  14457. this.emitWith(stmt);
  14458. } else {
  14459. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  14460. }
  14461. if (this.exit_blocks.has(this.environment_stack.block())) {
  14462. return;
  14463. }
  14464. }
  14465. }
  14466. emitWith(stmt) {
  14467. const targets = stmt.items;
  14468. const entered = [];
  14469. for (const target of targets) {
  14470. const e = target.context_expr;
  14471. const rhs = this.emitExpr(e);
  14472. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  14473. entered.push(rhs);
  14474. if (rhs.type() instanceof torch.ClassType === false) {
  14475. throw new python.Error('With item expression must return an object.');
  14476. }
  14477. const rhsClass = rhs.type();
  14478. const enterMethod = rhsClass.findMethod('__enter__');
  14479. const exitMethod = rhsClass.findMethod('__exit__');
  14480. if (!enterMethod || !exitMethod) {
  14481. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  14482. }
  14483. const enterSchema = enterMethod.getSchema();
  14484. if (enterSchema.arguments.length !== 1) {
  14485. throw new python.Error('__enter__ must have only one argument and one return value.');
  14486. }
  14487. const exitSchema = exitMethod.getSchema();
  14488. if (exitSchema.arguments.length === 4) {
  14489. for (let i = 1; i < 4; i++) {
  14490. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  14491. throw new python.Error('Argument of __exit__ must have Any type.');
  14492. }
  14493. }
  14494. } else {
  14495. throw new python.Error('__exit__ must have four arguments');
  14496. }
  14497. n.output(0).setType(enterSchema.returns[0].type);
  14498. if (target.optional_vars) {
  14499. throw new python.Error('Not implemented.');
  14500. // Var i = target.var().get();
  14501. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  14502. }
  14503. }
  14504. this.emitStatements(stmt.body);
  14505. while (entered.length > 0) {
  14506. const input = entered.pop();
  14507. const n = this.graph.create('prim::Exit');
  14508. this.graph.insertNode(n);
  14509. n.addInput(input);
  14510. }
  14511. }
  14512. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  14513. let max_trip_count_val = null;
  14514. if (iter_val === null) {
  14515. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  14516. } else {
  14517. max_trip_count_val = iter_val.len(range, this.method);
  14518. }
  14519. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  14520. const body_block = n.addBlock();
  14521. {
  14522. const condition_block = n.addBlock();
  14523. this.pushFrame(condition_block);
  14524. let out = null;
  14525. if (cond) {
  14526. const insert = new torch._C.WithInsertPoint(condition_block);
  14527. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  14528. insert.dispose();
  14529. } else {
  14530. const insert = new torch._C.WithInsertPoint(n);
  14531. out = this.graph.insertConstant(true, range);
  14532. insert.dispose();
  14533. }
  14534. condition_block.registerOutput(out);
  14535. this.popFrame();
  14536. }
  14537. n.addInput(max_trip_count_val);
  14538. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  14539. const trip_count = body_block.addInput().setType(torch.IntType.get());
  14540. {
  14541. this.pushFrame(body_block);
  14542. const guard = new torch._C.WithInsertPoint(body_block);
  14543. if (iter_val !== null && targets) {
  14544. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  14545. const sv = new torch._C.SimpleValue(cur_elem);
  14546. const target_exprs = targets;
  14547. this.validateAssignLhsExpr(target_exprs, range);
  14548. if (target_exprs.length > 1) {
  14549. throw new python.Error('Not implemented.');
  14550. // const tl = torch.TupleLiteral.create(range, target_exprs);
  14551. // target_exprs = ListExpr.create(range, [tl]);
  14552. }
  14553. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  14554. }
  14555. emit_body();
  14556. this.popFrame();
  14557. guard.dispose();
  14558. }
  14559. loop_guard.dispose();
  14560. }
  14561. emitFor(...args) {
  14562. if (args.length === 1 && args[0] instanceof ast.For) {
  14563. const [stmt] = args;
  14564. const emit_body = () => this.emitStatements(stmt.body);
  14565. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  14566. } else if (args.length === 4) {
  14567. const [targets, itrs, loc, emit_body] = args;
  14568. if (itrs instanceof ast.Tuple) {
  14569. throw new python.Error('List of iterables is not supported currently.');
  14570. }
  14571. const sv = this.emitSugaredExpr(itrs, 1);
  14572. const iterable = sv.iter(loc, this.method);
  14573. if (iterable.shouldEmitUnrolled()) {
  14574. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  14575. } else {
  14576. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  14577. }
  14578. } else {
  14579. throw new python.Error('Not implemented.');
  14580. }
  14581. }
  14582. emitWhile(stmt) {
  14583. const cond = stmt.test;
  14584. const emit_body = () => this.emitStatements(stmt.body);
  14585. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  14586. }
  14587. emitIsInstance(obj, classinfo) {
  14588. const lhs_val = this.emitExpr(obj);
  14589. const lhs_types = [];
  14590. const rhs_types = [];
  14591. const gather_rhs = (expr) => {
  14592. if (expr instanceof ast.Tuple) {
  14593. for (const e of expr.elts) {
  14594. gather_rhs(e);
  14595. }
  14596. return;
  14597. }
  14598. const type = this._typeParser.parseTypeFromExpr(expr);
  14599. rhs_types.push(type);
  14600. };
  14601. lhs_types.push(lhs_val.type());
  14602. gather_rhs(classinfo);
  14603. torch._C.standardizeVectorForUnion(lhs_types);
  14604. torch._C.standardizeVectorForUnion(rhs_types);
  14605. let refinement = new torch._C.RefinementSet([], []);
  14606. let unified_true = null;
  14607. let unified_false = null;
  14608. const isinstance_types = [];
  14609. const not_isinstance_types = [];
  14610. let true_refinements = [];
  14611. let false_refinements = [];
  14612. let all_lhs_subtype_some_rhs = true;
  14613. for (const lhs_type of lhs_types) {
  14614. if (lhs_type === torch.AnyType.get()) {
  14615. isinstance_types.push(...rhs_types);
  14616. not_isinstance_types.push(torch.AnyType.get());
  14617. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  14618. all_lhs_subtype_some_rhs = false;
  14619. }
  14620. break;
  14621. }
  14622. const get_smaller_type = (t1, t2) => {
  14623. if (t1.isSubtypeOf(t2)) {
  14624. return t1;
  14625. } else if (t2.isSubtypeOf(t1)) {
  14626. return t2;
  14627. }
  14628. return null;
  14629. };
  14630. let found_refinement = null;
  14631. for (const rhs_type of rhs_types) {
  14632. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  14633. if (!maybe_smaller_type) {
  14634. continue;
  14635. } else if (maybe_smaller_type === lhs_type) {
  14636. found_refinement = lhs_type;
  14637. } else if (maybe_smaller_type === rhs_type) {
  14638. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  14639. }
  14640. }
  14641. if (found_refinement) {
  14642. if (found_refinement === lhs_type) {
  14643. all_lhs_subtype_some_rhs &= true;
  14644. }
  14645. isinstance_types.push(found_refinement);
  14646. } else {
  14647. not_isinstance_types.push(lhs_type);
  14648. all_lhs_subtype_some_rhs = false;
  14649. }
  14650. }
  14651. if (isinstance_types.length > 0) {
  14652. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  14653. }
  14654. if (obj instanceof ast.Name && unified_true) {
  14655. const ident = obj.id;
  14656. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  14657. }
  14658. if (not_isinstance_types.length > 0) {
  14659. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  14660. }
  14661. if (obj instanceof ast.Name && unified_false) {
  14662. const ident = obj.id;
  14663. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  14664. }
  14665. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  14666. const is_statically_false = isinstance_types.length === 0;
  14667. if (all_lhs_subtype_some_rhs) {
  14668. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  14669. }
  14670. if (is_statically_false) {
  14671. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  14672. }
  14673. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  14674. return new torch._C.CondValue(result, refinement, null);
  14675. }
  14676. emitIf(stmt) {
  14677. const cond_value = this.emitCondExpr(stmt.test);
  14678. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  14679. }
  14680. emitCondExpr(expr) {
  14681. /*
  14682. switch (expr.kind()) {
  14683. case TK_AND:
  14684. case TK_OR: {
  14685. const binop = BinOp(expr);
  14686. return emitShortCircuitLogical(
  14687. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  14688. }
  14689. case TK_NOT: {
  14690. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  14691. Value* result = emitBuiltinCall(
  14692. expr.range(), *graph, aten::__not__, {v.value()}, {});
  14693. std::optional<bool> static_if;
  14694. if (v.staticIf()) {
  14695. static_if = !*v.staticIf();
  14696. }
  14697. return CondValue(result, v.refinements().Not(), static_if);
  14698. } break;
  14699. case TK_IS:
  14700. case TK_ISNOT: {
  14701. // meta programming on AST for is/is not cases and emit branches base on
  14702. const cond_op = BinOp(expr);
  14703. Value* lhs_val = emitExpr(cond_op.lhs());
  14704. Value* rhs_val = emitExpr(cond_op.rhs());
  14705. const lhs_none = canBeNone(lhs_val);
  14706. const rhs_none = canBeNone(rhs_val);
  14707. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  14708. // AA, -> statically IS always holds, IS_NOT never holds
  14709. // AN , NA-> statically IS_NOT always holds, IS never holds
  14710. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  14711. bool its_is = expr.kind() == TK_IS;
  14712. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  14713. return CondValue(*graph, expr.range(), its_is, {});
  14714. } else if (
  14715. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  14716. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  14717. // lhs_val/rhs_val with A/M: only emit never_none_branch
  14718. return CondValue(*graph, expr.range(), !its_is, {});
  14719. } else {
  14720. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  14721. Value* cond_value = emitBuiltinCall(
  14722. expr.get()->range(),
  14723. *method.graph(),
  14724. kind,
  14725. {lhs_val, rhs_val},
  14726. {});
  14727. const refinements = RefinementSet(findIsNoneRefinements(
  14728. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  14729. return CondValue(cond_value, refinements, null);
  14730. }
  14731. } break;
  14732. */
  14733. if (expr instanceof ast.UnaryOp) {
  14734. throw new python.Error('Not implemented.');
  14735. }
  14736. if (expr instanceof ast.Call) {
  14737. const apply = expr;
  14738. const callee = expr.func;
  14739. if (callee instanceof ast.Name) {
  14740. if (callee.id === 'isinstance') {
  14741. this.checkApplyNumInputs(apply, 2);
  14742. return this.emitIsInstance(apply.args[0], apply.args[1]);
  14743. }
  14744. if (callee.id === 'hasattr') {
  14745. this.checkApplyNumInputs(apply, 2);
  14746. return this.emitHasAttr(apply.args[0], apply.args[1]);
  14747. }
  14748. const sv = this.emitSugaredExpr(callee, 1);
  14749. if (sv instanceof torch._C.SpecialFormValue) {
  14750. if (sv.form() === 'prim::isinstance') {
  14751. this.checkApplyNumInputs(apply, 2);
  14752. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  14753. }
  14754. }
  14755. }
  14756. }
  14757. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  14758. let static_if = null;
  14759. const kind = expr_out.node().kind();
  14760. if (kind === 'aten::is_scripting') {
  14761. static_if = true;
  14762. } else if (kind === 'aten::has_torch_function') {
  14763. static_if = false;
  14764. }
  14765. const maybe_ivalue = torch._C.toIValue(expr_out);
  14766. if (maybe_ivalue) {
  14767. static_if = maybe_ivalue.toBool();
  14768. }
  14769. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  14770. }
  14771. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  14772. if (cond_value.staticIf() !== null) {
  14773. if (cond_value.staticIf()) {
  14774. this.insertRefinements(loc, cond_value.refinements());
  14775. this.emitStatements(trueBranch);
  14776. } else {
  14777. this.insertRefinements(loc, cond_value.refinements().Not());
  14778. this.emitStatements(falseBranch);
  14779. }
  14780. return;
  14781. }
  14782. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  14783. n.addInput(cond_value.value());
  14784. const true_block = n.addBlock();
  14785. const false_block = n.addBlock();
  14786. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  14787. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  14788. const true_exits = this.exit_blocks.has(true_block);
  14789. const false_exits = this.exit_blocks.has(false_block);
  14790. if (true_exits && false_exits) {
  14791. this.exit_blocks.add(n.owningBlock());
  14792. }
  14793. const mutated_variables = new Set();
  14794. for (const v of save_true.definedVariables()) {
  14795. const insert = new torch._C.WithInsertPoint(false_block);
  14796. if (save_false.findInAnyFrame(v) || false_exits) {
  14797. mutated_variables.add(v);
  14798. } else {
  14799. this.environment_stack.setVariableTypeError(v, () => 'Value is is not defined in the false branch.');
  14800. }
  14801. insert.dispose();
  14802. }
  14803. for (const v of save_false.definedVariables()) {
  14804. const insert = new torch._C.WithInsertPoint(true_block);
  14805. if (save_true.findInAnyFrame(v) || true_exits) {
  14806. mutated_variables.add(v);
  14807. } else {
  14808. this.environment_stack.setVariableTypeError(v, () => 'Value is is not defined in the true branch.');
  14809. }
  14810. insert.dispose();
  14811. }
  14812. for (const x of mutated_variables) {
  14813. let tv = null;
  14814. let fv = null;
  14815. {
  14816. const insert = new torch._C.WithInsertPoint(true_block);
  14817. if (!true_exits) {
  14818. tv = save_true.getVar(x, loc);
  14819. }
  14820. insert.dispose();
  14821. }
  14822. {
  14823. const insert = new torch._C.WithInsertPoint(false_block);
  14824. if (!false_exits) {
  14825. fv = save_false.getVar(x, loc);
  14826. }
  14827. insert.dispose();
  14828. }
  14829. if (true_exits && false_exits) {
  14830. continue;
  14831. } else if (true_exits) {
  14832. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  14833. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  14834. } else if (false_exits) {
  14835. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  14836. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  14837. }
  14838. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  14839. let full_type = null;
  14840. if (maybe_sugared_x) {
  14841. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  14842. if (maybe_simple) {
  14843. full_type = maybe_simple.type();
  14844. }
  14845. }
  14846. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  14847. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  14848. if (!unified) {
  14849. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  14850. throw new python.Error('Type mismatch.');
  14851. } else {
  14852. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  14853. continue;
  14854. }
  14855. }
  14856. this.environment_stack.setType(x, unified);
  14857. }
  14858. }
  14859. emitSingleIfBranch(b, branch, refinements) {
  14860. this.pushFrame(b);
  14861. const guard = new torch._C.WithInsertPoint(b);
  14862. this.insertRefinements(branch, refinements);
  14863. this.emitStatements(branch);
  14864. const frame = this.popFrame();
  14865. guard.dispose();
  14866. return frame;
  14867. }
  14868. create(kind, loc, n_outputs) {
  14869. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  14870. }
  14871. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  14872. is_dict_constructor = is_dict_constructor || false;
  14873. if (refined_type_hint_ptr instanceof torch.UnionType) {
  14874. throw new python.Error('Not implemented.');
  14875. } else if (refined_type_hint_ptr instanceof torch.OptionalType) {
  14876. refined_type_hint_ptr = refined_type_hint_ptr.getElementType();
  14877. }
  14878. if (is_dict_constructor) {
  14879. return;
  14880. }
  14881. if (all_candidates.length === 0) {
  14882. if (type_match(refined_type_hint_ptr)) {
  14883. do_if_match();
  14884. } else if (refined_type_hint_ptr.kind() === 'AnyType') {
  14885. do_if_anytype();
  14886. } else {
  14887. throw new python.Error('Invalid annotation type.');
  14888. }
  14889. }
  14890. }
  14891. emitToBool(loc, v) {
  14892. let out = null;
  14893. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  14894. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  14895. if (!out) {
  14896. throw new python.Error('Could not cast value to bool.');
  14897. }
  14898. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  14899. throw new python.Error('Expected a bool expression for condition.');
  14900. }
  14901. return out;
  14902. }
  14903. emitUnaryOp(tree, magicMethod, opSymbol) {
  14904. const inputs = [tree.operand];
  14905. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  14906. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  14907. if (val.node().kind() !== opSymbol) {
  14908. return val;
  14909. }
  14910. const maybe_out_stack = this.runNodeIfInputsAreConstant(val.node());
  14911. if (!maybe_out_stack) {
  14912. return val;
  14913. }
  14914. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  14915. return this.graph.insertConstant(maybe_out_stack[0], tree);
  14916. }
  14917. emitAssignment(stmt) {
  14918. if (stmt instanceof ast.AnnAssign) {
  14919. return this.emitSingleAssignment(stmt);
  14920. }
  14921. if (stmt.targets.length === 1) {
  14922. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  14923. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  14924. for (const [key, value] of entries) {
  14925. assign[key] = value;
  14926. }
  14927. return this.emitSingleAssignment(assign);
  14928. }
  14929. if (stmt.targets.length <= 1) {
  14930. throw new python.Error('Invalid assignment.');
  14931. }
  14932. throw new python.Error('Not implemented.');
  14933. /*
  14934. const tmp_name = this.createTempName('$tmp_assign_');
  14935. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  14936. const ident = new ast.Name(tmp_name);
  14937. for (const expr of lhs_list) {
  14938. const assign = new ast.Assign(targets, value, ctx);
  14939. this.emitSingleAssignment(Assign.create(stmt,
  14940. List<Expr>.create(expr.range(), [expr]),
  14941. Maybe<Expr>::create(stmt.rhs().range(), ident),
  14942. Maybe<Expr>::create(stmt.range())));
  14943. }
  14944. */
  14945. }
  14946. emitSingleAssignment(stmt) {
  14947. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  14948. const rhs = stmt.value;
  14949. const lhs = stmt.target;
  14950. if (lhs instanceof ast.Name) {
  14951. let type = null;
  14952. if (stmt.annotation) {
  14953. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  14954. }
  14955. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  14956. // BC HACK
  14957. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  14958. } else if (lhs instanceof ast.Tuple) {
  14959. this.emitTupleAssign(lhs, rhs);
  14960. } else if (lhs instanceof ast.Attribute) {
  14961. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  14962. } else {
  14963. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  14964. }
  14965. }
  14966. emitSelectAssign(lhs, rhs, type, loc) {
  14967. if (!rhs) {
  14968. throw new python.Error('Expected RHS for assignment.');
  14969. }
  14970. let type_hint = null;
  14971. if (type) {
  14972. type_hint = this._typeParser.parseTypeFromExpr(type);
  14973. }
  14974. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  14975. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  14976. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  14977. }
  14978. emitTupleAssign(...args) {
  14979. if (args.length === 2) {
  14980. const [tl, rhs] = args;
  14981. let n_binders = tl.elts.length;
  14982. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  14983. if (starred_unpack) {
  14984. n_binders--;
  14985. }
  14986. const output = this.emitSugaredExpr(rhs, n_binders);
  14987. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  14988. } else if (args.length === 5) {
  14989. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  14990. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  14991. if (outputs.length < n_binders) {
  14992. throw new python.Error('Not enough values to unpack.');
  14993. }
  14994. if (outputs.length > n_binders && !starred_unpack) {
  14995. throw new python.Error('Too many values to unpack.');
  14996. }
  14997. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  14998. } else {
  14999. throw new python.Error('Not implemented.');
  15000. }
  15001. }
  15002. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  15003. let i = 0;
  15004. for (const assignee of lhs_exprs) {
  15005. if (assignee instanceof ast.Subscript) {
  15006. throw new python.Error('Not implemented.');
  15007. /*
  15008. this.emitSubscriptAssign(
  15009. rhs_loc,
  15010. Subscript(assignee),
  15011. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  15012. i++;
  15013. */
  15014. } else if (assignee instanceof ast.Name) {
  15015. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  15016. i++;
  15017. } else if (assignee instanceof ast.Starred) {
  15018. throw new python.Error('Not implemented.');
  15019. /*
  15020. const var = Starred(assignee).expr();
  15021. if (var.kind() != TK_VAR) {
  15022. throw(
  15023. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  15024. }
  15025. size_t n_matched = outputs.size() - n_binders;
  15026. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  15027. const values = fmap(
  15028. outputs_ref.slice(i, n_matched),
  15029. [&](const std::shared_ptr<SugaredValue>& v) {
  15030. return v.asValue(assignee.range(), method);
  15031. });
  15032. const tup = graph.insertNode(graph.createTuple(values)).output();
  15033. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  15034. i += n_matched;
  15035. */
  15036. } else if (assignee instanceof ast.Tuple) {
  15037. throw new python.Error('Not implemented.');
  15038. /*
  15039. // recursively emit tuple assignments on tuple literal input
  15040. TupleLiteral sub_tl = TupleLiteral(assignee);
  15041. size_t sub_n_binders = sub_tl.inputs().size();
  15042. bool sub_starred_unpack =
  15043. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  15044. if (sub_starred_unpack)
  15045. sub_n_binders--;
  15046. emitTupleAssign(
  15047. sub_tl,
  15048. outputs.at(i),
  15049. rhs_loc,
  15050. sub_n_binders,
  15051. sub_starred_unpack);
  15052. i++;
  15053. */
  15054. } else if (assignee instanceof ast.Attribute) {
  15055. throw new python.Error('Not implemented.');
  15056. /*
  15057. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  15058. i++;
  15059. */
  15060. } else {
  15061. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  15062. }
  15063. }
  15064. }
  15065. emitReturn(stmt) {
  15066. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  15067. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  15068. if (declared_return_type) {
  15069. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  15070. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  15071. }
  15072. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  15073. throw new python.Error(`Invalid return type.`);
  15074. }
  15075. } else {
  15076. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  15077. if (!declared_return_type) {
  15078. declared_return_type = actual_return.type();
  15079. }
  15080. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  15081. if (!merged_return_type) {
  15082. throw new python.Error(`Invalid return type.`);
  15083. }
  15084. declared_return_type = merged_return_type;
  15085. }
  15086. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  15087. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  15088. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  15089. }
  15090. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  15091. this.exit_blocks.add(this.environment_stack.block());
  15092. }
  15093. getNamedValues(trees, maybe_unpack) {
  15094. const values = [];
  15095. for (const tree of trees) {
  15096. if (maybe_unpack && tree instanceof ast.Starred) {
  15097. throw new python.Error('Starred argument not supported.');
  15098. } else {
  15099. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  15100. }
  15101. }
  15102. return values;
  15103. }
  15104. getValues(trees, maybe_unpack) {
  15105. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  15106. }
  15107. emitExpr(tree, type_hint) {
  15108. type_hint = type_hint || null;
  15109. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  15110. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  15111. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  15112. }
  15113. return out_val;
  15114. }
  15115. emitSugaredExpr(tree, n_binders, type_hint) {
  15116. if (tree instanceof ast.Name) { // TK_VAR
  15117. return this.environment_stack.getSugaredVar(tree.id);
  15118. } else if (tree instanceof ast.Attribute) {
  15119. const sv = this.emitSugaredExpr(tree.value, 1);
  15120. return sv.attr(tree.range(), this.method, tree.attr);
  15121. } else if (tree instanceof ast.Call) { // TK_APPLY
  15122. return this.emitApplyExpr(tree, n_binders, type_hint);
  15123. } if (tree instanceof ast.Subscript) {
  15124. return this.emitSubscript(tree, type_hint);
  15125. }
  15126. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  15127. }
  15128. emitApplyExpr(apply, n_binders, type_hint) {
  15129. type_hint = type_hint || null;
  15130. const sv = this.emitSugaredExpr(apply.func, 1);
  15131. const loc = apply.func.range();
  15132. if (sv instanceof torch._C.SpecialFormValue) {
  15133. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  15134. }
  15135. const args = this.getNamedValues(apply.args, true);
  15136. const kwargs = this.emitAttributes(apply.keywords);
  15137. return sv.call(loc, this.method, args, kwargs, n_binders);
  15138. }
  15139. emitAttributes(attributes) {
  15140. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  15141. }
  15142. emitApplySpecialForm(form, apply, sv, type_hint) {
  15143. switch (form) {
  15144. case 'prim::fork': {
  15145. throw new python.Error('Not implemented.');
  15146. }
  15147. case 'prim::awaitable': {
  15148. throw new python.Error('Not implemented.');
  15149. }
  15150. case 'prim::annotate': {
  15151. this.checkApplyNumInputs(apply, 2);
  15152. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  15153. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  15154. if (!expr.type().isSubtypeOf(type)) {
  15155. throw new python.Error('Invalid expression type.');
  15156. }
  15157. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  15158. const none = this.graph.createNone();
  15159. none.output().setType(type);
  15160. this.graph.insertNode(none);
  15161. expr = none.output();
  15162. }
  15163. return new torch._C.SimpleValue(expr);
  15164. }
  15165. case 'prim::unchecked_cast': {
  15166. this.checkApplyNumInputs(apply, 2);
  15167. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  15168. let v = this.emitExpr(apply.args[1]);
  15169. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  15170. v = this.graph.insertUncheckedCast(v, type);
  15171. }
  15172. return new torch._C.SimpleValue(v);
  15173. }
  15174. case 'prim::GetAttr': {
  15175. this.checkApplyNumInputsRange(apply, 2, 3);
  15176. const obj = this.emitSugaredExpr(apply.args[0], 1);
  15177. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  15178. throw new python.Error('Invalid argument.');
  15179. }
  15180. const name = apply.args[1].value;
  15181. if (apply.args.length === 2) {
  15182. return obj.attr(apply, this.method, name);
  15183. } else if (obj.hasAttr(apply, this.method, name)) {
  15184. return obj.attr(apply, this.method, name);
  15185. }
  15186. return this.emitSugaredExpr(apply.inputs()[2], 1);
  15187. }
  15188. case 'prim::Uninitialized': {
  15189. this.checkApplyNumInputs(apply, 1);
  15190. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  15191. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  15192. return new torch._C.SimpleValue(out.output());
  15193. }
  15194. case 'prim::TupleConstruct': {
  15195. throw new python.Error('Not implemented.');
  15196. }
  15197. case 'prim::isinstance': {
  15198. this.checkApplyNumInputs(apply, 2);
  15199. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  15200. return new torch._C.SimpleValue(result.value());
  15201. }
  15202. case 'prim::tolist': {
  15203. const value = apply.func.value;
  15204. const operand = this.emitSugaredExpr(value, 1);
  15205. if (!type_hint) {
  15206. throw new python.Error('Expected type hint for result of tolist().');
  15207. }
  15208. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  15209. }
  15210. case 'prim::HasAttr': {
  15211. throw new python.Error('Not implemented.');
  15212. }
  15213. case 'prim::CreateObject': {
  15214. if (apply.args.length !== 1) {
  15215. throw python.Error('Only one argument to __new__ allowed.');
  15216. }
  15217. const arg = this.emitSugaredExpr(apply.args[0], 1);
  15218. if (arg instanceof torch._C.ClassValue === false) {
  15219. throw python.Error('Expected class value as argument to __new__.');
  15220. }
  15221. const class_arg = arg;
  15222. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  15223. createNode.setSourceRange(apply.range());
  15224. return new torch._C.SimpleValue(createNode.output());
  15225. }
  15226. case 'prim::range': {
  15227. const input_vals = this.getValues(apply.args, true);
  15228. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  15229. }
  15230. case 'prim::enumerate': {
  15231. throw new python.Error('Not implemented.');
  15232. }
  15233. case 'prim::zip': {
  15234. throw new python.Error('Not implemented.');
  15235. }
  15236. case 'prim::list': {
  15237. throw new python.Error('Not implemented.');
  15238. }
  15239. case 'prim::dict': {
  15240. throw new python.Error('Not implemented.');
  15241. }
  15242. case 'aten::index': {
  15243. throw new python.Error('Not implemented.');
  15244. }
  15245. default: {
  15246. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  15247. }
  15248. }
  15249. }
  15250. emitSimpleExpr(tree, type_hint) {
  15251. if (tree instanceof ast.Constant) {
  15252. if (tree.value === true) {
  15253. return this.graph.insertConstant(true, tree.range());
  15254. } else if (tree.value === false) {
  15255. return this.graph.insertConstant(false, tree.range());
  15256. } else if (tree.value === null) {
  15257. return this.graph.insertConstant(null, tree.range()); // IValue()
  15258. } else if (typeof tree.value === 'string') {
  15259. return this.emitStringLiteral(tree);
  15260. }
  15261. return this.emitConst(tree);
  15262. } else if (tree instanceof ast.List) {
  15263. return this.emitListLiteral(tree, type_hint);
  15264. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  15265. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  15266. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  15267. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  15268. } else if (tree instanceof ast.Dict) {
  15269. return this.emitDictLiteral(tree, type_hint);
  15270. } else if (tree instanceof ast.Tuple) {
  15271. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  15272. return this.graph.insertNode(this.graph.createTuple(values)).output();
  15273. }
  15274. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  15275. }
  15276. emitDictLiteral(dl, type_hint) {
  15277. const key_trees = dl.keys;
  15278. const value_trees = dl.values;
  15279. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  15280. const keys = [];
  15281. const values = [];
  15282. let rhs_value_type = null;
  15283. for (let i = 0; i < key_trees.length; i++) {
  15284. keys.push(this.emitExpr(key_trees[i]));
  15285. values.push(this.emitExpr(value_trees[i]));
  15286. if (i === 0) {
  15287. rhs_value_type = values[i].type();
  15288. } else {
  15289. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  15290. throw new python.Error('Dict keys must contain only a single type.');
  15291. }
  15292. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  15293. }
  15294. }
  15295. let refined_type_hint = type_hint;
  15296. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  15297. const all_candidates = [];
  15298. const default_refined_type_hint_setter = () => {
  15299. if (keys.length === 0) {
  15300. refined_type_hint = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  15301. } else {
  15302. refined_type_hint = torch.DictType.create(keys[0].type(), rhs_value_type);
  15303. if (rhs_value_type instanceof torch.UnionType) {
  15304. throw new python.Error('Dict values consist of heterogeneous types.');
  15305. }
  15306. }
  15307. };
  15308. if (type_hint) {
  15309. const type_match = (t) => t instanceof torch.DictType;
  15310. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  15311. if (all_candidates.length > 0 && values.length === 0) {
  15312. throw new python.Error('Cannot assign an empty dict.');
  15313. }
  15314. } else {
  15315. default_refined_type_hint_setter();
  15316. }
  15317. torch._C.TORCH_INTERNAL_ASSERT(all_candidates.length > 0 || refined_type_hint);
  15318. if (values.length > 0) {
  15319. if (all_candidates.length > 0) {
  15320. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  15321. }
  15322. if (refined_type_hint.getKeyType() !== keys[0].type()) {
  15323. throw new python.Error('Type annotation does not match key type.');
  15324. }
  15325. if (!rhs_value_type.isSubtypeOf(refined_type_hint.getValueType())) {
  15326. throw new python.Error('Type annotation does not match value type.');
  15327. }
  15328. }
  15329. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint.getKeyType(), refined_type_hint.getValueType(), keys, values));
  15330. if (annotated_union_type) {
  15331. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  15332. n.output().setType(annotated_union_type);
  15333. result = n;
  15334. }
  15335. return result.output();
  15336. }
  15337. emitStringLiteral(c) {
  15338. return torch._C.insertConstant(this.graph, c.value, c.range());
  15339. }
  15340. emitConst(c) {
  15341. if (c.type === 'int') {
  15342. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  15343. } else if (c.type === 'complex') {
  15344. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  15345. } else if (c.type === 'float') {
  15346. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  15347. }
  15348. throw new python.Error(`Unsupported constant type.`);
  15349. }
  15350. emitListLiteral(ll, type_hint) {
  15351. type_hint = type_hint || null;
  15352. const values = this.getValues(ll.elts, true);
  15353. if (values.length === 0 && type_hint === null) {
  15354. throw new python.Error('Not implemented.');
  15355. }
  15356. let inferred_elem_type = torch.TensorType.get();
  15357. const refined_type_hint = type_hint;
  15358. const annotated_union_type = refined_type_hint && refined_type_hint.isUnionType() ? refined_type_hint : null;
  15359. const all_candidates = [];
  15360. if (refined_type_hint) {
  15361. const do_if_type_match = () => {
  15362. inferred_elem_type = refined_type_hint.expect(torch.ListType).getElementType();
  15363. };
  15364. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  15365. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  15366. if (all_candidates.length > 0 && values.len === 0) {
  15367. throw new python.Error('Cannot assign an empty list.');
  15368. }
  15369. }
  15370. if (values.length !== 0) {
  15371. const types = values.map((v) => v.type());
  15372. const elem_type_hint = refined_type_hint && refined_type_hint.kind() === 'ListType' ? refined_type_hint.getElementType() : null;
  15373. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  15374. if (!refined_type_hint && unified_elem_type.kind() === 'UnionType') {
  15375. throw new python.Error('Not implemented.');
  15376. }
  15377. if (all_candidates.length === 0 && refined_type_hint && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  15378. throw new python.Error('Not implemented.');
  15379. }
  15380. if (all_candidates.length !== 0) {
  15381. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, unified_elem_type, ll);
  15382. inferred_elem_type = refined_type_hint.expect(torch.ListType).getElementType();
  15383. }
  15384. if (!refined_type_hint) {
  15385. inferred_elem_type = unified_elem_type;
  15386. }
  15387. }
  15388. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  15389. if (annotated_union_type) {
  15390. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  15391. n.output().setType(annotated_union_type);
  15392. result = n;
  15393. }
  15394. return result.output();
  15395. }
  15396. insertRefinements(loc, ref) {
  15397. for (const r of ref.activeRefinements()) {
  15398. const v = this.environment_stack.getVar(r.identifier(), loc);
  15399. const new_v = this.graph.insertUncheckedCast(v, r.type());
  15400. this.environment_stack.setVar(loc, r.identifier(), new_v);
  15401. }
  15402. }
  15403. shouldDeriveSetStateType(def, schema) {
  15404. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  15405. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  15406. if (!shouldInfer) {
  15407. return false;
  15408. }
  15409. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  15410. throw new python.Error(`Invalid '__setstate' method.`);
  15411. }
  15412. return true;
  15413. }
  15414. checkApplyNumInputs(apply, expected_inputs) {
  15415. if (apply.args.length !== expected_inputs) {
  15416. throw new python.Error('Invalid number of arguments.');
  15417. }
  15418. if (apply.keywords.length > 0) {
  15419. throw new python.Error('Invalid number of keyword arguments.');
  15420. }
  15421. }
  15422. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  15423. const position_arg_size = apply.args.length;
  15424. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  15425. throw new python.Error('Invalid number of arguments.');
  15426. }
  15427. if (apply.keywords.length > 0) {
  15428. throw new python.Error('Invalid number of keyword arguments.');
  15429. }
  15430. }
  15431. validateAssignLhsExpr(lhs /*, r */) {
  15432. let num_normal_assign = 0;
  15433. let num_starred = 0;
  15434. for (const assignee of lhs) {
  15435. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  15436. num_normal_assign++;
  15437. } else if (assignee instanceof ast.Starred) {
  15438. num_starred++;
  15439. } else {
  15440. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  15441. }
  15442. }
  15443. if (num_starred > 1) {
  15444. throw new python.Error('Only one starred expression is allowed.');
  15445. }
  15446. if (num_starred > 0 && num_normal_assign === 0) {
  15447. throw new python.Error('Invalid starred expression.');
  15448. }
  15449. return num_starred;
  15450. }
  15451. createTempName(prefix) {
  15452. return `${prefix}${this._temp_name_count++}`;
  15453. }
  15454. handleMaybeNoReturn(def, block) {
  15455. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  15456. if (this.exit_blocks.size === 0) {
  15457. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  15458. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  15459. }
  15460. const b = new torch._C.WithInsertPoint(block.nodes()[-1]);
  15461. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  15462. b.dispose();
  15463. throw new Error();
  15464. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  15465. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  15466. }
  15467. }
  15468. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  15469. let adj_index = input_index;
  15470. const tuple_len = tuple_type.elements().length;
  15471. if (input_index < 0) {
  15472. adj_index = tuple_len + input_index;
  15473. }
  15474. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  15475. throw new python.Error(`Tuple index out of range at ${loc}.`);
  15476. }
  15477. return adj_index;
  15478. }
  15479. emitTupleIndex(loc, tuple_val, idx_val) {
  15480. const tuple_typ = tuple_val.type();
  15481. const elems = tuple_typ.elements();
  15482. let output_type = null;
  15483. if (idx_val.type() !== torch.IntType.get()) {
  15484. throw new python.Error('Tuple index must be an integer.');
  15485. }
  15486. const idx = torch._C.toIValue(idx_val);
  15487. if (idx) {
  15488. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  15489. output_type = elems[adj_index];
  15490. } else {
  15491. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  15492. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  15493. }
  15494. [output_type] = elems;
  15495. }
  15496. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  15497. }
  15498. getSliceInd(idx_val, loc) {
  15499. const ivalue = torch._C.toIValue(idx_val);
  15500. if (ivalue && ivalue.isInt()) {
  15501. return ivalue.toInt();
  15502. }
  15503. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  15504. }
  15505. emitTupleSlice(loc, tuple_val, tuple_args) {
  15506. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  15507. const tuple_len = tuple_type.elements().length;
  15508. const [beg_val, end_val, step] = tuple_args;
  15509. let step_size = 1;
  15510. if (step) {
  15511. const val = torch._C.toIValue(step.value(this.graph));
  15512. torch._C.TORCH_CHECK(val.isInt());
  15513. step_size = val.toInt();
  15514. }
  15515. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  15516. if (beg_val) {
  15517. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  15518. }
  15519. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  15520. if (end_val) {
  15521. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  15522. }
  15523. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  15524. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  15525. }
  15526. emitSliceOp(loc, sliceable, dim, start, end, step) {
  15527. const args = [];
  15528. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  15529. if (dim) {
  15530. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  15531. args.emplace_back(new torch._C.NamedValue(dim));
  15532. } else {
  15533. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  15534. }
  15535. if (sliceable.type() instanceof torch.TupleType) {
  15536. const tuple_args = [];
  15537. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  15538. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  15539. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  15540. return this.emitTupleSlice(loc, args[0], tuple_args);
  15541. }
  15542. if (!step) {
  15543. step = this.graph.insertConstant(1, loc);
  15544. }
  15545. args.push(new torch._C.NamedValue(loc, 'start', start));
  15546. args.push(new torch._C.NamedValue(loc, 'end', end));
  15547. args.push(new torch._C.NamedValue(loc, 'step', step));
  15548. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  15549. }
  15550. emitSlice(loc, input, dim, slice) {
  15551. let start = null;
  15552. let end = null;
  15553. let step = null;
  15554. if (slice.lower) {
  15555. start = this.emitExpr(slice.lower);
  15556. }
  15557. if (slice.upper) {
  15558. end = this.emitExpr(slice.upper);
  15559. }
  15560. if (slice.step) {
  15561. step = this.emitExpr(slice.step);
  15562. }
  15563. return this.emitSliceOp(loc, input, dim, start, end, step);
  15564. }
  15565. emitBasicSlice(loc, sliceable, subscript_exprs) {
  15566. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  15567. const slice_exp = subscript_exprs;
  15568. let maybe_dim = null;
  15569. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  15570. maybe_dim = this.graph.insertConstant(0, loc);
  15571. }
  15572. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  15573. }
  15574. emitSubscript(subscript, type_hint) {
  15575. type_hint = type_hint === undefined ? null : type_hint;
  15576. const sv = this.emitSugaredExpr(subscript.value, 1);
  15577. const subscript_exprs = subscript.slice;
  15578. const range = subscript.range();
  15579. const val_range = subscript.value;
  15580. if (subscript_exprs instanceof ast.Tuple) {
  15581. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  15582. }
  15583. if (subscript_exprs instanceof ast.Slice) {
  15584. if (sv.kind() === 'module') {
  15585. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  15586. const [slice] = subscript_exprs;
  15587. const tuple_args = [];
  15588. if (slice.start().present()) {
  15589. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  15590. tuple_args.push(begin);
  15591. } else {
  15592. tuple_args.push(null);
  15593. }
  15594. if (slice.end().present()) {
  15595. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  15596. tuple_args.push(end);
  15597. } else {
  15598. tuple_args.push(null);
  15599. }
  15600. if (slice.step().present()) {
  15601. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  15602. tuple_args.push(step);
  15603. } else {
  15604. tuple_args.push(null);
  15605. }
  15606. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  15607. return new torch._C.SimpleValue(tupleSliceValue);
  15608. }
  15609. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  15610. }
  15611. const sliceable = sv.asValue(val_range, this.method);
  15612. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  15613. if (subscript_sv instanceof torch._C.SliceValue) {
  15614. const slice_value = subscript_sv;
  15615. let dim = null;
  15616. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  15617. dim = this.method.graph().insertConstant(0, val_range);
  15618. }
  15619. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  15620. return new torch._C.SimpleValue(sliced);
  15621. }
  15622. const idx = subscript_sv.asValue(val_range, this.method);
  15623. if (sliceable.type() instanceof torch.TupleType) {
  15624. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  15625. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  15626. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  15627. }
  15628. return sv.getitem(range, this.method, idx, type_hint);
  15629. }
  15630. });
  15631. this.registerType('torch.jit.CompilationUnit', class {
  15632. constructor() {
  15633. this._functions = new Map();
  15634. this._classes = new Map();
  15635. }
  15636. register_type(namedType) {
  15637. this._classes.set(namedType.annotation_str, namedType);
  15638. }
  15639. register_function(fn) {
  15640. const name = fn.qualname().qualifiedName();
  15641. torch._C.TORCH_CHECK(!this._functions.has(name));
  15642. this._functions.set(name, fn);
  15643. return fn;
  15644. }
  15645. define(...args) {
  15646. if (Array.isArray(args[1])) {
  15647. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  15648. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  15649. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  15650. const functions = [];
  15651. const function_table = new Map();
  15652. const record_function = (fn) => {
  15653. function_table.set(fn.name(), fn);
  15654. functions.push(fn);
  15655. this.register_function(fn);
  15656. };
  15657. for (let i = 0; i < properties.length; i++) {
  15658. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  15659. const getter_fn = property_fns.getGetter();
  15660. const setter_fn = property_fns.getSetter();
  15661. record_function(getter_fn);
  15662. if (setter_fn) {
  15663. record_function(setter_fn);
  15664. }
  15665. }
  15666. for (let i = 0; i < definitions.length; i++) {
  15667. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  15668. record_function(fn);
  15669. }
  15670. for (const [name, fn] of function_table) {
  15671. if (name === '__init__') {
  15672. fn.ensure_defined();
  15673. }
  15674. }
  15675. for (const fn of functions) {
  15676. fn.ensure_defined();
  15677. }
  15678. return functions;
  15679. } else if (args[1] instanceof ast.FunctionDef) {
  15680. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  15681. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  15682. const creator = (method) => {
  15683. return new torch._C.to_ir(def, _resolver, self, method);
  15684. };
  15685. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  15686. if (shouldMangle && this.find_function(name)) {
  15687. name = this.mangle(name);
  15688. }
  15689. const graph = new torch.Graph();
  15690. graph.set_op_version(operator_set_version);
  15691. const fn = new torch._C.GraphFunction(name, graph, creator);
  15692. fn.__ast__ = def; // remove
  15693. if (self) {
  15694. if (type === 'hook') {
  15695. self.getClassType().addForwardHook(fn);
  15696. } else if (type === 'prehook') {
  15697. self.getClassType().addPreHook(fn);
  15698. } else {
  15699. self.getClassType().addMethod(fn);
  15700. }
  15701. }
  15702. return fn;
  15703. }
  15704. throw new python.Error('Invalid arguments.');
  15705. }
  15706. get_type(name) {
  15707. return this._classes.get(name.qualifiedName());
  15708. }
  15709. get_class(name) {
  15710. return this.get_type(name);
  15711. }
  15712. find_function(name) {
  15713. const key = name.qualifiedName();
  15714. return this._functions.get(key);
  15715. }
  15716. });
  15717. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  15718. const ctrl = new torch._C.ControlFlowLoadStores();
  15719. ctrl.run(graph);
  15720. const exit_vars = new torch._C.LoopContinuations();
  15721. exit_vars.run(graph);
  15722. torch._C.InlineLoopCondition(graph);
  15723. const erase_loads_stores = new torch._C.EraseLoadStores();
  15724. erase_loads_stores.run(graph);
  15725. torch._C.TransformExits(graph);
  15726. });
  15727. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  15728. /*
  15729. LoopView loop(n);
  15730. if (loop.loopType() != LoopView::ModifiedLoop) {
  15731. return;
  15732. }
  15733. const g = n.owningGraph();
  15734. WithInsertPoint node_insert(n);
  15735. const zero = g.insertConstant(0);
  15736. const one = g.insertConstant(1);
  15737. const max_trip_count = loop.maxTripCount();
  15738. const condition = g.insert(aten::gt, {max_trip_count, zero});
  15739. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  15740. const inp_condition = toIValue(loop.inputCond());
  15741. if (inp_condition == null || inp_condition.toBool() == false) {
  15742. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  15743. }
  15744. loop.replaceInputCondition(condition);
  15745. n.addOutput().setType(IntType::get());
  15746. WithInsertPoint loop_insert(loop.bodyBlock());
  15747. n.addInput(zero);
  15748. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  15749. // unset unique name for jitter, its replacement does not have a name
  15750. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  15751. const inc_iter = g.insert(aten::add, {new_iter, one});
  15752. loop.bodyBlock().registerOutput(inc_iter);
  15753. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  15754. const loop_continue = loop.nextCond();
  15755. const new_condition =
  15756. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  15757. loop.bodyBlock().eraseOutput(0);
  15758. loop.bodyBlock().insertOutput(0, new_condition);
  15759. */
  15760. });
  15761. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  15762. for (const n of block.nodes()) {
  15763. for (const b of n.blocks()) {
  15764. torch._C.canonicalizeModifiedLoops(b);
  15765. }
  15766. if (n.kind() === 'prim::Loop') {
  15767. torch._C.canonicalizeModifiedLoop(n);
  15768. }
  15769. }
  15770. });
  15771. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  15772. torch._C.canonicalizeModifiedLoops(graph.block());
  15773. });
  15774. this.registerType('torch._C.MiniEnvironment', class {
  15775. constructor(b, next) {
  15776. this.next = next || null;
  15777. this.table = new Map();
  15778. }
  15779. setVar(name, value) {
  15780. this.table.set(name, value);
  15781. }
  15782. definedVariables() {
  15783. const result = Array.from(this.table.keys());
  15784. return result.sort();
  15785. }
  15786. findInThisFrame(name) {
  15787. if (this.table.has(name)) {
  15788. return this.table.get(name);
  15789. }
  15790. return null;
  15791. }
  15792. findInAnyFrame(name) {
  15793. for (let runner = this; runner; runner = runner.next) {
  15794. const r = runner.findInThisFrame(name);
  15795. if (r) {
  15796. return r;
  15797. }
  15798. }
  15799. return null;
  15800. }
  15801. });
  15802. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  15803. });
  15804. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  15805. });
  15806. this.registerType('torch._C.ControlFlowLoadStores', class {
  15807. constructor() {
  15808. this.environment_stack = null;
  15809. }
  15810. pushFrame(b) {
  15811. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  15812. }
  15813. popFrame() {
  15814. const old_frame = this.environment_stack;
  15815. this.environment_stack = this.environment_stack.next;
  15816. return old_frame;
  15817. }
  15818. addBlockInput(b, type, name) {
  15819. const g = b.owningGraph();
  15820. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  15821. }
  15822. addBlockOutput(exit_block, type, name) {
  15823. const insert = new torch._C.WithInsertPoint(exit_block);
  15824. const g = exit_block.owningGraph();
  15825. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  15826. exit_block.registerOutput(block_exit);
  15827. insert.dispose();
  15828. }
  15829. addNodeOutput(n, type, name) {
  15830. const out = n.addOutput().setType(type);
  15831. if (torch._C.meaningfulName(name)) {
  15832. out.setDebugName(name);
  15833. }
  15834. const g = n.owningGraph();
  15835. g.createStore(name, out).insertAfter(n);
  15836. }
  15837. addNodeInput(n, type, name) {
  15838. const g = n.owningGraph();
  15839. const inp = g.createLoad(name, type).insertBefore(n).output();
  15840. n.addInput(inp);
  15841. }
  15842. addIfLoadStores(n) {
  15843. const [true_block, false_block] = n.blocks();
  15844. const true_vars = this.addControlFlowLoadStores(true_block);
  15845. const false_vars = this.addControlFlowLoadStores(false_block);
  15846. const mutated_variables = new Set();
  15847. for (const v of true_vars.definedVariables()) {
  15848. if (false_vars.findInAnyFrame(v)) {
  15849. mutated_variables.add(v);
  15850. }
  15851. }
  15852. for (const v of false_vars.definedVariables()) {
  15853. if (true_vars.findInAnyFrame(v)) {
  15854. mutated_variables.add(v);
  15855. }
  15856. }
  15857. for (const x of mutated_variables) {
  15858. const true_type = true_vars.findInAnyFrame(x);
  15859. const false_type = false_vars.findInAnyFrame(x);
  15860. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  15861. this.addBlockOutput(true_block, true_type, x);
  15862. this.addBlockOutput(false_block, false_type, x);
  15863. this.addNodeOutput(n, unified, x);
  15864. }
  15865. }
  15866. addLoopLoadStores(n) {
  15867. const [body_block] = n.blocks();
  15868. const loop_vars = this.addControlFlowLoadStores(body_block);
  15869. for (const name of loop_vars.definedVariables()) {
  15870. const parent_type = this.environment_stack.findInAnyFrame(name);
  15871. if (!parent_type) {
  15872. continue;
  15873. }
  15874. const block_type = loop_vars.findInThisFrame(name);
  15875. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  15876. this.addNodeInput(n, parent_type, name);
  15877. this.addBlockInput(body_block, unified_type, name);
  15878. this.addBlockOutput(body_block, block_type, name);
  15879. this.addNodeOutput(n, unified_type, name);
  15880. }
  15881. }
  15882. addControlFlowLoadStores(block) {
  15883. this.pushFrame(block);
  15884. for (const n of block.nodes()) {
  15885. switch (n.kind()) {
  15886. case 'prim::If': {
  15887. this.addIfLoadStores(n);
  15888. break;
  15889. }
  15890. case 'prim::Loop': {
  15891. this.addLoopLoadStores(n);
  15892. break;
  15893. }
  15894. case 'prim::Closure': {
  15895. for (const b of n.blocks()) {
  15896. this.addControlFlowLoadStores(b);
  15897. }
  15898. break;
  15899. }
  15900. case 'prim::Store': {
  15901. this.environment_stack.setVar(n.s('name'), n.input().type());
  15902. break;
  15903. }
  15904. case 'prim::ComprehensionScope': {
  15905. this.addControlFlowLoadStores(n.blocks()[0]);
  15906. break;
  15907. }
  15908. default: {
  15909. break;
  15910. }
  15911. }
  15912. }
  15913. return this.popFrame();
  15914. }
  15915. run(graph) {
  15916. this.addControlFlowLoadStores(graph.block());
  15917. }
  15918. });
  15919. this.registerType('torch._C.LoopContinuations', class {
  15920. constructor() {
  15921. this._graph = null;
  15922. this._false_val = null;
  15923. this._curr_loop = null;
  15924. }
  15925. assignExitContinuations(block) {
  15926. for (const n of block.nodes()) {
  15927. switch (n.kind()) {
  15928. case 'prim::If': {
  15929. this.assignExitContinuations(n.blocks()[0]);
  15930. this.assignExitContinuations(n.blocks()[1]);
  15931. break;
  15932. }
  15933. case 'prim::Closure': {
  15934. const closure_block = new torch._C.LoopContinuations();
  15935. closure_block.run(n.blocks()[0]);
  15936. break;
  15937. }
  15938. case 'prim::Loop': {
  15939. const prev_loop = this._curr_loop;
  15940. this._curr_loop = n;
  15941. this.assignExitContinuations(n.blocks()[0]);
  15942. this._curr_loop = prev_loop;
  15943. break;
  15944. }
  15945. case 'prim::ContinueStmt': {
  15946. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  15947. const header_block = loop_continuation.addBlock();
  15948. const [, pre_header] = this._curr_loop.blocks();
  15949. header_block.cloneFrom(pre_header, (v) => v);
  15950. this.InlineBlockBeforeNode(n, header_block);
  15951. loop_continuation.addInput(header_block.outputs()[0]);
  15952. loop_continuation.eraseBlock(0);
  15953. this.addLoopCarriedOutputs(loop_continuation);
  15954. n.destroy();
  15955. break;
  15956. }
  15957. case 'prim::BreakStmt': {
  15958. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  15959. loop_exit.addInput(this._false_val);
  15960. this.addLoopCarriedOutputs(loop_exit);
  15961. n.destroy();
  15962. break;
  15963. }
  15964. default: {
  15965. break;
  15966. }
  15967. }
  15968. }
  15969. }
  15970. run(...args) {
  15971. if (args.length === 1 && args[0] instanceof torch.Graph) {
  15972. const [graph] = args;
  15973. this.run(graph.block());
  15974. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  15975. const [b] = args;
  15976. {
  15977. this._graph = b.owningGraph();
  15978. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  15979. this._false_val = this._graph.insertConstant(false);
  15980. guard.dispose();
  15981. }
  15982. this.assignExitContinuations(b);
  15983. } else {
  15984. throw new python.Error('Not implemented.');
  15985. }
  15986. }
  15987. });
  15988. this.registerType('torch._C.LoopView', class {
  15989. constructor(node) {
  15990. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  15991. this._node = node;
  15992. }
  15993. bodyBlock() {
  15994. return this._node.blocks()[0];
  15995. }
  15996. nextCond() {
  15997. return this.bodyBlock().outputs()[0];
  15998. }
  15999. carriedOutputs() {
  16000. return this._node.outputs();
  16001. }
  16002. bodyCarriedInputs() {
  16003. return this.bodyBlock().inputs().slice(1);
  16004. }
  16005. bodyCarriedOutputs() {
  16006. return this.bodyBlock().outputs().slice(1);
  16007. }
  16008. });
  16009. this.registerType('torch._C.WithLoopStatus', class {
  16010. constructor(to_ir, new_status) {
  16011. this._to_ir = to_ir;
  16012. this._prev = this._to_ir._loop_status;
  16013. this._to_ir._loop_status = new_status;
  16014. }
  16015. dispose() {
  16016. this._to_ir._loop_status = this._prev;
  16017. }
  16018. });
  16019. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  16020. for (const block_node of block.nodes()) {
  16021. block_node.moveBefore(before_node);
  16022. }
  16023. });
  16024. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  16025. if (args.length === 1 && args[0] instanceof torch.Block) {
  16026. const [block] = args;
  16027. for (const n of block.nodes()) {
  16028. for (const b of n.blocks()) {
  16029. torch._C.inlineLoopCondition(b);
  16030. }
  16031. if (n.kind() === 'prim::Loop') {
  16032. torch._C.inlineLoopCondition(n);
  16033. }
  16034. }
  16035. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  16036. const [n] = args;
  16037. const [body_block, pre_header] = n.blocks();
  16038. const temp_block = n.addBlock();
  16039. temp_block.cloneFrom(pre_header, (v) => v);
  16040. torch._C.InlineBlockBeforeNode(n, temp_block);
  16041. n.insertInput(1, temp_block.outputs()[0]);
  16042. n.eraseBlock(2);
  16043. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  16044. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  16045. n.eraseBlock(1);
  16046. } else {
  16047. throw new python.Error('Not implemented.');
  16048. }
  16049. });
  16050. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  16051. torch._C.inlineLoopCondition(graph.block());
  16052. });
  16053. this.registerType('torch._C.EraseLoadStores', class {
  16054. pushFrame(b) {
  16055. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  16056. }
  16057. popFrame() {
  16058. const old_frame = this.environment_stack;
  16059. this.environment_stack = this.environment_stack.next;
  16060. return old_frame;
  16061. }
  16062. eraseBlockLoadStores(block) {
  16063. this.pushFrame(block);
  16064. for (const n of block.nodes()) {
  16065. switch (n.kind()) {
  16066. case 'prim::Store': {
  16067. this.environment_stack.setVar(n.s('name'), n.input());
  16068. n.destroy();
  16069. break;
  16070. }
  16071. case 'prim::Load': {
  16072. const name = n.s('name');
  16073. const value = this.environment_stack.findInAnyFrame(name);
  16074. torch._C.TORCH_INTERNAL_ASSERT(value);
  16075. n.output().replaceAllUsesWith(value);
  16076. n.destroy();
  16077. break;
  16078. }
  16079. case 'prim::ComprehensionScope': {
  16080. const [body] = n.blocks();
  16081. this.eraseBlockLoadStores(body);
  16082. for (const body_node of body.nodes()) {
  16083. body_node.moveBefore(n);
  16084. }
  16085. n.destroy();
  16086. break;
  16087. }
  16088. default: {
  16089. for (const b of n.blocks()) {
  16090. this.eraseBlockLoadStores(b);
  16091. }
  16092. break;
  16093. }
  16094. }
  16095. }
  16096. this.popFrame();
  16097. }
  16098. run(graph) {
  16099. this.eraseBlockLoadStores(graph.block());
  16100. }
  16101. });
  16102. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  16103. });
  16104. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  16105. });
  16106. this.registerType('torch._C.ExitPair', class {
  16107. constructor(exit_v, exit_val_ref) {
  16108. const exit_vals = [];
  16109. for (const v of exit_val_ref) {
  16110. exit_vals.push(v);
  16111. }
  16112. if (exit_v.type() !== torch.BoolType.get()) {
  16113. throw new python.Error('Invalid exit value type.');
  16114. }
  16115. this.first = exit_v;
  16116. this.second = exit_vals;
  16117. }
  16118. hasExited() {
  16119. return this.first;
  16120. }
  16121. exitValues() {
  16122. return this.second;
  16123. }
  16124. });
  16125. this.registerType('torch._C.ExitTransformer', class {
  16126. constructor(graph) {
  16127. this._graph = graph;
  16128. this._target_block = null;
  16129. this._unit_values = new Map();
  16130. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  16131. this._true_val = this._graph.insertConstant(true);
  16132. this._false_val = this._graph.insertConstant(false);
  16133. this._throws_val = this.getUnitValue(torch.BoolType.get());
  16134. guard.dispose();
  16135. }
  16136. getUnitValue(type) {
  16137. const maybe_val = this._unit_values.get(type);
  16138. if (maybe_val) {
  16139. return maybe_val;
  16140. }
  16141. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  16142. this._unit_values.set(type, unit);
  16143. return unit;
  16144. }
  16145. transformReturnStmts() {
  16146. this._current_exit_kind = 'prim::ReturnStmt';
  16147. this.transformExits(this._graph.block());
  16148. }
  16149. transformLoopContinuations() {
  16150. this._current_exit_kind = 'prim::LoopContinuation';
  16151. this.transformExits(this._graph.block());
  16152. }
  16153. destroyNodeAfterExit(n) {
  16154. for (const output of n.outputs()) {
  16155. if (output.uses().length > 0) {
  16156. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  16157. }
  16158. }
  16159. n.destroy();
  16160. }
  16161. deleteAfterExitNodes(block, iter) {
  16162. const nodes = block.nodes();
  16163. if (iter === nodes.end()) {
  16164. return;
  16165. }
  16166. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  16167. for (const it of Array.from(nodes).reverse()) {
  16168. if (it === iter) {
  16169. break;
  16170. }
  16171. if (it !== block.return_node()) {
  16172. this.destroyNodeAfterExit(it);
  16173. }
  16174. }
  16175. this.destroyNodeAfterExit(iter);
  16176. insert.dispose();
  16177. }
  16178. updateTargetBlock(block) {
  16179. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  16180. this._target_block = block;
  16181. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  16182. this._target_block = block;
  16183. }
  16184. }
  16185. transformLoop(node) {
  16186. const loop = new torch._C.LoopView(node);
  16187. const body = loop.bodyBlock();
  16188. const exit_pair = this.transformExits(body);
  16189. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  16190. return this.constructWontExitPair();
  16191. }
  16192. const insert = new torch._C.WithInsertPoint(body);
  16193. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  16194. new_if.addInput(exit_pair.hasExited());
  16195. new_if.addBlock().registerOutput(this._false_val);
  16196. new_if.addBlock().registerOutput(loop.nextCond());
  16197. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  16198. loop.bodyBlock().eraseOutput(0);
  16199. loop.bodyBlock().insertOutput(0, new_condition);
  16200. node.addInput(this._false_val);
  16201. body.addInput().setType(torch.BoolType.get());
  16202. body.registerOutput(exit_pair.hasExited());
  16203. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  16204. for (const exit_value of exit_pair.exitValues()) {
  16205. const typ = exit_value.type();
  16206. node.addInput(this.getUnitValue(typ));
  16207. node.addOutput().setType(typ);
  16208. body.addInput().setType(typ);
  16209. body.registerOutput(exit_value);
  16210. }
  16211. const exit_vals = node.outputs().slice(node.outputs().size() - exit_pair.exitValues().size());
  16212. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  16213. insert.dispose();
  16214. return result;
  16215. }
  16216. calcIfExitStatus(then_status, else_status) {
  16217. if (then_status === 'THROWS') {
  16218. return else_status;
  16219. } else if (else_status === 'THROWS') {
  16220. return then_status;
  16221. }
  16222. if (then_status === 'WONT' && else_status === 'WONT') {
  16223. return 'WONT';
  16224. }
  16225. if (then_status === 'WILL' && else_status === 'WILL') {
  16226. return 'WILL';
  16227. }
  16228. return 'MIGHT';
  16229. }
  16230. transformIf(node) {
  16231. const [then_block, else_block] = node.blocks();
  16232. let then_pair = this.transformExits(then_block);
  16233. let else_pair = this.transformExits(else_block);
  16234. const then_status = this.getExitStatus(then_pair);
  16235. const else_status = this.getExitStatus(else_pair);
  16236. const if_status = this.calcIfExitStatus(then_status, else_status);
  16237. if (if_status === 'THROWS') {
  16238. return this.constructThrowsExitPair();
  16239. }
  16240. if (if_status === 'WONT') {
  16241. return this.constructWontExitPair();
  16242. }
  16243. if (then_status === 'WONT' || then_status === 'THROWS') {
  16244. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  16245. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  16246. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  16247. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  16248. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  16249. }
  16250. let has_exited = null;
  16251. if (if_status === 'WILL') {
  16252. has_exited = this._true_val;
  16253. } else {
  16254. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  16255. has_exited = node.outputs().at(node.outputs().size() - 1);
  16256. }
  16257. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  16258. const num_exit_vals = then_pair.exitValues().size();
  16259. const exit_vals = node.outputs().slice(node.outputs().size() - num_exit_vals);
  16260. return new torch._C.ExitPair(has_exited, exit_vals);
  16261. }
  16262. transformExits(block) {
  16263. const prev_target_block = this._target_block;
  16264. this.updateTargetBlock(block);
  16265. let exit_pair = this.constructWontExitPair();
  16266. for (const node of block.nodes()) {
  16267. const it = node.next;
  16268. switch (node.kind()) {
  16269. case 'prim::RaiseException': {
  16270. exit_pair = this.constructThrowsExitPair();
  16271. break;
  16272. }
  16273. case 'prim::ReturnStmt':
  16274. case 'prim::LoopContinuation': {
  16275. if (node.kind() === this._current_exit_kind) {
  16276. exit_pair = this.constructWillExitPair(node.inputs());
  16277. node.destroy();
  16278. }
  16279. break;
  16280. }
  16281. case 'prim::If': {
  16282. exit_pair = this.transformIf(node);
  16283. break;
  16284. }
  16285. case 'prim::With': {
  16286. exit_pair = this.transformWith(node);
  16287. break;
  16288. }
  16289. case 'prim::Closure': {
  16290. this.transformExits(node.blocks()[0]);
  16291. break;
  16292. }
  16293. case 'prim::Loop': {
  16294. exit_pair = this.transformLoop(node);
  16295. break;
  16296. }
  16297. default: {
  16298. break;
  16299. }
  16300. }
  16301. const status = this.getExitStatus(exit_pair);
  16302. if (status === 'WILL' || status === 'THROWS') {
  16303. this.deleteAfterExitNodes(block, it);
  16304. break;
  16305. }
  16306. if (status === 'MIGHT') {
  16307. throw new python.Error('Not implemented.');
  16308. // const nodes = block.nodes();
  16309. // if (node === nodes[nodes.length - 1]) {
  16310. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  16311. // }
  16312. // break;
  16313. }
  16314. }
  16315. if (this._target_block === block) {
  16316. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  16317. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  16318. new_if.addBlock();
  16319. new_if.addBlock();
  16320. new_if.addInput(exit_pair.hasExited());
  16321. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  16322. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  16323. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  16324. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  16325. }
  16326. exit_pair = this.constructWontExitPair();
  16327. }
  16328. this._target_block = prev_target_block;
  16329. return exit_pair;
  16330. }
  16331. constructThrowsExitPair() {
  16332. return new torch._C.ExitPair(this._throws_val, []);
  16333. }
  16334. constructWontExitPair() {
  16335. return new torch._C.ExitPair(this._false_val, []);
  16336. }
  16337. constructWillExitPair(exit_val_ref) {
  16338. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  16339. }
  16340. getExitStatus(exit_pair) {
  16341. const exit_v = exit_pair.hasExited();
  16342. if (exit_v === this._true_val) {
  16343. return 'WILL';
  16344. } else if (exit_v === this._false_val) {
  16345. return 'WONT';
  16346. } else if (exit_v === this._throws_val) {
  16347. return 'THROWS';
  16348. }
  16349. return 'MIGHT';
  16350. }
  16351. static owningNodeKind(block) {
  16352. if (block.owningNode()) {
  16353. return block.owningNode().kind();
  16354. }
  16355. return null;
  16356. }
  16357. static isGraphOrClosureBlock(block) {
  16358. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  16359. }
  16360. static removeOutputs(b) {
  16361. while (b.outputs().length > 0) {
  16362. b.eraseOutput(0);
  16363. }
  16364. }
  16365. static registerBlockOutputs(b, outs) {
  16366. for (const out of outs) {
  16367. b.registerOutput(out);
  16368. }
  16369. }
  16370. static replaceBlockOutputs(b, outs) {
  16371. torch._C.ExitTransformer.removeOutputs(b);
  16372. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  16373. }
  16374. });
  16375. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  16376. });
  16377. this.registerFunction('torch._C.TransformExits', (graph) => {
  16378. torch._C.convertEnterExitNodesToWithBlocks(graph);
  16379. const e_loop = new torch._C.ExitTransformer(graph);
  16380. e_loop.transformLoopContinuations();
  16381. const e_ret = new torch._C.ExitTransformer(graph);
  16382. e_ret.transformReturnStmts();
  16383. torch._C.inlineConsecutiveIfs(graph.block());
  16384. torch._C.convertWithBlocksToEnterExitNodes(graph);
  16385. });
  16386. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  16387. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  16388. const args = iter.inputs();
  16389. const newSub = iter.replaceWithNewSymbol('aten::sub');
  16390. newSub.replaceInput(0, args[1]);
  16391. newSub.replaceInput(1, args[0]);
  16392. iter.destroyCurrent();
  16393. return true;
  16394. }
  16395. return false;
  16396. });
  16397. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  16398. });
  16399. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  16400. const args = iter.inputs();
  16401. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  16402. if (iter.kind() === 'aten::__is__') {
  16403. iter.replaceWithNewSymbol('aten::eq');
  16404. iter.destroyCurrent();
  16405. return true;
  16406. }
  16407. if (iter.kind() === 'aten::__isnot__') {
  16408. iter.replaceWithNewSymbol('aten::ne');
  16409. iter.destroyCurrent();
  16410. return true;
  16411. }
  16412. }
  16413. return false;
  16414. });
  16415. this.registerFunction('torch._C.NormalizeOps', (block) => {
  16416. for (const it of block.nodes()) {
  16417. for (const sub of it.blocks()) {
  16418. torch._C.NormalizeOps(sub);
  16419. }
  16420. if (torch._C.normalizeRSub(it)) {
  16421. continue;
  16422. }
  16423. if (torch._C.normalizeOpAliases(it)) {
  16424. continue;
  16425. }
  16426. if (torch._C.normalizeIsBool(it)) {
  16427. continue;
  16428. }
  16429. }
  16430. });
  16431. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  16432. return false;
  16433. });
  16434. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  16435. /*
  16436. torch._C.liftClosures(to_clean);
  16437. torch._C.inlineForkedClosures(to_clean);
  16438. */
  16439. if (torch._C.getInlineEverythingMode()) {
  16440. torch._C.Inline(to_clean);
  16441. }
  16442. /*
  16443. torch._C.eraseListLiterals(to_clean);
  16444. */
  16445. torch._C.LowerSimpleTuples(to_clean);
  16446. torch._C.ConstantPropagationImmutableTypes(to_clean);
  16447. torch._C.ConstantPooling(to_clean);
  16448. /*
  16449. torch._C.CanonicalizeOutputs(to_clean);
  16450. torch._C.AnnotateWarns(to_clean);
  16451. */
  16452. });
  16453. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  16454. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  16455. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  16456. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  16457. constructor(cpp_module) {
  16458. super();
  16459. this._initializing = true;
  16460. this._c = cpp_module;
  16461. }
  16462. static _construct(cpp_module, init_fn) {
  16463. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  16464. init_fn(script_module);
  16465. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  16466. return script_module;
  16467. }
  16468. static _finalize_scriptmodule(script_module) {
  16469. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  16470. script_module._buffers = new torch.BufferDict(script_module._c).items();
  16471. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  16472. script_module._initializing = false;
  16473. }
  16474. get graph() {
  16475. // return this._c._get_method('forward').graph;
  16476. return this._c.graph;
  16477. }
  16478. get code_with_constants() {
  16479. // return this.forward.code_with_constants;
  16480. return this._c.code_with_constants;
  16481. }
  16482. __setattr__(name, value) {
  16483. if (this._initializing) {
  16484. super.__setattr__(name, value);
  16485. } else if (this._modules.has(name)) {
  16486. this._modules.set(name, value);
  16487. } else if (this._c.hasattr(name)) {
  16488. this._c.setattr(name, value);
  16489. } else {
  16490. //
  16491. }
  16492. }
  16493. __getattr__(name) {
  16494. if (this._initializing) {
  16495. return super.__getattr__(name);
  16496. }
  16497. if (this._modules.has(name)) {
  16498. return this._modules.get(name);
  16499. }
  16500. if (this._c.hasattr(name)) {
  16501. return this._c.getattr(name);
  16502. }
  16503. if (this._c._has_method(name)) {
  16504. //
  16505. }
  16506. return super.__getattr__(name);
  16507. }
  16508. });
  16509. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  16510. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  16511. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  16512. torch.CompilationUnit = torch.jit.CompilationUnit;
  16513. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  16514. torch._C.ScriptModule = torch.ScriptModule;
  16515. torch._C.ClassType = torch.ClassType;
  16516. this.registerType('torch._C.FlatBuffersLoader', class {
  16517. constructor(cu) {
  16518. this._cu = cu;
  16519. const torch = cu.execution.__import__('torch');
  16520. this._torch = torch;
  16521. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  16522. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  16523. this._ivalue_parsers = new Map();
  16524. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  16525. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  16526. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  16527. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  16528. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  16529. }
  16530. parseModule(module) {
  16531. this._module = module;
  16532. this._all_functions = new Map();
  16533. this._all_ivalues = new Array(module.ivalues.length);
  16534. this._all_types = new Array(module.object_types.length);
  16535. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  16536. for (let i = 0; i < mobile_ivalue_size; i++) {
  16537. this.parseAndPopulate(i, module.ivalues[i]);
  16538. }
  16539. const m = this._all_ivalues[module.state_obj];
  16540. for (const [name, value] of this._all_functions) {
  16541. const class_index = module.ivalues[name].val.class_type;
  16542. const class_type = this._all_types[class_index];
  16543. if (value) {
  16544. class_type.addMethod(value);
  16545. }
  16546. }
  16547. m._min_operator_version = module.operator_version;
  16548. m._bytecode_version = module.bytecode_version;
  16549. return m;
  16550. }
  16551. parseAndPopulate(i, ivalue) {
  16552. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  16553. this._all_functions.set(i, this.parseFunction(ivalue.val));
  16554. } else {
  16555. this._all_ivalues[i] = this.parseIValue(ivalue);
  16556. }
  16557. }
  16558. parseFunction(/* val */) {
  16559. return null;
  16560. }
  16561. parseIValue(ivalue) {
  16562. if (ivalue.val) {
  16563. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  16564. return callback(ivalue);
  16565. }
  16566. return null;
  16567. }
  16568. parseTensor(ivalue) {
  16569. return this.parseTensorFromMetadata(ivalue.val);
  16570. }
  16571. parseTensorFromMetadata(metadata) {
  16572. if (metadata.quantized_schema) {
  16573. throw new torch.Error('Quantized schema not implemented.');
  16574. }
  16575. const index = metadata.storage_location_index;
  16576. const data = this._module.storage_data[index].data;
  16577. const dtype = this._dtypes.get(metadata.scalar_type);
  16578. const size = data.length / dtype.itemsize();
  16579. const storage = this._cu.execution.invoke('torch.storage.TypedStorage', [size, dtype]);
  16580. storage._set_cdata(data);
  16581. const tensor = this._cu.execution.invoke('torch.Tensor', []);
  16582. const shape = Array.from(metadata.sizes);
  16583. const stride = Array.from(metadata.strides);
  16584. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  16585. return tensor;
  16586. }
  16587. parseObject(ivalue) {
  16588. const object = ivalue.val;
  16589. const obj_type = this._module.object_types[object.type_index];
  16590. const cls = this.getOrCreateClassTypeForObject(object);
  16591. switch (obj_type.type) {
  16592. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  16593. const torch = this._torch;
  16594. const obj = torch.ScriptObject.create(cls);
  16595. for (let i = 0; i < object.attrs.length; i++) {
  16596. const attr_name = obj_type.attr_names[i];
  16597. const val = this._all_ivalues[object.attrs[i]];
  16598. obj.__setattr__(attr_name, val);
  16599. }
  16600. return obj;
  16601. }
  16602. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  16603. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  16604. default: {
  16605. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  16606. }
  16607. }
  16608. }
  16609. getOrCreateClassTypeForObject(object) {
  16610. let cls = this._all_types[object.type_index];
  16611. const obj_type = this._module.object_types[object.type_index];
  16612. if (!cls) {
  16613. const name = obj_type.type_name;
  16614. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  16615. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  16616. if (!cls) {
  16617. const torch = this._torch;
  16618. cls = torch.ClassType.create(name, this._cu, true);
  16619. this._cu.register_type(cls);
  16620. }
  16621. } else {
  16622. // cls = c10::parseType(qn_str).cast<ClassType>();
  16623. }
  16624. this._all_types[object.type_index] = cls;
  16625. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  16626. for (let i = 0; i < object.attrs.length; i++) {
  16627. // const val = this._all_ivalues[object.attrs[i]];
  16628. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  16629. }
  16630. }
  16631. }
  16632. return cls;
  16633. }
  16634. });
  16635. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  16636. constructor(export_module, flat_args_adapter) {
  16637. super();
  16638. const export_graph = copy.deepcopy(export_module.graph);
  16639. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  16640. this.graph = torch.fx.Graph();
  16641. this.graph.owning_module = this;
  16642. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  16643. this.flat_args_adapter = flat_args_adapter;
  16644. this.adapted = false;
  16645. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  16646. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  16647. }
  16648. });
  16649. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  16650. constructor(input_specs, output_specs) {
  16651. this.input_specs = input_specs;
  16652. this.output_specs = output_specs;
  16653. }
  16654. user_inputs() {
  16655. const user_inputs = [];
  16656. for (const s of this.input_specs) {
  16657. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  16658. continue;
  16659. }
  16660. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  16661. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  16662. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  16663. user_inputs.push(s.arg.name);
  16664. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  16665. user_inputs.push(s.arg.value);
  16666. } else {
  16667. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  16668. }
  16669. }
  16670. return user_inputs;
  16671. }
  16672. user_outputs() {
  16673. const user_outputs = [];
  16674. for (const s of this.output_specs) {
  16675. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  16676. continue;
  16677. }
  16678. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  16679. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  16680. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  16681. user_outputs.push(s.arg.name);
  16682. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  16683. user_outputs.push(s.arg.value);
  16684. } else {
  16685. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  16686. }
  16687. }
  16688. return user_outputs;
  16689. }
  16690. inputs_to_parameters() {
  16691. return new Map(this.input_specs
  16692. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  16693. .map((s) => [s.arg.name, s.target]));
  16694. }
  16695. inputs_to_buffers() {
  16696. return new Map(this.input_specs
  16697. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  16698. .map((s) => [s.arg.name, s.target]));
  16699. }
  16700. inputs_to_lifted_tensor_constants() {
  16701. return new Map(this.input_specs
  16702. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  16703. .map((s) => [s.arg.name, s.target]));
  16704. }
  16705. });
  16706. torch.export.graph_signature.InputKind = {
  16707. USER_INPUT: 0,
  16708. PARAMETER: 1,
  16709. BUFFER: 2,
  16710. CONSTANT_TENSOR: 3,
  16711. CUSTOM_OBJ: 4,
  16712. TOKEN: 5
  16713. };
  16714. this.registerType('torch.export.graph_signature.InputSpec', class {
  16715. constructor(kind, arg, target, persistent) {
  16716. this.kind = kind;
  16717. this.arg = arg;
  16718. this.target = target;
  16719. this.persistent = persistent || null;
  16720. }
  16721. });
  16722. torch.export.graph_signature.OutputKind = {
  16723. USER_OUTPUT: 0,
  16724. LOSS_OUTPUT: 1,
  16725. BUFFER_MUTATION: 2,
  16726. GRADIENT_TO_PARAMETER: 3,
  16727. GRADIENT_TO_USER_INPUT: 4,
  16728. USER_INPUT_MUTATION: 5,
  16729. TOKEN: 6
  16730. };
  16731. this.registerType('torch.export.graph_signature.OutputSpec', class {
  16732. constructor(kind, arg, target) {
  16733. this.kind = kind;
  16734. this.arg = arg;
  16735. this.target = target;
  16736. }
  16737. });
  16738. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  16739. constructor(name, value) {
  16740. this.name = name;
  16741. this.value = value; // Union[int, float, bool, str, None]
  16742. }
  16743. });
  16744. this.registerType('torch.export.graph_signature.TensorArgument', class {
  16745. constructor(name) {
  16746. this.name = name;
  16747. }
  16748. });
  16749. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  16750. constructor(name) {
  16751. this.name = name;
  16752. }
  16753. });
  16754. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  16755. constructor(name, class_fqn, fake_val) {
  16756. this.name = name;
  16757. this.class_fqn = class_fqn;
  16758. this.fake_val = fake_val;
  16759. }
  16760. });
  16761. this.registerType('torch.export.exported_program.ExportedProgram', class {
  16762. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  16763. // graph._codegen = torch.fx.graph.CodeGen()
  16764. this._graph_module = this._create_graph_module_for_export(root, graph);
  16765. if (root instanceof torch.fx.GraphModule) {
  16766. // this._graph_module.meta.update(root.meta);
  16767. }
  16768. this._graph_signature = graph_signature;
  16769. this._state_dict = state_dict;
  16770. this._range_constraints = range_constraints;
  16771. this._module_call_graph = module_call_graph;
  16772. this._example_inputs = example_inputs;
  16773. this._constants = tensor_constants || constants || {};
  16774. }
  16775. _create_graph_module_for_export(root, graph) {
  16776. let gm = null;
  16777. try {
  16778. gm = new torch.fx.GraphModule(root, graph);
  16779. } catch {
  16780. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  16781. gm._graph = graph;
  16782. }
  16783. return gm;
  16784. }
  16785. get graph_module() {
  16786. return this._graph_module;
  16787. }
  16788. get graph() {
  16789. return this._graph_module.graph;
  16790. }
  16791. get graph_signature() {
  16792. return this._graph_signature;
  16793. }
  16794. get state_dict() {
  16795. return this._state_dict;
  16796. }
  16797. get constants() {
  16798. return this._constants;
  16799. }
  16800. });
  16801. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  16802. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  16803. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  16804. module = torch.export._remove_effect_tokens(module);
  16805. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  16806. });
  16807. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  16808. return new torch.fx.graph_module.GraphModule(root, graph);
  16809. });
  16810. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  16811. constructor(exported_program, state_dict, constants, example_inputs) {
  16812. this.exported_program = exported_program;
  16813. this.state_dict = state_dict;
  16814. this.constants = constants;
  16815. this.example_inputs = example_inputs;
  16816. }
  16817. });
  16818. torch._export.serde.serialize._SYM_INT_OPS = new Set([
  16819. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod,
  16820. torch.sym_sqrt, torch.sym_int, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt
  16821. ]);
  16822. torch._export.serde.serialize._SYM_BOOL_OPS = new Set([
  16823. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  16824. torch.sym_not
  16825. ]);
  16826. this.registerType('torch._export.serde.union._Union', class {
  16827. constructor(obj) {
  16828. if (obj.$type) {
  16829. this.type = obj.$type;
  16830. this[obj.$type] = obj.$value;
  16831. delete obj.$type;
  16832. delete obj.$value;
  16833. } else {
  16834. let entries = Object.entries(obj);
  16835. if (entries.length > 1) {
  16836. entries = entries.filter(([, value]) => value !== null);
  16837. }
  16838. if (entries.length !== 1) {
  16839. throw new Error();
  16840. }
  16841. const [entry] = entries;
  16842. const [type, value] = entry;
  16843. this.type = type;
  16844. this[type] = value;
  16845. }
  16846. }
  16847. get value() {
  16848. return this[this.type];
  16849. }
  16850. });
  16851. this.registerType('torch._export.serde.schema.NamedArgument', class {
  16852. constructor(obj) {
  16853. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  16854. this.name = obj.name;
  16855. }
  16856. });
  16857. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  16858. constructor(obj) {
  16859. super(obj);
  16860. if (this.type === 'as_int' || this.type === 'as_ints' ||
  16861. this.type === 'as_float' || this.type === 'as_floats' ||
  16862. this.type === 'as_bool' || this.type === 'as_bools' ||
  16863. this.type === 'as_string' || this.type === 'as_strings' ||
  16864. this.type === 'as_scalar_type' || this.type === 'as_device' ||
  16865. this.type === 'as_memory_format' || this.type === 'as_layout') {
  16866. // continue
  16867. } else if (this.type === 'as_none') {
  16868. this.as_none = null;
  16869. } else if (this.type === 'as_tensor') {
  16870. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  16871. } else if (this.type === 'as_tensors') {
  16872. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  16873. } else if (this.type === 'as_sym_int') {
  16874. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  16875. } else if (this.type === 'as_sym_ints') {
  16876. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  16877. } else if (this.type === 'as_optional_tensors') {
  16878. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  16879. } else {
  16880. throw new python.Error(`Unsupported argument '${this.type}'.`);
  16881. }
  16882. /*
  16883. as_tensors: List[TensorArgument]
  16884. as_string: str
  16885. as_strings: List[str]
  16886. as_sym_int: SymIntArgument
  16887. as_sym_ints: List[SymIntArgument]
  16888. as_scalar_type: ScalarType
  16889. as_memory_format: MemoryFormat
  16890. as_layout: Layout
  16891. as_bools: List[bool]
  16892. as_sym_bool: SymBoolArgument
  16893. as_sym_bools: List[SymBoolArgument]
  16894. as_graph: GraphArgument
  16895. as_optional_tensors: List[OptionalTensorArgument]
  16896. as_custom_obj: CustomObjArgument
  16897. */
  16898. }
  16899. });
  16900. this.registerType('torch._export.serde.schema.Node', class {
  16901. constructor(obj) {
  16902. this.target = obj.target;
  16903. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  16904. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  16905. this.metadata = new Map(Object.entries(obj.metadata));
  16906. }
  16907. });
  16908. torch._export.serde.schema.ScalarType = {
  16909. UNKNOWN: 0,
  16910. BYTE: 1,
  16911. CHAR: 2,
  16912. SHORT: 3,
  16913. INT: 4,
  16914. LONG: 5,
  16915. HALF: 6,
  16916. FLOAT: 7,
  16917. DOUBLE: 8,
  16918. COMPLEXHALF: 9,
  16919. COMPLEXFLOAT: 10,
  16920. COMPLEXDOUBLE: 11,
  16921. BOOL: 12,
  16922. BFLOAT16: 13
  16923. };
  16924. torch._export.serde.schema.Layout = {
  16925. Unknown: 0,
  16926. SparseCoo: 1,
  16927. SparseCsr: 2,
  16928. SparseCsc: 3,
  16929. SparseBsr: 4,
  16930. SparseBsc: 5,
  16931. _mkldnn: 6,
  16932. Strided: 7
  16933. };
  16934. torch._export.serde.schema.MemoryFormat = {
  16935. Unknown: 0,
  16936. ContiguousFormat: 1,
  16937. ChannelsLast: 2,
  16938. ChannelsLast3d: 3,
  16939. PreserveFormat: 4,
  16940. };
  16941. this.registerType('torch._export.serde.schema.Device', class {
  16942. constructor(obj) {
  16943. Object.assign(this, { ...obj });
  16944. }
  16945. });
  16946. this.registerType('torch._export.serde.schema.TensorMeta', class {
  16947. constructor(obj) {
  16948. obj = obj.meta || obj;
  16949. this.dtype = obj.dtype;
  16950. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  16951. this.requires_grad = obj.requires_grad;
  16952. this.device = obj.device;
  16953. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  16954. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  16955. this.layout = obj.layout;
  16956. }
  16957. });
  16958. this.registerType('torch._export.serde.schema.Graph', class {
  16959. constructor(obj) {
  16960. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  16961. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  16962. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  16963. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  16964. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  16965. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  16966. this.is_single_tensor_return = obj.is_single_tensor_return;
  16967. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  16968. if (obj.contants) {
  16969. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  16970. // graph_signature -> input_specs -> tensor_constant
  16971. }
  16972. }
  16973. });
  16974. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  16975. constructor(obj) {
  16976. Object.assign(this, { ...obj });
  16977. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  16978. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  16979. }
  16980. });
  16981. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  16982. constructor(obj) {
  16983. Object.assign(this, { ...obj });
  16984. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  16985. }
  16986. });
  16987. this.registerType('torch._export.serde.schema.GraphModule', class {
  16988. constructor(obj) {
  16989. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  16990. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  16991. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  16992. this.metadata = new Map(Object.entries(obj.metadata || {}));
  16993. }
  16994. });
  16995. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  16996. constructor(obj) {
  16997. Object.assign(this, { ...obj });
  16998. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  16999. }
  17000. });
  17001. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  17002. this.registerType('torch._export.serde.schema.SymExpr', class {
  17003. constructor(obj) {
  17004. this.expr_str = obj.expr_str;
  17005. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  17006. }
  17007. });
  17008. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  17009. constructor(obj) {
  17010. super(obj);
  17011. if (this.type === 'as_int') {
  17012. // continue
  17013. } else if (this.type === 'as_expr') {
  17014. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  17015. } else {
  17016. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  17017. }
  17018. }
  17019. });
  17020. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  17021. constructor(obj) {
  17022. super(obj);
  17023. Object.assign(this, { ...obj });
  17024. }
  17025. });
  17026. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  17027. constructor(obj) {
  17028. super(obj);
  17029. if (this.type === 'as_bool') {
  17030. // continue
  17031. } else if (this.type === 'as_expr') {
  17032. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  17033. } else {
  17034. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  17035. }
  17036. }
  17037. });
  17038. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  17039. constructor(obj) {
  17040. super(obj);
  17041. Object.assign(this, { ...obj });
  17042. }
  17043. });
  17044. this.registerType('torch._export.serde.schema.GraphSignature', class {
  17045. constructor(obj) {
  17046. this.input_specs = [];
  17047. if (Array.isArray(obj.input_specs)) {
  17048. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  17049. }
  17050. if (Array.isArray(obj.user_inputs)) {
  17051. for (const user_input of obj.user_inputs) {
  17052. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  17053. }
  17054. }
  17055. if (obj.inputs_to_parameters) {
  17056. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  17057. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  17058. }
  17059. }
  17060. this.output_specs = [];
  17061. if (Array.isArray(obj.output_specs)) {
  17062. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  17063. }
  17064. }
  17065. });
  17066. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  17067. constructor(obj) {
  17068. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17069. }
  17070. });
  17071. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  17072. constructor(obj) {
  17073. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17074. this.parameter_name = obj.parameter_name;
  17075. }
  17076. });
  17077. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  17078. constructor(obj) {
  17079. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17080. this.buffer_name = obj.buffer_name;
  17081. }
  17082. });
  17083. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  17084. constructor(obj) {
  17085. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  17086. this.tensor_constant_name = obj.tensor_constant_name;
  17087. }
  17088. });
  17089. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  17090. constructor(obj) {
  17091. this.name = obj.name;
  17092. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  17093. }
  17094. });
  17095. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  17096. constructor(obj) {
  17097. super(obj);
  17098. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  17099. // continue
  17100. } else if (this.type === 'as_none') {
  17101. this.as_none = null;
  17102. } else {
  17103. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  17104. }
  17105. }
  17106. });
  17107. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  17108. constructor(obj) {
  17109. super(obj);
  17110. if (this.type === 'user_input') {
  17111. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  17112. } else if (this.type === 'parameter') {
  17113. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  17114. } else if (this.type === 'buffer') {
  17115. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  17116. } else if (this.type === 'tensor_constant') {
  17117. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  17118. } else if (this.type === 'constant_input') {
  17119. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  17120. } else {
  17121. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  17122. }
  17123. /*
  17124. custom_obj: InputToCustomObjSpec
  17125. token: InputTokenSpec
  17126. */
  17127. }
  17128. });
  17129. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  17130. constructor(obj) {
  17131. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17132. }
  17133. });
  17134. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  17135. constructor(obj) {
  17136. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17137. this.buffer_name = obj.buffer_name;
  17138. }
  17139. });
  17140. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  17141. constructor(obj) {
  17142. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17143. this.parameter_name = obj.parameter_name;
  17144. }
  17145. });
  17146. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  17147. constructor(obj) {
  17148. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17149. this.user_input_name = obj.user_input_name;
  17150. }
  17151. });
  17152. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  17153. constructor(obj) {
  17154. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  17155. this.user_input_name = obj.user_input_name;
  17156. }
  17157. });
  17158. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  17159. constructor(obj) {
  17160. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  17161. }
  17162. });
  17163. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  17164. constructor(obj) {
  17165. super(obj);
  17166. if (this.type === 'user_output') {
  17167. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  17168. } else if (this.type === 'loss_output') {
  17169. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  17170. } else if (this.type === 'buffer_mutation') {
  17171. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  17172. } else if (this.type === 'gradient_to_parameter') {
  17173. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  17174. } else if (this.type === 'gradient_to_user_input') {
  17175. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  17176. } else if (this.type === 'user_input_mutation') {
  17177. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  17178. } else if (this.type === 'token') {
  17179. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  17180. }
  17181. }
  17182. });
  17183. this.registerType('torch._export.serde.schema.TensorArgument', class {
  17184. constructor(obj) {
  17185. this.name = obj.name;
  17186. }
  17187. });
  17188. this.registerType('torch._export.serde.schema.TokenArgument', class {
  17189. constructor(obj) {
  17190. this.name = obj.name;
  17191. }
  17192. });
  17193. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  17194. constructor(obj) {
  17195. super(obj);
  17196. if (this.type === 'as_tensor') {
  17197. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  17198. } else if (this.type === 'as_none') {
  17199. this.as_none = null;
  17200. } else {
  17201. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  17202. }
  17203. }
  17204. });
  17205. this.registerFunction('torch._export.load', (f, expected_opset_version) => {
  17206. const serialized_exported_program = f.get('serialized_exported_program.json');
  17207. const serialized_state_dict = f.get('serialized_state_dict.pt');
  17208. const serialized_constants = f.get('serialized_constants.pt');
  17209. const serialized_example_inputs = f.get('serialized_example_inputs.pt');
  17210. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  17211. return torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  17212. });
  17213. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  17214. if (data === null) {
  17215. return data;
  17216. }
  17217. if (cls) {
  17218. return new cls(data);
  17219. }
  17220. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  17221. });
  17222. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  17223. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  17224. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  17225. });
  17226. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  17227. constructor(expected_opset_version) {
  17228. this.expected_opset_version = expected_opset_version;
  17229. }
  17230. deserialize(exported_program, state_dict, constants, example_inputs) {
  17231. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  17232. /*
  17233. symbol_name_to_range = {
  17234. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  17235. for k, v in exported_program.range_constraints.items()
  17236. }
  17237. */
  17238. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  17239. const res = deserializer.deserialize(
  17240. exported_program.graph_module,
  17241. state_dict,
  17242. constants,
  17243. example_inputs,
  17244. symbol_name_to_range);
  17245. const range_constraints = null;
  17246. /*
  17247. range_constraints = self.deserialize_range_constraints(
  17248. symbol_name_to_range, res.names_to_symbols,
  17249. )
  17250. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  17251. self._validate_model_opset_version(model_opset_version)
  17252. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  17253. */
  17254. return new torch.export.exported_program.ExportedProgram(
  17255. res.graph_module, res.graph_module.graph, res.signature,
  17256. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  17257. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  17258. res.constants);
  17259. // return upgrader.upgrade(exported_program)
  17260. }
  17261. });
  17262. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  17263. if (!serialized) {
  17264. return new builtins.dict();
  17265. }
  17266. const artifact = torch.load(serialized);
  17267. return artifact;
  17268. });
  17269. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  17270. constructor() {
  17271. this.serialized_name_to_node = new Map();
  17272. this.serialized_name_to_meta = new Map();
  17273. this.graph = new torch.fx.Graph();
  17274. this.module = new torch.nn.Module();
  17275. }
  17276. deserialize_graph_output(output) {
  17277. if (output.type === 'as_tensor') {
  17278. return this.serialized_name_to_node.get(output.as_tensor.name);
  17279. } else if (output.type === 'as_sym_int') {
  17280. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  17281. } else if (output.type === 'as_sym_bool') {
  17282. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  17283. } else if (output.type === 'as_int') {
  17284. return this.serialized_name_to_node.get(output.as_int.as_name);
  17285. } else if (output.type === 'as_none') {
  17286. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  17287. }
  17288. throw new python.Error(`Unsupported graph node ${output.type}.`);
  17289. }
  17290. deserialize_graph(serialized_graph) {
  17291. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  17292. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  17293. this.serialized_name_to_meta.set(name, meta_val);
  17294. }
  17295. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  17296. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  17297. }
  17298. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  17299. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  17300. }
  17301. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  17302. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  17303. }
  17304. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  17305. const input = serialized_graph.inputs[i];
  17306. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  17307. const node_name = input.value.name;
  17308. const placeholder_node = this.graph.placeholder(node_name);
  17309. placeholder_node.name = node_name;
  17310. this.sync_fx_node(node_name, placeholder_node);
  17311. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  17312. const node_name = this.signature.input_specs[i].arg.name;
  17313. const placeholder_node = this.graph.placeholder(node_name);
  17314. placeholder_node.meta.set('val', this.deserialize_input(input));
  17315. } else {
  17316. throw new python.Error(`Invalid input ${input.type}.`);
  17317. }
  17318. }
  17319. for (const serialized_node of serialized_graph.nodes) {
  17320. const target = this.deserialize_operator(serialized_node.target);
  17321. this.deserialize_node(serialized_node, target);
  17322. }
  17323. let outputs = [];
  17324. for (const output of serialized_graph.outputs) {
  17325. outputs.push(this.deserialize_graph_output(output));
  17326. }
  17327. if (serialized_graph.is_single_tensor_return) {
  17328. [outputs] = outputs;
  17329. } else {
  17330. outputs = new builtins.tuple(outputs);
  17331. }
  17332. const output_node = this.graph.output(outputs);
  17333. if (serialized_graph.is_single_tensor_return) {
  17334. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  17335. } else {
  17336. /* output_node.meta['val'] = tuple(
  17337. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  17338. for arg in output_node.args[0]
  17339. ) */
  17340. }
  17341. return self.graph;
  17342. }
  17343. deserialize_operator(serialized_target) {
  17344. let module = null;
  17345. let serialized_target_names = null;
  17346. if (serialized_target.startsWith('_operator')) {
  17347. module = operator;
  17348. serialized_target_names = serialized_target.split('.').slice(1);
  17349. } else if (serialized_target.startsWith('torch')) {
  17350. module = torch;
  17351. serialized_target_names = serialized_target.split('.').slice(1);
  17352. } else if (serialized_target.startsWith('#')) {
  17353. return self.deserialize_extension_operator(serialized_target);
  17354. } else {
  17355. return serialized_target;
  17356. }
  17357. let target = module;
  17358. for (const name of serialized_target_names) {
  17359. target = builtins.getattr(target, name);
  17360. if (!target) {
  17361. return serialized_target;
  17362. }
  17363. }
  17364. return target;
  17365. }
  17366. deserialize_node(serialized_node, target) {
  17367. let fx_node = null;
  17368. if (torch._export.serde.serialize._SYM_BOOL_OPS.has(target) || torch._export.serde.serialize._SYM_INT_OPS.has(target)) {
  17369. const name = serialized_node.outputs[0].value.as_name;
  17370. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  17371. fx_node = this.graph.create_node('call_function', target, args, null, name);
  17372. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  17373. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  17374. // 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.')
  17375. const [output] = serialized_node.outputs;
  17376. const name = output.type === 'as_tensor' ? output.value.name : null;
  17377. const args = serialized_node.inputs.map((input) => this.deserialize_input(input.arg));
  17378. fx_node = this.graph.create_node('call_function', target, args, {}, name);
  17379. if (output.as_tensor !== null) {
  17380. this.sync_fx_node(name, fx_node);
  17381. }
  17382. if (output.as_tensors !== null) {
  17383. this.deserialize_multiple_outputs(serialized_node, fx_node);
  17384. }
  17385. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  17386. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  17387. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  17388. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  17389. this.deserialize_outputs(serialized_node, fx_node);
  17390. } else {
  17391. throw new python.Error(`Unsupported node target type '${target}'.`);
  17392. }
  17393. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  17394. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  17395. fx_node.meta.set('nn_module_stack', new builtins.dict());
  17396. }
  17397. }
  17398. deserialize_input_spec(i) {
  17399. if (i.type === 'user_input') {
  17400. return new torch.export.graph_signature.InputSpec(
  17401. torch.export.graph_signature.InputKind.USER_INPUT,
  17402. this.deserialize_argument_spec(i.user_input.arg),
  17403. null);
  17404. } else if (i.type === 'parameter') {
  17405. return new torch.export.graph_signature.InputSpec(
  17406. torch.export.graph_signature.InputKind.PARAMETER,
  17407. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  17408. i.parameter.parameter_name,
  17409. );
  17410. } else if (i.type === 'buffer') {
  17411. return new torch.export.graph_signature.InputSpec(
  17412. torch.export.graph_signature.InputKind.BUFFER,
  17413. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  17414. i.buffer.buffer_name,
  17415. i.buffer.persistent,
  17416. );
  17417. } else if (i.type === 'tensor_constant') {
  17418. return new torch.export.graph_signature.InputSpec(
  17419. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  17420. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  17421. i.tensor_constant.tensor_constant_name);
  17422. } else if (i.type === 'custom_obj') {
  17423. return new torch.export.graph_signature.InputSpec(
  17424. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  17425. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  17426. i.custom_obj.custom_obj_name);
  17427. } else if (i.type === 'token') {
  17428. return new torch.export.graph_signature.InputSpec(
  17429. torch.export.graph_signature.InputKind.TOKEN,
  17430. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  17431. null);
  17432. } else if (i.type === 'constant_input') {
  17433. return new torch.export.graph_signature.InputSpec(
  17434. torch.export.graph_signature.InputKind.USER_INPUT,
  17435. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  17436. null);
  17437. }
  17438. throw new python.Error(`Unknown input spec ${i}`);
  17439. }
  17440. deserialize_constant_input(inp) {
  17441. if (inp.type === 'as_int') {
  17442. return inp.as_int;
  17443. } else if (inp.type === 'as_float') {
  17444. return inp.as_float;
  17445. } else if (inp.type === 'as_string') {
  17446. return inp.as_string;
  17447. } else if (inp.type === 'as_bool') {
  17448. return inp.as_bool;
  17449. } else if (inp.type === 'as_none') {
  17450. return null;
  17451. }
  17452. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  17453. }
  17454. deserialize_output_spec(o) {
  17455. if (o.type === 'user_output') {
  17456. return new torch.export.graph_signature.OutputSpec(
  17457. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  17458. this.deserialize_argument_spec(o.user_output.arg),
  17459. null);
  17460. } else if (o.type === 'loss_output') {
  17461. return new torch.export.graph_signature.OutputSpec(
  17462. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  17463. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  17464. null);
  17465. } else if (o.type === 'buffer_mutation') {
  17466. return new torch.export.graph_signature.OutputSpec(
  17467. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  17468. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  17469. o.buffer_mutation.buffer_name);
  17470. } else if (o.type === 'gradient_to_parameter') {
  17471. return new torch.export.graph_signature.OutputSpec(
  17472. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  17473. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  17474. o.gradient_to_parameter.parameter_name);
  17475. } else if (o.type === 'gradient_to_user_input') {
  17476. return new torch.export.graph_signature.OutputSpec(
  17477. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  17478. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  17479. o.gradient_to_user_input.user_input_name);
  17480. } else if (o.type === 'user_input_mutation') {
  17481. return new torch.export.graph_signature.OutputSpec(
  17482. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  17483. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  17484. o.user_input_mutation.user_input_name);
  17485. } else if (o.type === 'token') {
  17486. return new torch.export.graph_signature.OutputSpec(
  17487. torch.export.graph_signature.OutputKind.TOKEN,
  17488. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  17489. null);
  17490. }
  17491. throw new python.Error(`Unknown output spec ${o}.`);
  17492. }
  17493. deserialize_signature(sig) {
  17494. return new torch.export.graph_signature.ExportGraphSignature(
  17495. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  17496. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  17497. }
  17498. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  17499. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  17500. /*
  17501. this.fake_tensor_mode = FakeTensorMode(
  17502. allow_fallback_kernels=False,
  17503. allow_non_fake_inputs=True,
  17504. shape_env=this.shape_env,
  17505. )
  17506. */
  17507. this.symbol_name_to_symbol = new Map();
  17508. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  17509. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  17510. this.symbol_name_to_range = symbol_name_to_range || new Map();
  17511. /*
  17512. if symbol_name_to_range:
  17513. for k, vr in symbol_name_to_range.items():
  17514. lower = int(vr.lower)
  17515. if vr.upper >= 2: # max is >= 2, not sym bool range
  17516. lower = max(2, lower)
  17517. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  17518. */
  17519. this.example_inputs = null;
  17520. if (example_inputs && example_inputs.length > 0) {
  17521. torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  17522. }
  17523. this.deserialize_graph(serialized_graph_module.graph);
  17524. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  17525. return {
  17526. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  17527. signature: this.signature,
  17528. module_call_graph,
  17529. names_to_symbols: this.symbol_name_to_symbol,
  17530. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  17531. constants: this.constants,
  17532. example_inputs: this.example_inputs,
  17533. };
  17534. }
  17535. sync_fx_node(name, fx_node) {
  17536. if (this.serialized_name_to_node.has(name)) {
  17537. throw new python.Error(`Node ${name} has already been deserialized before.`);
  17538. }
  17539. this.serialized_name_to_node.set(name, fx_node);
  17540. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  17541. }
  17542. deserialize_sym_op_inputs(inputs) {
  17543. return inputs.map((input) => this.deserialize_input(input.arg));
  17544. }
  17545. deserialize_inputs(target, serialized_node) {
  17546. const schema_args = this._get_schema_from_target(target).arguments;
  17547. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  17548. const args = new builtins.list();
  17549. const kwargs = new builtins.dict();
  17550. for (const schema_arg of schema_args) {
  17551. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  17552. if (is_positional) {
  17553. args.push(actual_args.get(schema_arg.name));
  17554. } else if (actual_args.has(schema_arg.name)) {
  17555. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  17556. }
  17557. }
  17558. return [args, kwargs];
  17559. }
  17560. deserialize_input(inp) {
  17561. const value = inp.value;
  17562. const typ_ = inp.type;
  17563. if (typ_ === 'as_none') {
  17564. return null;
  17565. } else if (typ_ === 'as_tensor') {
  17566. return this.serialized_name_to_node.get(inp.as_tensor.name);
  17567. } else if (typ_ === 'as_scalar_type') {
  17568. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[inp.as_scalar_type];
  17569. } else if (typ_ === 'as_memory_format') {
  17570. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  17571. } else if (typ_ === 'as_layout') {
  17572. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  17573. } else if (typ_ === 'as_graph') {
  17574. /* assert isinstance(value, GraphArgument)
  17575. with this.save_graph_module():
  17576. this.deserialize_graph(value.graph)
  17577. submodule = ep._create_graph_module_for_export(this.module, this.graph)
  17578. this.module.register_module(value.name, submodule)
  17579. return this.graph.create_node(
  17580. 'get_attr',
  17581. value.name,
  17582. name=value.name,
  17583. )*/
  17584. } else if (typ_ === 'as_device') {
  17585. return this.deserialize_device(inp.as_device);
  17586. } else if (typ_ === 'as_int') {
  17587. return inp.as_int;
  17588. } else if (typ_ === 'as_float') {
  17589. return inp.as_float;
  17590. } else if (typ_ === 'as_bool') {
  17591. return inp.as_bool;
  17592. } else if (typ_ === 'as_string') {
  17593. return inp.as_string;
  17594. } else if (typ_ === 'as_sym_int') {
  17595. return this.deserialize_sym_argument(inp.as_sym_int);
  17596. } else if (typ_ === 'as_sym_bool') {
  17597. return this.deserialize_sym_argument(inp.as_sym_bool);
  17598. } else if (Array.isArray(value)) {
  17599. if (value.length === 0) {
  17600. return [];
  17601. } else if (typ_ === 'as_tensors') {
  17602. const result = [];
  17603. for (const arg of value) {
  17604. result.push(this.serialized_name_to_node.get(arg.name));
  17605. }
  17606. return result;
  17607. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  17608. return Array.from(value);
  17609. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  17610. return value.map((arg) => this.deserialize_sym_argument(arg));
  17611. } else if (typ_ === 'as_optional_tensors') {
  17612. const deserialize_optional_tensor_args = (a) => {
  17613. if (a.type === 'as_none') {
  17614. return null;
  17615. } else if (a.type === 'as_tensor') {
  17616. return this.serialized_name_to_node.get(a.value.name);
  17617. }
  17618. throw new python.Error(`Unsupported argument '${typ_}'.`);
  17619. };
  17620. return value.map((item) => deserialize_optional_tensor_args(item));
  17621. }
  17622. throw new python.Error(`Unsupported argument '${typ_}'.`);
  17623. } else if (typ_ === 'as_custom_obj') {
  17624. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  17625. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  17626. }
  17627. return this.constants[inp.as_custom_obj.name];
  17628. } else if (typ_ === 'as_operator') {
  17629. return this.deserialize_operator(inp.as_operator);
  17630. }
  17631. throw new python.Error(`Unsupported argument '${typ_}'.`);
  17632. }
  17633. deserialize_sym_argument(sym_arg) {
  17634. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  17635. if (sym_arg.type === 'as_int') {
  17636. return sym_arg.as_int;
  17637. } else if (sym_arg.type === 'as_name') {
  17638. return this.serialized_name_to_node.get(sym_arg.as_name);
  17639. }
  17640. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  17641. if (sym_arg.type === 'as_bool') {
  17642. return sym_arg.as_bool;
  17643. } else if (sym_arg.type === 'as_name') {
  17644. return self.serialized_name_to_node.get(sym_arg.as_name);
  17645. }
  17646. }
  17647. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  17648. }
  17649. deserialize_sym_op_outputs(serialized_node, fx_node) {
  17650. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  17651. }
  17652. deserialize_outputs(serialized_node, fx_node) {
  17653. if (serialized_node.outputs.length === 0) {
  17654. return;
  17655. }
  17656. if (serialized_node.outputs.length === 1 &&
  17657. serialized_node.outputs[0].type === 'as_tensor') {
  17658. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  17659. return;
  17660. } else if (serialized_node.outputs.length === 1 &&
  17661. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  17662. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  17663. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  17664. return;
  17665. }
  17666. this.deserialize_multiple_outputs(serialized_node, fx_node);
  17667. }
  17668. deserialize_multiple_outputs(serialized_node, fx_node) {
  17669. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  17670. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  17671. let name = '';
  17672. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  17673. name = arg.name;
  17674. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  17675. name = arg.as_name;
  17676. } else {
  17677. throw new python.Error(`Unsupported argument type '${arg}'.`);
  17678. }
  17679. const individual_output = this.graph.create_node(
  17680. 'call_function',
  17681. operator.getitem,
  17682. new builtins.tuple([fx_node, idx]),
  17683. null,
  17684. name,
  17685. );
  17686. this.sync_fx_node(name, individual_output);
  17687. meta_val.push(this.serialized_name_to_meta.get(name));
  17688. individual_output.meta.update(deserialized_metadata);
  17689. };
  17690. const generate_getitems = (meta_val, fx_node, args) => {
  17691. for (let idx = 0; idx < args.length; idx++) {
  17692. let arg = args[idx];
  17693. if (arg instanceof torch._export.serde.schema.Argument) {
  17694. arg = arg.value;
  17695. }
  17696. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  17697. generate_getitem(meta_val, fx_node, arg, idx);
  17698. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  17699. const list_output = this.graph.create_node(
  17700. 'call_function',
  17701. operator.getitem,
  17702. (fx_node, idx),
  17703. );
  17704. meta_val.append([]);
  17705. generate_getitems(meta_val[-1], list_output, arg);
  17706. list_output.meta.update(deserialized_metadata);
  17707. list_output.meta.set('val', meta_val[-1]);
  17708. } else {
  17709. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  17710. }
  17711. }
  17712. };
  17713. const meta_val = [];
  17714. if (serialized_node.outputs.length === 1) {
  17715. // assert isinstance(serialized_node.outputs[0].value, list)
  17716. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  17717. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  17718. } else {
  17719. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  17720. }
  17721. fx_node.meta.set('val', new builtins.tuple(meta_val));
  17722. this.serialized_name_to_node.set(fx_node.name, fx_node);
  17723. }
  17724. deserialize_metadata(metadata) {
  17725. const ret = new builtins.dict();
  17726. const stack_trace = metadata.get('stack_trace');
  17727. if (stack_trace) {
  17728. ret.set('stack_trace', stack_trace);
  17729. }
  17730. const deserialize_meta_func = (serialized_target) => {
  17731. let module = null;
  17732. let serialized_target_names = [];
  17733. if (serialized_target.startsWith('torch.nn')) {
  17734. module = torch.nn;
  17735. serialized_target_names = serialized_target.split('.').slice(1);
  17736. } else if (serialized_target.startsWith('torch')) {
  17737. module = torch;
  17738. serialized_target_names = serialized_target.split('.').slice(1);
  17739. } else {
  17740. return this.deserialize_operator(serialized_target);
  17741. }
  17742. let target = module;
  17743. for (const name of serialized_target_names) {
  17744. if (!builtins.hasattr(target, name)) {
  17745. return serialized_target;
  17746. }
  17747. target = builtins.getattr(target, name);
  17748. }
  17749. return target;
  17750. };
  17751. const nn_module_stack_str = metadata.get('nn_module_stack');
  17752. if (nn_module_stack_str) {
  17753. const import_nn_module_stack = (key, path, ty) => {
  17754. return [key, [path, ty]];
  17755. };
  17756. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  17757. ret.set('nn_module_stack', nn_module_stack);
  17758. }
  17759. const source_fn_st_str = metadata.get('source_fn_stack');
  17760. if (source_fn_st_str) {
  17761. const source_fn_st = [];
  17762. for (const source_fn_str of source_fn_st_str.split(';')) {
  17763. const [name, target_str] = source_fn_str.split(',');
  17764. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  17765. }
  17766. ret.set('source_fn_stack', source_fn_st);
  17767. }
  17768. const torch_fn = metadata.get('torch_fn');
  17769. if (torch_fn) {
  17770. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  17771. }
  17772. const custom_str = metadata.get('custom');
  17773. if (custom_str) {
  17774. ret.set('custom', JSON.parse(custom_str));
  17775. }
  17776. return ret;
  17777. }
  17778. deserialize_argument_spec(x) {
  17779. if (x.type === 'as_tensor') {
  17780. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  17781. } else if (x.type === 'as_sym_int') {
  17782. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  17783. } else if (x.type === 'as_custom_obj') {
  17784. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  17785. }
  17786. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  17787. }
  17788. deserialize_tensor_meta(tensor_meta) {
  17789. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  17790. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  17791. const device = this.deserialize_device(tensor_meta.device);
  17792. const dtype = torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE[tensor_meta.dtype];
  17793. return torch.empty_strided(sizes, strides, dtype, null, device);
  17794. }
  17795. deserialize_sym_int(s) {
  17796. if (s.as_expr !== undefined && s.as_expr !== null) {
  17797. let sym = {};
  17798. if (this.symbol_name_to_symbol.has(s.as_expr.expr_str)) {
  17799. sym = this.symbol_name_to_symbol.get(s.as_expr.expr_str);
  17800. } else {
  17801. sym = {};
  17802. /*
  17803. sym = sympy.sympify(val.expr_str, locals=this.symbol_name_to_symbol)
  17804. if isinstance(sym, sympy.Symbol) {
  17805. this.symbol_name_to_symbol[val.expr_str] = sym
  17806. if vr := this.symbol_name_to_range.get(val.expr_str):
  17807. symbolic_shapes._constrain_symbol_range(
  17808. this.shape_env,
  17809. sym,
  17810. compiler_min=vr.lower, # type: ignore[arg-type]
  17811. compiler_max=vr.upper, # type: ignore[arg-type]
  17812. runtime_min=vr.lower, # type: ignore[arg-type]
  17813. runtime_max=vr.upper # type: ignore[arg-type]
  17814. )
  17815. }
  17816. */
  17817. }
  17818. const hint = s.as_expr.hint || null;
  17819. if (hint && (hint.$type === 'as_int' || hint.as_int !== undefined)) {
  17820. return this.deserialize_sym_int(hint);
  17821. }
  17822. return this.shape_env.create_symintnode(sym, hint);
  17823. } else if (s.as_int !== undefined && s.as_int !== null) {
  17824. return s.as_int;
  17825. } else if (s.$type === 'as_int') {
  17826. return s.$value;
  17827. }
  17828. throw new python.Error('SymInt has invalid field type.');
  17829. }
  17830. deserialize_device(d) {
  17831. if (d.index === null) {
  17832. return new torch.device(d.type);
  17833. }
  17834. return new torch.device(d.type, d.index);
  17835. }
  17836. _get_schema_from_target(target) {
  17837. if (target instanceof torch._ops.OpOverload) {
  17838. return target._schema;
  17839. }
  17840. throw new python.Error(`Unsupported schema '${target.name}'.`);
  17841. }
  17842. _is_single_tensor_return(target) {
  17843. const schema = this._get_schema_from_target(target);
  17844. const returns = schema.returns;
  17845. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  17846. }
  17847. });
  17848. this.registerType('torch._export.verifier.Verifier', class {});
  17849. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  17850. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  17851. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  17852. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  17853. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {});
  17854. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  17855. this.registerType('torch._dynamo.hooks.Hooks', class {});
  17856. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  17857. this.registerType('torch._TorchCompileInductorWrapper', class {});
  17858. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  17859. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  17860. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  17861. const module = new types.ModuleType(name);
  17862. execution.register('sys').modules.set(name, module);
  17863. const context = new python.Execution.Context(module, null);
  17864. execution.exec(meta.get('module_src'), context);
  17865. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  17866. const state = meta.get('state');
  17867. if (state) {
  17868. if (obj.__setstate__) {
  17869. obj.__setstate__(state);
  17870. } else {
  17871. for (const [key, value] of state) {
  17872. obj[key] = value;
  17873. }
  17874. }
  17875. }
  17876. return obj;
  17877. });
  17878. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  17879. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  17880. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  17881. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  17882. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  17883. this.registerType('torch.device', class {
  17884. constructor(type, index) {
  17885. this.type = type;
  17886. this.index = index ? index : null;
  17887. }
  17888. __str__() {
  17889. return this.index === null ? this.type : `${this.type}:${this.index}`;
  17890. }
  17891. toString() {
  17892. const index = this.index === null ? '' : `, index=${this.index}`;
  17893. return `device(type='${this.type}'${index})`;
  17894. }
  17895. });
  17896. this.registerType('torch.memory_format', class {
  17897. constructor(name) {
  17898. this.name = name;
  17899. }
  17900. __str__() {
  17901. return `torch.${this.name}`;
  17902. }
  17903. toString() {
  17904. return this.__str__();
  17905. }
  17906. });
  17907. this.registerType('torch.dtype', class {
  17908. constructor(scalar_type, name, itemsize) {
  17909. this._scalar_type = scalar_type;
  17910. this._name = name;
  17911. this._itemsize = itemsize;
  17912. }
  17913. scalar_type() {
  17914. return this._scalar_type;
  17915. }
  17916. itemsize() {
  17917. return this._itemsize;
  17918. }
  17919. __reduce__() {
  17920. return this._name;
  17921. }
  17922. __str__() {
  17923. return `torch.${this._name}`;
  17924. }
  17925. toString() {
  17926. return this.__str__();
  17927. }
  17928. });
  17929. this.registerType('torch.layout', class {
  17930. constructor(name) {
  17931. this._name = name;
  17932. }
  17933. __str__() {
  17934. return `torch.${this._name}`;
  17935. }
  17936. toString() {
  17937. return this.__str__();
  17938. }
  17939. });
  17940. this.registerType('torch.qscheme', class {
  17941. constructor(name) {
  17942. this._name = name;
  17943. }
  17944. __str__() {
  17945. return this._name;
  17946. }
  17947. toString() {
  17948. return this.__str__();
  17949. }
  17950. });
  17951. this.registerType('torch.utils.hooks.RemovableHandle', class {
  17952. __setstate__(state) {
  17953. [this.hooks_dict_ref, this.id] = state;
  17954. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  17955. }
  17956. });
  17957. this.registerType('torch.storage._StorageBase', class {
  17958. constructor(size, dtype) {
  17959. this._size = size;
  17960. this._dtype = dtype;
  17961. this._device = null;
  17962. }
  17963. get device() {
  17964. return this._device;
  17965. }
  17966. get dtype() {
  17967. return this._dtype;
  17968. }
  17969. element_size() {
  17970. return this._dtype.element_size;
  17971. }
  17972. size() {
  17973. return this._size;
  17974. }
  17975. get data() {
  17976. return this._cdata;
  17977. }
  17978. _set_cdata(data) {
  17979. const length = this.size() * this.dtype.itemsize();
  17980. if (length !== data.length) {
  17981. throw new python.Error('Storage data size mismatch.');
  17982. }
  17983. this._cdata = data;
  17984. }
  17985. _set_from_file(unpickler) {
  17986. const buffer = unpickler.read(8);
  17987. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  17988. if (size !== this.size()) {
  17989. throw new python.Error('Storage size mismatch.');
  17990. }
  17991. const itemsize = this.dtype.itemsize();
  17992. const data = unpickler.stream(itemsize * size);
  17993. this._set_cdata(data);
  17994. }
  17995. static _new_with_file(unpickler) {
  17996. const buffer = unpickler.read(8);
  17997. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  17998. const storage = new this(size);
  17999. const itemsize = storage.dtype.itemsize();
  18000. const data = unpickler.stream(itemsize * size);
  18001. storage._set_cdata(data);
  18002. return storage;
  18003. }
  18004. });
  18005. this.registerType('torch.storage.UntypedStorage', class extends torch.storage._StorageBase {
  18006. constructor() {
  18007. super();
  18008. throw new python.Error('UntypedStorage not implemented.');
  18009. }
  18010. });
  18011. this.registerType('torch.storage.TypedStorage', class {
  18012. constructor(...args) {
  18013. if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  18014. if (args[3] instanceof torch.device) {
  18015. [this._size, this._dtype, , this._device] = args;
  18016. } else {
  18017. [this._size, this._dtype] = args;
  18018. }
  18019. } else {
  18020. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  18021. }
  18022. }
  18023. get device() {
  18024. return this._device;
  18025. }
  18026. get dtype() {
  18027. return this._dtype;
  18028. }
  18029. element_size() {
  18030. return this._dtype.element_size;
  18031. }
  18032. size() {
  18033. return this._size;
  18034. }
  18035. get data() {
  18036. return this._cdata;
  18037. }
  18038. _set_cdata(data) {
  18039. const length = this.size() * this.dtype.itemsize();
  18040. if (length !== data.length) {
  18041. throw new python.Error('Storage data size mismatch.');
  18042. }
  18043. this._cdata = data;
  18044. }
  18045. _set_from_file(unpickler) {
  18046. const buffer = unpickler.read(8);
  18047. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  18048. if (size !== this.size()) {
  18049. throw new python.Error('Storage size mismatch.');
  18050. }
  18051. const itemsize = this.dtype.itemsize();
  18052. const data = unpickler.stream(itemsize * size);
  18053. this._set_cdata(data);
  18054. }
  18055. static _new_with_file(unpickler) {
  18056. const buffer = unpickler.read(8);
  18057. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  18058. const storage = new this(size);
  18059. const itemsize = storage.dtype.itemsize();
  18060. const data = unpickler.stream(itemsize * size);
  18061. storage._set_cdata(data);
  18062. return storage;
  18063. }
  18064. });
  18065. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  18066. constructor() {
  18067. super();
  18068. throw new python.Error('_LegacyStorage not implemented.');
  18069. }
  18070. });
  18071. this.registerType('torch.BoolStorage', class extends torch.storage._StorageBase {
  18072. constructor(size) {
  18073. super(size, torch.bool);
  18074. }
  18075. });
  18076. this.registerType('torch.ByteStorage', class extends torch.storage._StorageBase {
  18077. constructor(size) {
  18078. super(size, torch.uint8);
  18079. }
  18080. });
  18081. this.registerType('torch.CharStorage', class extends torch.storage._StorageBase {
  18082. constructor(size) {
  18083. super(size, torch.int8);
  18084. }
  18085. });
  18086. this.registerType('torch.ShortStorage', class extends torch.storage._StorageBase {
  18087. constructor(size) {
  18088. super(size, torch.int16);
  18089. }
  18090. });
  18091. this.registerType('torch.IntStorage', class extends torch.storage._StorageBase {
  18092. constructor(size) {
  18093. super(size, torch.int32);
  18094. }
  18095. });
  18096. this.registerType('torch.LongStorage', class extends torch.storage._StorageBase {
  18097. constructor(size) {
  18098. super(size, torch.int64);
  18099. }
  18100. });
  18101. this.registerType('torch.HalfStorage', class extends torch.storage._StorageBase {
  18102. constructor(size) {
  18103. super(size, torch.float16);
  18104. }
  18105. });
  18106. this.registerType('torch.FloatStorage', class extends torch.storage._StorageBase {
  18107. constructor(size) {
  18108. super(size, torch.float32);
  18109. }
  18110. });
  18111. this.registerType('torch.DoubleStorage', class extends torch.storage._StorageBase {
  18112. constructor(size) {
  18113. super(size, torch.float64);
  18114. }
  18115. });
  18116. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._StorageBase {
  18117. constructor(size) {
  18118. super(size, torch.complex32);
  18119. }
  18120. });
  18121. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._StorageBase {
  18122. constructor(size) {
  18123. super(size, torch.complex64);
  18124. }
  18125. });
  18126. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._StorageBase {
  18127. constructor(size) {
  18128. super(size, torch.complex128);
  18129. }
  18130. });
  18131. this.registerType('torch.QInt8Storage', class extends torch.storage._StorageBase {
  18132. constructor(size) {
  18133. super(size, torch.qint8);
  18134. }
  18135. });
  18136. this.registerType('torch.QUInt8Storage', class extends torch.storage._StorageBase {
  18137. constructor(size) {
  18138. super(size, torch.quint8);
  18139. }
  18140. });
  18141. this.registerType('torch.QInt32Storage', class extends torch.storage._StorageBase {
  18142. constructor(size) {
  18143. super(size, torch.qint32);
  18144. }
  18145. });
  18146. this.registerType('torch.BFloat16Storage', class extends torch.storage._StorageBase {
  18147. constructor(size) {
  18148. super(size, torch.bfloat16);
  18149. }
  18150. });
  18151. this.registerType('torch.Size', class extends Array {
  18152. constructor(size) {
  18153. super(size.length);
  18154. for (let i = 0; i < size.length; i++) {
  18155. this[i] = size[i];
  18156. }
  18157. }
  18158. __len__() {
  18159. return this.length;
  18160. }
  18161. });
  18162. this.registerType('torch.Tensor', class {
  18163. constructor() {
  18164. this._layout = torch.strided;
  18165. }
  18166. get device() {
  18167. return this.storage().device;
  18168. }
  18169. get dtype() {
  18170. if (this._layout === torch.sparse_coo) {
  18171. return this._values.dtype();
  18172. }
  18173. return this.storage().dtype;
  18174. }
  18175. get shape() {
  18176. return this._shape;
  18177. }
  18178. get layout() {
  18179. return this._layout;
  18180. }
  18181. get values() {
  18182. if (this._layout === torch.sparse_coo) {
  18183. return this._values;
  18184. }
  18185. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  18186. }
  18187. get indices() {
  18188. if (this._layout === torch.sparse_coo) {
  18189. return this._indices;
  18190. }
  18191. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  18192. }
  18193. get is_quantized() {
  18194. return this.__quantized__ === true;
  18195. }
  18196. get is_nested() {
  18197. return this.__nested__ === true;
  18198. }
  18199. get is_sparse() {
  18200. return this.layout !== torch.strided;
  18201. }
  18202. size() {
  18203. return this._shape;
  18204. }
  18205. storage() {
  18206. if (!this._storage) {
  18207. const name = this.__class__.__name__ === 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  18208. this._storage = self.invoke(`${this.__class__.__module__}.${name}`, []);
  18209. }
  18210. return this._storage;
  18211. }
  18212. storage_offset() {
  18213. return this._storage_offset;
  18214. }
  18215. stride() {
  18216. return this._stride;
  18217. }
  18218. resize_(shape) {
  18219. this._shape = shape;
  18220. }
  18221. __len__() {
  18222. return this._shape[0];
  18223. }
  18224. __setstate__(state) {
  18225. switch (state.length) {
  18226. case 3:
  18227. break;
  18228. case 4:
  18229. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  18230. break;
  18231. case 5:
  18232. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  18233. break;
  18234. default:
  18235. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  18236. }
  18237. }
  18238. __bool__() {
  18239. return true;
  18240. }
  18241. __int__() {
  18242. const storage = this.storage();
  18243. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  18244. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  18245. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  18246. return view.getBigInt64(0, true);
  18247. }
  18248. return NaN;
  18249. }
  18250. __float__() {
  18251. const storage = this.storage();
  18252. if (storage && storage.dtype.__reduce__() === 'float32') {
  18253. if (storage.size() !== undefined && storage.data.length === 4) {
  18254. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  18255. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  18256. return view.getFloat32(0, true);
  18257. }
  18258. }
  18259. return NaN;
  18260. }
  18261. __str__() {
  18262. return 'tensor(...)';
  18263. }
  18264. });
  18265. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  18266. constructor(data, requires_grad) {
  18267. super();
  18268. this.data = data || new torch.Tensor([]);
  18269. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  18270. }
  18271. });
  18272. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  18273. constructor(requires_grad /*, device, dtype */) {
  18274. super(undefined, requires_grad);
  18275. }
  18276. });
  18277. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  18278. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  18279. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  18280. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  18281. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  18282. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  18283. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  18284. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  18285. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  18286. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  18287. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {});
  18288. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {});
  18289. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  18290. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  18291. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  18292. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  18293. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  18294. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  18295. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  18296. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  18297. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  18298. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  18299. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  18300. this.registerType('torch.SymBool', class {
  18301. constructor(node) {
  18302. this.node = node;
  18303. }
  18304. });
  18305. this.registerType('torch.SymInt', class {
  18306. constructor(node) {
  18307. this.node = node;
  18308. }
  18309. });
  18310. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  18311. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  18312. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  18313. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  18314. /* eslint-disable no-multi-assign */
  18315. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  18316. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  18317. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  18318. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  18319. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  18320. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  18321. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  18322. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  18323. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  18324. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex32', 4);
  18325. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex64', 8);
  18326. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex128', 16);
  18327. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  18328. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  18329. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  18330. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  18331. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  18332. torch.quint4x2 = new torch.dtype(16, 'quint4x2');
  18333. torch.quint2x4 = new torch.dtype(17, 'quint2x4');
  18334. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  18335. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  18336. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  18337. torch.bits8 = new torch.dtype(21, 'bits8');
  18338. torch.bits16 = new torch.dtype(22, 'bits16');
  18339. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  18340. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  18341. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  18342. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  18343. torch.uint16 = new torch.dtype(27, 'uint16', 2);
  18344. torch.uint32 = new torch.dtype(28, 'uint32', 4);
  18345. torch.uint64 = new torch.dtype(29, 'uint64', 8);
  18346. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = Object.fromEntries([
  18347. ['uint8', 'BYTE'],
  18348. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  18349. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  18350. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  18351. ['bool', 'BOOL'],
  18352. ['bfloat16', 'BFLOAT16']
  18353. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  18354. torch.contiguous_format = new torch.memory_format('contiguous_format');
  18355. torch.channels_last = new torch.memory_format('channels_last');
  18356. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  18357. torch.preserve_format = new torch.memory_format('preserve_format');
  18358. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  18359. ['contiguous_format', 'ContiguousFormat'],
  18360. ['channels_last', 'ChannelsLast'],
  18361. ['channels_last_3d', 'ChannelsLast3d'],
  18362. ['preserve_format', 'PreserveFormat']
  18363. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  18364. /* eslint-enable no-multi-assign */
  18365. torch.strided = new torch.layout('strided');
  18366. torch.sparse_coo = new torch.layout('sparse_coo');
  18367. torch.sparse_csr = new torch.layout('sparse_csr');
  18368. torch.sparse_csc = new torch.layout('sparse_csc');
  18369. torch.sparse_bsr = new torch.layout('sparse_bsr');
  18370. torch.sparse_bsc = new torch.layout('sparse_bsc');
  18371. torch._mkldnn = new torch.layout('_mkldnn');
  18372. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  18373. ['sparse_coo', 'SparseCoo'],
  18374. ['sparse_csr', 'SparseCsr'],
  18375. ['sparse_csc', 'SparseCsc'],
  18376. ['sparse_bsr', 'SparseBsr'],
  18377. ['sparse_bsc', 'SparseBsc'],
  18378. ['_mkldnn', '_mkldnn'],
  18379. ['strided', 'Strided'],
  18380. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  18381. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  18382. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  18383. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  18384. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  18385. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  18386. torch.inf = this.register('math').inf;
  18387. this.registerFunction('fastcore.basics._using_attr');
  18388. this.registerFunction('fastcore.imports.noop');
  18389. this.registerType('fastcore.basics.fastuple', class {});
  18390. this.registerType('fastcore.basics.GetAttr', class {});
  18391. this.registerType('fastcore.dispatch._TypeDict', class {});
  18392. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  18393. this.registerType('fastcore.foundation.L', class {});
  18394. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  18395. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  18396. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  18397. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  18398. this.registerType('fastai.basic_train.Learner', class {});
  18399. this.registerType('fastai.basic_train.Recorder', class {});
  18400. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  18401. const tensor = torch._utils._rebuild_tensor_v2(...args);
  18402. return self.invoke(cls, tensor);
  18403. });
  18404. this.registerFunction('fastai.torch_core.trainable_params');
  18405. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  18406. const tensor = self.invoke(type, [func(...args)]);
  18407. Object.assign(tensor, dict);
  18408. return tensor;
  18409. });
  18410. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  18411. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  18412. constructor(x) {
  18413. super();
  18414. Object.assign(this, x);
  18415. }
  18416. });
  18417. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  18418. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  18419. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  18420. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  18421. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  18422. this.registerFunction('fastai.torch_core.uniform');
  18423. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  18424. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  18425. this.registerType('fastai.callback.fp16.AMPMode', class extends this._enum.Enum {});
  18426. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  18427. this.registerFunction('fastai.callback.hook._hook_inner');
  18428. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  18429. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  18430. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  18431. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  18432. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  18433. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  18434. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  18435. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  18436. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  18437. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  18438. this.registerType('fastai.data.core.Datasets', class {});
  18439. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  18440. this.registerType('fastai.data.core.FilteredBase', class {});
  18441. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  18442. this.registerType('fastai.data.core.TfmdLists', class {});
  18443. this.registerType('fastai.data.load._FakeLoader', class {});
  18444. this.registerFunction('fastai.data.load._wif');
  18445. this.registerType('fastai.data.transforms.Categorize', class {});
  18446. this.registerType('fastai.data.transforms.Category', class {});
  18447. this.registerType('fastai.data.transforms.CategoryMap', class {});
  18448. this.registerType('fastai.data.transforms.ColReader', class {});
  18449. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  18450. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  18451. this.registerType('fastai.data.transforms.Normalize', class {});
  18452. this.registerType('fastai.data.transforms.parent_label', class {});
  18453. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  18454. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  18455. this.registerType('fastai.data.transforms.ToTensor', class {});
  18456. this.registerType('fastai.data_block.CategoryList', class {});
  18457. this.registerType('fastai.data_block.CategoryProcessor', class {});
  18458. this.registerType('fastai.imports.noop', class {});
  18459. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  18460. this.registerType('fastai.layers.ConvLayer', class {});
  18461. this.registerType('fastai.layers.Embedding', class {});
  18462. this.registerType('fastai.layers.Flatten', class {});
  18463. this.registerType('fastai.layers.FlattenedLoss', class {});
  18464. this.registerType('fastai.layers.LinBnDrop', class {});
  18465. this.registerType('fastai.layers.MergeLayer', class {});
  18466. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  18467. this.registerType('fastai.layers.ResBlock', class {});
  18468. this.registerType('fastai.layers.SelfAttention', class {});
  18469. this.registerType('fastai.layers.SigmoidRange', class {});
  18470. this.registerType('fastai.layers.TimeDistributed', class {});
  18471. this.registerType('fastai.layers.ToTensorBase', class {});
  18472. this.registerType('fastai.learner._ConstantFunc', class {});
  18473. this.registerType('fastai.learner.Metric', class {});
  18474. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  18475. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  18476. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  18477. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  18478. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  18479. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  18480. this.registerType('fastai.learner.Recorder', class {});
  18481. this.registerType('fastai.losses.BaseLoss', class {});
  18482. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  18483. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  18484. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  18485. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  18486. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  18487. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  18488. this.registerType('fastai.metrics.Dice', class {});
  18489. this.registerType('fastai.metrics.JaccardCoeff', class {});
  18490. this.registerFunction('fastai.metrics._rmse');
  18491. this.registerFunction('fastai.metrics.accuracy');
  18492. this.registerFunction('fastai.metrics.accuracy_multi');
  18493. this.registerFunction('fastai.metrics.foreground_acc');
  18494. this.registerFunction('fastai.metrics.mse');
  18495. this.registerFunction('fastai.metrics.error_rate');
  18496. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  18497. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  18498. this.registerFunction('fastai.optimizer.Adam');
  18499. this.registerFunction('fastai.optimizer.adam_step');
  18500. this.registerFunction('fastai.optimizer.average_grad');
  18501. this.registerFunction('fastai.optimizer.average_sqr_grad');
  18502. this.registerFunction('fastai.optimizer.RAdam');
  18503. this.registerFunction('fastai.optimizer.step_stat');
  18504. this.registerFunction('fastai.optimizer.weight_decay');
  18505. this.registerType('fastai.tabular.core.Categorify', class {});
  18506. this.registerType('fastai.tabular.core.FillMissing', class {});
  18507. this.registerType('fastai.tabular.core.FillStrategy', class {});
  18508. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  18509. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  18510. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  18511. this.registerType('fastai.tabular.core.Tabular', class {});
  18512. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  18513. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  18514. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  18515. this.registerType('fastai.tabular.model.TabularModel', class {});
  18516. this.registerFunction('fastai.vision.augment.aug_transforms');
  18517. this.registerFunction('fastai.vision.augment.dihedral_mat');
  18518. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  18519. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  18520. this.registerType('fastai.vision.augment._WarpCoord', class {});
  18521. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  18522. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  18523. this.registerType('fastai.vision.augment.Brightness', class {});
  18524. this.registerType('fastai.vision.augment.flip_mat', class {});
  18525. this.registerType('fastai.vision.augment.Flip', class {});
  18526. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  18527. this.registerType('fastai.vision.augment.Resize', class {});
  18528. this.registerType('fastai.vision.augment.rotate_mat', class {});
  18529. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  18530. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  18531. this.registerType('fastai.vision.augment.zoom_mat', class {});
  18532. this.registerType('fastai.vision.core.PILImage', class {});
  18533. this.registerType('fastai.vision.core.PILMask', class {});
  18534. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  18535. this.registerType('fastai.vision.data.ImageList', class {});
  18536. this.registerType('fastai.vision.image.Image', class {});
  18537. this.registerType('fastai.vision.image.RandTransform', class {});
  18538. this.registerType('fastai.vision.image.TfmCrop', class {});
  18539. this.registerFunction('fastai.vision.learner._resnet_split');
  18540. this.registerFunction('fastai.vision.learner.default_split');
  18541. this.registerFunction('fastai.vision.learner.default_split');
  18542. this.registerType('fastai.vision.learner.TimmBody', class {});
  18543. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  18544. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  18545. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  18546. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  18547. this.registerFunction('fastai.vision.transform._crop_pad');
  18548. }
  18549. exec(code , context) {
  18550. const ast = this.ast;
  18551. const program = ast.parse(code, '', null);
  18552. if (!program) {
  18553. throw new python.Error("Module '?' parse error.");
  18554. }
  18555. this.block(program.body, context);
  18556. }
  18557. debug(/* file */) {
  18558. }
  18559. source(file) {
  18560. if (this._sources.has(file)) {
  18561. return this._sources.get(file);
  18562. }
  18563. return null;
  18564. }
  18565. read(file) {
  18566. const buffer = this.source(file);
  18567. if (buffer) {
  18568. const debug = this.debug(file);
  18569. return this.parse(file, buffer, debug);
  18570. }
  18571. return null;
  18572. }
  18573. parse(filename, buffer, debug) {
  18574. const ast = this.ast;
  18575. const source = this._utf8Decoder.decode(buffer);
  18576. const program = ast.parse(source, filename, debug);
  18577. if (!program) {
  18578. throw new python.Error(`Module '${filename}' parse error.`);
  18579. }
  18580. return program;
  18581. }
  18582. import(name, current, level) {
  18583. if (level) {
  18584. let bits = current.split('.');
  18585. if (bits.length < level) {
  18586. throw new python.Error('Invalid relative import beyond top-level package.');
  18587. }
  18588. bits = bits.slice(0, bits.length - level);
  18589. const base = bits.join('.');
  18590. name = name ? [base, name].join('.') : base;
  18591. }
  18592. const index = name.lastIndexOf('.');
  18593. let parent = null;
  18594. let child = null;
  18595. if (index > 0) {
  18596. parent = name.substring(0, index);
  18597. child = name.substring(index + 1);
  18598. this.import(parent);
  18599. }
  18600. if (!this._modules.has(name)) {
  18601. const module = this._registry.get(name) || new this.builtins.module(name);
  18602. module.__package__ = name;
  18603. this._modules.set(name, module);
  18604. const path = name.split('.').join('/');
  18605. module.__path__ = [path];
  18606. const file = `${path}.py`;
  18607. const program = this.read(file);
  18608. if (program) {
  18609. module.__file__ = file;
  18610. for (const [name, value] of Object.entries(this.builtins)) {
  18611. switch (name) {
  18612. case '__class__':
  18613. case '__package__':
  18614. case '__module__':
  18615. case '__name__':
  18616. case '__path__':
  18617. case '__file__':
  18618. break;
  18619. default:
  18620. module[name] = value;
  18621. break;
  18622. }
  18623. }
  18624. const context = new python.Execution.Context(module, null);
  18625. if (name !== 'builtins') {
  18626. context.set('__builtins__', this._modules.get('builtins'));
  18627. }
  18628. this.block(program.body, context);
  18629. }
  18630. if (parent) {
  18631. const parent_module = this._modules.get(parent);
  18632. parent_module[child] = module;
  18633. }
  18634. }
  18635. return this._modules.get(name);
  18636. }
  18637. __import__(name, globals, locals, fromlist, level) {
  18638. let module = null;
  18639. level = level || 0;
  18640. if (level === 0) {
  18641. module = this.import(name);
  18642. } else {
  18643. globals = globals || {};
  18644. let current = globals.__package__;
  18645. if (!current) {
  18646. const spec = globals.__spec__;
  18647. if (spec) {
  18648. current = spec.parent;
  18649. } else {
  18650. const name = globals.__name__;
  18651. const bits = name.split('.');
  18652. bits.pop();
  18653. current = bits.join('.');
  18654. }
  18655. }
  18656. module = this.import(name, current, level);
  18657. }
  18658. if (!fromlist) {
  18659. if (level === 0) {
  18660. return this.import(name.split('.')[0]);
  18661. } else if (name) {
  18662. throw new python.Error(`Unsupported relative import '${name}'.`);
  18663. // cut_off = len(name) - len(name.partition('.')[0])
  18664. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  18665. }
  18666. } else if (module.__path__) {
  18667. const handle_fromlist = (module, fromlist, recursive) => {
  18668. for (const name of fromlist) {
  18669. if (name === '*') {
  18670. if (!recursive && module.__all__) {
  18671. handle_fromlist(module, module.__all__, true);
  18672. }
  18673. } else if (!module[name]) {
  18674. this.import(`${module.__name__}.${name}`);
  18675. }
  18676. }
  18677. return module;
  18678. };
  18679. handle_fromlist(module, fromlist);
  18680. }
  18681. return module;
  18682. }
  18683. module(name) {
  18684. return this._modules.get(name);
  18685. }
  18686. resolve(name) {
  18687. const index = name.lastIndexOf('.');
  18688. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  18689. const moduleName = index === -1 ? '' : name.substring(0, index);
  18690. const module = this.import(moduleName);
  18691. let type = module ? module[memberName] : null;
  18692. if (!type) {
  18693. if (!this._unresolved.has(name)) {
  18694. const moduleName = name.split('.').shift();
  18695. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  18696. this.emit('resolve', name);
  18697. }
  18698. const type = this._createType(name, class {});
  18699. this._unresolved.set(name, type);
  18700. }
  18701. type = this._unresolved.get(name);
  18702. }
  18703. return type;
  18704. }
  18705. invoke(target, args) {
  18706. const builtins = this.builtins;
  18707. if (typeof target === 'string') {
  18708. target = this.resolve(target);
  18709. }
  18710. if (target) {
  18711. if (target.__class__ === builtins.type) {
  18712. if (target.prototype && target.prototype.__class__ === target) {
  18713. return Reflect.construct(target, args);
  18714. }
  18715. const obj = Object.create(target);
  18716. if (obj.__init__ && typeof obj.__init__ === 'function') {
  18717. obj.__init__(...args);
  18718. }
  18719. return obj;
  18720. } else if (target.__class__ === builtins.function) {
  18721. if (target.__call__) {
  18722. return target.__call__(args);
  18723. }
  18724. return target(...args);
  18725. }
  18726. }
  18727. throw new python.Error('Unsupported invoke target.');
  18728. }
  18729. call(target, name, args, keywords, context) {
  18730. const builtins = this.builtins;
  18731. const callTarget = this.target(target, context);
  18732. const callArguments = args.map((arg) => this.expression(arg, context));
  18733. if (!callTarget || (name !== null && !callTarget[name])) {
  18734. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  18735. name = null;
  18736. callArguments.shift();
  18737. } else {
  18738. const targetName = `${this.identifier(target)}.${name}`;
  18739. throw new python.Error(`Unknown function '${targetName}'.`);
  18740. }
  18741. }
  18742. const func = name ? callTarget[name] : callTarget;
  18743. if (func.__class__ === builtins.type) {
  18744. if (func.prototype && func.prototype.__class__ === func) {
  18745. return Reflect.construct(func, callArguments);
  18746. }
  18747. const obj = Object.create(func);
  18748. obj.__class__ = func;
  18749. if (obj.__init__ && typeof obj.__init__ === 'function') {
  18750. obj.__init__(...args);
  18751. }
  18752. return obj;
  18753. }
  18754. if (func.__class__ === builtins.function) {
  18755. if (func.__call__) {
  18756. return func.__call__(callArguments);
  18757. }
  18758. }
  18759. if (func.__class__ === builtins.method) {
  18760. if (func.__call__) {
  18761. return func.__call__([callTarget].concat(callArguments));
  18762. }
  18763. }
  18764. if (typeof func === 'function') {
  18765. return func.apply(callTarget, callArguments);
  18766. }
  18767. throw new python.Error('Unsupported call expression.');
  18768. }
  18769. apply(method, args, context) {
  18770. const locals = Array.prototype.slice.call(args);
  18771. context = new python.Execution.Context(context.globals, {});
  18772. args = method.args.posonlyargs.concat(method.args.args);
  18773. const default_pos = args.length - method.args.defaults.length;
  18774. for (let i = 0; i < method.args.args.length; i++) {
  18775. const arg = method.args.args[i];
  18776. let value = null;
  18777. if (locals.length > 0) {
  18778. value = locals.shift();
  18779. } else if (i >= default_pos) {
  18780. value = this.expression(method.args.defaults[i - default_pos], context);
  18781. } else {
  18782. throw new python.Error('Missing required positional argument.');
  18783. }
  18784. context.set(arg.arg, value);
  18785. }
  18786. return this.block(method.body, context);
  18787. }
  18788. block(statements, context) {
  18789. statements = Array.prototype.slice.call(statements);
  18790. while (statements.length > 0) {
  18791. const stmt = statements.shift();
  18792. const value = this.statement(stmt, context);
  18793. if (value !== undefined) {
  18794. return value;
  18795. }
  18796. }
  18797. return undefined;
  18798. }
  18799. statement(stmt, context) {
  18800. const ast = this.ast;
  18801. const builtins = this.builtins;
  18802. if (stmt instanceof ast.Pass) {
  18803. // pass
  18804. } else if (stmt instanceof ast.Constant) {
  18805. // pass
  18806. } else if (stmt instanceof ast.Return) {
  18807. return this.expression(stmt.value, context);
  18808. } else if (stmt instanceof ast.FunctionDef) {
  18809. const module = context.get('__name__');
  18810. const self = this;
  18811. const parent = context.get('__class__');
  18812. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  18813. const func = {
  18814. __class__: type,
  18815. __globals__: context,
  18816. __module__: module,
  18817. __name__: stmt.name,
  18818. __code__: stmt,
  18819. __call__(args) {
  18820. return self.apply(this.__code__, args, this.__globals__);
  18821. }
  18822. };
  18823. context.set(stmt.name, func);
  18824. } else if (stmt instanceof ast.ClassDef) {
  18825. const bases = stmt.bases.map((base) => this.expression(base, context));
  18826. if (bases.length > 1) {
  18827. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  18828. }
  18829. const base = bases.length === 1 ? bases[0] : null;
  18830. const name = `${context.get('__name__')}.${stmt.name}`;
  18831. const value = this._createType(name, base ? class extends base {} : class {});
  18832. value.__bases__ = bases;
  18833. context.set(stmt.name, value);
  18834. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  18835. } else if (stmt instanceof ast.AnnAssign) {
  18836. const target = this.identifier(stmt.target, context);
  18837. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  18838. } else if (stmt instanceof ast.Assign) {
  18839. this.expression(stmt, context);
  18840. } else if (stmt instanceof ast.If) {
  18841. const test = this.expression(stmt.test, context);
  18842. if (test === true || test) {
  18843. const value = this.block(stmt.body, context);
  18844. if (value !== undefined) {
  18845. return value;
  18846. }
  18847. } else if (test === false) {
  18848. if (stmt.orelse) {
  18849. const value = this.block(stmt.orelse, context);
  18850. if (value !== undefined) {
  18851. return value;
  18852. }
  18853. }
  18854. } else {
  18855. throw new python.Error('Unsupported condition.');
  18856. }
  18857. } else if (stmt instanceof ast.For) {
  18858. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  18859. const range = this.expression(stmt.iter, context);
  18860. const variable = stmt.target;
  18861. for (const current of range) {
  18862. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  18863. const value = this.block(stmt.body.statements, context);
  18864. if (value !== undefined) {
  18865. return value;
  18866. }
  18867. }
  18868. } else {
  18869. throw new python.Error("Unsupported 'for' statement.");
  18870. }
  18871. } else if (stmt instanceof ast.While) {
  18872. const test = this.expression(stmt.test, context);
  18873. if (test) {
  18874. const value = this.block(stmt.body.statements, context);
  18875. if (value !== undefined) {
  18876. return value;
  18877. }
  18878. }
  18879. } else if (stmt instanceof ast.With) {
  18880. const items = [];
  18881. for (const item of stmt.items) {
  18882. items.push(this.expression(item.context_expr, context));
  18883. }
  18884. for (const item of items) {
  18885. if (item.__enter__ && item.__enter__.__call__) {
  18886. item.__enter__.__call__([item]);
  18887. }
  18888. }
  18889. const value = this.block(stmt.body, context);
  18890. for (const item of items) {
  18891. if (item.__exit__ && item.__exit__.__call__) {
  18892. item.__exit__.__call__([item]);
  18893. }
  18894. }
  18895. if (value !== undefined) {
  18896. return value;
  18897. }
  18898. } else if (stmt instanceof ast.Expr) {
  18899. this.expression(stmt.value, context);
  18900. } else if (stmt instanceof ast.Import) {
  18901. for (const alias of stmt.names) {
  18902. let module = this.__import__(alias.name, context);
  18903. if (alias.asname) {
  18904. const bits = alias.name.split('.').reverse();
  18905. bits.pop();
  18906. while (bits.length > 0) {
  18907. module = module[bits.pop()];
  18908. }
  18909. context.set(alias.asname, module);
  18910. } else {
  18911. context.set(alias.name.split('.')[0], module);
  18912. }
  18913. }
  18914. } else if (stmt instanceof ast.ImportFrom) {
  18915. const fromlist = stmt.names.map((name) => name.name);
  18916. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  18917. for (const entry of stmt.names) {
  18918. const name = entry.name;
  18919. const asname = entry.asname ? entry.asname : null;
  18920. if (!module[name]) {
  18921. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  18922. }
  18923. context.set(asname ? asname : name, module[name]);
  18924. }
  18925. } else {
  18926. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  18927. }
  18928. return undefined;
  18929. }
  18930. expression(expr, context) {
  18931. const ast = this.ast;
  18932. const builtins = this.builtins;
  18933. const typing = this.typing;
  18934. const self = context.get('self');
  18935. switch (expr.__class__.__name__) {
  18936. case 'Assign': {
  18937. const [target] = expr.targets;
  18938. if (target instanceof ast.Name) {
  18939. const value = this.expression(expr.value, context);
  18940. context.set(target.id, value);
  18941. return undefined;
  18942. } else if (target instanceof ast.Subscript) {
  18943. if (target.value instanceof ast.Name &&
  18944. target.slice instanceof ast.List &&
  18945. target.slice.elts.length === 1) {
  18946. const index = this.expression(target.slice.elts[0], context);
  18947. const id = target.value.id;
  18948. if (id === '__annotations__') {
  18949. context.set(id, context.get(id) || {});
  18950. }
  18951. const obj = context.get(id);
  18952. const value = this.expression(expr.value, context);
  18953. if (obj instanceof Map) {
  18954. obj.set(index, value);
  18955. } else {
  18956. obj[index] = value;
  18957. }
  18958. return undefined;
  18959. }
  18960. } else if (target instanceof ast.Attribute) {
  18961. const obj = this.expression(target.value, context);
  18962. const value = this.expression(expr.value, context);
  18963. obj[target.attr] = value;
  18964. return undefined;
  18965. } else if (target instanceof ast.Tuple) {
  18966. context.target.push(target.elts);
  18967. const value = this.expression(expr.value, context);
  18968. context.target.pop();
  18969. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  18970. if (target.elts.length < value.length) {
  18971. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  18972. }
  18973. if (target.elts.length > value.length) {
  18974. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  18975. }
  18976. for (let i = 0; i < value.length; i++) {
  18977. context.set(target.elts[i].id, value[i]);
  18978. }
  18979. return undefined;
  18980. }
  18981. }
  18982. break;
  18983. }
  18984. case 'List': {
  18985. return expr.elts.map((expr) => this.expression(expr, context));
  18986. }
  18987. case 'Constant': {
  18988. return expr.value;
  18989. }
  18990. case 'Subscript': {
  18991. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  18992. const id = expr.value.id;
  18993. if (context.get(id)) {
  18994. const index = this.expression(expr.slice, context);
  18995. const target = context.get(id);
  18996. if (target instanceof Map) {
  18997. return target.get(index);
  18998. }
  18999. return target[index < 0 ? target.length + index : index];
  19000. }
  19001. }
  19002. const value = this.expression(expr.value, context);
  19003. if (value && expr.slice instanceof ast.List &&
  19004. (value.__class__ === typing._TupleType ||
  19005. value.__class__ === typing._SpecialGenericAlias ||
  19006. value.__class__ === typing._SpecialForm)) {
  19007. const type = { ...value };
  19008. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  19009. return type;
  19010. }
  19011. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  19012. const index = this.expression(expr.slice.elts[0], context);
  19013. if (value instanceof Map) {
  19014. return value.get(index);
  19015. }
  19016. return value[index < 0 ? value.length + index : index];
  19017. }
  19018. break;
  19019. }
  19020. case 'Attribute': {
  19021. const value = this.target(expr.value, context);
  19022. return value[expr.attr];
  19023. }
  19024. case 'Call': {
  19025. const func = expr.func;
  19026. if (func instanceof ast.Attribute) {
  19027. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  19028. }
  19029. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  19030. }
  19031. case 'Name': {
  19032. const id = expr.id;
  19033. if (id === 'self') {
  19034. return self;
  19035. }
  19036. const type = (value) => {
  19037. return value &&
  19038. (value.__class__ === builtins.type ||
  19039. value.__class__ === typing._TupleType ||
  19040. value.__class__ === typing._SpecialGenericAlias ||
  19041. value.__class__ === typing._SpecialForm);
  19042. };
  19043. const builtin = builtins[id];
  19044. if (type(builtin)) {
  19045. return builtin;
  19046. }
  19047. const value = context.get(id);
  19048. if (value === undefined) {
  19049. const value = typing[id];
  19050. if (type(value)) {
  19051. return value;
  19052. }
  19053. }
  19054. return value;
  19055. }
  19056. case 'Tuple': {
  19057. return expr.elts.map((expr) => this.expression(expr, context));
  19058. }
  19059. case 'Dict': {
  19060. const dict = {};
  19061. for (let i = 0; i < expr.keys.length; i++) {
  19062. const key = this.expression(expr.keys[i], context);
  19063. const value = this.expression(expr.values[i], context);
  19064. dict[key] = value;
  19065. }
  19066. return dict;
  19067. }
  19068. case 'UnaryOp': {
  19069. if (expr.op instanceof ast.USub) {
  19070. return -this.expression(expr.operand, context);
  19071. }
  19072. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  19073. }
  19074. case 'binary': {
  19075. switch (expr.op) {
  19076. case '==': {
  19077. return this.expression(expr.left, context) === this.expression(expr.right, context);
  19078. }
  19079. default: {
  19080. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  19081. }
  19082. }
  19083. }
  19084. default: {
  19085. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  19086. }
  19087. }
  19088. return undefined;
  19089. }
  19090. identifier(expr) {
  19091. const ast = this.ast;
  19092. if (expr instanceof ast.Name) {
  19093. return expr.id;
  19094. }
  19095. if (expr instanceof ast.Attribute) {
  19096. return `${this.identifier(expr.value)}.${expr.attr}`;
  19097. }
  19098. return null;
  19099. }
  19100. target(expr, context) {
  19101. const ast = this.ast;
  19102. let current = expr;
  19103. let path = [];
  19104. for (;;) {
  19105. if (current instanceof ast.Attribute) {
  19106. path.push(current.attr);
  19107. current = current.value;
  19108. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  19109. path.push(current.id);
  19110. break;
  19111. } else {
  19112. path = null;
  19113. break;
  19114. }
  19115. }
  19116. if (path) {
  19117. let target = null;
  19118. for (let i = path.length - 1; i >= 0; i--) {
  19119. const name = path[i];
  19120. if (target) {
  19121. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  19122. } else {
  19123. target = context.get(name);
  19124. }
  19125. if (!target) {
  19126. break;
  19127. }
  19128. }
  19129. if (!target) {
  19130. path.reverse();
  19131. const name = path.join('.');
  19132. const file = `${path.join('/')}.py`;
  19133. if (this._sources.has(file)) {
  19134. target = this.import(name);
  19135. } else {
  19136. target = this.resolve(name);
  19137. }
  19138. }
  19139. return target;
  19140. }
  19141. return this.expression(expr, context);
  19142. }
  19143. add(name, source) {
  19144. this._sources.set(name, source);
  19145. }
  19146. on(event, listener) {
  19147. const value = this._events.get(event) || [];
  19148. value.push(listener);
  19149. this._events.set(event, value);
  19150. }
  19151. emit(event, ...args) {
  19152. if (this._events.has(event)) {
  19153. for (const callback of this._events.get(event)) {
  19154. callback(this, ...args);
  19155. }
  19156. }
  19157. }
  19158. register(name, value) {
  19159. if (!this._registry.has(name)) {
  19160. value = value || new (this._registry.get('builtins').module)(name);
  19161. this._registry.set(name, value);
  19162. let current = name;
  19163. for (;;) {
  19164. const index = current.lastIndexOf('.');
  19165. if (index === -1) {
  19166. break;
  19167. }
  19168. const child = current.substring(index + 1);
  19169. current = current.substring(0, index);
  19170. if (!value.__module__) {
  19171. value.__module__ = current;
  19172. }
  19173. const parent = this.register(current);
  19174. parent[child] = value;
  19175. value = parent;
  19176. }
  19177. }
  19178. return this._registry.get(name);
  19179. }
  19180. registerFunction(name, value) {
  19181. const builtins = this.builtins;
  19182. const index = name.lastIndexOf('.');
  19183. if (!value) {
  19184. value = () => {
  19185. throw new python.Error(`'${name}' is not implemented.`);
  19186. };
  19187. }
  19188. value.__class__ = builtins.function;
  19189. value.__name__ = index === -1 ? name : name.substring(index + 1);
  19190. value.__module__ = index === -1 ? '' : name.substring(0, index);
  19191. const module = this.register(value.__module__);
  19192. if (module[name]) {
  19193. throw new python.Error(`Function '${name}' is already registered.`);
  19194. }
  19195. module[value.__name__] = value;
  19196. return value;
  19197. }
  19198. _createType(name, value) {
  19199. const builtins = this.builtins;
  19200. const index = name.lastIndexOf('.');
  19201. value.__class__ = builtins.type;
  19202. value.__name__ = index === -1 ? name : name.substring(index + 1);
  19203. value.__module__ = index === -1 ? '' : name.substring(0, index);
  19204. value.prototype.__class__ = value;
  19205. return value;
  19206. }
  19207. registerType(name, value) {
  19208. value = this._createType(name, value);
  19209. const parts = name.split('.');
  19210. const memberName = parts.pop();
  19211. const moduleName = parts.join('.');
  19212. const module = this.register(moduleName);
  19213. if (module[memberName]) {
  19214. throw new python.Error(`Class '${memberName}' is already registered.`);
  19215. }
  19216. module[memberName] = value;
  19217. return value;
  19218. }
  19219. };
  19220. python.Execution.Context = class {
  19221. constructor(globals, locals) {
  19222. this.globals = globals;
  19223. this.locals = locals;
  19224. }
  19225. set(name, value) {
  19226. if (this.locals) {
  19227. this.locals[name] = value;
  19228. } else {
  19229. this.globals[name] = value;
  19230. }
  19231. }
  19232. get(name) {
  19233. if (this.locals && name in this.locals) {
  19234. return this.locals[name];
  19235. }
  19236. if (name in this.globals) {
  19237. return this.globals[name];
  19238. }
  19239. return undefined;
  19240. }
  19241. get target() {
  19242. this._target = this._target || [];
  19243. return this._target;
  19244. }
  19245. };
  19246. python.BinaryReader = class {
  19247. constructor(buffer) {
  19248. this._buffer = buffer;
  19249. this._length = buffer.length;
  19250. this._position = 0;
  19251. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  19252. this._utf8Decoder = new TextDecoder('utf-8');
  19253. this._asciiDecoder = new TextDecoder('ascii');
  19254. }
  19255. get position() {
  19256. return this._position;
  19257. }
  19258. get length() {
  19259. return this._length;
  19260. }
  19261. seek(position) {
  19262. this._position = position >= 0 ? position : this._length + position;
  19263. if (this._position > this._buffer.length) {
  19264. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  19265. }
  19266. }
  19267. skip(offset) {
  19268. this._position += offset;
  19269. if (this._position > this._buffer.length) {
  19270. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  19271. }
  19272. }
  19273. stream(length) {
  19274. const buffer = this.read(length);
  19275. return new python.BinaryReader(buffer);
  19276. }
  19277. peek(length) {
  19278. const position = this._position;
  19279. length = length === undefined ? this._length - this._position : length;
  19280. this.skip(length);
  19281. const end = this._position;
  19282. this.skip(-length);
  19283. if (position === 0 && length === this._length) {
  19284. return this._buffer;
  19285. }
  19286. return this._buffer.subarray(position, end);
  19287. }
  19288. read(length) {
  19289. const position = this._position;
  19290. length = length === undefined ? this._length - this._position : length;
  19291. this.skip(length);
  19292. if (position === 0 && length === this._length) {
  19293. return this._buffer;
  19294. }
  19295. return this._buffer.subarray(position, this._position);
  19296. }
  19297. byte() {
  19298. const position = this._position;
  19299. this.skip(1);
  19300. return this._view.getUint8(position);
  19301. }
  19302. uint16() {
  19303. const position = this._position;
  19304. this.skip(2);
  19305. return this._view.getUint16(position, true);
  19306. }
  19307. int32() {
  19308. const position = this._position;
  19309. this.skip(4);
  19310. return this._view.getInt32(position, true);
  19311. }
  19312. uint32() {
  19313. const position = this._position;
  19314. this.skip(4);
  19315. return this._view.getUint32(position, true);
  19316. }
  19317. int64() {
  19318. const position = this._position;
  19319. this.skip(8);
  19320. return this._view.getBigInt64(position, true);
  19321. }
  19322. float64() {
  19323. const position = this._position;
  19324. this.skip(8);
  19325. return this._view.getFloat64(position, false);
  19326. }
  19327. string(size, encoding) {
  19328. const data = this.read(size);
  19329. return (encoding === 'utf-8') ?
  19330. this._utf8Decoder.decode(data) :
  19331. this._asciiDecoder.decode(data);
  19332. }
  19333. line() {
  19334. const index = this._buffer.indexOf(0x0A, this._position);
  19335. if (index === -1) {
  19336. throw new python.Error('Could not find end of line.');
  19337. }
  19338. const size = index - this._position;
  19339. const text = this.string(size, 'ascii');
  19340. this.skip(1);
  19341. return text;
  19342. }
  19343. };
  19344. python.StreamReader = class {
  19345. constructor(stream) {
  19346. this._stream = stream;
  19347. this._length = stream.length;
  19348. this._position = 0;
  19349. this._utf8Decoder = new TextDecoder('utf-8');
  19350. this._asciiDecoder = new TextDecoder('ascii');
  19351. }
  19352. get position() {
  19353. return this._position;
  19354. }
  19355. get length() {
  19356. return this._length;
  19357. }
  19358. seek(position) {
  19359. this._stream.seek(position);
  19360. this._position = this._stream.position;
  19361. }
  19362. skip(offset) {
  19363. this._position += offset;
  19364. if (this._position > this._length) {
  19365. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  19366. }
  19367. }
  19368. stream(length) {
  19369. this._stream.seek(this._position);
  19370. this.skip(length);
  19371. return this._stream.stream(length);
  19372. }
  19373. peek(length) {
  19374. this._stream.seek(this._position);
  19375. return this._stream.peek(length);
  19376. }
  19377. read(length) {
  19378. this._stream.seek(this._position);
  19379. this.skip(length);
  19380. return this._stream.read(length);
  19381. }
  19382. byte() {
  19383. const position = this._fill(1);
  19384. return this._view.getUint8(position);
  19385. }
  19386. uint16() {
  19387. const position = this._fill(2);
  19388. return this._view.getUint16(position, true);
  19389. }
  19390. int32() {
  19391. const position = this._fill(4);
  19392. return this._view.getInt32(position, true);
  19393. }
  19394. uint32() {
  19395. const position = this._fill(4);
  19396. return this._view.getUint32(position, true);
  19397. }
  19398. int64() {
  19399. const position = this._fill(8);
  19400. return this._view.getBigInt64(position, true);
  19401. }
  19402. float64() {
  19403. const position = this._fill(8);
  19404. return this._view.getFloat64(position, false);
  19405. }
  19406. string(size, encoding) {
  19407. const data = this.read(size);
  19408. return (encoding === 'utf-8') ?
  19409. this._utf8Decoder.decode(data) :
  19410. this._asciiDecoder.decode(data);
  19411. }
  19412. line() {
  19413. let position = this._fill(0);
  19414. let index = this._buffer.indexOf(0x0A, position);
  19415. if (index === -1) {
  19416. const size = Math.min(0x20000000, this._stream.length - this._position);
  19417. this._fill(size);
  19418. this.skip(-size);
  19419. position = this._fill(0);
  19420. index = this._buffer.indexOf(0x0A, position);
  19421. if (index === -1) {
  19422. throw new python.Error('Could not find end of line.');
  19423. }
  19424. }
  19425. const size = index - position;
  19426. const text = this.string(size, 'ascii');
  19427. this.skip(1);
  19428. return text;
  19429. }
  19430. _fill(length) {
  19431. if (this._position + length > this._length) {
  19432. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  19433. }
  19434. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  19435. this._offset = this._position;
  19436. this._stream.seek(this._offset);
  19437. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  19438. this._buffer = this._stream.read(size);
  19439. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  19440. }
  19441. const position = this._position;
  19442. this._position += length;
  19443. return position - this._offset;
  19444. }
  19445. };
  19446. python.Error = class extends Error {
  19447. constructor(message) {
  19448. super(message);
  19449. this.name = 'Python Error';
  19450. }
  19451. };
  19452. export const Execution = python.Execution;