python.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Execution = class {
  4. constructor(sources) {
  5. /* eslint-disable consistent-this */
  6. const self = this;
  7. /* eslint-enable consistent-this */
  8. const execution = self;
  9. this._sources = sources || new Map();
  10. this._events = new Map();
  11. this._utf8Decoder = new TextDecoder('utf-8');
  12. this._unresolved = new Map();
  13. this._operators = new Map();
  14. const dict = class extends Map {
  15. constructor(items) {
  16. super();
  17. if (items) {
  18. if (items instanceof Map) {
  19. items = Array.from(items);
  20. } else if (!Array.isArray(items)) {
  21. items = Object.entries(items);
  22. }
  23. for (const [name, value] of items) {
  24. this.__setitem__(name, value);
  25. }
  26. }
  27. }
  28. __contains__(key) {
  29. return this.has(key);
  30. }
  31. __setitem__(key, value) {
  32. this.set(key, value);
  33. }
  34. __getitem__(key) {
  35. return this.get(key);
  36. }
  37. __delitem__(key) {
  38. this.delete(key);
  39. }
  40. get(key, defaultValue) {
  41. return super.has(key) ? super.get(key) : defaultValue;
  42. }
  43. setdefault(key, defaultValue) {
  44. if (this.has(key)) {
  45. return this.get(key);
  46. }
  47. const value = defaultValue || null;
  48. this.set(key, value);
  49. return value;
  50. }
  51. pop(key) {
  52. if (this.__contains__(key)) {
  53. const v = this.__getitem__(key);
  54. this.__delitem__(key);
  55. return v;
  56. }
  57. return null;
  58. }
  59. items() {
  60. return Array.from(this);
  61. }
  62. update(other) {
  63. for (const [key, value] of other) {
  64. this.set(key, value);
  65. }
  66. }
  67. };
  68. this._modules = new dict();
  69. this._registry = new Map();
  70. const module = class {
  71. constructor(name) {
  72. this.__name__ = name;
  73. }
  74. };
  75. const builtins = this.register('builtins', new module('builtins'));
  76. this.builtins = builtins;
  77. this._registry.set('__builtin__', builtins);
  78. this.registerType('builtins.type', class {
  79. constructor(...args) {
  80. if (args.length === 1) {
  81. const [obj] = args;
  82. if (obj === null) {
  83. /* eslint-disable no-constructor-return */
  84. return builtins.NoneType;
  85. /* eslint-enable no-constructor-return */
  86. }
  87. if (obj && obj.__class__) {
  88. /* eslint-disable no-constructor-return */
  89. return obj.__class__;
  90. /* eslint-enable no-constructor-return */
  91. }
  92. throw new python.Error(`Unknown type '${obj}'`);
  93. }
  94. if (args.length === 3) {
  95. const [name, bases, body] = args;
  96. const cls = bases.length > 0 ? class extends bases[0] {} : class {};
  97. execution.registerType(name, cls);
  98. for (const [key, value] of body) {
  99. cls[key] = value;
  100. }
  101. /* eslint-disable no-constructor-return */
  102. return cls;
  103. /* eslint-enable no-constructor-return */
  104. }
  105. throw new python.Error(`Invalid 'builtins.dict' argument count.`);
  106. }
  107. }).__class__ = builtins.type;
  108. this.registerType('builtins.module', module);
  109. this.registerType('builtins.method', class {});
  110. this.registerType('builtins.function', class {
  111. constructor(code, globals, name) {
  112. this.__code__ = code;
  113. this.__globals__ = globals;
  114. this.__name__ = name;
  115. }
  116. });
  117. this.registerType('builtins.classmethod', class {});
  118. this.registerType('builtins.code', class {});
  119. this.import('builtins');
  120. this.registerType('builtins.builtin_function_or_method', class {});
  121. const typing = this.register('typing');
  122. this.typing = typing;
  123. const operator = this.register('operator');
  124. this.register('_codecs');
  125. this.register('argparse');
  126. this.enum = this.register('enum');
  127. const collections = this.register('collections');
  128. const copy = this.register('copy');
  129. this.register('copy_reg');
  130. const ast = this.register('ast');
  131. this.ast = ast;
  132. this.register('cuml');
  133. const cloudpickle = this.register('cloudpickle');
  134. const datetime = this.register('datetime');
  135. this.register('gensim');
  136. const io = this.register('io');
  137. const joblib = this.register('joblib');
  138. const jax = this.register('jax');
  139. this.register('jax.numpy');
  140. this.register('jax._src.array');
  141. this.register('jax._src.device_array');
  142. const functools = this.register('functools');
  143. this.registerType('functools.partial', class {});
  144. const keras = this.register('keras');
  145. const catboost = this.register('catboost');
  146. this.register('lightgbm');
  147. this.register('nolearn');
  148. const fastcore = this.register('fastcore');
  149. const fastai = this.register('fastai');
  150. const math = this.register('math');
  151. math.inf = Infinity;
  152. const numpy = this.register('numpy');
  153. this.register('numpy.core.multiarray');
  154. this.register('numpy.core._multiarray_umath');
  155. this.register('numpy.matrixlib.defmatrix');
  156. const pandas = this.register('pandas');
  157. this.register('pandas.indexes.base');
  158. this.register('pandas.indexes.range');
  159. this.register('pandas._libs.tslib');
  160. this.register('pandas._libs.internals');
  161. const pickle = this.register('pickle');
  162. const shap = this.register('shap');
  163. this.register('shap.explainers.linear');
  164. const sklearn = this.register('sklearn');
  165. this.register('sklearn.externals.joblib.numpy_pickle');
  166. const torch = this.register('torch');
  167. this.torch = torch;
  168. const torchvision = this.register('torchvision');
  169. const torchao = this.register('torchao');
  170. const sympy = this.register('sympy');
  171. this.register('torch.storage');
  172. this.register('torch.nn.parameter');
  173. this.register('torch.ops');
  174. this.register('torch._ops');
  175. this.register('torch.ops.higher_order');
  176. this.register('torch.ops.torchvision');
  177. this.register('torch.ops.torchaudio');
  178. this.register('torch.ops._caffe2');
  179. this.register('torchvision');
  180. this.register('__torch__');
  181. const sys = this.register('sys');
  182. sys.modules = this._modules;
  183. this.register('xgboost');
  184. this.registerType('ast.AST', class {});
  185. this.registerType('ast.mod', class extends ast.AST {});
  186. this.registerType('ast.expr', class extends ast.AST {});
  187. this.registerType('ast.unaryop', class extends ast.AST {});
  188. this.registerType('ast.binop', class extends ast.AST {});
  189. this.registerType('ast.operator', class extends ast.AST {});
  190. this.registerType('ast.boolop', class extends ast.AST {});
  191. this.registerType('ast.cmpop', class extends ast.AST {});
  192. this.registerType('ast.stmt', class extends ast.AST {});
  193. this.registerType('ast.excepthandler', class extends ast.AST {});
  194. this.registerType('ast.keyword', class extends ast.AST {
  195. constructor(arg, value) {
  196. super();
  197. this.arg = arg;
  198. this.value = value;
  199. }
  200. });
  201. this.registerType('ast.alias', class extends ast.AST {
  202. constructor(name, asname) {
  203. super();
  204. this.name = name;
  205. this.asname = asname;
  206. }
  207. });
  208. this.registerType('ast.Name', class extends ast.expr {
  209. constructor(id, ctx) {
  210. super();
  211. this.id = id;
  212. if (ctx) {
  213. this.ctx = ctx;
  214. }
  215. }
  216. });
  217. this.registerType('ast.Constant', class extends ast.expr {
  218. constructor(value, type) {
  219. super();
  220. this.value = value;
  221. this.type = type || null;
  222. }
  223. });
  224. this.registerType('ast.Ellipsis', class extends ast.Constant {
  225. constructor() {
  226. super(builtins.ellipsis);
  227. }
  228. });
  229. this.registerType('ast.Starred', class extends ast.expr {
  230. constructor(value, ctx) {
  231. super();
  232. this.value = value;
  233. if (ctx) {
  234. this.ctx = ctx;
  235. }
  236. }
  237. });
  238. this.registerType('ast.List', class extends ast.expr {
  239. constructor(elts, ctx) {
  240. super();
  241. this.elts = elts;
  242. if (ctx) {
  243. this.ctx = ctx;
  244. }
  245. }
  246. });
  247. this.registerType('ast.Set', class extends ast.expr {
  248. constructor(elts) {
  249. super();
  250. this.elts = elts;
  251. }
  252. });
  253. this.registerType('ast.Tuple', class extends ast.expr {
  254. constructor(elts, ctx) {
  255. super();
  256. this.elts = elts;
  257. if (ctx) {
  258. this.ctx = ctx;
  259. }
  260. }
  261. });
  262. this.registerType('ast.Dict', class extends ast.expr {
  263. constructor(keys, values) {
  264. super();
  265. this.keys = keys;
  266. this.values = values;
  267. }
  268. });
  269. this.registerType('ast.ListComp', class extends ast.expr {
  270. constructor(elt, generators) {
  271. super();
  272. this.elt = elt;
  273. this.generators = generators;
  274. }
  275. });
  276. this.registerType('ast.SetComp', class extends ast.expr {
  277. constructor(elt, generators) {
  278. super();
  279. this.elt = elt;
  280. this.generators = generators;
  281. }
  282. });
  283. this.registerType('ast.GeneratorExp', class extends ast.expr {
  284. constructor(elt, generators) {
  285. super();
  286. this.elt = elt;
  287. this.generators = generators;
  288. }
  289. });
  290. this.registerType('ast.DictComp', class extends ast.expr {
  291. constructor(key, value, generators) {
  292. super();
  293. this.key = key;
  294. this.value = value;
  295. this.generators = generators;
  296. }
  297. });
  298. this.registerType('ast.comprehension', class extends ast.AST {
  299. constructor(target, iter, ifs, is_async) {
  300. super();
  301. this.target = target;
  302. this.iter = iter;
  303. this.ifs = ifs;
  304. this.is_async = is_async;
  305. }
  306. });
  307. this.registerType('ast.Subscript', class extends ast.expr {
  308. constructor(value, slice, ctx) {
  309. super();
  310. this.value = value;
  311. this.slice = slice;
  312. if (ctx) {
  313. this.ctx = ctx;
  314. }
  315. }
  316. });
  317. this.registerType('ast.Slice', class extends ast.expr {
  318. constructor(lower, upper, step) {
  319. super();
  320. this.lower = lower;
  321. this.upper = upper;
  322. this.step = step;
  323. }
  324. });
  325. this.registerType('ast.UnaryOp', class extends ast.expr {
  326. constructor(op, operand) {
  327. super();
  328. this.op = op;
  329. this.operand = operand;
  330. }
  331. });
  332. this.registerType('ast.UAdd', class extends ast.unaryop {});
  333. this.registerType('ast.USub', class extends ast.unaryop {});
  334. this.registerType('ast.Not', class extends ast.unaryop {});
  335. this.registerType('ast.Invert', class extends ast.unaryop {});
  336. this.registerType('ast.BinOp', class extends ast.expr {
  337. constructor(left, op, right) {
  338. super();
  339. this.left = left;
  340. this.op = op;
  341. this.right = right;
  342. }
  343. });
  344. this.registerType('ast.Add', class extends ast.operator {});
  345. this.registerType('ast.Sub', class extends ast.operator {});
  346. this.registerType('ast.Mult', class extends ast.operator {});
  347. this.registerType('ast.Div', class extends ast.operator {});
  348. this.registerType('ast.FloorDiv', class extends ast.operator {});
  349. this.registerType('ast.Mod', class extends ast.operator {});
  350. this.registerType('ast.Pow', class extends ast.operator {});
  351. this.registerType('ast.LShift', class extends ast.operator {});
  352. this.registerType('ast.RShift', class extends ast.operator {});
  353. this.registerType('ast.BitOr', class extends ast.operator {});
  354. this.registerType('ast.BitXor', class extends ast.operator {});
  355. this.registerType('ast.BitAnd', class extends ast.operator {});
  356. this.registerType('ast.MatMult', class extends ast.operator {});
  357. this.registerType('ast.BoolOp', class extends ast.expr {
  358. constructor(op, values) {
  359. super();
  360. this.op = op;
  361. this.values = values;
  362. }
  363. });
  364. this.registerType('ast.And', class extends ast.boolop {});
  365. this.registerType('ast.Or', class extends ast.boolop {});
  366. this.registerType('ast.Compare', class extends ast.expr {
  367. constructor(left, ops, comparators) {
  368. super();
  369. this.left = left;
  370. this.ops = ops;
  371. this.comparators = comparators;
  372. }
  373. });
  374. this.registerType('ast.Eq', class extends ast.cmpop {});
  375. this.registerType('ast.NotEq', class extends ast.cmpop {});
  376. this.registerType('ast.Lt', class extends ast.cmpop {});
  377. this.registerType('ast.LtE', class extends ast.cmpop {});
  378. this.registerType('ast.Gt', class extends ast.cmpop {});
  379. this.registerType('ast.GtE', class extends ast.cmpop {});
  380. this.registerType('ast.Is', class extends ast.cmpop {});
  381. this.registerType('ast.IsNot', class extends ast.cmpop {});
  382. this.registerType('ast.In', class extends ast.cmpop {});
  383. this.registerType('ast.NotIn', class extends ast.cmpop {});
  384. this.registerType('ast.Call', class extends ast.expr {
  385. constructor(func, args, keywords) {
  386. super();
  387. this.func = func;
  388. this.args = args;
  389. this.keywords = keywords || [];
  390. }
  391. });
  392. this.registerType('ast.Attribute', class extends ast.expr {
  393. constructor(value, attr, ctx) {
  394. super();
  395. this.value = value;
  396. this.attr = attr;
  397. if (ctx) {
  398. this.ctx = ctx;
  399. }
  400. }
  401. });
  402. this.registerType('ast.Lambda', class extends ast.expr {
  403. constructor(args, body) {
  404. super();
  405. this.args = args;
  406. this.body = body;
  407. }
  408. });
  409. this.registerType('ast.IfExp', class extends ast.expr {
  410. constructor(test, body, orelse) {
  411. super();
  412. this.test = test;
  413. this.body = body;
  414. this.orelse = orelse;
  415. }
  416. });
  417. this.registerType('ast.NamedExpr', class extends ast.expr {
  418. constructor(target, value) {
  419. super();
  420. this.target = target;
  421. this.value = value;
  422. }
  423. });
  424. this.registerType('ast.Yield', class extends ast.expr {
  425. constructor(value) {
  426. super();
  427. this.value = value;
  428. }
  429. });
  430. this.registerType('ast.YieldFrom', class extends ast.expr {
  431. constructor(value) {
  432. super();
  433. this.value = value;
  434. }
  435. });
  436. this.registerType('ast.Expr', class extends ast.stmt {
  437. constructor(value) {
  438. super();
  439. this.value = value;
  440. }
  441. });
  442. this.registerType('ast.Assign', class extends ast.stmt {
  443. constructor(targets, value, ctx) {
  444. super();
  445. this.targets = targets;
  446. this.value = value;
  447. if (ctx) {
  448. this.ctx = ctx;
  449. }
  450. }
  451. });
  452. this.registerType('ast.AnnAssign', class extends ast.stmt {
  453. constructor(target, annotation, value, simple) {
  454. super();
  455. this.target = target;
  456. this.annotation = annotation;
  457. this.value = value;
  458. this.simple = simple;
  459. }
  460. });
  461. this.registerType('ast.AugAssign', class extends ast.stmt {
  462. constructor(target, op, value) {
  463. super();
  464. this.target = target;
  465. this.op = op;
  466. this.value = value;
  467. }
  468. });
  469. this.registerType('ast.If', class extends ast.stmt {
  470. constructor(test, body, orelse) {
  471. super();
  472. this.test = test;
  473. this.body = body;
  474. this.orelse = orelse;
  475. }
  476. });
  477. this.registerType('ast.For', class extends ast.stmt {
  478. constructor(target, iter, body, orelse /*, type_comment */) {
  479. super();
  480. this.target = target;
  481. this.iter = iter;
  482. this.body = body;
  483. this.orelse = orelse;
  484. }
  485. });
  486. this.registerType('ast.While', class extends ast.stmt {
  487. constructor(test, body, orelse /*, type_comment */) {
  488. super();
  489. this.test = test;
  490. this.body = body;
  491. this.orelse = orelse;
  492. }
  493. });
  494. this.registerType('ast.Del', class extends ast.stmt {
  495. constructor(targets) {
  496. super();
  497. this.targets = targets;
  498. }
  499. });
  500. this.registerType('ast.Return', class extends ast.stmt {
  501. constructor(value) {
  502. super();
  503. this.value = value;
  504. }
  505. });
  506. this.registerType('ast.Try', class extends ast.stmt {
  507. constructor(body, handlers, orelse, finalbody) {
  508. super();
  509. this.body = body;
  510. this.handlers = handlers;
  511. this.orelse = orelse;
  512. this.finalbody = finalbody;
  513. }
  514. });
  515. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  516. constructor(type, name, body) {
  517. super();
  518. this.type_ = type;
  519. this.name = name;
  520. this.body = body;
  521. }
  522. });
  523. this.registerType('ast.ClassDef', class extends ast.stmt {
  524. constructor(name, bases, keywords, body, decorator_list, type_params) {
  525. super();
  526. this.name = name;
  527. this.bases = bases;
  528. this.keywords = keywords;
  529. this.body = body;
  530. this.decorator_list = decorator_list;
  531. this.type_params = type_params;
  532. }
  533. });
  534. this.registerType('ast.FunctionDef', class extends ast.stmt {
  535. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  536. super();
  537. this.name = name;
  538. this.args = args;
  539. this.body = body;
  540. this.decorator_list = decorator_list;
  541. this.returns = returns;
  542. this.type_comment = type_comment;
  543. this.type_params = type_params;
  544. }
  545. });
  546. this.registerType('ast.arguments', class extends ast.AST {
  547. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  548. super();
  549. this.posonlyargs = posonlyargs;
  550. this.args = args;
  551. this.vararg = vararg;
  552. this.kwonlyargs = kwonlyargs;
  553. this.kw_defaults = kw_defaults;
  554. this.kwarg = kwarg;
  555. this.defaults = defaults;
  556. }
  557. });
  558. this.registerType('ast.arg', class extends ast.AST {
  559. constructor(arg, annotation, type_comment) {
  560. super();
  561. this.arg = arg;
  562. this.annotation = annotation;
  563. this.type_comment = type_comment;
  564. }
  565. });
  566. this.registerType('ast.Import', class extends ast.stmt {
  567. constructor(names) {
  568. super();
  569. this.names = names;
  570. }
  571. });
  572. this.registerType('ast.ImportFrom', class extends ast.stmt {
  573. constructor(module, names, level) {
  574. super();
  575. this.module = module;
  576. this.names = names;
  577. this.level = level;
  578. }
  579. });
  580. this.registerType('ast.Assert', class extends ast.stmt {
  581. constructor(test, msg) {
  582. super();
  583. this.test = test;
  584. this.msg = msg;
  585. }
  586. });
  587. this.registerType('ast.Raise', class extends ast.stmt {
  588. constructor(exc, cause) {
  589. super();
  590. this.exc = exc;
  591. this.cause = cause;
  592. }
  593. });
  594. this.registerType('ast.With', class extends ast.stmt {
  595. constructor(items, body, type_comment) {
  596. super();
  597. this.items = items;
  598. this.body = body;
  599. this.type_comment = type_comment;
  600. }
  601. });
  602. this.registerType('ast.withitem', class extends ast.AST {
  603. constructor(context_expr, optional_vars) {
  604. super();
  605. this.context_expr = context_expr;
  606. this.optional_vars = optional_vars;
  607. }
  608. });
  609. this.registerType('ast.Global', class extends ast.stmt {
  610. constructor(names) {
  611. super();
  612. this.names = names;
  613. }
  614. });
  615. this.registerType('ast.Nonlocal', class extends ast.stmt {
  616. constructor(names) {
  617. super();
  618. this.names = names;
  619. }
  620. });
  621. this.registerType('ast.Continue', class extends ast.stmt {});
  622. this.registerType('ast.Break', class extends ast.stmt {});
  623. this.registerType('ast.Pass', class extends ast.stmt {});
  624. this.registerType('ast.Await', class extends ast.stmt {
  625. constructor(value) {
  626. super();
  627. this.value = value;
  628. }
  629. });
  630. this.registerType('ast.Module', class extends ast.mod {
  631. constructor(body, type_ignores) {
  632. super();
  633. this.body = body;
  634. this.type_ignores = type_ignores;
  635. }
  636. });
  637. this.registerFunction('ast.parse', (source, filename, mode, debug) => {
  638. const parser = new ast._Parser();
  639. const module = parser.parse(source, filename, debug, mode);
  640. return module;
  641. });
  642. this.registerFunction('ast._convert_literal', (node) => {
  643. if (node instanceof ast.Constant) {
  644. return node.value;
  645. }
  646. if (node instanceof ast.Dict && node.keys.length === node.values.length) {
  647. const keys = node.keys.map((k) => ast._convert_literal(k));
  648. const values = node.values.map((v) => ast._convert_literal(v));
  649. return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  650. }
  651. if (node instanceof ast.Tuple) {
  652. return new builtins.tuple(node.elts.map((e) => ast._convert_literal(e)));
  653. }
  654. if (node instanceof ast.List) {
  655. return new builtins.list(node.elts.map((e) => ast._convert_literal(e)));
  656. }
  657. throw new python.Error(`'${node.__class__.__name__}' not implemented.`);
  658. });
  659. this.registerFunction('ast.literal_eval', (node_or_string) => {
  660. if (typeof node_or_string === 'string') {
  661. node_or_string = ast.parse(node_or_string, '', 'eval').body;
  662. } else {
  663. throw new python.Error(`'ast.literal_eval' node eval not implemented.`);
  664. }
  665. return ast._convert_literal(node_or_string);
  666. });
  667. this.registerType('ast._Parser', class {
  668. constructor() {
  669. ast._Parser._precedence = ast._Parser._precedence || {
  670. 'or': 2, 'and': 3, 'not' : 4,
  671. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  672. '|': 6, '^' : 7, '&' : 8,
  673. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  674. // '+': 12, '-': 12,
  675. '~': 13, '**': 14
  676. };
  677. }
  678. parse(text, file, debug, mode) {
  679. this._tokenizer = new ast._Tokenizer(text, file);
  680. this._debug = debug;
  681. const position = this._position();
  682. let body = [];
  683. while (!this._tokenizer.match('eof')) {
  684. const statement = this._parseStatement();
  685. if (statement) {
  686. body.push(statement);
  687. continue;
  688. }
  689. if (this._tokenizer.accept('\n') || this._tokenizer.accept(';') || this._tokenizer.peek().type === 'eof') {
  690. continue;
  691. }
  692. if (this._tokenizer.accept('indent') && this._tokenizer.peek().type === 'eof') {
  693. continue;
  694. }
  695. throw new python.Error(`Unsupported statement ${this._location()}`);
  696. }
  697. if (mode === 'eval') {
  698. if (body.length !== 1 || body[0] instanceof ast.Expr === false) {
  699. throw new python.Error('Expected expression.');
  700. }
  701. body = body[0].value;
  702. }
  703. const module = new ast.Module(body);
  704. this._mark(module, position);
  705. return module;
  706. }
  707. _parseSuite() {
  708. const body = [];
  709. let statement = null;
  710. if (this._tokenizer.accept('\n')) {
  711. if (this._tokenizer.accept('indent')) {
  712. while (!this._tokenizer.accept('eof') && !this._tokenizer.accept('dedent')) {
  713. if (this._tokenizer.accept(';')) {
  714. continue;
  715. }
  716. statement = this._parseStatement();
  717. if (statement) {
  718. body.push(statement);
  719. continue;
  720. }
  721. if (this._tokenizer.accept('\n')) {
  722. continue;
  723. }
  724. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  725. continue;
  726. }
  727. throw new python.Error(`Empty statement ${this._location()}`);
  728. }
  729. }
  730. } else if (!this._tokenizer.accept('eof')) {
  731. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  732. if (this._tokenizer.accept(';')) {
  733. continue;
  734. }
  735. statement = this._parseStatement();
  736. if (statement) {
  737. body.push(statement);
  738. continue;
  739. }
  740. throw new python.Error(`Empty statement ${this._location()}`);
  741. }
  742. this._tokenizer.accept('\n');
  743. }
  744. return body;
  745. }
  746. _parseStatement() {
  747. let node = null;
  748. let position = this._position();
  749. if (this._eat('id', 'break')) {
  750. const node = new ast.Break();
  751. return this._mark(node, position);
  752. }
  753. if (this._eat('id', 'continue')) {
  754. const node = new ast.Continue();
  755. return this._mark(node, position);
  756. }
  757. if (this._eat('id', 'return')) {
  758. const value = this._parseExpression(-1, [], true);
  759. const node = new ast.Return(value);
  760. return this._mark(node, position);
  761. }
  762. if (this._eat('id', 'raise')) {
  763. let exc = this._parseExpression(-1, ['from']);
  764. let cause = null;
  765. if (this._tokenizer.accept('id', 'from')) {
  766. cause = this._parseExpression();
  767. } else if (this._tokenizer.accept(',')) {
  768. exc = [exc];
  769. exc.push(this._parseExpression());
  770. if (this._tokenizer.accept(',')) {
  771. exc.push(this._parseExpression());
  772. }
  773. }
  774. node = new ast.Raise(exc, cause);
  775. return this._mark(node, position);
  776. }
  777. if (this._eat('id', 'assert')) {
  778. const test = this._parseExpression(-1, [',']);
  779. let msg = null;
  780. if (this._tokenizer.accept(',')) {
  781. msg = this._parseExpression();
  782. }
  783. node = new ast.Assert(test, msg);
  784. return this._mark(node, position);
  785. }
  786. if (this._eat('id', 'global')) {
  787. const names = [];
  788. do {
  789. const name = this._parseName(true);
  790. names.push(name.id);
  791. }
  792. while (this._tokenizer.accept(','));
  793. const node = new ast.Global(names);
  794. return this._mark(node, position);
  795. }
  796. if (this._eat('id', 'nonlocal')) {
  797. const names = [];
  798. do {
  799. const name = this._parseName(true);
  800. names.push(name.id);
  801. }
  802. while (this._tokenizer.accept(','));
  803. const node = new ast.Nonlocal(names);
  804. return this._mark(node, position);
  805. }
  806. if (this._eat('id', 'import')) {
  807. const names = [];
  808. do {
  809. const name = this._parseDottedName();
  810. let asname = null;
  811. if (this._tokenizer.accept('id', 'as')) {
  812. asname = this._parseName(true).id;
  813. }
  814. const node = new ast.alias(name, asname);
  815. names.push(node);
  816. }
  817. while (this._tokenizer.accept(','));
  818. const node = new ast.Import(names);
  819. return this._mark(node, position);
  820. }
  821. if (this._eat('id', 'from')) {
  822. let level = 0;
  823. const dots = this._tokenizer.peek();
  824. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  825. this._eat(dots.type);
  826. level = Array.from(dots.type).length;
  827. }
  828. const module = this._parseDottedName();
  829. this._tokenizer.expect('id', 'import');
  830. const names = [];
  831. const close = this._tokenizer.accept('(');
  832. do {
  833. const name = this._parseName(true).id;
  834. let asname = null;
  835. if (this._tokenizer.accept('id', 'as')) {
  836. asname = this._parseName(true).id;
  837. }
  838. const node = new ast.alias(name, asname);
  839. names.push(node);
  840. }
  841. while (this._tokenizer.accept(','));
  842. if (close) {
  843. this._tokenizer.expect(')');
  844. }
  845. const node = new ast.ImportFrom(module, names, level);
  846. return this._mark(node, position);
  847. }
  848. const decorator_list = this._decorator();
  849. position = this._position();
  850. if (this._eat('id', 'class')) {
  851. const name = this._parseName(true);
  852. const bases = [];
  853. if (this._tokenizer.accept('(')) {
  854. while (!this._tokenizer.accept(')')) {
  855. if (this._tokenizer.accept('\n')) {
  856. continue;
  857. }
  858. const expression = this._parseExpression(-1, [], false);
  859. if (expression === null) {
  860. throw new python.Error(`Expected expression ${this._location()}`);
  861. }
  862. bases.push(expression);
  863. if (!this._tokenizer.accept(',')) {
  864. this._tokenizer.accept('\n');
  865. this._tokenizer.expect(')');
  866. break;
  867. }
  868. }
  869. }
  870. this._tokenizer.expect(':');
  871. const body = this._parseSuite();
  872. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  873. return this._mark(node, position);
  874. }
  875. const async = this._eat('id', 'async') !== null;
  876. if (async &&
  877. !this._tokenizer.match('id', 'def') &&
  878. !this._tokenizer.match('id', 'with') &&
  879. !this._tokenizer.match('id', 'for')) {
  880. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  881. }
  882. if (this._eat('id', 'def')) {
  883. const name = this._parseName(true);
  884. this._tokenizer.expect('(');
  885. const args = this._parseArguments(')');
  886. let returns = null;
  887. if (this._tokenizer.accept('->')) {
  888. returns = this._parseType();
  889. }
  890. this._tokenizer.expect(':');
  891. const body = this._parseSuite();
  892. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  893. if (async) {
  894. node.async = async;
  895. }
  896. return this._mark(node, position);
  897. }
  898. if (decorator_list && decorator_list.length > 0) {
  899. throw new python.Error('Unexpected decorator.');
  900. }
  901. if (this._eat('id', 'del')) {
  902. const targets = this._parseExpression(-1, [], true);
  903. node = new ast.Del(targets);
  904. return this._mark(node, position);
  905. }
  906. if (this._eat('id', 'if')) {
  907. const test = this._parseExpression();
  908. this._tokenizer.expect(':');
  909. const body = this._parseSuite();
  910. const node = new ast.If(test, body);
  911. let current = node;
  912. this._tokenizer.accept('\n');
  913. while (this._tokenizer.accept('id', 'elif')) {
  914. const test = this._parseExpression();
  915. this._tokenizer.expect(':');
  916. const body = this._parseSuite();
  917. current.orelse = new ast.If(test, body);
  918. current = current.orelse;
  919. this._tokenizer.accept('\n');
  920. }
  921. if (this._tokenizer.accept('id', 'else')) {
  922. this._tokenizer.expect(':');
  923. current.orelse = this._parseSuite();
  924. }
  925. return this._mark(node, position);
  926. }
  927. if (this._eat('id', 'while')) {
  928. const test = this._parseExpression();
  929. this._tokenizer.expect(':');
  930. const body = this._parseSuite();
  931. let orelse = null;
  932. if (this._tokenizer.accept('id', 'else')) {
  933. this._tokenizer.expect(':');
  934. orelse = this._parseSuite();
  935. }
  936. const node = new ast.While(test, body, orelse);
  937. return this._mark(node, position);
  938. }
  939. if (this._eat('id', 'pass')) {
  940. const node = new ast.Pass();
  941. return this._mark(node, position);
  942. }
  943. if (this._eat('id', 'for')) {
  944. let target = this._parseExpression(-1, ['in']);
  945. while (this._tokenizer.accept(',')) {
  946. if (target instanceof ast.Tuple === false) {
  947. target = new ast.Tuple([target]);
  948. }
  949. if (this._tokenizer.match('id', 'in')) {
  950. target.elts.push({});
  951. break;
  952. }
  953. target.elts.push(this._parseExpression(-1, ['in']));
  954. }
  955. this._tokenizer.expect('id', 'in');
  956. let iter = this._parseExpression();
  957. while (this._tokenizer.accept(',')) {
  958. if (iter.type !== 'tuple') {
  959. iter = new ast.Tuple([iter]);
  960. }
  961. if (this._tokenizer.match(':')) {
  962. iter.elts.push({});
  963. break;
  964. }
  965. iter.elts.push(this._parseExpression(-1, ['in']));
  966. }
  967. this._tokenizer.expect(':');
  968. const body = this._parseSuite();
  969. let orelse = null;
  970. if (this._tokenizer.accept('id', 'else')) {
  971. this._tokenizer.expect(':');
  972. orelse = this._parseSuite();
  973. }
  974. const node = new ast.For(target, iter, body, orelse);
  975. return this._mark(node, position);
  976. }
  977. if (this._eat('id', 'with')) {
  978. const items = [];
  979. do {
  980. const context_expr = this._parseExpression();
  981. let optional_vars = null;
  982. if (this._tokenizer.accept('id', 'as')) {
  983. optional_vars = this._parseExpression();
  984. }
  985. const node = new ast.withitem(context_expr, optional_vars);
  986. items.push(node);
  987. }
  988. while (this._tokenizer.accept(','));
  989. this._tokenizer.expect(':');
  990. const body = this._parseSuite();
  991. const node = new ast.With(items, body, null);
  992. if (async) {
  993. node.async = async;
  994. }
  995. return this._mark(node, position);
  996. }
  997. if (this._eat('id', 'try')) {
  998. this._tokenizer.expect(':');
  999. const body = this._parseSuite();
  1000. const handlers = [];
  1001. let orelse = null;
  1002. let finalbody = null;
  1003. while (this._tokenizer.match('id', 'except')) {
  1004. this._tokenizer.expect('id', 'except');
  1005. const type = this._parseExpression();
  1006. const name = this._tokenizer.accept('id', 'as') ? this._parseExpression() : null;
  1007. this._tokenizer.expect(':');
  1008. const body = this._parseSuite();
  1009. const except = new ast.ExceptHandler(type, name, body);
  1010. handlers.push(except);
  1011. }
  1012. if (this._tokenizer.match('id', 'else')) {
  1013. this._tokenizer.expect('id', 'else');
  1014. this._tokenizer.expect(':');
  1015. orelse = this._parseSuite();
  1016. }
  1017. if (this._tokenizer.match('id', 'finally')) {
  1018. this._tokenizer.expect('id', 'finally');
  1019. this._tokenizer.expect(':');
  1020. finalbody = this._parseSuite();
  1021. }
  1022. const node = new ast.Try(body, handlers, orelse, finalbody);
  1023. return this._mark(node, position);
  1024. }
  1025. const expr = this._parseExpression(-1, [], true);
  1026. if (expr) {
  1027. if (expr instanceof ast.Name && this._tokenizer.accept(':')) {
  1028. const position = this._position();
  1029. const annotation = this._parseExpression(-1, ['=']);
  1030. let value = null;
  1031. if (this._tokenizer.accept('=')) {
  1032. value = this._parseExpression();
  1033. }
  1034. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  1035. return this._mark(node, position);
  1036. }
  1037. if (expr instanceof ast.stmt) {
  1038. return expr;
  1039. }
  1040. switch (expr.__class__.__name__) {
  1041. case 'AnnAssign':
  1042. case 'Assert':
  1043. case 'Assign':
  1044. case 'Attribute':
  1045. case 'AugAssign':
  1046. case 'Await':
  1047. case 'BinOp':
  1048. case 'Call':
  1049. case 'Compare':
  1050. case 'Constant':
  1051. case 'Dict':
  1052. case 'Ellipsis':
  1053. case 'For':
  1054. case 'If':
  1055. case 'Lambda':
  1056. case 'List':
  1057. case 'Name':
  1058. case 'NamedExpr':
  1059. case 'Raise':
  1060. case 'Subscript':
  1061. case 'Tuple':
  1062. case 'Yield':
  1063. // return expr;
  1064. return new ast.Expr(expr);
  1065. default:
  1066. throw new python.Error(`Unhandled expression ${this._location()}`);
  1067. }
  1068. }
  1069. return null;
  1070. }
  1071. _parseExpression(minPrecedence, terminal, tuple) {
  1072. minPrecedence = minPrecedence || -1;
  1073. const terminalSet = new Set(terminal);
  1074. const stack = [];
  1075. for (;;) {
  1076. let position = this._position();
  1077. let node = null;
  1078. const token = this._tokenizer.peek();
  1079. if (stack.length === 1 && terminalSet.has(token.value)) {
  1080. break;
  1081. }
  1082. const precedence = ast._Parser._precedence[token.value];
  1083. if (precedence) {
  1084. if (precedence >= minPrecedence) {
  1085. this._tokenizer.read();
  1086. if (token.value === 'not' && this._tokenizer.accept('id', 'in')) {
  1087. token.value = 'not in';
  1088. } else if (token.value === 'is' && this._tokenizer.accept('id', 'not')) {
  1089. token.value = 'is not';
  1090. }
  1091. if (stack.length > 0) {
  1092. let op = null;
  1093. switch (token.value) {
  1094. case '+': op = new ast.Add(); break;
  1095. case '-': op = new ast.Sub(); break;
  1096. case '*': op = new ast.Mult(); break;
  1097. case '/': op = new ast.Div(); break;
  1098. case '//': op = new ast.FloorDiv(); break;
  1099. case '**': op = new ast.Pow(); break;
  1100. case '@': op = new ast.MatMult(); break;
  1101. case '&': op = new ast.BitAnd(); break;
  1102. case '^': op = new ast.BitXor(); break;
  1103. case '|': op = new ast.BitOr(); break;
  1104. case '%': op = new ast.Mod(); break;
  1105. case '>>': op = new ast.RShift(); break;
  1106. case '<<': op = new ast.LShift(); break;
  1107. default: break;
  1108. }
  1109. if (op) {
  1110. const left = stack.pop();
  1111. const right = this._parseExpression(precedence, terminal, tuple === true);
  1112. node = new ast.BinOp(left, op, right);
  1113. } else {
  1114. switch (token.value) {
  1115. case '==': op = new ast.Eq(); break;
  1116. case '!=': op = new ast.NotEq(); break;
  1117. case '>=': op = new ast.GtE(); break;
  1118. case '<=': op = new ast.LtE(); break;
  1119. case '<': op = new ast.Lt(); break;
  1120. case '>': op = new ast.Gt(); break;
  1121. case 'is': op = new ast.Is(); break;
  1122. case 'is not': op = new ast.IsNot(); break;
  1123. case 'in': op = new ast.In(); break;
  1124. case 'not in': op = new ast.NotIn(); break;
  1125. default: break;
  1126. }
  1127. const left = stack.pop();
  1128. const comparator = this._parseExpression(precedence, ['for', 'if'], tuple === true);
  1129. node = new ast.Compare(left, [op], [comparator]);
  1130. }
  1131. } else if (token.value === '*') {
  1132. const value = this._parseExpression(precedence, terminal, tuple === true);
  1133. node = new ast.Starred(value);
  1134. } else if (token.value === '**') {
  1135. const value = this._parseExpression(precedence, terminal, tuple === true);
  1136. node = new ast.keyword(null, value);
  1137. } else {
  1138. let op = null;
  1139. switch (token.value) {
  1140. case '-': op = new ast.USub(); break;
  1141. case '+': op = new ast.UAdd(); break;
  1142. case '~': op = new ast.Invert(); break;
  1143. case 'not': op = new ast.Not(); break;
  1144. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1145. }
  1146. const operand = this._parseExpression(precedence, terminal, tuple === true);
  1147. node = new ast.UnaryOp(op, operand);
  1148. node = this._mark(node, position);
  1149. }
  1150. stack.push(node);
  1151. continue;
  1152. }
  1153. }
  1154. if (this._tokenizer.accept(':=')) {
  1155. const target = stack.pop();
  1156. const value = this._parseExpression(-1, terminal, tuple !== false);
  1157. const node = new ast.NamedExpr(target, value);
  1158. this._mark(node, position);
  1159. stack.push(node);
  1160. continue;
  1161. }
  1162. if (this._tokenizer.accept('=')) {
  1163. const position = this._position();
  1164. const targets = stack.pop();
  1165. const value = this._parseExpression(-1, terminal, tuple !== false);
  1166. const node = new ast.Assign([targets], value);
  1167. this._mark(node, position);
  1168. stack.push(node);
  1169. continue;
  1170. }
  1171. let op = null;
  1172. switch (token.type) {
  1173. case '+=': op = new ast.Add(); break;
  1174. case '-=': op = new ast.Sub(); break;
  1175. case '**=': op = new ast.Pow(); break;
  1176. case '*=': op = new ast.Mult(); break;
  1177. case '//=': op = new ast.FloorDiv(); break;
  1178. case '/=': op = new ast.Div(); break;
  1179. case '&=': op = new ast.BitAnd(); break;
  1180. case '%=': op = new ast.Mod(); break;
  1181. case '^=': op = new ast.BitXor(); break;
  1182. case '<<=': op = new ast.LShift(); break;
  1183. case '>>=': op = new ast.RShift(); break;
  1184. case '|=': op = new ast.BitOr(); break;
  1185. case '@=': op = new ast.MatMul(); break;
  1186. default: break;
  1187. }
  1188. if (op) {
  1189. this._tokenizer.expect(token.type);
  1190. const target = stack.pop();
  1191. const value = this._parseExpression(-1, terminal, true);
  1192. const node = new ast.AugAssign(target, op, value);
  1193. stack.push(node);
  1194. continue;
  1195. }
  1196. position = this._position();
  1197. if (this._eat('id', 'if')) {
  1198. const body = stack.pop();
  1199. const test = this._parseExpression();
  1200. this._tokenizer.expect('id', 'else');
  1201. const orelse = this._parseExpression();
  1202. const node = new ast.IfExp(test, body, orelse);
  1203. this._mark(node, position);
  1204. stack.push(node);
  1205. continue;
  1206. }
  1207. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1208. const position = this._position();
  1209. const elt = stack.pop();
  1210. const generators = this._parseGenerators();
  1211. let node = null;
  1212. if (elt instanceof ast.Dict) {
  1213. if (elt.keys.length !== 1 || elt.values.length !== 1) {
  1214. throw new python.Error(`Invalid dict comprehension ${this._location()}`);
  1215. }
  1216. node = new ast.DictComp(elt.keys[0], elt.values[0], generators);
  1217. } else if (elt instanceof ast.Set) {
  1218. if (elt.elts.length !== 1) {
  1219. throw new python.Error(`Invalid set comprehension ${this._location()}`);
  1220. }
  1221. node = new ast.SetComp(elt.elts[0], generators);
  1222. } else {
  1223. node = new ast.GeneratorExp(elt, generators);
  1224. }
  1225. this._mark(node, position);
  1226. stack.push(node);
  1227. continue;
  1228. }
  1229. if (this._eat('id', 'lambda')) {
  1230. const args = this._parseArguments(':');
  1231. const body = this._parseExpression(-1, terminal, false);
  1232. const node = new ast.Lambda(args, body);
  1233. this._mark(node, position);
  1234. stack.push(node);
  1235. continue;
  1236. }
  1237. if (this._eat('id', 'yield')) {
  1238. if (this._tokenizer.accept('id', 'from')) {
  1239. const value = this._parseExpression(-1, [], true);
  1240. node = new ast.YieldFrom(value);
  1241. stack.push(node);
  1242. } else {
  1243. const value = [];
  1244. do {
  1245. value.push(this._parseExpression(-1, [], false));
  1246. }
  1247. while (this._tokenizer.accept(','));
  1248. node = new ast.Yield(value);
  1249. stack.push(node);
  1250. }
  1251. continue;
  1252. }
  1253. if (this._eat('id', 'await')) {
  1254. const value = this._parseExpression(minPrecedence, terminal, tuple);
  1255. const node = new ast.Await(value);
  1256. this._mark(node, position);
  1257. stack.push(node);
  1258. continue;
  1259. }
  1260. if (this._eat('.')) {
  1261. const value = stack.pop();
  1262. const attr = this._parseName().id;
  1263. const node = new ast.Attribute(value, attr);
  1264. this._mark(node, position);
  1265. stack.push(node);
  1266. continue;
  1267. }
  1268. if (this._tokenizer.peek().type === '(') {
  1269. const position = this._position();
  1270. const args = [];
  1271. const keywords = [];
  1272. this._tokenizer.expect('(');
  1273. let tuple = false;
  1274. while (!this._tokenizer.accept(')')) {
  1275. if (this._tokenizer.accept('\n')) {
  1276. continue;
  1277. }
  1278. const position = this._position();
  1279. const expr = this._parseExpression(-1, [], false);
  1280. if (expr === null) {
  1281. throw new python.Error(`Expected expression ${this._location()}`);
  1282. }
  1283. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1284. const [target] = expr.targets;
  1285. if (target instanceof ast.Name === false) {
  1286. throw new python.Error(`Expected name ${this._location()}`);
  1287. }
  1288. const node = new ast.keyword(target.id, expr.value);
  1289. this._mark(node, position);
  1290. keywords.push(node);
  1291. } else {
  1292. args.push(expr);
  1293. }
  1294. if (this._tokenizer.accept(',')) {
  1295. tuple = true;
  1296. } else {
  1297. this._tokenizer.accept('\n');
  1298. this._tokenizer.expect(')');
  1299. break;
  1300. }
  1301. }
  1302. if (stack.length === 0 && keywords.length === 0) {
  1303. node = args.length === 1 && !tuple ? args[0] : new ast.Tuple(args);
  1304. this._mark(node, position);
  1305. } else {
  1306. const func = stack.pop();
  1307. node = new ast.Call(func, args, keywords);
  1308. let start = func;
  1309. while (start instanceof ast.Attribute) {
  1310. start = start.value;
  1311. }
  1312. position.lineno = start.lineno;
  1313. position.col_offset = start.col_offset;
  1314. this._mark(node, position);
  1315. }
  1316. stack.push(node);
  1317. continue;
  1318. }
  1319. if (this._tokenizer.peek().type === '[') {
  1320. if (stack.length === 0) {
  1321. stack.push(this._parseList());
  1322. } else {
  1323. const value = stack.pop();
  1324. const position = this._position();
  1325. const slice = this._parseSlice();
  1326. node = new ast.Subscript(value, slice);
  1327. this._mark(node, position);
  1328. stack.push(node);
  1329. }
  1330. continue;
  1331. }
  1332. if (this._tokenizer.peek().type === '{') {
  1333. const elts = [];
  1334. const keys = [];
  1335. const values = [];
  1336. this._tokenizer.expect('{');
  1337. let dict = true;
  1338. while (!this._tokenizer.accept('}')) {
  1339. const item = this._parseExpression(-1, [], false);
  1340. if (item === null) {
  1341. throw new python.Error(`Expected expression ${this._location()}`);
  1342. }
  1343. if (!this._tokenizer.accept(':')) {
  1344. dict = false;
  1345. }
  1346. if (dict) {
  1347. const value = this._parseExpression(-1, ['for'], false);
  1348. if (value === null) {
  1349. throw new python.Error(`Expected expression ${this._location()}`);
  1350. }
  1351. if (this._eat('id', 'for')) {
  1352. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1353. throw new python.Error(`Invalid list expression ${this._location()}`);
  1354. }
  1355. const target = this._parseExpression(-1, ['in'], true);
  1356. this._tokenizer.expect('id', 'in');
  1357. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1358. const ifs = [];
  1359. while (this._tokenizer.accept('id', 'if')) {
  1360. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1361. }
  1362. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1363. const generators = [comprehension];
  1364. this._tokenizer.expect('}');
  1365. return new ast.DictComp(item, value, generators);
  1366. }
  1367. keys.push(item);
  1368. values.push(value);
  1369. } else {
  1370. elts.push(item);
  1371. }
  1372. this._tokenizer.accept(',');
  1373. this._tokenizer.accept('\n');
  1374. if (this._tokenizer.accept('}')) {
  1375. break;
  1376. }
  1377. }
  1378. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1379. throw new python.Error(`Invalid set expression ${this._location()}`);
  1380. }
  1381. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1382. stack.push(node);
  1383. continue;
  1384. }
  1385. const literal = this._parseLiteral();
  1386. if (literal) {
  1387. if (stack.length > 0 &&
  1388. (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') &&
  1389. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  1390. const op = literal.value < 0 ? new ast.Sub() : new ast.Add();
  1391. const left = stack.pop();
  1392. const right = new ast.Constant(Math.abs(literal.value));
  1393. node = new ast.BinOp(left, op, right);
  1394. stack.push(node);
  1395. } else if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1396. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1397. } else {
  1398. let value = literal.value;
  1399. if (literal.type === 'int' || literal.type === 'float' || literal.type === 'complex') {
  1400. switch (value) {
  1401. case 'inf': value = Infinity; break;
  1402. case '-inf': value = -Infinity; break;
  1403. default: value = Number(value); break;
  1404. }
  1405. } else if (literal.type === 'str') {
  1406. value = literal.value.substring(1, literal.value.length - 1);
  1407. } else {
  1408. throw new python.Error(`Invalid literal ${this._location()}`);
  1409. }
  1410. const node = new ast.Constant(value, literal.type);
  1411. this._mark(node, position);
  1412. stack.push(node);
  1413. }
  1414. continue;
  1415. }
  1416. if (this._eat('id', 'False')) {
  1417. const node = new ast.Constant(false, 'bool');
  1418. this._mark(node, position);
  1419. stack.push(node);
  1420. continue;
  1421. }
  1422. if (this._eat('id', 'True')) {
  1423. const node = new ast.Constant(true, 'bool');
  1424. this._mark(node, position);
  1425. stack.push(node);
  1426. continue;
  1427. }
  1428. if (this._eat('id', 'None')) {
  1429. const node = new ast.Constant(null);
  1430. this._mark(node, position);
  1431. stack.push(node);
  1432. continue;
  1433. }
  1434. if (this._tokenizer.peek().keyword) {
  1435. break;
  1436. }
  1437. if (this._eat('...')) {
  1438. const node = new ast.Ellipsis();
  1439. this._mark(node, position);
  1440. stack.push(node);
  1441. continue;
  1442. }
  1443. const name = this._parseName();
  1444. if (name) {
  1445. stack.push(name);
  1446. continue;
  1447. }
  1448. if (tuple === true && stack.length === 1 && this._tokenizer.accept(',')) {
  1449. if (stack[0] instanceof ast.Tuple) {
  1450. [node] = stack;
  1451. } else {
  1452. const position = this._position();
  1453. const elts = [stack.pop()];
  1454. node = new ast.Tuple(elts);
  1455. this._mark(node, position);
  1456. stack.push(node);
  1457. }
  1458. // for, bar, = <expr>
  1459. if (this._tokenizer.peek().type === '=') {
  1460. continue;
  1461. }
  1462. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1463. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1464. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1465. if (expression) {
  1466. node.elts.push(expression);
  1467. continue;
  1468. }
  1469. }
  1470. break;
  1471. }
  1472. break;
  1473. }
  1474. if (stack.length === 1) {
  1475. return stack.pop();
  1476. }
  1477. if (stack.length !== 0) {
  1478. throw new python.Error(`Unexpected expression ${this._location()}`);
  1479. }
  1480. return null;
  1481. }
  1482. _decorator() {
  1483. const list = [];
  1484. while (this._tokenizer.accept('@')) {
  1485. const value = this._parseExpression();
  1486. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1487. throw new python.Error(`Invalid decorator ${this._location()}`);
  1488. }
  1489. this._tokenizer.accept('\n');
  1490. list.push(value);
  1491. }
  1492. return list;
  1493. }
  1494. _parseGenerators() {
  1495. const generators = [];
  1496. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1497. const is_async = this._eat('id', 'async') ? 1 : 0;
  1498. this._tokenizer.expect('id', 'for');
  1499. const target = this._parseExpression(-1, ['in'], true);
  1500. this._tokenizer.expect('id', 'in');
  1501. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1502. const ifs = [];
  1503. while (this._tokenizer.accept('id', 'if')) {
  1504. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1505. }
  1506. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1507. generators.push(comprehension);
  1508. }
  1509. return generators;
  1510. }
  1511. _parseList() {
  1512. const elts = [];
  1513. this._tokenizer.expect('[');
  1514. if (!this._tokenizer.match(']')) {
  1515. const position = this._position();
  1516. const expr = this._parseExpression(-1, ['for']);
  1517. if (this._tokenizer.match('id', 'for')) {
  1518. const generators = this._parseGenerators();
  1519. this._tokenizer.expect(']');
  1520. const node = new ast.ListComp(expr, generators);
  1521. this._mark(node, position);
  1522. return node;
  1523. }
  1524. if (expr === null) {
  1525. throw new python.Error(`Expected expression ${this._location()}`);
  1526. }
  1527. elts.push(expr);
  1528. while (this._tokenizer.accept(',')) {
  1529. if (this._tokenizer.match(']')) {
  1530. break;
  1531. }
  1532. const expr = this._parseExpression(-1, ['for']);
  1533. if (!expr) {
  1534. throw new python.Error(`Expected expression ${this._location()}`);
  1535. }
  1536. elts.push(expr);
  1537. }
  1538. }
  1539. this._tokenizer.expect(']');
  1540. return new ast.List(elts);
  1541. }
  1542. _parseSlice() {
  1543. const elts = [];
  1544. let slice = [null, null, null];
  1545. let index = 0;
  1546. let valid = false;
  1547. this._tokenizer.expect('[');
  1548. while (true) {
  1549. if (this._tokenizer.accept(':')) {
  1550. index++;
  1551. valid = true;
  1552. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1553. if (!valid || index > 2) {
  1554. throw new python.Error(`Invalid slice at ${this._location()}`);
  1555. }
  1556. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1557. slice = [null, null, null];
  1558. index = 0;
  1559. if (this._tokenizer.accept(']')) {
  1560. break;
  1561. }
  1562. this._tokenizer.expect(',');
  1563. } else {
  1564. const expression = this._parseExpression();
  1565. if (expression === null) {
  1566. throw new python.Error(`Expected expression ${this._location()}`);
  1567. }
  1568. slice[index] = expression;
  1569. valid = true;
  1570. }
  1571. }
  1572. if (elts.length > 1) {
  1573. return new ast.Tuple(elts);
  1574. }
  1575. return elts[0];
  1576. }
  1577. _parseName(required) {
  1578. const token = this._tokenizer.peek();
  1579. if (token.type === 'id' && !token.keyword) {
  1580. const position = this._position();
  1581. this._tokenizer.read();
  1582. const node = new ast.Name(token.value);
  1583. return this._mark(node, position);
  1584. }
  1585. if (required) {
  1586. throw new python.Error(`Invalid syntax ${this._location()}`);
  1587. }
  1588. return null;
  1589. }
  1590. _parseDottedName() {
  1591. const list = [];
  1592. do {
  1593. const name = this._parseName(true);
  1594. list.push(name.id);
  1595. }
  1596. while (this._tokenizer.accept('.'));
  1597. return list.join('.');
  1598. }
  1599. _parseLiteral() {
  1600. const token = this._tokenizer.peek();
  1601. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1602. this._tokenizer.read();
  1603. return token;
  1604. }
  1605. return null;
  1606. }
  1607. _parseTypeArguments() {
  1608. const list = [];
  1609. this._tokenizer.expect('[');
  1610. while (!this._tokenizer.accept(']')) {
  1611. const type = this._parseType();
  1612. if (type === null) {
  1613. throw new python.Error(`Expected type ${this._location()}`);
  1614. }
  1615. list.push(type);
  1616. if (!this._tokenizer.accept(',')) {
  1617. this._tokenizer.expect(']');
  1618. break;
  1619. }
  1620. }
  1621. return list;
  1622. }
  1623. _parseType() {
  1624. const target = this._parseExpression(-1, ['[', '=']);
  1625. if (target) {
  1626. if (this._tokenizer.peek().value === '[') {
  1627. const list = this._parseList();
  1628. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1629. return new ast.Subscript(target, slice);
  1630. }
  1631. return target;
  1632. }
  1633. return null;
  1634. }
  1635. _parseArguments(terminal) {
  1636. let posonlyargs = [];
  1637. let args = [];
  1638. let vararg = null;
  1639. const kwonlyargs = [];
  1640. const kw_defaults = [];
  1641. let kwarg = null;
  1642. const defaults = [];
  1643. let is_slash = false;
  1644. let is_vararg = false; // '*'
  1645. let is_kwarg = false; // '**'
  1646. const read = (required) => {
  1647. const name = this._parseName(required);
  1648. if (name) {
  1649. const annotation = terminal !== ':' && this._tokenizer.accept(':') ? this._parseType() : null;
  1650. return new ast.arg(name.id, annotation, null);
  1651. }
  1652. return null;
  1653. };
  1654. while (!this._tokenizer.accept(terminal)) {
  1655. this._tokenizer.accept('\n');
  1656. if (this._tokenizer.accept('/')) {
  1657. if (is_slash || is_vararg || is_kwarg) {
  1658. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1659. }
  1660. is_slash = true;
  1661. } else if (this._tokenizer.accept('*')) {
  1662. if (is_vararg) {
  1663. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1664. }
  1665. is_vararg = true;
  1666. const arg = read(false);
  1667. vararg = arg ? arg : vararg;
  1668. } else if (this._tokenizer.accept('**')) {
  1669. if (is_kwarg) {
  1670. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1671. }
  1672. is_kwarg = true;
  1673. kwarg = read(true);
  1674. } else {
  1675. const arg = read(false);
  1676. if (!arg) {
  1677. this._tokenizer.expect(terminal);
  1678. break;
  1679. }
  1680. const default_value = this._tokenizer.accept('=') ? this._parseExpression() : null;
  1681. if (!is_vararg && !is_kwarg) {
  1682. if (is_slash) {
  1683. args.push(arg);
  1684. } else {
  1685. posonlyargs.push(arg);
  1686. }
  1687. if (default_value !== null) {
  1688. defaults.push(default_value);
  1689. }
  1690. } else if (is_vararg && !is_kwarg) {
  1691. kwonlyargs.push(arg);
  1692. kw_defaults.push(default_value);
  1693. } else {
  1694. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1695. }
  1696. }
  1697. this._tokenizer.accept('\n');
  1698. if (!this._tokenizer.accept(',')) {
  1699. this._tokenizer.expect(terminal);
  1700. break;
  1701. }
  1702. }
  1703. if (!is_slash) {
  1704. args = posonlyargs.concat(args);
  1705. posonlyargs = [];
  1706. }
  1707. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1708. }
  1709. _eat(type, value) {
  1710. if (this._tokenizer.match(type, value)) {
  1711. const position = this._position();
  1712. this._tokenizer.expect(type, value);
  1713. return position;
  1714. }
  1715. return null;
  1716. }
  1717. _mark(node, position) {
  1718. node.filename = position.filename;
  1719. node.lineno = position.lineno;
  1720. node.col_offset = position.col_offset;
  1721. node.end_lineno = this._tokenizer.lineno;
  1722. node.end_col_offset = this._tokenizer.col_offset;
  1723. return node;
  1724. }
  1725. _position() {
  1726. return {
  1727. filename: this._tokenizer.filename,
  1728. lineno: this._tokenizer.lineno,
  1729. col_offset: this._tokenizer.col_offset
  1730. };
  1731. }
  1732. _location() {
  1733. return this._tokenizer.location();
  1734. }
  1735. });
  1736. this.registerType('ast._Tokenizer', class {
  1737. constructor(text, file) {
  1738. this._text = text;
  1739. this.filename = file;
  1740. this.linepos = 0;
  1741. this.lineno = 1;
  1742. this._position = 0;
  1743. this._token = { type: '', value: '' };
  1744. this._brackets = 0;
  1745. this._indentation = [];
  1746. this._outdent = 0;
  1747. if (!ast._Tokenizer._whitespace) {
  1748. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1749. 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';
  1750. 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';
  1751. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1752. /* eslint-disable no-misleading-character-class */
  1753. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1754. /* eslint-enable no-misleading-character-class */
  1755. }
  1756. }
  1757. peek() {
  1758. if (!this._cache) {
  1759. this._tokenize();
  1760. this._cache = true;
  1761. }
  1762. return this._token;
  1763. }
  1764. read() {
  1765. if (!this._cache) {
  1766. this._tokenize();
  1767. }
  1768. const next = this._position + this._token.value.length;
  1769. while (this._position < next) {
  1770. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1771. this._position = this._newLine(this._position);
  1772. this.linepos = this._position;
  1773. this.lineno++;
  1774. } else {
  1775. this._position++;
  1776. }
  1777. }
  1778. this._cache = false;
  1779. return this._token;
  1780. }
  1781. match(type, value) {
  1782. const token = this.peek();
  1783. if (token.type === type && (!value || token.value === value)) {
  1784. return true;
  1785. }
  1786. return false;
  1787. }
  1788. accept(type, value) {
  1789. const token = this.peek();
  1790. if (token.type === type && (!value || token.value === value)) {
  1791. this.read();
  1792. return true;
  1793. }
  1794. return false;
  1795. }
  1796. expect(type, value) {
  1797. const token = this.peek();
  1798. if (token.type !== type) {
  1799. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1800. }
  1801. if (value && token.value !== value) {
  1802. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1803. }
  1804. this.read();
  1805. }
  1806. location() {
  1807. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1808. }
  1809. get col_offset() {
  1810. return this._position - this.linepos + 1;
  1811. }
  1812. static _isSpace(c) {
  1813. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1814. return true;
  1815. }
  1816. if (c.charCodeAt(0) >= 0x1680) {
  1817. return ast._Tokenizer._whitespace.test(c);
  1818. }
  1819. return false;
  1820. }
  1821. static _isNewline(c) {
  1822. switch (c) {
  1823. case '\n':
  1824. case '\r':
  1825. case '\u2028': // 8232
  1826. case '\u2029': // 8233
  1827. return true;
  1828. default:
  1829. return false;
  1830. }
  1831. }
  1832. static _isIdentifierStartChar(c) {
  1833. if (c < 'A') {
  1834. return c === '$';
  1835. }
  1836. if (c <= 'Z') {
  1837. return true;
  1838. }
  1839. if (c < 'a') {
  1840. return c === '_';
  1841. }
  1842. if (c <= 'z') {
  1843. return true;
  1844. }
  1845. const code = c.charCodeAt(0);
  1846. if (code >= 0xAA) {
  1847. return ast._Tokenizer._identifierStart.test(c);
  1848. }
  1849. return false;
  1850. }
  1851. static _isIdentifierChar(c) {
  1852. if (c < '0') {
  1853. return c === '$';
  1854. }
  1855. if (c <= '9') {
  1856. return true;
  1857. }
  1858. if (c < 'A') {
  1859. return false;
  1860. }
  1861. if (c <= 'Z') {
  1862. return true;
  1863. }
  1864. if (c < 'a') {
  1865. return c === '_';
  1866. }
  1867. if (c <= 'z') {
  1868. return true;
  1869. }
  1870. const code = c.charCodeAt(0);
  1871. if (code >= 0xAA) {
  1872. return ast._Tokenizer._identifierChar.test(c);
  1873. }
  1874. return false;
  1875. }
  1876. _get(position) {
  1877. return position >= this._text.length ? '\0' : this._text[position];
  1878. }
  1879. _skipLine() {
  1880. while (this._position < this._text.length) {
  1881. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1882. break;
  1883. }
  1884. this._position++;
  1885. }
  1886. }
  1887. _skipWhitespace() {
  1888. while (this._position < this._text.length) {
  1889. const c = this._text[this._position];
  1890. if (c === '#') {
  1891. this._skipLine();
  1892. } else if (ast._Tokenizer._isSpace(c)) {
  1893. this._position++;
  1894. } else if (c === '\\') {
  1895. // Explicit Line Continuation
  1896. this._position++;
  1897. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1898. this._position = this._newLine(this._position);
  1899. this.linepos = this._position;
  1900. this.lineno += 1;
  1901. } else {
  1902. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1903. }
  1904. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1905. // Implicit Line Continuation
  1906. this._position = this._newLine(this._position);
  1907. this.linepos = this._position;
  1908. this.lineno += 1;
  1909. } else {
  1910. break;
  1911. }
  1912. }
  1913. }
  1914. _newLine(position) {
  1915. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1916. return position + 2;
  1917. }
  1918. return position + 1;
  1919. }
  1920. _tokenize() {
  1921. if (this._token.type !== '\n') {
  1922. this._skipWhitespace();
  1923. }
  1924. if (this._token.type === 'dedent') {
  1925. this._indentation.pop();
  1926. this._outdent--;
  1927. if (this._outdent > 0) {
  1928. this._token = { type: 'dedent', value: '' };
  1929. return;
  1930. }
  1931. }
  1932. if (this._token.type === '\n') {
  1933. let indent = '';
  1934. let i = this._position;
  1935. while (i < this._text.length) {
  1936. const c = this._text[i];
  1937. if (ast._Tokenizer._isSpace(c)) {
  1938. indent += c;
  1939. i++;
  1940. } else if (ast._Tokenizer._isNewline(c)) {
  1941. indent = '';
  1942. i = this._newLine(i);
  1943. this._position = i;
  1944. this.linepos = i;
  1945. this.lineno += 1;
  1946. } else if (c === '#') {
  1947. indent = '';
  1948. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1949. i++;
  1950. }
  1951. continue;
  1952. } else {
  1953. break;
  1954. }
  1955. }
  1956. let type = null;
  1957. if (indent.length > 0) {
  1958. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1959. if (indent.length > current.length) {
  1960. type = 'indent';
  1961. this._indentation.push(indent);
  1962. } else if (indent.length > 0 && indent.length < current.length) {
  1963. type = 'dedent';
  1964. this._outdent = 0;
  1965. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1966. this._outdent++;
  1967. }
  1968. } else {
  1969. this._position += indent.length;
  1970. }
  1971. } else if (i >= this._text.length) {
  1972. this._token = { type: 'eof', value: '' };
  1973. return;
  1974. } else if (this._indentation.length > 0) {
  1975. type = 'dedent';
  1976. this._outdent = this._indentation.length;
  1977. }
  1978. if (type === 'indent' || type === 'dedent') {
  1979. this._token = { type, value: indent };
  1980. return;
  1981. }
  1982. }
  1983. if (this._position >= this._text.length) {
  1984. this._token = { type: 'eof', value: '' };
  1985. return;
  1986. }
  1987. const c = this._get(this._position);
  1988. const string = this._string();
  1989. if (string) {
  1990. this._token = string;
  1991. return;
  1992. }
  1993. switch (c) {
  1994. case '(':
  1995. case '[':
  1996. case '{':
  1997. this._brackets++;
  1998. this._token = { type: c, value: c };
  1999. return;
  2000. case ')':
  2001. case ']':
  2002. case '}':
  2003. if (this._brackets === 0) {
  2004. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  2005. }
  2006. this._brackets--;
  2007. this._token = { type: c, value: c };
  2008. return;
  2009. case ',':
  2010. case ';':
  2011. case '?':
  2012. this._token = { type: c, value: c };
  2013. return;
  2014. default: {
  2015. const number = this._number();
  2016. if (number) {
  2017. this._token = number;
  2018. return;
  2019. }
  2020. if (c === '.') {
  2021. let end = this._position + 1;
  2022. while (this._get(end) === '.') {
  2023. end++;
  2024. }
  2025. const text = this._text.substring(this._position, end);
  2026. this._token = { type: text, value: text };
  2027. return;
  2028. }
  2029. const identifier = this._identifier();
  2030. if (identifier) {
  2031. this._token = identifier;
  2032. return;
  2033. }
  2034. const operator = this._operator();
  2035. if (operator) {
  2036. this._token = operator;
  2037. return;
  2038. }
  2039. break;
  2040. }
  2041. }
  2042. if (c === '.') {
  2043. this._token = { type: c, value: c };
  2044. return;
  2045. }
  2046. if (c === '\\') {
  2047. this._token = { type: '\\', value: c };
  2048. return;
  2049. }
  2050. if (ast._Tokenizer._isNewline(c)) {
  2051. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2052. return;
  2053. }
  2054. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2055. }
  2056. _number() {
  2057. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2058. const binary = (c) => c === '0' || c === '1' || c === '_';
  2059. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2060. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2061. let c = this._get(this._position);
  2062. const sign = (c === '-' || c === '+') ? 1 : 0;
  2063. let i = this._position + sign;
  2064. c = this._get(i);
  2065. if (c === '0') {
  2066. let radix = 0;
  2067. const n = this._get(i + 1);
  2068. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2069. i += 2;
  2070. while (hex(this._get(i))) {
  2071. i += 1;
  2072. }
  2073. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2074. i += 1;
  2075. }
  2076. radix = 16;
  2077. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2078. i += 2;
  2079. while (binary(this._get(i))) {
  2080. i++;
  2081. }
  2082. radix = 2;
  2083. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2084. i += 2;
  2085. while (octal(this._get(i))) {
  2086. i++;
  2087. }
  2088. radix = 8;
  2089. } else if (n >= '0' && n <= '7') {
  2090. i++;
  2091. while (octal(this._get(i))) {
  2092. i += 1;
  2093. }
  2094. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2095. i += 1;
  2096. }
  2097. radix = 8;
  2098. }
  2099. if (radix > 0 && this._get(i) !== '.') {
  2100. const radixText = this._text.substring(this._position, i);
  2101. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2102. if (!isNaN(parseInt(radixParseText, radix))) {
  2103. return { type: 'int', value: radixText };
  2104. }
  2105. }
  2106. }
  2107. i = this._position + sign;
  2108. let isDecimal = false;
  2109. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2110. while (decimal(this._get(i))) {
  2111. i++;
  2112. }
  2113. c = this._get(i).toLowerCase();
  2114. isDecimal = c !== '.' && c !== 'e';
  2115. }
  2116. if (this._get(i) === '0') {
  2117. i++;
  2118. c = this._get(i).toLowerCase();
  2119. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2120. }
  2121. if (isDecimal) {
  2122. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2123. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2124. }
  2125. // if (this._get(i) === 'l' || this._get(i) === 'L') {
  2126. // Python 2 long integer
  2127. // }
  2128. const intText = this._text.substring(this._position, i);
  2129. if (!isNaN(parseInt(intText, 10))) {
  2130. return { type: 'int', value: intText };
  2131. }
  2132. }
  2133. i = this._position + sign;
  2134. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2135. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2136. while (decimal(this._get(i))) {
  2137. i++;
  2138. }
  2139. if (this._get(i) === '.') {
  2140. i++;
  2141. }
  2142. while (decimal(this._get(i))) {
  2143. i++;
  2144. }
  2145. if (i > (this._position + sign)) {
  2146. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2147. i++;
  2148. if (this._get(i) === '-' || this._get(i) === '+') {
  2149. i++;
  2150. }
  2151. if (decimal(this._get(i))) {
  2152. while (decimal(this._get(i))) {
  2153. i++;
  2154. }
  2155. } else {
  2156. i = this._position;
  2157. }
  2158. } else {
  2159. while (decimal(this._get(i))) {
  2160. i++;
  2161. }
  2162. }
  2163. }
  2164. if (i > (this._position + sign)) {
  2165. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2166. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2167. }
  2168. const floatText = this._text.substring(this._position, i);
  2169. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2170. if (!isNaN(parseFloat(floatParseText))) {
  2171. return { type: 'float', value: floatText };
  2172. }
  2173. }
  2174. }
  2175. return null;
  2176. }
  2177. _identifier() {
  2178. let i = this._position;
  2179. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2180. i++;
  2181. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2182. i++;
  2183. }
  2184. }
  2185. if (i > this._position) {
  2186. const text = this._text.substring(this._position, i);
  2187. let keyword = false;
  2188. switch (text) {
  2189. case 'and':
  2190. case 'as':
  2191. case 'else':
  2192. case 'For':
  2193. case 'If':
  2194. case 'Import':
  2195. case 'in':
  2196. case 'is':
  2197. case 'not':
  2198. case 'or':
  2199. keyword = true;
  2200. break;
  2201. default:
  2202. break;
  2203. }
  2204. return { type: 'id', value: text, keyword };
  2205. }
  2206. return null;
  2207. }
  2208. _operator() {
  2209. let length = 0;
  2210. const c0 = this._get(this._position);
  2211. const c1 = this._get(this._position + 1);
  2212. const c2 = this._get(this._position + 2);
  2213. switch (c0) {
  2214. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2215. length = c1 === '=' ? 2 : 1;
  2216. break;
  2217. case '-':
  2218. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2219. break;
  2220. case '*':
  2221. switch (c1) {
  2222. case '*': length = c2 === '=' ? 3 : 2; break;
  2223. case '=': length = 2; break;
  2224. default: length = 1; break;
  2225. }
  2226. break;
  2227. case '/':
  2228. switch (c1) {
  2229. case '/': length = c2 === '=' ? 3 : 2; break;
  2230. case '=': length = 2; break;
  2231. default: length = 1; break;
  2232. }
  2233. break;
  2234. case '<':
  2235. switch (c1) {
  2236. case '>': length = 2; break;
  2237. case '<': length = c2 === '=' ? 3 : 2; break;
  2238. case '=': length = 2; break;
  2239. default: length = 1; break;
  2240. }
  2241. break;
  2242. case '>':
  2243. switch (c1) {
  2244. case '>': length = c2 === '=' ? 3 : 2; break;
  2245. case '=': length = 2; break;
  2246. default: length = 1; break;
  2247. }
  2248. break;
  2249. case '@':
  2250. length = c1 === '=' ? 2 : 1;
  2251. break;
  2252. case ':':
  2253. length = c1 === '=' ? 2 : 1;
  2254. break;
  2255. default:
  2256. return null;
  2257. }
  2258. const text = this._text.substring(this._position, this._position + length);
  2259. return { type: text, value: text };
  2260. }
  2261. _string() {
  2262. let i = this._position;
  2263. let prefix = -1;
  2264. if (this._get(i) === "'" || this._get(i) === '"') {
  2265. prefix = '';
  2266. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2267. const c = this._get(i);
  2268. const cc = c.toLowerCase();
  2269. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2270. prefix = c;
  2271. }
  2272. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2273. const c = this._text.substring(this._position, this._position + 2);
  2274. const cc = c.toLowerCase();
  2275. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2276. prefix = c;
  2277. }
  2278. }
  2279. if (prefix.length >= 0) {
  2280. i += prefix.length;
  2281. let quote = '';
  2282. let count = 0;
  2283. const q0 = this._get(i);
  2284. const q1 = this._get(i + 1);
  2285. const q2 = this._get(i + 2);
  2286. switch (q0) {
  2287. case "'":
  2288. quote = q0;
  2289. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2290. break;
  2291. case '"':
  2292. quote = q0;
  2293. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2294. break;
  2295. default:
  2296. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2297. }
  2298. i += count;
  2299. if (count === 1) {
  2300. while (i < this._text.length) {
  2301. if (this._text[i] === quote) {
  2302. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2303. } else if (this._text[i] === '\\' &&
  2304. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2305. i += 2;
  2306. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2307. break;
  2308. } else {
  2309. i++;
  2310. }
  2311. }
  2312. } else if (count === 3) {
  2313. while (i < this._text.length) {
  2314. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2315. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2316. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2317. i += 2;
  2318. continue;
  2319. }
  2320. i++;
  2321. }
  2322. }
  2323. }
  2324. i = this._position;
  2325. if (this._get(i) === '`') {
  2326. i++;
  2327. while (i < this._text.length) {
  2328. if (this._text[i] === '`') {
  2329. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2330. }
  2331. i++;
  2332. }
  2333. }
  2334. return null;
  2335. }
  2336. });
  2337. this.registerType('builtins.dict', dict);
  2338. this.registerType('builtins.ellipsis', class {});
  2339. this.registerType('builtins.cell', class {});
  2340. this.registerType('builtins.list', class extends Array {
  2341. constructor(iterable) {
  2342. super();
  2343. if (Array.isArray(iterable)) {
  2344. this.push(...iterable);
  2345. }
  2346. }
  2347. });
  2348. this.registerType('builtins.number', class {});
  2349. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2350. return execution.__import__(name, globals, locals, fromlist, level);
  2351. });
  2352. this.registerType('builtins.bool', class extends Boolean {
  2353. constructor(value) {
  2354. if (value && value.__bool__) {
  2355. value = value.__bool__();
  2356. } else if (value && value.__len__) {
  2357. value = value.__len__() > 0;
  2358. } else {
  2359. value = value ? true : false;
  2360. }
  2361. super(value);
  2362. }
  2363. });
  2364. this.registerType('builtins.int', class extends Number {
  2365. constructor(value) {
  2366. if (value && value.__int__) {
  2367. value = value.__int__();
  2368. } else if (!Number.isInteger(value)) {
  2369. value = NaN;
  2370. }
  2371. super(value);
  2372. }
  2373. });
  2374. this.registerType('builtins.float', class extends Number {
  2375. constructor(value) {
  2376. if (value && value.__float__) {
  2377. value = value.__float__();
  2378. } else if (Number(value) !== value) {
  2379. value = NaN;
  2380. }
  2381. super(value);
  2382. }
  2383. });
  2384. this.registerType('builtins.long', class extends Number {
  2385. constructor(value) {
  2386. if (value && value.__int__) {
  2387. value = value.__int__();
  2388. } else if (!Number.isInteger(value)) {
  2389. value = NaN;
  2390. }
  2391. super(value);
  2392. }
  2393. });
  2394. this.registerType('builtins.str', class extends String {
  2395. constructor(value) {
  2396. if (value && value.__str__) {
  2397. value = value.__str__();
  2398. } else if (typeof value !== 'string') {
  2399. value = JSON.stringify(value);
  2400. }
  2401. super(value);
  2402. }
  2403. });
  2404. this.registerType('builtins.complex', class {
  2405. constructor(real, imaginary) {
  2406. this.real = real;
  2407. this.imag = imaginary;
  2408. }
  2409. });
  2410. this.registerType('builtins.NoneType', class {});
  2411. this.registerType('builtins.object', class {
  2412. static __new__(cls, ...args) {
  2413. return execution.invoke(cls, args);
  2414. }
  2415. static __setattr__(obj, name, value) {
  2416. builtins.setattr(obj, name, value);
  2417. }
  2418. });
  2419. this.registerType('builtins.tuple', class extends Array {
  2420. constructor(items) {
  2421. super(items ? items.length : 0);
  2422. if (items) {
  2423. for (let i = 0; i < items.length; i++) {
  2424. this[i] = items[i];
  2425. }
  2426. }
  2427. }
  2428. });
  2429. this.registerType('builtins.staticmethod', class {});
  2430. this.registerType('builtins.Warning', class {});
  2431. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2432. this.registerType('builtins.BaseException', class {});
  2433. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2434. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2435. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2436. this.registerFunction('builtins.print', () => {});
  2437. this.registerFunction('builtins.unicode');
  2438. builtins.Ellipsis = new builtins.ellipsis();
  2439. this.registerType('typing._Final', class {});
  2440. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2441. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2442. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2443. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2444. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2445. this.registerType('typing._CallableType', class {});
  2446. this.registerFunction('typing.cast');
  2447. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2448. typing.Callable = Reflect.construct(typing._CallableType, []);
  2449. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2450. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2451. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2452. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2453. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2454. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2455. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2456. this.registerType('enum.Enum', class {
  2457. // __reduce_ex__(proto) {
  2458. // return self.__class__, (self._value_, )
  2459. // }
  2460. });
  2461. this.registerFunction('operator.add');
  2462. this.registerFunction('operator.and_');
  2463. this.registerFunction('operator.and_');
  2464. this.registerFunction('operator.eq');
  2465. this.registerFunction('operator.floordiv');
  2466. this.registerFunction('operator.ge');
  2467. this.registerFunction('operator.getitem');
  2468. this.registerFunction('operator.gt');
  2469. this.registerFunction('operator.le');
  2470. this.registerFunction('operator.lt');
  2471. this.registerFunction('operator.mod');
  2472. this.registerFunction('operator.mul');
  2473. this.registerFunction('operator.ne');
  2474. this.registerFunction('operator.neg');
  2475. this.registerFunction('operator.or_');
  2476. this.registerFunction('operator.pos');
  2477. this.registerFunction('operator.pow');
  2478. this.registerFunction('operator.sub');
  2479. this.registerFunction('operator.truediv');
  2480. this.registerFunction('sys.path.append', () => {});
  2481. this.registerFunction('sys.path.insert', () => {});
  2482. this.registerType('argparse.Namespace', class {
  2483. constructor(args) {
  2484. this.args = args;
  2485. }
  2486. });
  2487. this.registerType('catboost._catboost._CatBoost', class {
  2488. _deserialize_model(/* serialized_model_str */) {
  2489. }
  2490. });
  2491. this.registerType('catboost.core._CatBoostBase', class {
  2492. constructor() {
  2493. this._object = new catboost._catboost._CatBoost();
  2494. }
  2495. __setstate__(state) {
  2496. for (const [key, value] of state) {
  2497. if (key === '__model') {
  2498. this._load_from_string(value);
  2499. continue;
  2500. }
  2501. this[key] = value;
  2502. }
  2503. }
  2504. _load_from_string(dump_model_str) {
  2505. this._deserialize_model(dump_model_str);
  2506. }
  2507. _deserialize_model(dump_model_str) {
  2508. this._object._deserialize_model(dump_model_str);
  2509. }
  2510. });
  2511. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2512. load_model(/* blob */) {
  2513. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2514. // this._load_from_string(blob);
  2515. }
  2516. });
  2517. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2518. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2519. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2520. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2521. catboost.CatBoost = catboost.core.CatBoost;
  2522. this.registerType('collections.deque', class extends Array {
  2523. constructor(iterable) {
  2524. super();
  2525. if (Array.isArray(iterable)) {
  2526. for (const value of iterable) {
  2527. this.push(value);
  2528. }
  2529. }
  2530. }
  2531. });
  2532. this.registerType('collections.OrderedDict', class extends dict {});
  2533. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2534. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2535. this.registerType('cuml.internals.array.CumlArray', class {});
  2536. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2537. this.registerType('cuml.raft.common.handle.Handle', class {
  2538. __setstate__(state) {
  2539. this._handle = state;
  2540. }
  2541. });
  2542. this.registerType('cuml.svm.svr.SVR', class {});
  2543. this.registerType('datetime.date', class {});
  2544. this.registerType('datetime.datetime', class extends datetime.date {});
  2545. this.registerType('datetime.timedelta', class {});
  2546. this.registerType('datetime.tzinfo', class {});
  2547. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2548. this.registerType('dnnlib.tflib.network.Network', class {});
  2549. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2550. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2551. constructor(dict) {
  2552. Object.assign(this, dict);
  2553. }
  2554. });
  2555. this.registerType('haiku._src.data_structures.frozendict', class {
  2556. constructor(obj) {
  2557. Object.assign(this, obj);
  2558. }
  2559. });
  2560. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2561. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2562. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2563. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2564. this.registerType('io.BytesIO', class {
  2565. constructor(buf, mode) {
  2566. this.mode = mode || 'r';
  2567. this._buf = this.mode === 'w' ? null : buf;
  2568. this._point = 0;
  2569. }
  2570. seek(offset) {
  2571. if (this._buf.seek) {
  2572. this._buf.seek(offset);
  2573. }
  2574. this._point = offset;
  2575. }
  2576. read(size, stream) {
  2577. if (this._buf.stream && stream) {
  2578. return this._buf.stream(size);
  2579. }
  2580. if (this._buf.peek) {
  2581. return this._buf.read(size);
  2582. }
  2583. if (this._buf instanceof Uint8Array) {
  2584. const start = this._point;
  2585. this._point = size === undefined ? this._buf.length : start + size;
  2586. return this._buf.subarray(start, this._point);
  2587. }
  2588. throw new python.Error('Unsupported buffer type.');
  2589. }
  2590. write(data) {
  2591. const src = this._buf || new Uint8Array();
  2592. const end = this._point + data.length;
  2593. const size = Math.max(src.length, end);
  2594. this._buf = new Uint8Array(size);
  2595. this._buf.set(src, 0);
  2596. this._buf.set(data, this._point);
  2597. this._point = end;
  2598. }
  2599. getbuffer() {
  2600. return new builtins.memoryview(this._buf);
  2601. }
  2602. });
  2603. this.registerType('io.StringIO', class {
  2604. constructor() {
  2605. this._buf = [];
  2606. }
  2607. write(text) {
  2608. this._buf.push(text);
  2609. }
  2610. toString() {
  2611. return this._buf.join('');
  2612. }
  2613. });
  2614. this.registerType('numpy.dtype', class {
  2615. constructor(obj, align, copy) {
  2616. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2617. this.kind = 'V';
  2618. this.byteorder = '|';
  2619. this.itemsize = obj.itemsize;
  2620. this.names = obj.names;
  2621. this.fields = new Map();
  2622. for (let i = 0; i < obj.names.length; i++) {
  2623. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2624. }
  2625. return;
  2626. }
  2627. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2628. this.byteorder = obj.substring(0, 1);
  2629. obj = obj.substring(1);
  2630. } else {
  2631. this.byteorder = '=';
  2632. }
  2633. switch (obj) {
  2634. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2635. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2636. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2637. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2638. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2639. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2640. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2641. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2642. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2643. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2644. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2645. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2646. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2647. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2648. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2649. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2650. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2651. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2652. default:
  2653. if (obj.startsWith('V')) {
  2654. this.itemsize = parseInt(obj.substring(1), 10);
  2655. this.kind = 'V';
  2656. } else if (obj.startsWith('O')) {
  2657. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2658. this.kind = 'O';
  2659. } else if (obj.startsWith('S')) {
  2660. this.itemsize = parseInt(obj.substring(1), 10);
  2661. this.kind = 'S';
  2662. } else if (obj.startsWith('U')) { // Unicode string
  2663. this.kind = 'U';
  2664. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2665. } else if (obj.startsWith('T')) {
  2666. this.kind = 'T';
  2667. this.itemsize = parseInt(obj.substring(1), 10);
  2668. } else {
  2669. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2670. }
  2671. break;
  2672. }
  2673. if (align) {
  2674. this.align = align;
  2675. }
  2676. if (copy) {
  2677. this.copy = copy;
  2678. }
  2679. }
  2680. get str() {
  2681. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2682. }
  2683. get name() {
  2684. switch (this.kind) {
  2685. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2686. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2687. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2688. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2689. case 'M': return 'datetime64';
  2690. case 'm': return 'timedelta64';
  2691. case 'b': return 'bool';
  2692. default: return this.__name__;
  2693. }
  2694. }
  2695. __setstate__(state) {
  2696. switch (state.length) {
  2697. case 8:
  2698. [
  2699. this.version, this.byteorder, this.subarray, this.names,
  2700. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2701. ] = state;
  2702. break;
  2703. case 9:
  2704. [
  2705. this.version, this.byteorder, this.subarray, this.names,
  2706. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2707. this.metadata
  2708. ] = state;
  2709. break;
  2710. default:
  2711. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2712. }
  2713. }
  2714. get __name__() {
  2715. switch (this.kind) {
  2716. case 'b':
  2717. switch (this.itemsize) {
  2718. case 1: return 'boolean';
  2719. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2720. }
  2721. case 'i':
  2722. switch (this.itemsize) {
  2723. case 1: return 'int8';
  2724. case 2: return 'int16';
  2725. case 4: return 'int32';
  2726. case 8: return 'int64';
  2727. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2728. }
  2729. case 'u':
  2730. switch (this.itemsize) {
  2731. case 1: return 'uint8';
  2732. case 2: return 'uint16';
  2733. case 4: return 'uint32';
  2734. case 8: return 'uint64';
  2735. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2736. }
  2737. case 'f':
  2738. switch (this.itemsize) {
  2739. case 1: return 'float8e5m2';
  2740. case 2: return 'float16';
  2741. case 4: return 'float32';
  2742. case 8: return 'float64';
  2743. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2744. }
  2745. case 'c':
  2746. switch (this.itemsize) {
  2747. case 8: return 'complex<float32>';
  2748. case 16: return 'complex<float64>';
  2749. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2750. }
  2751. case 'S':
  2752. case 'T':
  2753. return 'string';
  2754. case 'U':
  2755. return 'string';
  2756. case 'M':
  2757. return 'datetime';
  2758. case 'm':
  2759. return 'timedelta';
  2760. case 'O':
  2761. return 'object';
  2762. case 'V':
  2763. return 'void';
  2764. default:
  2765. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2766. }
  2767. }
  2768. });
  2769. this.registerType('numpy.generic', class {});
  2770. this.registerType('numpy.inexact', class {});
  2771. this.registerType('numpy.flexible', class extends numpy.generic {});
  2772. this.registerType('numpy.void', class extends numpy.flexible {});
  2773. this.registerType('numpy.bool_', class extends numpy.generic {});
  2774. this.registerType('numpy.number', class extends numpy.generic {});
  2775. this.registerType('numpy.integer', class extends numpy.number {});
  2776. this.registerType('numpy.floating', class extends numpy.inexact {});
  2777. this.registerType('numpy.float16', class extends numpy.floating {});
  2778. this.registerType('numpy.float32', class extends numpy.floating {});
  2779. this.registerType('numpy.float64', class extends numpy.floating {});
  2780. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2781. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2782. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2783. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2784. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2785. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2786. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2787. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2788. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2789. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2790. this.registerType('numpy.datetime64', class extends numpy.generic {
  2791. constructor(...args) {
  2792. super();
  2793. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2794. [this.buffer] = args;
  2795. }
  2796. }
  2797. toString() {
  2798. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2799. const value = view.getBigInt64(0, true);
  2800. if (value === -9223372036854775808n) {
  2801. return 'NaT';
  2802. }
  2803. const date = new Date(Number(value / 1000000n));
  2804. return date.toISOString().slice(0, -1);
  2805. }
  2806. });
  2807. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2808. constructor() {
  2809. super('|T16');
  2810. }
  2811. });
  2812. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2813. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2814. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2815. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2816. this.registerType('gensim.models.fasttext.FastText', class {});
  2817. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2818. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2819. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2820. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2821. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2822. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2823. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2824. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2825. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2826. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2827. this.registerFunction('gensim.models.phrases.original_scorer');
  2828. this.registerType('gensim.models.phrases.Phraser', class {});
  2829. this.registerType('gensim.models.phrases.Phrases', class {});
  2830. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2831. this.registerType('gensim.models.word2vec.Vocab', class {});
  2832. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2833. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2834. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2835. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2836. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2837. throw new builtins.AttributeError('This method should be called on a class object.');
  2838. });
  2839. this.registerFunction('gensim.utils.identity');
  2840. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2841. constructor(obj) {
  2842. Object.assign(this, obj);
  2843. }
  2844. });
  2845. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2846. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2847. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2848. __read__(unpickler) {
  2849. if (this.dtype.__name__ === 'object') {
  2850. return unpickler.load();
  2851. }
  2852. if (this.numpy_array_alignment_bytes) {
  2853. const [size] = unpickler.read(1);
  2854. unpickler.read(size);
  2855. }
  2856. if (this.order === 'F') {
  2857. throw new python.Error('Fortran order not implemented.');
  2858. }
  2859. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2860. this.data = unpickler.read(size);
  2861. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2862. }
  2863. });
  2864. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2865. __setstate__(state) {
  2866. this.subclass = state.get('subclass');
  2867. this.filename = state.get('state');
  2868. this.allow_mmap = state.get('allow_mmap');
  2869. }
  2870. __read__(/* unpickler */) {
  2871. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2872. }
  2873. });
  2874. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2875. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2876. this.registerType('keras.engine.sequential.Sequential', class {});
  2877. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2878. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2879. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2880. this.registerType('lasagne.layers.input.InputLayer', class {});
  2881. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2882. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2883. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2884. this.registerType('lightgbm.basic.Booster', class {
  2885. constructor() {
  2886. this.average_output = false;
  2887. this.models = [];
  2888. this.loaded_parameter = '';
  2889. }
  2890. __setstate__(state) {
  2891. const model_str = state.get('_handle', state.get('handle', null));
  2892. if (model_str) {
  2893. this.LoadModelFromString(model_str);
  2894. return;
  2895. }
  2896. for (const [key, value] of state) {
  2897. this[key] = value;
  2898. }
  2899. }
  2900. LoadModelFromString(model_str) {
  2901. const lines = model_str.split('\n');
  2902. const signature = lines.shift() || '?';
  2903. if (signature.trim() !== 'tree') {
  2904. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2905. }
  2906. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2907. const key_vals = new Map();
  2908. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2909. const cur_line = lines.shift().trim();
  2910. if (cur_line.length > 0) {
  2911. const strs = cur_line.split('=');
  2912. if (strs.length === 1) {
  2913. key_vals.set(strs[0], '');
  2914. } else if (strs.length === 2) {
  2915. key_vals.set(strs[0], strs[1]);
  2916. } else if (strs.length > 2) {
  2917. if (strs[0] === "feature_names") {
  2918. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2919. } else if (strs[0] === 'monotone_constraints') {
  2920. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2921. } else {
  2922. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2923. }
  2924. }
  2925. }
  2926. }
  2927. const atoi = (key, value) => {
  2928. if (key_vals.has(key)) {
  2929. return parseInt(key_vals.get(key), 10);
  2930. }
  2931. if (value !== undefined) {
  2932. return value;
  2933. }
  2934. throw new python.Error(`Model file does not specify ${key}.`);
  2935. };
  2936. const list = (key, size) => {
  2937. if (key_vals.has(key)) {
  2938. const value = key_vals.get(key).split(' ');
  2939. if (value.length !== size) {
  2940. throw new python.Error(`Wrong size of ${key}.`);
  2941. }
  2942. return value;
  2943. }
  2944. throw new python.Error(`Model file does not contain ${key}.`);
  2945. };
  2946. this.version = key_vals.get('version') || '';
  2947. this.num_class = atoi('num_class');
  2948. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2949. this.label_index = atoi('label_index');
  2950. this.max_feature_idx = atoi('max_feature_idx');
  2951. if (key_vals.has('average_output')) {
  2952. this.average_output = true;
  2953. }
  2954. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2955. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2956. if (key_vals.has('monotone_constraints')) {
  2957. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2958. }
  2959. if (key_vals.has('objective')) {
  2960. this.objective = key_vals.get('objective');
  2961. }
  2962. let tree = null;
  2963. while (lines.length > 0) {
  2964. const text = lines.shift();
  2965. const line = text.trim();
  2966. if (line.length === 0) {
  2967. continue;
  2968. }
  2969. if (line.startsWith('Tree=')) {
  2970. tree = { index: parseInt(line.split('=').pop(), 10) };
  2971. this.models.push(tree);
  2972. continue;
  2973. }
  2974. if (line === 'end of trees') {
  2975. break;
  2976. }
  2977. const param = line.split('=');
  2978. if (param.length !== 2) {
  2979. throw new python.Error(`Invalid property '${line}'.`);
  2980. }
  2981. const name = param[0].trim();
  2982. const value = param[1].trim();
  2983. tree[name] = value;
  2984. }
  2985. const ss = [];
  2986. let is_inparameter = false;
  2987. while (lines.length > 0) {
  2988. const text = lines.shift();
  2989. const line = text.trim();
  2990. if (line === 'parameters:') {
  2991. is_inparameter = true;
  2992. continue;
  2993. } else if (line === 'end of parameters') {
  2994. break;
  2995. } else if (is_inparameter) {
  2996. ss.push(line);
  2997. }
  2998. }
  2999. if (ss.length > 0) {
  3000. this.loaded_parameter = ss.join('\n');
  3001. }
  3002. }
  3003. });
  3004. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  3005. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  3006. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  3007. this.registerFunction('megengine.functional.nn.relu', () => {});
  3008. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3009. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3010. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3011. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3012. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3013. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3014. this.registerFunction('megengine.functional.tensor.full', () => {});
  3015. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3016. this.registerFunction('megengine.functional.tensor.split', () => {});
  3017. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3018. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3019. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3020. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3021. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3022. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3023. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3024. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3025. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3026. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3027. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3028. this.registerType('megengine.distributed.group.Group', class {});
  3029. this.registerType('megengine.module.activation.ReLU', class {});
  3030. this.registerType('megengine.module.activation.Softmax', class {});
  3031. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3032. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3033. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3034. this.registerType('megengine.module.conv.Conv2d', class {});
  3035. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3036. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3037. this.registerType('megengine.module.dropout.Dropout', class {});
  3038. this.registerType('megengine.module.identity.Identity', class {});
  3039. this.registerType('megengine.module.linear.Linear', class {});
  3040. this.registerType('megengine.module.module.Module', class {});
  3041. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3042. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3043. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3044. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3045. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3046. this.registerType('megengine.module.qat.concat.Concat', class {});
  3047. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3048. this.registerType('megengine.module.sequential.Sequential', class {});
  3049. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3050. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3051. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3052. this.registerType('megengine.quantization.utils.QParams', class {});
  3053. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3054. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3055. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3056. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3057. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3058. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3059. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3060. this.registerType('megengine.traced_module.expr.Apply', class {});
  3061. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3062. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3063. this.registerType('megengine.traced_module.expr.Constant', class {});
  3064. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3065. this.registerType('megengine.traced_module.expr.Input', class {});
  3066. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3067. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3068. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3069. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3070. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3071. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3072. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3073. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3074. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3075. this.registerType('megengine.tensor.Parameter', class {
  3076. constructor(data, dtype, device) {
  3077. this.data = data;
  3078. this.dtype = dtype;
  3079. this.device = device;
  3080. }
  3081. });
  3082. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3083. toString() {
  3084. let content = '';
  3085. for (const child of this.children_defs) {
  3086. content += `${child},`;
  3087. }
  3088. if (typeof this.type === "string") {
  3089. return `${this.type.split(".").slice(-1)}(${content})`;
  3090. }
  3091. return `${this.type.__name__}(${content})`;
  3092. }
  3093. });
  3094. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3095. toString() {
  3096. let content = '';
  3097. if (this.const_val === null) {
  3098. content += '[';
  3099. } else {
  3100. content += this.const_val;
  3101. }
  3102. for (const t of Object.values(this.type)) {
  3103. content += t.__name__;
  3104. }
  3105. content += ']';
  3106. return content;
  3107. }
  3108. });
  3109. this.registerType('megengine.tensor.Tensor', class {
  3110. constructor(data, dtype, device) {
  3111. this.data = data;
  3112. this.dtype = dtype;
  3113. this.device = device;
  3114. }
  3115. });
  3116. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3117. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3118. this.name = name;
  3119. this.cname = cname;
  3120. this.np_dtype = np_dtype;
  3121. this.qmin = qmin;
  3122. this.qmax = qmax;
  3123. this.is_signed = is_signed;
  3124. }
  3125. });
  3126. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3127. this.registerType('nolearn.lasagne.base.Layers', class {});
  3128. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3129. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3130. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3131. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3132. this.registerType('numpy.ndarray', class {
  3133. constructor(shape, dtype, buffer, offset, strides, order) {
  3134. this.shape = shape;
  3135. this.dtype = dtype;
  3136. this.data = buffer === undefined ? null : buffer;
  3137. this.offset = offset === undefined ? 0 : offset;
  3138. this._strides = strides === undefined ? null : strides;
  3139. this.order = order === undefined ? null : order;
  3140. this.flags = {};
  3141. this._read();
  3142. }
  3143. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3144. return new cls(shape, dtype, buffer, offset, strides, order);
  3145. }
  3146. __setstate__(state) {
  3147. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3148. this._read();
  3149. }
  3150. flatten() {
  3151. const size = this.shape.reduce((a, b) => a * b, 1);
  3152. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3153. value.flags = this.flags;
  3154. return value;
  3155. }
  3156. reshape(shape, order) {
  3157. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3158. }
  3159. tobytes() {
  3160. return this.data;
  3161. }
  3162. tolist() {
  3163. if (this.shape.length < 0 || this.shape.length > 1) {
  3164. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3165. }
  3166. const size = this.shape.reduce((a, b) => a * b, 1);
  3167. const list = new Array(size);
  3168. switch (this.dtype.kind) {
  3169. case 'U': {
  3170. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3171. const itemsize = this.dtype.itemsize >> 2;
  3172. let offset = 0;
  3173. for (let i = 0; i < size; i++) {
  3174. const buffer = data.subarray(offset, offset + itemsize);
  3175. const index = buffer.indexOf(0);
  3176. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3177. offset += itemsize;
  3178. }
  3179. return list;
  3180. }
  3181. case 'S': {
  3182. const data = this.data;
  3183. const itemsize = this.dtype.itemsize;
  3184. const decoder = new TextDecoder('utf-8');
  3185. let offset = 0;
  3186. for (let i = 0; i < size; i++) {
  3187. const buffer = data.subarray(offset, offset + itemsize);
  3188. const index = buffer.indexOf(0);
  3189. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3190. offset += itemsize;
  3191. }
  3192. return list;
  3193. }
  3194. case 'V': {
  3195. const itemsize = this.dtype.itemsize;
  3196. let offset = 0;
  3197. for (let i = 0; i < size; i++) {
  3198. list[i] = this.data.slice(offset, offset + itemsize);
  3199. offset += itemsize;
  3200. }
  3201. return list;
  3202. }
  3203. case 'M': {
  3204. const itemsize = this.dtype.itemsize;
  3205. let offset = 0;
  3206. for (let i = 0; i < size; i++) {
  3207. const buffer = this.data.slice(offset, offset + itemsize);
  3208. list[i] = new numpy.datetime64(buffer);
  3209. offset += itemsize;
  3210. }
  3211. return list;
  3212. }
  3213. case 'T': {
  3214. return this.data;
  3215. }
  3216. case 'O': {
  3217. return this.data;
  3218. }
  3219. default: {
  3220. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3221. }
  3222. }
  3223. }
  3224. get itemsize() {
  3225. return this.dtype.itemsize;
  3226. }
  3227. get size() {
  3228. return (this.shape || []).reduce((a, b) => a * b, 1);
  3229. }
  3230. get strides() {
  3231. if (!this._strides) {
  3232. const shape = this.shape;
  3233. const strides = new Array(shape.length);
  3234. let stride = this.itemsize;
  3235. for (let i = shape.length - 1; i >= 0; i--) {
  3236. strides[i] = stride;
  3237. stride *= shape[i];
  3238. }
  3239. return strides;
  3240. }
  3241. return this._strides;
  3242. }
  3243. _read() {
  3244. if (this.data) {
  3245. const length = this.dtype.itemsize * this.size;
  3246. if (typeof this.data === 'string') {
  3247. this.data = this._unescape(this.data, length);
  3248. if (this.data.length !== length) {
  3249. throw new python.Error('Invalid string array data size.');
  3250. }
  3251. } else if (this.data.length !== length) {
  3252. // throw new python.Error('Invalid array data size.');
  3253. }
  3254. }
  3255. }
  3256. _unescape(token, size) {
  3257. const length = token.length;
  3258. const a = new Uint8Array(length);
  3259. if (size && size === length) {
  3260. for (let p = 0; p < size; p++) {
  3261. a[p] = token.charCodeAt(p);
  3262. }
  3263. return a;
  3264. }
  3265. let i = 0;
  3266. let o = 0;
  3267. while (i < length) {
  3268. let c = token.charCodeAt(i++);
  3269. if (c !== 0x5C || i >= length) {
  3270. a[o++] = c;
  3271. } else {
  3272. c = token.charCodeAt(i++);
  3273. switch (c) {
  3274. case 0x27: a[o++] = 0x27; break; // '
  3275. case 0x5C: a[o++] = 0x5C; break; // \\
  3276. case 0x22: a[o++] = 0x22; break; // "
  3277. case 0x72: a[o++] = 0x0D; break; // \r
  3278. case 0x6E: a[o++] = 0x0A; break; // \n
  3279. case 0x74: a[o++] = 0x09; break; // \t
  3280. case 0x62: a[o++] = 0x08; break; // \b
  3281. case 0x58: // x
  3282. case 0x78: { // X
  3283. const xsi = i - 1;
  3284. const xso = o;
  3285. for (let xi = 0; xi < 2; xi++) {
  3286. if (i >= length) {
  3287. i = xsi;
  3288. o = xso;
  3289. a[o] = 0x5c;
  3290. break;
  3291. }
  3292. let c = token.charCodeAt(i++);
  3293. if (c >= 65 && c <= 70) {
  3294. c -= 55;
  3295. } else if (c >= 97 && c <= 102) {
  3296. c -= 87;
  3297. } else if (c >= 48 && c <= 57) {
  3298. c -= 48;
  3299. } else {
  3300. c = -1;
  3301. }
  3302. if (c === -1) {
  3303. i = xsi;
  3304. o = xso;
  3305. a[o] = 0x5c;
  3306. break;
  3307. }
  3308. a[o] = a[o] << 4 | c;
  3309. }
  3310. o++;
  3311. break;
  3312. }
  3313. default:
  3314. if (c < 48 || c > 57) { // 0-9
  3315. a[o++] = 0x5c;
  3316. a[o++] = c;
  3317. } else {
  3318. i--;
  3319. const osi = i;
  3320. const oso = o;
  3321. for (let oi = 0; oi < 3; oi++) {
  3322. if (i >= length) {
  3323. i = osi;
  3324. o = oso;
  3325. a[o] = 0x5c;
  3326. break;
  3327. }
  3328. const od = token.charCodeAt(i++);
  3329. if (od < 48 || od > 57) {
  3330. i = osi;
  3331. o = oso;
  3332. a[o] = 0x5c;
  3333. break;
  3334. }
  3335. a[o] = a[o] << 3 | od - 48;
  3336. }
  3337. o++;
  3338. }
  3339. break;
  3340. }
  3341. }
  3342. }
  3343. return a.slice(0, o);
  3344. }
  3345. });
  3346. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3347. static __new__(/* subtype, data, dtype, copy */) {
  3348. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3349. }
  3350. });
  3351. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3352. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3353. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3354. super(data.shape, data.dtype, data.data);
  3355. }
  3356. });
  3357. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3358. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3359. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3360. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3361. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3362. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3363. __setstate__(state) {
  3364. [this._dtype, this._ndarray] = state;
  3365. Object.assign(this, Object.fromEntries(state[2]));
  3366. }
  3367. });
  3368. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3369. __setstate__(state) {
  3370. [this._dtype, this._ndarray] = state;
  3371. Object.assign(this, Object.fromEntries(state[2]));
  3372. }
  3373. });
  3374. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3375. __setstate__(state) {
  3376. [this._dtype, this._ndarray] = state;
  3377. Object.assign(this, Object.fromEntries(state[2]));
  3378. }
  3379. });
  3380. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3381. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3382. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3383. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3384. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3385. this.registerType('pandas.core.generic.Flags', class {});
  3386. this.registerType('pandas.core.generic.NDFrame', class {
  3387. constructor(data) {
  3388. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3389. this._metadata = [];
  3390. builtins.object.__setattr__(self, "_mgr", data);
  3391. builtins.object.__setattr__(self, "_attrs", {});
  3392. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3393. }
  3394. __setstate__(state) {
  3395. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3396. this._mgr = state;
  3397. } else if (state instanceof builtins.dict) {
  3398. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3399. state.__setitem__('_mgr', state.pop('_data'));
  3400. }
  3401. const typ = state.get('_typ');
  3402. if (typ) {
  3403. let attrs = state.get('_attrs', new builtins.dict());
  3404. if (!attrs) {
  3405. attrs = new builtins.dict();
  3406. }
  3407. builtins.object.__setattr__(this, '_attrs', attrs);
  3408. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3409. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3410. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3411. for (const k of meta) {
  3412. if (state.__contains__(k) && k !== '_flags') {
  3413. const v = state.__getitem__(k);
  3414. builtins.object.__setattr__(this, k, v);
  3415. }
  3416. }
  3417. for (const [k, v] of state) {
  3418. if (!meta.has(k)) {
  3419. builtins.object.__setattr__(this, k, v);
  3420. }
  3421. }
  3422. } else {
  3423. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3424. }
  3425. } else if (state.size === 2) {
  3426. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3427. }
  3428. }
  3429. });
  3430. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3431. });
  3432. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3433. return new cls(d);
  3434. });
  3435. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3436. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3437. this.registerType('pandas.core.indexes.base.Index', class {});
  3438. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3439. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3440. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3441. this.registerType('pandas.core.index.Int64Index', class {});
  3442. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3443. });
  3444. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3445. });
  3446. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3447. return pandas.core.internals.blocks.NumpyBlock;
  3448. });
  3449. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3450. return values;
  3451. });
  3452. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3453. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3454. return new klass(values, ndim, placement, refs);
  3455. });
  3456. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3457. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3458. this.registerType('pandas.core.series.Series', class {});
  3459. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3460. const obj = new cls();
  3461. if (state && obj.__setstate__) {
  3462. obj.__setstate__(state);
  3463. }
  3464. return obj;
  3465. });
  3466. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3467. const obj = new cls();
  3468. if (state && obj.__setstate__) {
  3469. obj.__setstate__(state);
  3470. }
  3471. return obj;
  3472. });
  3473. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3474. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3475. // if not isinstance(placement, BlockPlacement):
  3476. // placement = BlockPlacement(placement)
  3477. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3478. });
  3479. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3480. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3481. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3482. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3483. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3484. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3485. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3486. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3487. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3488. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3489. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3490. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3491. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3492. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3493. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3494. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3495. this.registerType('pathlib.Path', class {});
  3496. this.registerType('pathlib._local.PosixPath', class {});
  3497. this.registerType('pathlib._local.WindowsPath', class {});
  3498. const pathlib = this.register('pathlib');
  3499. pathlib.PosixPath = pathlib._local.PosixPath;
  3500. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3501. this.registerType('shap._serializable.Serializable', class {});
  3502. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3503. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3504. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3505. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3506. this.registerType('sklearn._loss.link.BaseLink', class {});
  3507. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3508. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3509. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3510. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3511. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3512. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3513. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3514. this.registerType('sklearn._loss.link.Interval', class {});
  3515. this.registerType('sklearn._loss.link.LogitLink', class {});
  3516. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3517. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3518. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3519. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3520. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3521. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3522. this.registerType('sklearn.base.BaseEstimator', class {});
  3523. this.registerType('sklearn.base.TransformerMixin', class {});
  3524. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3525. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3526. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3527. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3528. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3529. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3530. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3531. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3532. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3533. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3534. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3535. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3536. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3537. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3538. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3539. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3540. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3541. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3542. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3543. this.registerType('sklearn.decomposition.PCA', class {});
  3544. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3545. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3546. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3547. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3548. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3549. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3550. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3551. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3552. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3553. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3554. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3555. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3556. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3557. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3558. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3559. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3560. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3561. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3562. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3563. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3564. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3565. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3566. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3567. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3568. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3569. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3570. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3571. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3572. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3573. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3574. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3575. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3576. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3577. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3578. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3579. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3580. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3581. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3582. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3583. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3584. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3585. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3586. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3587. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3588. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3589. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3590. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3591. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3592. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3593. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3594. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3595. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3596. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3597. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3598. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3599. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3600. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3601. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3602. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3603. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3604. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3605. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3606. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3607. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3608. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3609. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3610. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3611. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3612. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3613. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3614. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3615. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3616. this.registerType('sklearn.impute.SimpleImputer', class {});
  3617. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3618. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3619. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3620. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3621. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3622. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3623. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3624. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3625. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3626. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3627. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3628. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3629. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3630. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3631. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3632. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3633. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3634. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3635. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3636. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3637. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3638. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3639. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3640. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3641. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3642. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3643. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3644. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3645. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3646. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3647. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3648. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3649. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3650. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3651. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3652. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3653. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3654. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3655. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3656. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3657. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3658. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3659. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3660. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3661. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3662. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3663. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3664. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3665. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3666. this.registerType('sklearn.model_selection._split.KFold', class {});
  3667. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3668. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3669. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3670. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3671. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3672. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3673. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3674. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3675. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3676. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3677. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3678. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3679. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3680. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3681. return obj.__new__(obj);
  3682. });
  3683. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3684. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3685. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3686. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3687. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3688. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3689. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3690. return obj.__new__(obj);
  3691. });
  3692. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3693. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3694. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3695. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3696. return obj.__new__(obj);
  3697. });
  3698. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3699. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3700. return obj.__new__(obj);
  3701. });
  3702. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3703. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3704. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3705. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3706. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3707. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3708. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3709. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3710. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3711. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3712. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3713. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3714. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3715. this.registerType('sklearn.pipeline.Pipeline', class {});
  3716. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3717. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3718. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3719. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3720. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3721. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3722. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3723. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3724. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3725. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3726. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3727. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3728. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3729. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3730. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3731. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3732. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3733. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3734. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3735. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3736. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3737. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3738. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3739. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3740. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3741. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3742. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3743. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3744. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3745. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3746. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3747. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3748. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3749. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3750. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3751. this.registerType('sklearn.svm._classes.SVC', class {});
  3752. this.registerType('sklearn.svm._classes.SVR', class {});
  3753. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3754. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3755. this.registerType('sklearn.svm.classes.SVC', class {});
  3756. this.registerType('sklearn.svm.classes.SVR', class {});
  3757. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3758. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3759. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3760. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3761. this.registerType('sklearn.tree._tree.Tree', class {
  3762. constructor(n_features, n_classes, n_outputs) {
  3763. this.n_features = n_features;
  3764. this.n_classes = n_classes;
  3765. this.n_outputs = n_outputs;
  3766. }
  3767. __setstate__(state) {
  3768. this.max_depth = state.get('max_depth');
  3769. this.node_count = state.get('node_count');
  3770. this.nodes = state.get('nodes');
  3771. this.values = state.get('values');
  3772. }
  3773. });
  3774. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3775. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3776. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3777. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3778. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3779. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3780. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3781. this.registerType('pickle.Unpickler', class {
  3782. constructor(data) {
  3783. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3784. this.persistent_load = () => {
  3785. throw new python.Error('Unsupported persistent id.');
  3786. };
  3787. }
  3788. load() {
  3789. const reader = this._reader;
  3790. const marker = [];
  3791. let stack = [];
  3792. const memo = {};
  3793. let size = 0;
  3794. while (reader.position < reader.length) {
  3795. const opcode = reader.byte();
  3796. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3797. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3798. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3799. switch (opcode) {
  3800. case 128: { // PROTO
  3801. const version = reader.byte();
  3802. if (version > 5) {
  3803. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3804. }
  3805. break;
  3806. }
  3807. case 99: { // GLOBAL 'c'
  3808. const module = reader.line();
  3809. const name = reader.line();
  3810. stack.push(this.find_class(module, name));
  3811. break;
  3812. }
  3813. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3814. const name = stack.pop();
  3815. const module = stack.pop();
  3816. stack.push(this.find_class(module, name));
  3817. break;
  3818. }
  3819. case 111: { // OBJ 'o'
  3820. const args = stack;
  3821. const cls = args.pop();
  3822. stack = marker.pop();
  3823. const obj = this._instantiate(cls, args);
  3824. stack.push(obj);
  3825. break;
  3826. }
  3827. case 112 : { // PUT 'p'
  3828. const index = parseInt(reader.line(), 10);
  3829. if (stack.length === 0) {
  3830. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3831. }
  3832. memo[index] = stack[stack.length - 1];
  3833. size++;
  3834. break;
  3835. }
  3836. case 103: { // GET 'g'
  3837. const index = parseInt(reader.line(), 10);
  3838. stack.push(memo[index]);
  3839. break;
  3840. }
  3841. case 48: // POP '0'
  3842. stack.pop();
  3843. break;
  3844. case 49: // POP_MARK '1'
  3845. stack = marker.pop();
  3846. break;
  3847. case 50: // DUP '2'
  3848. if (stack.length === 0) {
  3849. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3850. }
  3851. stack.push(stack[stack.length - 1]);
  3852. break;
  3853. case 80: // PERSID 'P'
  3854. stack.push(this.persistent_load(reader.line()));
  3855. break;
  3856. case 81: // BINPERSID 'Q'
  3857. stack.push(this.persistent_load(stack.pop()));
  3858. break;
  3859. case 82: { // REDUCE 'R'
  3860. const args = stack.pop();
  3861. const func = stack.pop();
  3862. stack.push(this._reduce(func, args));
  3863. break;
  3864. }
  3865. case 129: { // NEWOBJ
  3866. const args = stack.pop();
  3867. const cls = stack.pop();
  3868. const obj = this._newobj(cls, args);
  3869. stack.push(obj);
  3870. break;
  3871. }
  3872. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3873. const kwargs = stack.pop();
  3874. const args = stack.pop();
  3875. const cls = stack.pop();
  3876. if (Object.entries(kwargs).length > 0) {
  3877. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3878. }
  3879. const obj = this._newobj(cls, args);
  3880. stack.push(obj);
  3881. break;
  3882. }
  3883. case 104: // BINGET 'h'
  3884. stack.push(memo[reader.byte()]);
  3885. break;
  3886. case 105: { // INST 'i'
  3887. const module = reader.line();
  3888. const name = reader.line();
  3889. const args = stack;
  3890. const cls = `${module}.${name}`;
  3891. stack = marker.pop();
  3892. // cls = this.find_class(module, name)
  3893. const obj = this._instantiate(cls, args);
  3894. stack.push(obj);
  3895. break;
  3896. }
  3897. case 106: // LONG_BINGET 'j'
  3898. stack.push(memo[reader.uint32()]);
  3899. break;
  3900. case 113: // BINPUT 'q'
  3901. if (stack.length === 0) {
  3902. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3903. }
  3904. memo[reader.byte()] = stack[stack.length - 1];
  3905. size++;
  3906. break;
  3907. case 114: // LONG_BINPUT 'r'
  3908. if (stack.length === 0) {
  3909. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3910. }
  3911. memo[reader.uint32()] = stack[stack.length - 1];
  3912. size++;
  3913. break;
  3914. case 74: // BININT 'J'
  3915. stack.push(reader.int32());
  3916. break;
  3917. case 75: // BININT1 'K'
  3918. stack.push(reader.byte());
  3919. break;
  3920. case 76: // LONG 'L'
  3921. stack.push(parseInt(reader.line(), 10));
  3922. break;
  3923. case 77: // BININT2 'M'
  3924. stack.push(reader.uint16());
  3925. break;
  3926. case 66: // BINBYTES 'B' (Protocol 3)
  3927. stack.push(reader.read(reader.int32()));
  3928. break;
  3929. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3930. stack.push(reader.read(reader.byte()));
  3931. break;
  3932. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3933. stack.push(reader.read(reader.int64().toNumber()));
  3934. break;
  3935. case 70: // FLOAT 'F'
  3936. stack.push(parseFloat(reader.line()));
  3937. break;
  3938. case 71: // BINFLOAT 'G'
  3939. stack.push(reader.float64());
  3940. break;
  3941. case 73: { // INT 'I'
  3942. const value = reader.line();
  3943. if (value === '01') {
  3944. stack.push(true);
  3945. } else if (value === '00') {
  3946. stack.push(false);
  3947. } else {
  3948. stack.push(parseInt(value, 10));
  3949. }
  3950. break;
  3951. }
  3952. case 93: // EMPTY_LIST ']'
  3953. stack.push(new builtins.list());
  3954. break;
  3955. case 41: // EMPTY_TUPLE ')'
  3956. stack.push([]);
  3957. break;
  3958. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3959. stack.push([]);
  3960. break;
  3961. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3962. const items = stack;
  3963. stack = marker.pop();
  3964. const obj = stack[stack.length - 1];
  3965. for (let i = 0; i < items.length; i++) {
  3966. obj.push(items[i]);
  3967. }
  3968. break;
  3969. }
  3970. case 145: { // FROZENSET '\x91' (Protocol 4)
  3971. const items = stack;
  3972. stack = marker.pop();
  3973. stack.push(items);
  3974. break;
  3975. }
  3976. case 100: { // DICT 'd'
  3977. const items = stack;
  3978. stack = marker.pop();
  3979. const dict = new builtins.dict();
  3980. for (let i = 0; i < items.length; i += 2) {
  3981. dict.__setitem__(items[i], items[i + 1]);
  3982. }
  3983. stack.push(dict);
  3984. break;
  3985. }
  3986. case 108: { // LIST 'l'
  3987. const items = stack;
  3988. stack = marker.pop();
  3989. stack.push(items);
  3990. break;
  3991. }
  3992. case 116: { // TUPLE 't'
  3993. const items = stack;
  3994. stack = marker.pop();
  3995. stack.push(items);
  3996. break;
  3997. }
  3998. case 133: { // TUPLE1 // '\x85'
  3999. stack.push([stack.pop()]);
  4000. break;
  4001. }
  4002. case 134: { // TUPLE2 '\x86'
  4003. const b = stack.pop();
  4004. const a = stack.pop();
  4005. stack.push([a, b]);
  4006. break;
  4007. }
  4008. case 135: { // TUPLE3 '\x87'
  4009. const c = stack.pop();
  4010. const b = stack.pop();
  4011. const a = stack.pop();
  4012. stack.push([a, b, c]);
  4013. break;
  4014. }
  4015. case 115: { // SETITEM 's'
  4016. const value = stack.pop();
  4017. const key = stack.pop();
  4018. const obj = stack[stack.length - 1];
  4019. if (obj.__setitem__) {
  4020. obj.__setitem__(key, value);
  4021. } else {
  4022. obj[key] = value;
  4023. }
  4024. break;
  4025. }
  4026. case 117: { // SETITEMS 'u'
  4027. const items = stack;
  4028. stack = marker.pop();
  4029. const obj = stack[stack.length - 1];
  4030. if (obj.__setitem__) {
  4031. for (let i = 0; i < items.length; i += 2) {
  4032. obj.__setitem__(items[i], items[i + 1]);
  4033. }
  4034. } else {
  4035. for (let i = 0; i < items.length; i += 2) {
  4036. obj[items[i]] = items[i + 1];
  4037. }
  4038. }
  4039. break;
  4040. }
  4041. case 125: // EMPTY_DICT '}'
  4042. stack.push(new builtins.dict());
  4043. break;
  4044. case 97: { // APPEND 'a'
  4045. const append = stack.pop();
  4046. stack[stack.length - 1].push(append);
  4047. break;
  4048. }
  4049. case 101: { // APPENDS 'e'
  4050. const appends = stack;
  4051. stack = marker.pop();
  4052. const list = stack[stack.length - 1];
  4053. list.push(...appends);
  4054. break;
  4055. }
  4056. case 83: { // STRING 'S'
  4057. const str = reader.line();
  4058. stack.push(str.substring(1, str.length - 1));
  4059. break;
  4060. }
  4061. case 84: // BINSTRING 'T'
  4062. stack.push(reader.string(reader.uint32()));
  4063. break;
  4064. case 85 : // SHORT_BINSTRING 'U'
  4065. stack.push(reader.string(reader.byte()));
  4066. break;
  4067. case 86: // UNICODE 'V'
  4068. stack.push(reader.line());
  4069. break;
  4070. case 88: // BINUNICODE 'X
  4071. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4072. break;
  4073. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4074. stack.push(reader.string(reader.byte(), 'utf-8'));
  4075. break;
  4076. case 98: { // BUILD 'b'
  4077. const state = stack.pop();
  4078. let obj = stack.pop();
  4079. if (obj.__setstate__) {
  4080. if (obj.__setstate__.__call__) {
  4081. obj.__setstate__.__call__([obj, state]);
  4082. } else {
  4083. obj.__setstate__(state);
  4084. }
  4085. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4086. obj.__state__ = state;
  4087. } else if (obj instanceof Map && state instanceof Map) {
  4088. for (const [key, value] of state) {
  4089. obj.set(key, value);
  4090. }
  4091. } else if (obj instanceof Map) {
  4092. /* eslint-disable guard-for-in */
  4093. for (const key in state) {
  4094. obj.set(key, state[key]);
  4095. }
  4096. /* eslint-enable guard-for-in */
  4097. } else if (state instanceof Map) {
  4098. for (const [key, value] of state) {
  4099. obj[key] = value;
  4100. }
  4101. } else {
  4102. Object.assign(obj, state);
  4103. }
  4104. if (obj.__read__) {
  4105. obj = obj.__read__(this);
  4106. }
  4107. stack.push(obj);
  4108. break;
  4109. }
  4110. case 40: // MARK '('
  4111. marker.push(stack);
  4112. stack = [];
  4113. break;
  4114. case 136: // NEWTRUE '\x88'
  4115. stack.push(true);
  4116. break;
  4117. case 137: // NEWFALSE '\x89'
  4118. stack.push(false);
  4119. break;
  4120. case 138: { // LONG1 '\x8a'
  4121. const data = reader.read(reader.byte());
  4122. let number = 0;
  4123. switch (data.length) {
  4124. case 0: number = 0; break;
  4125. case 1: [number] = data; break;
  4126. case 2: number = data[1] << 8 | data[0]; break;
  4127. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4128. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  4129. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4130. default: number = Array.prototype.slice.call(data, 0); break;
  4131. }
  4132. stack.push(number);
  4133. break;
  4134. }
  4135. case 139: // LONG4 '\x8b'
  4136. // decode LONG4
  4137. stack.push(reader.read(reader.uint32()));
  4138. break;
  4139. case 148: // MEMOIZE '\x94' (Protocol 4)
  4140. memo[size++] = stack[stack.length - 1];
  4141. break;
  4142. case 149: // FRAME '\x95' (Protocol 4)
  4143. reader.read(8);
  4144. break;
  4145. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4146. stack.push(reader.read(reader.int64().toNumber()));
  4147. break;
  4148. }
  4149. case 78: // NONE 'N'
  4150. stack.push(null);
  4151. break;
  4152. case 46: // STOP '.'
  4153. return stack.pop();
  4154. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4155. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4156. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4157. default:
  4158. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4159. }
  4160. }
  4161. throw new python.Error('Unexpected end of file.');
  4162. }
  4163. find_class(module, name) {
  4164. execution.__import__(module);
  4165. return execution.resolve(`${module}.${name}`);
  4166. }
  4167. _instantiate(cls, args) {
  4168. return execution.invoke(cls, args);
  4169. }
  4170. _newobj(cls, args) {
  4171. // cls.__new__(cls, args)
  4172. return execution.invoke(cls, args);
  4173. }
  4174. _reduce(func, args) {
  4175. return execution.invoke(func, args);
  4176. }
  4177. read(size) {
  4178. return this._reader.read(size);
  4179. }
  4180. stream(size) {
  4181. return this._reader.stream(size);
  4182. }
  4183. });
  4184. this.registerType('random.Random', class {});
  4185. this.registerType('re.Pattern', class {
  4186. constructor(pattern, flags) {
  4187. this.pattern = pattern;
  4188. this.flags = flags;
  4189. }
  4190. });
  4191. this.registerType('spacy._ml.PrecomputableAffine', class {
  4192. __setstate__(state) {
  4193. Object.assign(this, new pickle.Unpickler(state).load());
  4194. }
  4195. });
  4196. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4197. __setstate__(state) {
  4198. Object.assign(this, new pickle.Unpickler(state).load());
  4199. }
  4200. });
  4201. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4202. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4203. this.registerType('theano.compile.function_module.Function', class {});
  4204. this.registerType('theano.compile.function_module.Supervisor', class {});
  4205. this.registerType('theano.compile.io.In', class {});
  4206. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4207. this.registerType('theano.compile.mode.Mode', class {});
  4208. this.registerType('theano.compile.ops.OutputGuard', class {});
  4209. this.registerType('theano.compile.ops.Shape', class {});
  4210. this.registerType('theano.compile.ops.Shape_i', class {});
  4211. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4212. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4213. this.registerType('theano.gof.graph.Apply', class {});
  4214. this.registerType('theano.gof.link.Container', class {});
  4215. this.registerType('theano.gof.opt._metadict', class {});
  4216. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4217. this.registerType('theano.gof.opt.MergeFeature', class {});
  4218. this.registerType('theano.gof.optdb.Query', class {});
  4219. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4220. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4221. this.registerType('theano.gof.utils.scratchpad', class {});
  4222. this.registerType('theano.misc.ordered_set.Link', class {});
  4223. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4224. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4225. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4226. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4227. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4228. this.registerType('theano.scalar.basic.Abs', class {});
  4229. this.registerType('theano.scalar.basic.Add', class {});
  4230. this.registerType('theano.scalar.basic.Cast', class {});
  4231. this.registerType('theano.scalar.basic.Composite', class {});
  4232. this.registerType('theano.scalar.basic.EQ', class {});
  4233. this.registerType('theano.scalar.basic.GE', class {});
  4234. this.registerType('theano.scalar.basic.Identity', class {});
  4235. this.registerType('theano.scalar.basic.IntDiv', class {});
  4236. this.registerType('theano.scalar.basic.Inv', class {});
  4237. this.registerType('theano.scalar.basic.LE', class {});
  4238. this.registerType('theano.scalar.basic.LT', class {});
  4239. this.registerType('theano.scalar.basic.Mul', class {});
  4240. this.registerType('theano.scalar.basic.Neg', class {});
  4241. this.registerType('theano.scalar.basic.Pow', class {});
  4242. this.registerType('theano.scalar.basic.Scalar', class {});
  4243. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4244. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4245. this.registerType('theano.scalar.basic.Second', class {});
  4246. this.registerType('theano.scalar.basic.Sgn', class {});
  4247. this.registerType('theano.scalar.basic.specific_out', class {});
  4248. this.registerType('theano.scalar.basic.Sub', class {});
  4249. this.registerType('theano.scalar.basic.Switch', class {});
  4250. this.registerType('theano.scalar.basic.Tanh', class {});
  4251. this.registerType('theano.scalar.basic.transfer_type', class {});
  4252. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4253. this.registerType('theano.tensor.basic.Alloc', class {});
  4254. this.registerType('theano.tensor.basic.Dot', class {});
  4255. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4256. this.registerType('theano.tensor.basic.Reshape', class {});
  4257. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4258. this.registerType('theano.tensor.blas.Dot22', class {});
  4259. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4260. this.registerType('theano.tensor.blas.Gemm', class {});
  4261. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4262. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4263. this.registerType('theano.tensor.elemwise.Sum', class {});
  4264. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4265. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4266. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4267. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4268. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4269. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4270. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4271. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4272. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4273. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4274. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4275. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4276. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4277. this.registerType('theano.tensor.opt.MakeVector', class {});
  4278. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4279. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4280. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4281. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4282. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4283. this.registerType('theano.tensor.type.TensorType', class {});
  4284. this.registerType('theano.tensor.var.TensorConstant', class {});
  4285. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4286. this.registerType('theano.tensor.var.TensorVariable', class {});
  4287. this.registerType('thinc.describe.Biases', class {});
  4288. this.registerType('thinc.describe.Dimension', class {});
  4289. this.registerType('thinc.describe.Gradient', class {});
  4290. this.registerType('thinc.describe.Weights', class {});
  4291. this.registerType('thinc.describe.Synapses', class {});
  4292. this.registerType('thinc.neural._classes.affine.Affine', class {
  4293. __setstate__(state) {
  4294. Object.assign(this, new pickle.Unpickler(state).load());
  4295. }
  4296. });
  4297. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4298. __setstate__(state) {
  4299. Object.assign(this, new pickle.Unpickler(state).load());
  4300. }
  4301. });
  4302. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4303. __setstate__(state) {
  4304. Object.assign(this, new pickle.Unpickler(state).load());
  4305. }
  4306. });
  4307. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4308. __setstate__(state) {
  4309. Object.assign(this, new pickle.Unpickler(state).load());
  4310. }
  4311. });
  4312. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4313. __setstate__(state) {
  4314. Object.assign(this, new pickle.Unpickler(state).load());
  4315. }
  4316. });
  4317. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4318. __setstate__(state) {
  4319. Object.assign(this, new pickle.Unpickler(state).load());
  4320. }
  4321. });
  4322. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4323. __setstate__(state) {
  4324. Object.assign(this, new pickle.Unpickler(state).load());
  4325. }
  4326. });
  4327. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4328. __setstate__(state) {
  4329. Object.assign(this, new pickle.Unpickler(state).load());
  4330. }
  4331. });
  4332. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4333. __setstate__(state) {
  4334. Object.assign(this, new pickle.Unpickler(state).load());
  4335. }
  4336. });
  4337. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4338. __setstate__(state) {
  4339. Object.assign(this, new pickle.Unpickler(state).load());
  4340. }
  4341. });
  4342. this.registerType('thinc.neural.mem.Memory', class {
  4343. });
  4344. this.registerType('thinc.neural.ops.NumpyOps', class {
  4345. });
  4346. this.registerType('__main__.BYOLState', class {
  4347. constructor(dict) {
  4348. Object.assign(this, dict);
  4349. }
  4350. });
  4351. const types = this.register('types');
  4352. this.registerType('types.GenericAlias', class {});
  4353. this.registerType('types.SimpleNamespace', class {});
  4354. this.registerType('types.BuiltinFunctionType', class {});
  4355. this.registerType('types.BuiltinMethodType', class {});
  4356. this.registerFunction('types.resolve_bases', (bases) => {
  4357. return bases;
  4358. });
  4359. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4360. if (kwds) {
  4361. kwds = new builtins.dict(kwds);
  4362. } else {
  4363. kwds = new builtins.dict();
  4364. }
  4365. let meta = null;
  4366. if (kwds.__contains__('metaclass')) {
  4367. meta = kwds.pop('metaclass');
  4368. } else if (bases && bases.length > 0) {
  4369. meta = builtins.type(bases[0]);
  4370. } else {
  4371. meta = builtins.type;
  4372. }
  4373. if (meta instanceof builtins.type) {
  4374. meta = types._calculate_meta(meta, bases);
  4375. }
  4376. let ns = null;
  4377. if (builtins.hasattr(meta, '__prepare__')) {
  4378. // ns = meta.__prepare__(name, bases, **kwds)
  4379. } else {
  4380. ns = new builtins.dict();
  4381. }
  4382. return [meta, ns, kwds];
  4383. });
  4384. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4385. const winner = meta;
  4386. return winner;
  4387. });
  4388. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4389. const resolved_bases = types.resolve_bases(bases);
  4390. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4391. if (exec_body) {
  4392. exec_body(ns);
  4393. }
  4394. return new meta(name, resolved_bases, ns);
  4395. });
  4396. types.ObjectType = builtins.object;
  4397. types.ModuleType = builtins.module;
  4398. types.MethodType = builtins.method;
  4399. types.FunctionType = builtins.function;
  4400. types.TypeType = builtins.type;
  4401. types.CodeType = builtins.code;
  4402. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4403. this.registerType('xgboost.core.Booster', class {
  4404. load_model(fname) {
  4405. if (fname instanceof Uint8Array) {
  4406. // XGBoosterLoadModel()
  4407. } else {
  4408. // XGBoosterUnserializeFromBuffer(handle) {
  4409. }
  4410. }
  4411. __setstate__(state) {
  4412. const handle = state.get('handle');
  4413. if (handle) {
  4414. this.handle = handle;
  4415. // XGBoosterLoadModelFromBuffer()
  4416. }
  4417. }
  4418. });
  4419. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4420. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4421. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4422. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4423. return new builtins.bytearray(obj, encoding);
  4424. });
  4425. this.registerType('builtins.bytearray', class extends Uint8Array {
  4426. constructor(source, encoding /*, errors */) {
  4427. source = builtins.bytes.__encode__(source, encoding);
  4428. super(Number.isInteger(source) ? source : source.length);
  4429. if (Array.isArray(source)) {
  4430. for (let i = 0; i < source.length; i++) {
  4431. this[i] = source;
  4432. }
  4433. } else if (source instanceof Uint8Array) {
  4434. this.set(source, 0);
  4435. } else if (typeof source === 'string') {
  4436. for (let i = 0; i < source.length; i++) {
  4437. this[i] = source.charCodeAt(i);
  4438. }
  4439. }
  4440. }
  4441. static __encode__(source, encoding) {
  4442. if (source === undefined) {
  4443. return 0;
  4444. }
  4445. if (Number.isInteger(source)) {
  4446. return source;
  4447. }
  4448. if (Array.isArray(source) || source instanceof Uint8Array) {
  4449. return source;
  4450. }
  4451. if (typeof source === 'string') {
  4452. switch (encoding) {
  4453. case 'latin1':
  4454. case 'latin-1':
  4455. return source;
  4456. case 'utf8':
  4457. case 'utf-8':
  4458. return new TextEncoder('utf-8').encode(source);
  4459. case undefined:
  4460. throw new python.Error('Unsupported string argument without an encoding.');
  4461. default:
  4462. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4463. }
  4464. }
  4465. throw new python.Error('Unsupported source.');
  4466. }
  4467. });
  4468. this.registerType('builtins.bytes', class extends Uint8Array {
  4469. constructor(source, encoding /*, errors */) {
  4470. source = builtins.bytes.__encode__(source, encoding);
  4471. super(Number.isInteger(source) ? source : source.length);
  4472. if (Array.isArray(source)) {
  4473. for (let i = 0; i < source.length; i++) {
  4474. this[i] = source;
  4475. }
  4476. } else if (source instanceof Uint8Array) {
  4477. this.set(source, 0);
  4478. } else if (typeof source === 'string') {
  4479. for (let i = 0; i < source.length; i++) {
  4480. this[i] = source.charCodeAt(i);
  4481. }
  4482. }
  4483. }
  4484. static __encode__(source, encoding) {
  4485. if (source === undefined) {
  4486. return 0;
  4487. }
  4488. if (Number.isInteger(source)) {
  4489. return source;
  4490. }
  4491. if (Array.isArray(source) || source instanceof Uint8Array) {
  4492. return source;
  4493. }
  4494. if (typeof source === 'string') {
  4495. switch (encoding) {
  4496. case 'latin1':
  4497. case 'latin-1':
  4498. return source;
  4499. case 'utf8':
  4500. case 'utf-8':
  4501. return new TextEncoder('utf-8').encode(source);
  4502. case undefined:
  4503. throw new python.Error('Unsupported string argument without an encoding.');
  4504. default:
  4505. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4506. }
  4507. }
  4508. throw new python.Error('Unsupported source.');
  4509. }
  4510. });
  4511. this.registerType('builtins.memoryview', class {
  4512. constructor(buf) {
  4513. this._buf = buf;
  4514. }
  4515. get nbytes() {
  4516. return this._buf.length;
  4517. }
  4518. });
  4519. this.registerType('builtins.frozenset', class extends Set {
  4520. constructor(iterable) {
  4521. super();
  4522. if (iterable) {
  4523. for (const item of iterable) {
  4524. this.add(item);
  4525. }
  4526. }
  4527. }
  4528. });
  4529. this.registerFunction('builtins.exec');
  4530. this.registerFunction('builtins.issubclass', (obj, type) => {
  4531. const name = `${type.__module__}.${type.__name__}`;
  4532. if (obj.__module__ && obj.__name__) {
  4533. if (name === `${obj.__module__}.${obj.__name__}`) {
  4534. return true;
  4535. }
  4536. }
  4537. if (obj.__bases__) {
  4538. for (const base of obj.__bases__) {
  4539. if (builtins.issubclass(base, type)) {
  4540. return true;
  4541. }
  4542. }
  4543. }
  4544. return false;
  4545. });
  4546. this.registerFunction('builtins.isinstance', (obj, type) => {
  4547. if (obj && type && obj instanceof type) {
  4548. return true;
  4549. }
  4550. if (obj && obj.__class__) {
  4551. return builtins.issubclass(obj.__class__, type);
  4552. }
  4553. return false;
  4554. });
  4555. this.registerFunction('builtins.hasattr', (obj, name) => {
  4556. if (obj instanceof Map && obj.__contains__) {
  4557. return obj.__contains__(name);
  4558. }
  4559. return Object.prototype.hasOwnProperty.call(obj, name);
  4560. });
  4561. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4562. if (obj && obj.__getattr__) {
  4563. return obj.__getattr__(name);
  4564. }
  4565. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4566. return obj[name];
  4567. }
  4568. return defaultValue;
  4569. });
  4570. this.registerFunction('builtins.len', (obj) => {
  4571. return obj.length;
  4572. });
  4573. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4574. if (obj && obj.__setattr__) {
  4575. obj.__setattr__(name, value);
  4576. } else {
  4577. obj[name] = value;
  4578. }
  4579. });
  4580. this.registerType('builtins.set', class extends Set {
  4581. __contains__(item) {
  4582. return this.has(item);
  4583. }
  4584. update(iterable) {
  4585. for (const item of iterable) {
  4586. this.add(item);
  4587. }
  4588. }
  4589. });
  4590. this.registerType('builtins.slice', class {
  4591. constructor(start, stop, step) {
  4592. this.start = start;
  4593. this.stop = stop;
  4594. this.step = step;
  4595. }
  4596. });
  4597. this.registerFunction('builtins.hash');
  4598. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4599. return name;
  4600. });
  4601. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4602. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4603. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4604. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4605. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4606. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4607. cell.cell_contents = value;
  4608. }
  4609. return cell;
  4610. });
  4611. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4612. // globals["__builtins__"] = __builtins__
  4613. return new types.FunctionType(code, globals, name, argdefs, closure);
  4614. });
  4615. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4616. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4617. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4618. if (class_tracker_id) {
  4619. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4620. }
  4621. return class_def;
  4622. });
  4623. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4624. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4625. const kwds = { 'metaclass': type_constructor };
  4626. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4627. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4628. });
  4629. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4630. return new builtins.cell();
  4631. });
  4632. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4633. [state] = state;
  4634. let registry = null;
  4635. for (const [attrname, attr] of state.items()) {
  4636. if (attrname === '_abc_impl') {
  4637. registry = attr;
  4638. } else {
  4639. builtins.setattr(obj, attrname, attr);
  4640. }
  4641. }
  4642. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4643. obj.__firstlineno__ = state.get('__firstlineno__');
  4644. }
  4645. if (registry) {
  4646. for (const subclass of registry) {
  4647. obj.register(subclass);
  4648. }
  4649. }
  4650. return obj;
  4651. });
  4652. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4653. const [, slotstate] = state;
  4654. [state] = state;
  4655. // obj.__dict__.update(state)
  4656. /* const obj_globals = */ slotstate.pop('__globals__');
  4657. const obj_closure = slotstate.pop('__closure__');
  4658. slotstate.pop('_cloudpickle_submodules');
  4659. if (obj.__globals__) {
  4660. // obj.__globals__.update(obj_globals);
  4661. // obj.__globals__.__builtins__ = __builtins__;
  4662. }
  4663. if (obj_closure) {
  4664. // let value = null;
  4665. for (let i = 0; i < obj_closure.length; i++) {
  4666. // const cell = obj_closure[i];
  4667. try {
  4668. // value = cell.cell_contents;
  4669. } catch {
  4670. // cell is empty
  4671. }
  4672. // obj.__closure__[i].cell_contents = value;
  4673. }
  4674. }
  4675. for (const [k, v] of slotstate.items()) {
  4676. builtins.setattr(obj, k, v);
  4677. }
  4678. });
  4679. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4680. execution.__import__(name);
  4681. return sys.modules.get(name);
  4682. });
  4683. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4684. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4685. const ray = this.register('ray');
  4686. this.register('ray.cloudpickle.cloudpickle');
  4687. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4688. this.registerType('collections.Counter', class {});
  4689. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4690. return {};
  4691. });
  4692. this.registerFunction('copy.deepcopy');
  4693. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4694. // copyreg._reconstructor in Python 3
  4695. if (base === '__builtin__.object' || base === builtins.object) {
  4696. return self.invoke(cls, []);
  4697. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4698. const obj = self.invoke(cls, []);
  4699. for (let i = 0; i < state.length; i++) {
  4700. obj[i] = state[i];
  4701. }
  4702. return obj;
  4703. }
  4704. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4705. });
  4706. this.registerFunction('copy.deepcopy', (/* x */) => {
  4707. throw new python.Error('Unsupported copy.deepcopy().');
  4708. });
  4709. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4710. const array = f(...args);
  4711. if (array.__setstate__) {
  4712. array.__setstate__(state);
  4713. }
  4714. if (npdict) {
  4715. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4716. }
  4717. return array;
  4718. });
  4719. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4720. return function() {
  4721. };
  4722. });
  4723. this.registerFunction('dill._dill._create_code', (args) => {
  4724. return self.invoke('types.CodeType', [args]);
  4725. });
  4726. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4727. return function() {
  4728. };
  4729. });
  4730. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4731. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4732. if (obj) {
  4733. return obj;
  4734. }
  4735. return undefined;
  4736. });
  4737. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4738. const [name, bases, dict] = args;
  4739. const type = class extends bases[0] {};
  4740. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4741. return self.registerType(identifier, Object.assign(type, dict));
  4742. });
  4743. this.registerFunction('dill._dill._eval_repr');
  4744. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4745. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4746. return self[name];
  4747. }
  4748. return undefined;
  4749. });
  4750. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4751. try {
  4752. if (import_name.startsWith('__runtime__.')) {
  4753. return execution.module(import_name);
  4754. } else if (import_name.indexOf('.') === -1) {
  4755. return execution.__import__(import_name);
  4756. }
  4757. return execution.resolve(import_name);
  4758. } catch (error) {
  4759. if (safe) {
  4760. return null;
  4761. }
  4762. throw error;
  4763. }
  4764. });
  4765. this.registerFunction('dill._dill._load_type', (name) => {
  4766. const _dill = self.register('dill._dill');
  4767. if (!_dill._reverse_typemap) {
  4768. _dill._reverse_typemap = new Map();
  4769. for (const name of ['__builtin__', 'types']) {
  4770. const module = self.register(name);
  4771. for (const [name, obj] of Object.entries(module)) {
  4772. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4773. _dill._reverse_typemap.set(name, obj);
  4774. }
  4775. }
  4776. }
  4777. _dill._reverse_typemap.set('PartialType', functools.partial);
  4778. _dill._reverse_typemap.set('CellType', builtins.cell);
  4779. }
  4780. if (!_dill._reverse_typemap.has(name)) {
  4781. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4782. }
  4783. return _dill._reverse_typemap.get(name);
  4784. });
  4785. this.registerFunction('dill._dill.loads');
  4786. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4787. const np_value = fun(...args);
  4788. np_value.__setstate__(arr_state);
  4789. const jnp_value = jax.device_put(np_value);
  4790. jnp_value.aval = jnp_value.aval.update(aval_state);
  4791. return jnp_value;
  4792. });
  4793. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4794. this.registerFunction('jax.device_put', (x) => {
  4795. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4796. return new jax.Array(aval, x.data);
  4797. });
  4798. this.registerType('jax._src.core.AbstractValue', class {});
  4799. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4800. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4801. constructor(shape, dtype, weak_type) {
  4802. super();
  4803. this.shape = shape;
  4804. this.dtype = dtype;
  4805. this.weak_type = weak_type || false;
  4806. }
  4807. update(dict) {
  4808. const shape = dict.get('shape') || this.shape;
  4809. const dtype = dict.get('dtype') || this.dtype;
  4810. const weak_type = dict.get('weak_type') || this.weak_type;
  4811. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4812. }
  4813. });
  4814. this.registerType('jax.Array', class {
  4815. constructor(aval, data) {
  4816. this.aval = aval;
  4817. this.data = data;
  4818. }
  4819. get dtype() {
  4820. return this.aval.dtype;
  4821. }
  4822. get shape() {
  4823. return this.aval.shape;
  4824. }
  4825. tobytes() {
  4826. return this.data;
  4827. }
  4828. });
  4829. jax.numpy.ndarray = jax.Array;
  4830. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4831. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4832. });
  4833. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4834. this.registerFunction('lasagne.nonlinearities.rectify');
  4835. this.registerFunction('lasagne.nonlinearities.softmax');
  4836. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4837. this.registerFunction('lasagne.updates.nesterov_momentum');
  4838. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4839. const BinaryReader = class {
  4840. constructor(buffer, ext_hook) {
  4841. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4842. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4843. this._buffer = buffer;
  4844. this._position = 0;
  4845. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4846. this._ext_hook = ext_hook;
  4847. }
  4848. value() {
  4849. const c = this._view.getUint8(this.skip(1));
  4850. if (c >= 0xe0) {
  4851. return c - 0x100;
  4852. }
  4853. if (c < 0xC0) {
  4854. if (c < 0x80) {
  4855. return c;
  4856. }
  4857. if (c < 0x90) {
  4858. return this.map(c - 0x80);
  4859. }
  4860. if (c < 0xa0) {
  4861. return this.array(c - 0x90);
  4862. }
  4863. return this.string(c - 0xa0);
  4864. }
  4865. switch (c) {
  4866. case 0xC0: return null;
  4867. case 0xC2: return false;
  4868. case 0xC3: return true;
  4869. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4870. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4871. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4872. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4873. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4874. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4875. case 0xCA: return this._view.getFloat32(this.skip(4));
  4876. case 0xCB: return this._view.getFloat64(this.skip(8));
  4877. case 0xCC: return this._view.getUint8(this.skip(1));
  4878. case 0xCD: return this._view.getUint16(this.skip(2));
  4879. case 0xCE: return this._view.getUint32(this.skip(4));
  4880. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4881. case 0xD0: return this._view.getInt8(this.skip(1));
  4882. case 0xD1: return this._view.getInt16(this.skip(2));
  4883. case 0xD2: return this._view.getInt32(this.skip(4));
  4884. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4885. case 0xD4: return this.extension(1);
  4886. case 0xD5: return this.extension(2);
  4887. case 0xD6: return this.extension(4);
  4888. case 0xD7: return this.extension(8);
  4889. case 0xD8: return this.extension(16);
  4890. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4891. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4892. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4893. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4894. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4895. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4896. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4897. default: throw new python.Error(`Invalid code '${c}'.`);
  4898. }
  4899. }
  4900. map(size) {
  4901. const map = {};
  4902. for (let i = 0; i < size; i++) {
  4903. const key = this.value();
  4904. const value = this.value();
  4905. map[key] = value;
  4906. }
  4907. return map;
  4908. }
  4909. array(size) {
  4910. const array = new Array(size);
  4911. for (let i = 0; i < size; i++) {
  4912. array[i] = this.value();
  4913. }
  4914. return array;
  4915. }
  4916. extension(size) {
  4917. const code = this._view.getUint8(this.skip(1));
  4918. const data = this.read(size);
  4919. return this._ext_hook(code, data);
  4920. }
  4921. skip(offset) {
  4922. const position = this._position;
  4923. this._position += offset;
  4924. if (this._position > this._buffer.length) {
  4925. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4926. }
  4927. return position;
  4928. }
  4929. read(size) {
  4930. const data = this._buffer.subarray(this._position, this._position + size);
  4931. this._position += size;
  4932. return data;
  4933. }
  4934. string(size) {
  4935. const buffer = this.read(size);
  4936. this._decoder = this._decoder || new TextDecoder('utf8');
  4937. return this._decoder.decode(buffer);
  4938. }
  4939. };
  4940. return new BinaryReader(packed, ext_hook).value();
  4941. });
  4942. this.registerFunction('nolearn.lasagne.base.objective');
  4943. this.registerFunction('numpy.core._DType_reconstruct');
  4944. this.registerFunction('numpy.core._ufunc_reconstruct');
  4945. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4946. return numpy.ndarray.__new__(subtype, shape, dtype);
  4947. });
  4948. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4949. const shape = [buf.length / dtype.itemsize];
  4950. return new numpy.ndarray(shape, dtype, buf);
  4951. });
  4952. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  4953. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  4954. });
  4955. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  4956. return new numpy.dtypes.StringDType();
  4957. });
  4958. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  4959. let data = rawData;
  4960. if (typeof rawData === 'string' || rawData instanceof String) {
  4961. data = new Uint8Array(rawData.length);
  4962. for (let i = 0; i < rawData.length; i++) {
  4963. data[i] = rawData.charCodeAt(i);
  4964. }
  4965. }
  4966. switch (dtype.kind) {
  4967. case 'b': {
  4968. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4969. switch (dtype.itemsize) {
  4970. case 1: return view.getInt8(0) ? true : false;
  4971. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  4972. }
  4973. }
  4974. case 'f': {
  4975. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4976. switch (dtype.itemsize) {
  4977. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  4978. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  4979. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  4980. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  4981. }
  4982. }
  4983. case 'i': {
  4984. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4985. switch (dtype.itemsize) {
  4986. case 1: return view.getInt8(0);
  4987. case 2: return view.getInt16(0, dtype.byteorder === '<');
  4988. case 4: return view.getInt32(0, dtype.byteorder === '<');
  4989. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  4990. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  4991. }
  4992. }
  4993. case 'u': {
  4994. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  4995. switch (dtype.itemsize) {
  4996. case 1: return view.getUint8(0);
  4997. case 2: return view.getUint16(0, dtype.byteorder === '<');
  4998. case 4: return view.getUint32(0, dtype.byteorder === '<');
  4999. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5000. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5001. }
  5002. }
  5003. case 'U': {
  5004. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5005. const list = [];
  5006. for (let i = 0; i < dtype.itemsize; i += 4) {
  5007. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5008. }
  5009. return list.join('');
  5010. }
  5011. default: {
  5012. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5013. }
  5014. }
  5015. });
  5016. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5017. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5018. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5019. this.registerFunction('numpy.core._multiarray_umath.greater');
  5020. this.registerFunction('numpy.core._multiarray_umath.less');
  5021. this.registerFunction('numpy.core._multiarray_umath.log');
  5022. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5023. let data = rawData;
  5024. if (typeof rawData === 'string') {
  5025. data = new Uint8Array(rawData.length);
  5026. for (let i = 0; i < rawData.length; i++) {
  5027. data[i] = rawData.charCodeAt(i);
  5028. }
  5029. }
  5030. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5031. switch (dtype.__name__) {
  5032. case 'uint8':
  5033. return dataView.getUint8(0);
  5034. case 'float32':
  5035. return dataView.getFloat32(0, true);
  5036. case 'float64':
  5037. return dataView.getFloat64(0, true);
  5038. case 'int8':
  5039. return dataView.getInt8(0, true);
  5040. case 'int16':
  5041. return dataView.getInt16(0, true);
  5042. case 'int32':
  5043. return dataView.getInt32(0, true);
  5044. case 'int64':
  5045. return dataView.getBigInt64(0, true);
  5046. default:
  5047. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5048. }
  5049. });
  5050. this.registerFunction('numpy.core._multiarray_umath.sin');
  5051. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5052. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5053. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5054. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5055. this.register('numpy.core.numeric', numpy._core.numeric);
  5056. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5057. this.registerFunction('numpy.load', (file) => {
  5058. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5059. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5060. if (!file.read(6).every((v, i) => v === signature[i])) {
  5061. throw new python.Error('Invalid signature.');
  5062. }
  5063. const version = file.read(2);
  5064. const [major, minor] = version;
  5065. if (major > 3) {
  5066. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5067. }
  5068. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5069. let data = null;
  5070. switch (dtype.byteorder) {
  5071. case '|': {
  5072. data = file.read();
  5073. if (dtype.kind === 'O') {
  5074. const unpickler = new pickle.Unpickler(data);
  5075. return unpickler.load();
  5076. }
  5077. break;
  5078. }
  5079. case '>':
  5080. case '<': {
  5081. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5082. const stream = file.getbuffer().nbytes > 0x1000000;
  5083. data = file.read(dtype.itemsize * count, stream);
  5084. break;
  5085. }
  5086. default: {
  5087. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5088. }
  5089. }
  5090. if (fortran_order) {
  5091. data = null;
  5092. }
  5093. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5094. });
  5095. this.registerFunction('numpy.save', (file, arr) => {
  5096. const descr = arr.dtype.str;
  5097. if (descr[0] !== '<' && descr[0] !== '>') {
  5098. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5099. }
  5100. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5101. throw new python.Error(`Unsupported data type '${descr}'.`);
  5102. }
  5103. let shape = '';
  5104. switch (arr.shape.length) {
  5105. case 0: shape = '()'; break;
  5106. case 1: shape = `(${arr.shape[0]},)`; break;
  5107. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5108. }
  5109. const properties = [
  5110. `'descr': '${descr}'`,
  5111. "'fortran_order': False",
  5112. `'shape': ${shape}`
  5113. ];
  5114. let header = `{ ${properties.join(', ')} }`;
  5115. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5116. const encoder = new TextEncoder('ascii');
  5117. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5118. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5119. file.write(encoder.encode(header));
  5120. file.write(arr.tobytes());
  5121. });
  5122. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5123. const buffer = new Uint8Array([0, 0, 0, 0]);
  5124. const [major] = version;
  5125. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5126. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5127. let header = file.read(header_length);
  5128. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5129. header = decoder.decode(header).trim();
  5130. try {
  5131. header = ast.literal_eval(header);
  5132. } catch {
  5133. if (major <= 2) {
  5134. header = numpy.lib._format_impl._filter_header(header);
  5135. header = ast.literal_eval(header);
  5136. }
  5137. }
  5138. if (header.descr === undefined) {
  5139. throw new python.Error("Invalid 'descr'.");
  5140. }
  5141. if (!Array.isArray(header.shape)) {
  5142. throw new python.Error("Invalid 'shape'.");
  5143. }
  5144. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5145. return [header.shape, header.fortran_order, dtype];
  5146. });
  5147. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5148. if (typeof descr === 'string') {
  5149. return new numpy.dtype(descr);
  5150. } else if (descr instanceof builtins.tuple) {
  5151. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5152. return new numpy.dtype([dt, descr[1]]);
  5153. }
  5154. const titles = [];
  5155. const names = [];
  5156. const formats = [];
  5157. const offsets = [];
  5158. let offset = 0;
  5159. for (const field of descr) {
  5160. let name = null;
  5161. let dt = null;
  5162. let descr_str = null;
  5163. let shape = null;
  5164. let title = null;
  5165. if (field.length === 2) {
  5166. [name, descr_str] = field;
  5167. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5168. } else {
  5169. [name, descr_str, shape] = field;
  5170. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5171. }
  5172. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5173. if (!is_pad) {
  5174. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5175. titles.push(title);
  5176. names.push(name);
  5177. formats.push(dt);
  5178. offsets.push(offset);
  5179. }
  5180. offset += dt.itemsize;
  5181. }
  5182. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5183. });
  5184. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5185. const tokens = [];
  5186. const tokenizer = new ast._Tokenizer(s, '');
  5187. while (!tokenizer.match('eof')) {
  5188. const token = tokenizer.read();
  5189. if (token.type === 'int') {
  5190. const next = tokenizer.peek();
  5191. if (next.type === 'id' && next.value === 'L') {
  5192. tokenizer.read();
  5193. }
  5194. }
  5195. tokens.push(token.value);
  5196. }
  5197. return tokens.join('');
  5198. });
  5199. this.registerFunction('numpy.amin');
  5200. this.registerFunction('numpy.amax');
  5201. this.registerFunction('numpy.std');
  5202. this.registerFunction('numpy.asarray', (a, dtype) => {
  5203. const encode = (context, data, dim) => {
  5204. const size = context.shape[dim];
  5205. const littleendian = context.littleendian;
  5206. if (dim === context.shape.length - 1) {
  5207. for (let i = 0; i < size; i++) {
  5208. switch (context.dtype) {
  5209. case 'f2':
  5210. context.view.setFloat16(context.position, data[i], littleendian);
  5211. break;
  5212. case 'f4':
  5213. context.view.setFloat32(context.position, data[i], littleendian);
  5214. break;
  5215. case 'f8':
  5216. context.view.setFloat64(context.position, data[i], littleendian);
  5217. break;
  5218. case 'i1':
  5219. context.view.setInt8(context.position, data[i], littleendian);
  5220. break;
  5221. case 'i2':
  5222. context.view.setInt16(context.position, data[i], littleendian);
  5223. break;
  5224. case 'i4':
  5225. context.view.setInt32(context.position, data[i], littleendian);
  5226. break;
  5227. case 'i8':
  5228. context.view.setBigInt64(context.position, data[i], littleendian);
  5229. break;
  5230. case 'u1':
  5231. context.view.setUint8(context.position, data[i], littleendian);
  5232. break;
  5233. case 'u2':
  5234. context.view.setUint16(context.position, data[i], littleendian);
  5235. break;
  5236. case 'u4':
  5237. context.view.setUint32(context.position, data[i], littleendian);
  5238. break;
  5239. case 'u8':
  5240. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5241. break;
  5242. case 'c8':
  5243. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5244. break;
  5245. case 'c16':
  5246. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5247. break;
  5248. case 'b1':
  5249. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5250. break;
  5251. default:
  5252. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5253. }
  5254. context.position += context.itemsize;
  5255. }
  5256. } else {
  5257. for (let j = 0; j < size; j++) {
  5258. encode(context, data[j], dim + 1);
  5259. }
  5260. }
  5261. };
  5262. const array_size = (value) => {
  5263. if (value.every((item) => Array.isArray(item))) {
  5264. const dims = value.map((item) => array_size(item));
  5265. const [dim] = dims;
  5266. for (let i = 1; i < dims.length; i++) {
  5267. if (dim.length === dims[i].length) {
  5268. if (!dims[i].every((value, i) => value === dim[i])) {
  5269. throw new python.Error('Invalid array shape.');
  5270. }
  5271. }
  5272. }
  5273. return [value.length].concat(dim);
  5274. }
  5275. return [value.length];
  5276. };
  5277. const shape = Array.isArray(a) ? array_size(a) : [];
  5278. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5279. const context = {
  5280. position: 0,
  5281. itemsize: dtype.itemsize,
  5282. dtype: dtype.str.substring(1),
  5283. littleendian: dtype.str[0],
  5284. shape,
  5285. data: new Uint8Array(size)
  5286. };
  5287. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5288. encode(context, a, 0);
  5289. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5290. });
  5291. this.registerFunction('numpy.max');
  5292. this.registerFunction('numpy.mean');
  5293. this.registerFunction('numpy.min');
  5294. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5295. const data = self.invoke(baseclass, [baseshape, basetype]);
  5296. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5297. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5298. return self.invoke(subtype, [data, mask, basetype]);
  5299. });
  5300. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5301. return {};
  5302. });
  5303. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5304. return {};
  5305. });
  5306. this.registerType('numpy.random.bit_generator.BitGenerator', class {});
  5307. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5308. __setstate__(/* state */) {
  5309. }
  5310. });
  5311. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5312. const obj = new cls();
  5313. if (state) {
  5314. obj.__setstate__(state);
  5315. }
  5316. return obj;
  5317. });
  5318. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5319. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5320. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5321. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5322. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5323. numpy.random._pickle.BitGenerators = {
  5324. 'MT19937': numpy.random._mt19937.MT19937,
  5325. 'PCG64': numpy.random._pcg64.PCG64,
  5326. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5327. 'Philox': numpy.random._philox.Philox,
  5328. 'SFC64': numpy.random._sfc64.SFC64,
  5329. };
  5330. this.registerType('numpy.random._generator.Generator', class {
  5331. constructor(bit_generator) {
  5332. this.bit_generator = bit_generator;
  5333. }
  5334. });
  5335. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5336. bit_generator = bit_generator || 'MT19937';
  5337. let bit_gen_class = null;
  5338. if (builtins.isinstance(bit_generator, builtins.type)) {
  5339. bit_gen_class = bit_generator;
  5340. } else {
  5341. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5342. }
  5343. if (bit_gen_class) {
  5344. return new bit_gen_class();
  5345. }
  5346. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5347. });
  5348. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5349. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5350. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5351. });
  5352. this.registerFunction('numpy.reshape');
  5353. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5354. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5355. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5356. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5357. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5358. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5359. this.registerFunction('sklearn.metrics._classification.f1_score');
  5360. this.registerFunction('sklearn.metrics._classification.log_loss');
  5361. this.registerFunction('sklearn.metrics._classification.precision_score');
  5362. this.registerFunction('sklearn.metrics._classification.recall_score');
  5363. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5364. return obj.__new__(obj);
  5365. });
  5366. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5367. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5368. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5369. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5370. this.registerFunction('sklearn.metrics._regression.r2_score');
  5371. sklearn.metrics.regression = sklearn.metrics._regression;
  5372. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5373. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5374. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5375. this.registerFunction('re._compile', (pattern, flags) => {
  5376. return self.invoke('re.Pattern', [pattern, flags]);
  5377. });
  5378. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5379. return function() {
  5380. return self.invoke(`types.${args[0]}`, args);
  5381. };
  5382. });
  5383. this.registerType('sympy.printing.defaults.Printable', class {});
  5384. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5385. constructor(...args) {
  5386. super();
  5387. this._args = args;
  5388. }
  5389. get args() {
  5390. return this._args;
  5391. }
  5392. });
  5393. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5394. });
  5395. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5396. });
  5397. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5398. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5399. __str__() {
  5400. return this._args.map((a) => a.__str__()).join('**');
  5401. }
  5402. });
  5403. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5404. __str__() {
  5405. return this._args.map((a) => a.__str__()).join(' + ');
  5406. }
  5407. });
  5408. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5409. __str__() {
  5410. return this._args.map((a) => a.__str__()).join('*');
  5411. }
  5412. });
  5413. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5414. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5415. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5416. constructor(value) {
  5417. super();
  5418. this.value = value;
  5419. this.is_Integer = true;
  5420. }
  5421. __int__() {
  5422. return this.value;
  5423. }
  5424. __str__() {
  5425. return this.value.toString();
  5426. }
  5427. });
  5428. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5429. constructor(name) {
  5430. super();
  5431. this.name = name;
  5432. }
  5433. __int__() {
  5434. throw new python.Error('Cannot convert symbols to int.');
  5435. }
  5436. __str__() {
  5437. return this.name;
  5438. }
  5439. });
  5440. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5441. constructor(lhs, rhs, op) {
  5442. super();
  5443. this._args = [lhs, rhs];
  5444. this._op = op;
  5445. }
  5446. __str__() {
  5447. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5448. }
  5449. });
  5450. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5451. });
  5452. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5453. });
  5454. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5455. constructor(lhs, rhs) {
  5456. super(lhs, rhs, '>=');
  5457. }
  5458. });
  5459. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5460. });
  5461. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5462. constructor(lhs, rhs) {
  5463. super(lhs, rhs, '<=');
  5464. }
  5465. });
  5466. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5467. constructor(lhs, rhs) {
  5468. super(lhs, rhs, '<');
  5469. }
  5470. });
  5471. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5472. constructor(lhs, rhs) {
  5473. super(lhs, rhs, '>');
  5474. }
  5475. });
  5476. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5477. constructor(lhs, rhs) {
  5478. super(lhs, rhs, '==');
  5479. }
  5480. });
  5481. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5482. });
  5483. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5484. __str__() {
  5485. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5486. }
  5487. });
  5488. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5489. if (a instanceof sympy.core.expr.Expr) {
  5490. return a;
  5491. }
  5492. const p = ast.parse(a);
  5493. const sympify = (node) => {
  5494. if (node instanceof ast.Call) {
  5495. switch (node.func.id) {
  5496. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5497. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5498. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5499. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5500. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5501. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5502. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5503. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5504. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5505. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5506. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5507. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5508. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5509. }
  5510. }
  5511. if (node instanceof ast.Name) {
  5512. return new sympy.core.symbol.Symbol(node.id);
  5513. }
  5514. if (node instanceof ast.Constant) {
  5515. if (node.type === 'int') {
  5516. return new sympy.core.numbers.Integer(node.value);
  5517. }
  5518. }
  5519. if (node instanceof ast.BinOp) {
  5520. if (node.op instanceof ast.Mult) {
  5521. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5522. }
  5523. if (node.op instanceof ast.Pow) {
  5524. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5525. }
  5526. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5527. }
  5528. if (node instanceof ast.Compare) {
  5529. const left = sympify(node.left);
  5530. const right = sympify(node.comparators[0]);
  5531. const [op] = node.ops;
  5532. if (op instanceof ast.Gt) {
  5533. return new sympy.core.relational.StrictGreaterThan(left, right);
  5534. }
  5535. if (op instanceof ast.GtE) {
  5536. return new sympy.core.relational.GreaterThan(left, right);
  5537. }
  5538. if (op instanceof ast.Lt) {
  5539. return new sympy.core.relational.StrictLessThan(left, right);
  5540. }
  5541. if (op instanceof ast.LtE) {
  5542. return new sympy.core.relational.LessThan(left, right);
  5543. }
  5544. if (op instanceof ast.Eq) {
  5545. return new sympy.core.relational.Equality(left, right);
  5546. }
  5547. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5548. }
  5549. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5550. };
  5551. return sympify(p.body[0].value);
  5552. });
  5553. this.registerFunction('theano.scalar.basic.same_out');
  5554. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5555. this.registerFunction('theano.scalar.basic.upcast_out');
  5556. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5557. this.registerFunction('theano.tensor.nnet.conv2d');
  5558. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5559. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5560. this.registerType('torch.nn.modules.module.Module', class {
  5561. constructor() {
  5562. this._modules = new collections.OrderedDict();
  5563. this._parameters = new collections.OrderedDict();
  5564. this._buffers = new collections.OrderedDict();
  5565. }
  5566. __setattr__(name, value) {
  5567. if (value instanceof torch.nn.modules.module.Module) {
  5568. this._modules.set(name, value);
  5569. } else {
  5570. this[name] = value;
  5571. }
  5572. }
  5573. __getattr__(name) {
  5574. if (this._modules.has(name)) {
  5575. return this._modules.get(name);
  5576. }
  5577. return this[name];
  5578. }
  5579. __delattr__(name) {
  5580. if (this._modules.has(name)) {
  5581. this._modules.delete(name);
  5582. }
  5583. }
  5584. children() {
  5585. return this._modules.values();
  5586. }
  5587. named_modules(memo, prefix, remove_duplicate) {
  5588. memo = memo || new Set();
  5589. prefix = prefix || '';
  5590. const modules = new builtins.dict();
  5591. if (!memo.has(this)) {
  5592. if (remove_duplicate) {
  5593. memo.add(this);
  5594. }
  5595. modules.set(prefix, this);
  5596. for (const [name, module] of this._modules.items()) {
  5597. if (module && module.named_modules) {
  5598. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5599. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5600. modules.set(k, v);
  5601. }
  5602. }
  5603. }
  5604. }
  5605. return modules;
  5606. }
  5607. named_children() {
  5608. return this._modules;
  5609. }
  5610. parameters() {
  5611. return this._parameters.values();
  5612. }
  5613. named_parameters(recurse) {
  5614. if (recurse) {
  5615. throw new python.Error('Named parameters with recurse not implemented.');
  5616. }
  5617. return this._parameters;
  5618. }
  5619. buffers() {
  5620. return this._buffers.values();
  5621. }
  5622. named_buffers(recurse) {
  5623. if (recurse) {
  5624. throw new python.Error('Named parameters with recurse not implemented.');
  5625. }
  5626. return this._buffers;
  5627. }
  5628. _get_name() {
  5629. return this.__class__.__name__;
  5630. }
  5631. add_module(name, module) {
  5632. this._modules.set(name, module);
  5633. }
  5634. register_module(name, module) {
  5635. this.add_module(name, module);
  5636. }
  5637. });
  5638. torch.nn.Module = torch.nn.modules.module.Module;
  5639. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5640. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5641. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5642. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5643. this.registerType('torch._C.SchemaParser', class {
  5644. constructor(str, allow_typevars) {
  5645. this.L = new torch._C.Lexer(str);
  5646. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5647. }
  5648. parseName() {
  5649. const L = this.L;
  5650. let name = L.expect('id').text();
  5651. if (L.nextIf(':')) {
  5652. L.expect(':');
  5653. name = `${name}::${L.expect('ident').text()}`;
  5654. }
  5655. let overload_name = '';
  5656. if (L.nextIf('.')) {
  5657. overload_name = L.expect('ident').text();
  5658. }
  5659. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5660. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5661. return new torch._C.OperatorName(name, overload_name);
  5662. }
  5663. parseDeclaration() {
  5664. const L = this.L;
  5665. const name = this.parseName();
  5666. if (L.cur().kind !== '(') {
  5667. return name;
  5668. }
  5669. throw new python.Error('Not implemented.');
  5670. }
  5671. parseExactlyOneDeclaration() {
  5672. // const L = this.L;
  5673. const result = this.parseDeclaration();
  5674. // L.nextIf(TK_NEWLINE);
  5675. // L.expect(TK_EOF);
  5676. return result;
  5677. }
  5678. parseArgument(idx, is_return, kwarg_only) {
  5679. const L = this.L;
  5680. const type_parser = this.type_parser;
  5681. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5682. let N = null;
  5683. if (L.nextIf('[')) {
  5684. fake_type = torch.ListType.create(fake_type);
  5685. real_type = torch.ListType.create(real_type);
  5686. if (L.cur().kind === '#') {
  5687. N = Number(L.cur().text());
  5688. L.next();
  5689. }
  5690. L.expect(']');
  5691. let container = type_parser.parseAliasAnnotation();
  5692. if (alias_info) {
  5693. if (!container) {
  5694. container = new torch._C.AliasInfo();
  5695. container.is_write = alias_info.is_write;
  5696. }
  5697. container.addContainedType(alias_info);
  5698. }
  5699. alias_info = container;
  5700. if (L.nextIf('?')) {
  5701. fake_type = torch.OptionalType.create(fake_type);
  5702. real_type = torch.OptionalType.create(real_type);
  5703. }
  5704. }
  5705. let name = null;
  5706. /* eslint-disable no-undef-init */
  5707. let default_value = undefined;
  5708. /* eslint-enable no-undef-init */
  5709. if (is_return) {
  5710. kwarg_only = false;
  5711. if (L.cur().kind === 'id') {
  5712. name = L.next().text();
  5713. } else {
  5714. name = '';
  5715. }
  5716. } else {
  5717. name = L.expect('id').text();
  5718. if (L.nextIf('=')) {
  5719. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5720. }
  5721. }
  5722. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5723. }
  5724. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5725. // auto range = L.cur().range;
  5726. const L = this.L;
  5727. const range = null;
  5728. switch (kind) {
  5729. case torch._C.TypeKind.StringType:
  5730. case torch._C.TypeKind.OptionalType:
  5731. case torch._C.TypeKind.NumberType:
  5732. case torch._C.TypeKind.IntType:
  5733. case torch._C.TypeKind.BoolType:
  5734. case torch._C.TypeKind.FloatType:
  5735. case torch._C.TypeKind.ComplexType:
  5736. return this.parseSingleConstant(arg_type, kind, real_type);
  5737. case torch._C.TypeKind.ListType: {
  5738. const elem_type = arg_type.containedType(0);
  5739. const real_elem_type = real_type.containedType(0);
  5740. if (L.cur().kind === 'id') {
  5741. return this.parseTensorDefault(range);
  5742. } else if (arg_N && L.cur().kind !== '[') {
  5743. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5744. const repeated = Array(arg_N).fill(v);
  5745. // std::vector<IValue> repeated(arg_N, v);
  5746. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5747. }
  5748. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5749. }
  5750. case torch._C.TypeKind.DynamicType:
  5751. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5752. default:
  5753. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5754. }
  5755. }
  5756. parseSingleConstant(type, kind, real_type) {
  5757. const L = this.L;
  5758. if (kind === torch._C.TypeKind.DynamicType) {
  5759. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5760. }
  5761. // const auto& str2dtype = c10::getStringToDtypeMap();
  5762. if (L.cur().kind === 'id') {
  5763. if (L.cur().text() === 'True') {
  5764. L.next();
  5765. return new torch._C.IValue(true);
  5766. }
  5767. if (L.cur().text() === 'False') {
  5768. L.next();
  5769. return new torch._C.IValue(false);
  5770. }
  5771. if (L.cur().text() === 'None') {
  5772. L.next();
  5773. return new torch._C.IValue();
  5774. }
  5775. } else if (L.cur().kind === 'string') {
  5776. const token = L.next();
  5777. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5778. } else if (L.cur().kind === '#') {
  5779. let n = '';
  5780. if (L.nextIf('-')) {
  5781. n = `-${L.expect('#').text()}`; // # .text();
  5782. } else {
  5783. n = L.expect('#').text(); // # .text();
  5784. }
  5785. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5786. throw new Error("Complex type not implemented.");
  5787. /*
  5788. const imag = std::stod(n.substr(0, n.size() - 1));
  5789. return c10::complex<double>(0, imag);
  5790. */
  5791. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5792. const v = parseFloat(n);
  5793. return new torch._C.IValue(v, 'Double');
  5794. } else {
  5795. const v = parseInt(n, 10);
  5796. return new torch._C.IValue(v, 'Int');
  5797. }
  5798. }
  5799. throw new python.Error('Not implemented.');
  5800. /*
  5801. switch (L.cur().kind) {
  5802. case TK_TRUE:
  5803. L.next();
  5804. return true;
  5805. case TK_FALSE:
  5806. L.next();
  5807. return false;
  5808. case TK_NONE:
  5809. L.next();
  5810. return IValue();
  5811. case TK_STRINGLITERAL: {
  5812. const token = L.next();
  5813. return parseStringLiteral(token.range, token.text());
  5814. }
  5815. case TK_IDENT: {
  5816. const tok = L.next();
  5817. const text_view = tok.text_view();
  5818. // NB: float/complex/long are here for BC purposes. Other dtypes
  5819. // are handled via str2dtype.
  5820. // Please don't add more cases to this if-else block.
  5821. if ("float" == text_view) {
  5822. return static_cast<int64_t>("at::kFloat");
  5823. } else if ("complex" == text_view) {
  5824. return static_cast<int64_t>("at::kComplexFloat");
  5825. } else if ("long" == text_view) {
  5826. return static_cast<int64_t>("at::kLong");
  5827. } else if ("strided" == text_view) {
  5828. return static_cast<int64_t>("at::kStrided");
  5829. } else if ("Mean" == text_view) {
  5830. return static_cast<int64_t>("at::Reduction::Mean");
  5831. } else if ("contiguous_format" == text_view) {
  5832. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5833. } else {
  5834. const text = tok.text();
  5835. if (isPossiblyOptionalScalarType(real_type) &&
  5836. str2dtype.count(text) > 0) {
  5837. return static_cast<int64_t>(str2dtype.at(text));
  5838. } else {
  5839. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5840. }
  5841. }
  5842. }
  5843. default: {
  5844. let n;
  5845. if (L.nextIf('-')) {
  5846. n = "-" + L.expect(TK_NUMBER).text();
  5847. }
  5848. else {
  5849. n = L.expect(TK_NUMBER).text();
  5850. }
  5851. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5852. throw new python.Error('Complex type not implemented.');
  5853. const imag = std::stod(n.substr(0, n.size() - 1));
  5854. return c10::complex<double>(0, imag);
  5855. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5856. throw new python.Error('Float type not implemented.');
  5857. return std::stod(n);
  5858. } else {
  5859. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5860. int64_t v = std::stoll(n);
  5861. return v;
  5862. }
  5863. }
  5864. }
  5865. */
  5866. }
  5867. parseConstantList(type, kind, real_type) {
  5868. const L = this.L;
  5869. const tok = L.expect('[');
  5870. const vs = [];
  5871. if (L.cur().kind !== ']') {
  5872. do {
  5873. vs.push(this.parseSingleConstant(type, kind, real_type));
  5874. } while (L.nextIf(','));
  5875. }
  5876. L.expect(']');
  5877. return this.convertToList(type, kind, tok.range, vs);
  5878. }
  5879. convertToList(type, kind, range, vs) {
  5880. switch (kind) {
  5881. case torch._C.TypeKind.ComplexType:
  5882. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5883. case torch._C.TypeKind.FloatType:
  5884. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5885. case torch._C.TypeKind.IntType:
  5886. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5887. case torch._C.TypeKind.BoolType:
  5888. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5889. case torch._C.TypeKindDynamicType:
  5890. return this.convertToList(type.dynamicKind(), range, vs);
  5891. default:
  5892. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5893. throw new python.Error('lists are only supported for float, int and complex types');
  5894. }
  5895. }
  5896. });
  5897. this.registerType('torch.FunctionSchema', class {
  5898. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5899. const index = name.indexOf('(');
  5900. if (index === -1) {
  5901. this._name = name;
  5902. this._overload_name = overload_name || '';
  5903. this._arguments = args || [];
  5904. this._returns = returns || [];
  5905. this._is_vararg = is_vararg || false;
  5906. this._is_varret = is_varret || false;
  5907. } else {
  5908. const value = name.substring(0, index).trim();
  5909. const dot = value.indexOf('.');
  5910. if (dot === -1) {
  5911. this._name = value;
  5912. this._overload_name = '';
  5913. } else {
  5914. this._name = value.substring(0, dot);
  5915. this._overload_name = value.substring(dot + 1, value.length);
  5916. }
  5917. this._buffer = name.substring(index, name.length);
  5918. }
  5919. }
  5920. static parse(schema) {
  5921. return new torch.FunctionSchema(schema);
  5922. }
  5923. get name() {
  5924. return this._name;
  5925. }
  5926. get overload_name() {
  5927. return this._overload_name;
  5928. }
  5929. get arguments() {
  5930. this._parse();
  5931. return this._arguments;
  5932. }
  5933. get returns() {
  5934. this._parse();
  5935. return this._returns;
  5936. }
  5937. get is_vararg() {
  5938. this._parse();
  5939. return this._is_vararg;
  5940. }
  5941. get is_varret() {
  5942. this._parse();
  5943. return this._is_varret;
  5944. }
  5945. argumentIndexWithName(name) {
  5946. const index = this.arguments.findIndex((arg) => arg.name === name);
  5947. return index === -1 ? null : index;
  5948. }
  5949. _parse() {
  5950. if (this._buffer) {
  5951. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  5952. const L = parser.L;
  5953. this._arguments = [];
  5954. this._is_vararg = false;
  5955. this._kwarg_only = false;
  5956. let idx = 0;
  5957. L.expect('(');
  5958. if (!L.nextIf(')')) {
  5959. while (true) {
  5960. if (this._is_vararg) {
  5961. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  5962. }
  5963. if (L.nextIf('*')) {
  5964. this._kwarg_only = true;
  5965. } else if (L.nextIf('...')) {
  5966. this._is_vararg = true;
  5967. } else {
  5968. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  5969. this._arguments.push(argument);
  5970. }
  5971. if (!L.nextIf(',')) {
  5972. break;
  5973. }
  5974. }
  5975. L.expect(')');
  5976. }
  5977. L.expect('->');
  5978. this._returns = [];
  5979. this._is_varret = false;
  5980. if (L.nextIf('...')) {
  5981. this._is_varret = true;
  5982. } else if (L.nextIf('(')) {
  5983. if (!L.nextIf(')')) {
  5984. while (true) {
  5985. if (this._is_varret) {
  5986. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  5987. }
  5988. if (L.nextIf('...')) {
  5989. this._is_varret = true;
  5990. } else {
  5991. const argument = parser.parseArgument(idx++, true, false);
  5992. this._returns.push(argument);
  5993. }
  5994. if (!L.nextIf(',')) {
  5995. break;
  5996. }
  5997. }
  5998. L.expect(')');
  5999. }
  6000. } else {
  6001. this._returns.push(parser.parseArgument(0, true, false));
  6002. }
  6003. delete this._buffer;
  6004. }
  6005. }
  6006. __str__() {
  6007. const list = [this.name];
  6008. const overload_name = this.overload_name;
  6009. if (overload_name !== '' && overload_name !== 'default') {
  6010. list.push(`.${this.overload_name}`);
  6011. }
  6012. list.push('(');
  6013. let first = true;
  6014. let kwarg_only = false;
  6015. for (const argument of this.arguments) {
  6016. if (!first) {
  6017. list.push(', ');
  6018. }
  6019. if (argument.kwarg_only && !kwarg_only) {
  6020. list.push('*, ');
  6021. kwarg_only = true;
  6022. }
  6023. first = false;
  6024. list.push(argument.str());
  6025. }
  6026. if (this.is_vararg) {
  6027. if (!first) {
  6028. list.push(', ');
  6029. }
  6030. first = true;
  6031. list.push('...');
  6032. }
  6033. list.push(') -> ');
  6034. const returns = this.returns;
  6035. const braces = !this.is_varret &&
  6036. (returns.length !== 1 ||
  6037. returns[0].name ||
  6038. returns[0].real_type instanceof torch.TupleType ||
  6039. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6040. if (braces) {
  6041. list.push('(');
  6042. }
  6043. first = true;
  6044. for (const argument of this.returns) {
  6045. if (!first) {
  6046. list.push(', ');
  6047. }
  6048. first = false;
  6049. list.push(argument.str());
  6050. }
  6051. if (this.is_varret) {
  6052. if (!first) {
  6053. list.push(', ');
  6054. }
  6055. first = true;
  6056. list.push('...');
  6057. }
  6058. if (braces) {
  6059. list.push(')');
  6060. }
  6061. return list.join('');
  6062. }
  6063. aliasAnalysis() {
  6064. return this._alias_kind || 'CONSERVATIVE';
  6065. }
  6066. setAliasAnalysis(v) {
  6067. this._alias_kind = v;
  6068. }
  6069. hasAnyAliasInfo() {
  6070. for (const arg of this.arguments) {
  6071. if (arg.alias_info !== null) {
  6072. return true;
  6073. }
  6074. }
  6075. for (const ret of this.returns) {
  6076. if (ret.alias_info !== null) {
  6077. return true;
  6078. }
  6079. }
  6080. return false;
  6081. }
  6082. is_mutable() {
  6083. return this.arguments.some((arg) => {
  6084. const aliasInfo = arg.alias_info;
  6085. return aliasInfo && aliasInfo.is_write;
  6086. });
  6087. }
  6088. });
  6089. this.registerType('torch._C.SchemaInfo', class {
  6090. constructor(schema) {
  6091. this._schema = schema;
  6092. this._alias_maps_current = false;
  6093. this._has_init = false;
  6094. }
  6095. is_nondeterministic() {
  6096. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6097. //
  6098. }
  6099. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6100. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6101. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6102. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6103. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6104. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6105. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6106. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6107. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6108. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6109. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6110. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6111. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6112. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6113. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6114. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6115. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6116. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6117. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6118. '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',
  6119. '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',
  6120. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6121. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6122. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6123. ]);
  6124. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6125. return true;
  6126. }
  6127. /*
  6128. const auto& op = c10::Dispatcher::singleton().findOp(
  6129. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6130. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6131. */
  6132. return false;
  6133. }
  6134. });
  6135. this.registerType('torch._C.OperatorRegistry', class {
  6136. constructor() {
  6137. this.to_register = [];
  6138. this.operators = new Map();
  6139. }
  6140. registerPendingOperators() {
  6141. for (const op of this.to_register) {
  6142. const sym = op.schema().name;
  6143. if (!this.operators.has(sym)) {
  6144. this.operators.set(sym, []);
  6145. }
  6146. this.operators.get(sym).push(op);
  6147. }
  6148. this.to_register = [];
  6149. }
  6150. registerOperator(op) {
  6151. this.to_register.push(op);
  6152. }
  6153. getOperators(name) {
  6154. this.registerPendingOperators();
  6155. if (this.operators.has(name)) {
  6156. return this.operators.get(name);
  6157. }
  6158. return [];
  6159. }
  6160. });
  6161. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6162. return torch._C.getRegistry().getOperators(name);
  6163. });
  6164. this.registerType('torch._C.Operator', class {
  6165. constructor(schema) {
  6166. this._schema = schema;
  6167. }
  6168. schema() {
  6169. return this._schema;
  6170. }
  6171. getOperation(/* node */) {
  6172. return null;
  6173. }
  6174. aliasAnalysisKind() {
  6175. const schemaRef = this.schema();
  6176. const alias_analysis = schemaRef.aliasAnalysis();
  6177. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6178. return alias_analysis;
  6179. }
  6180. });
  6181. this.registerFunction('torch._C.getRegistry', () => {
  6182. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6183. return torch._C.r;
  6184. });
  6185. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6186. const operations = torch._C.getAllOperatorsFor(op_name);
  6187. for (const op of operations) {
  6188. if (op.schema().overload_name === overload_name) {
  6189. return op.schema();
  6190. }
  6191. }
  6192. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6193. });
  6194. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6195. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6196. });
  6197. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6198. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6199. if (sortedOps.length === 0) {
  6200. return [null, null];
  6201. }
  6202. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6203. return [{}, overload_names];
  6204. });
  6205. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6206. const operations = torch._C.getAllOperatorsFor(op_name);
  6207. for (const op of operations) {
  6208. if (op.schema().overload_name === overload_name) {
  6209. return [{}, {}, null];
  6210. }
  6211. }
  6212. return null;
  6213. });
  6214. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6215. return null;
  6216. });
  6217. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6218. });
  6219. this.registerType('torch._C.MatchedSchema', class {
  6220. constructor(inputs, return_types, return_field_names, schema_name) {
  6221. this.inputs = inputs;
  6222. this.return_types = return_types;
  6223. this.register_field_names = return_field_names;
  6224. this.schema_name = schema_name;
  6225. }
  6226. });
  6227. this.registerType('torch._C.Self', class {
  6228. });
  6229. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6230. return nvs.map((v) => v.value(g));
  6231. });
  6232. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6233. constructor(classType) {
  6234. super();
  6235. this._classType = classType;
  6236. }
  6237. makeSugared(v) {
  6238. v.setType(this._classType);
  6239. return new torch._C.SimpleValue(v);
  6240. }
  6241. getClassType() {
  6242. return this._classType;
  6243. }
  6244. });
  6245. this.registerType('torch._C.Function', class {
  6246. isGraphFunction() {
  6247. return false;
  6248. }
  6249. name() {
  6250. return this.qualname().name();
  6251. }
  6252. });
  6253. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6254. constructor(qualname, schema) {
  6255. super();
  6256. this._name = qualname;
  6257. this._schema = schema;
  6258. }
  6259. qualname() {
  6260. return this._name;
  6261. }
  6262. getSchema() {
  6263. return this._schema;
  6264. }
  6265. ensure_defined() {
  6266. }
  6267. });
  6268. this.registerType('torch._C.DeadCodeEliminator', class {
  6269. constructor(...args) {
  6270. this._aliasDb = null;
  6271. this._useAliasDb = false;
  6272. this._memo = new Map();
  6273. this._marked = new Set();
  6274. this._liveValues = new Set();
  6275. this._deleteCallback = () => {};
  6276. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6277. [this._graph, this._sideEffectPolicy] = args;
  6278. this._useAliasDb = true;
  6279. } else {
  6280. [this._sideEffectPolicy] = args;
  6281. }
  6282. }
  6283. run(block, recurse) {
  6284. this.eliminateDeadForkInputs(block, recurse);
  6285. this.mark(block.return_node());
  6286. this.mark(block);
  6287. this._deleteCallback(this._liveValues);
  6288. this.sweep(block, recurse);
  6289. }
  6290. setDeleteCallback(deleteCallback) {
  6291. this._deleteCallback = deleteCallback;
  6292. }
  6293. eliminateDeadForkInputs(block, recurse) {
  6294. for (const node of block.nodes()) {
  6295. if (recurse) {
  6296. for (const sb of node.blocks()) {
  6297. this.eliminateDeadForkInputs(sb, recurse);
  6298. }
  6299. }
  6300. if (node.kind() !== 'prim::fork') {
  6301. continue;
  6302. }
  6303. const g = node.g("Subgraph");
  6304. for (let i = 0; i < g.inputs().length; i++) {
  6305. if (!g.inputs()[i].hasUses()) {
  6306. g.eraseInput(i);
  6307. node.removeInput(i);
  6308. }
  6309. }
  6310. }
  6311. }
  6312. markReturnNode(node) {
  6313. if (this._marked.has(node)) {
  6314. return false;
  6315. }
  6316. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6317. const outerNode = node.owningBlock().owningNode();
  6318. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6319. return this.mark(node);
  6320. }
  6321. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6322. const loop = new torch._C.LoopView(outerNode);
  6323. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6324. if (outerNode.kind() === 'onnx::Loop') {
  6325. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6326. continue;
  6327. }
  6328. const innerInput = loop.bodyCarriedInputs()[i];
  6329. const innerOutput = loop.bodyCarriedOutputs()[i];
  6330. const outerOutput = loop.carriedOutputs()[i];
  6331. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6332. this._liveValues.add(innerOutput);
  6333. }
  6334. }
  6335. this._liveValues.add(loop.nextCond());
  6336. } else {
  6337. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6338. for (let i = 0; i < outerNode.outputs().length; i++) {
  6339. const innerOutput = node.inputs()[i];
  6340. const outerOutput = outerNode.outputs()[i];
  6341. if (!this._liveValues.has(outerOutput)) {
  6342. this._liveValues.add(innerOutput);
  6343. }
  6344. }
  6345. }
  6346. this._marked.add(node);
  6347. return true;
  6348. }
  6349. markLoop(node) {
  6350. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6351. let marked = false;
  6352. let anyMarked = false;
  6353. do {
  6354. marked = this.mark(node.blocks().at(0));
  6355. anyMarked = anyMarked || marked;
  6356. } while (marked);
  6357. return anyMarked;
  6358. }
  6359. mark(...args) {
  6360. if (args.length === 1 && args[0] instanceof torch.Block) {
  6361. const [block] = args;
  6362. let anyMarked = false;
  6363. for (const node of block.nodes()) {
  6364. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6365. const marked = this.mark(node);
  6366. anyMarked = anyMarked || marked;
  6367. }
  6368. }
  6369. const marked = this.markReturnNode(block.return_node());
  6370. anyMarked = anyMarked || marked;
  6371. for (const node of block.nodes()) {
  6372. if (node.kind() === 'prim::Loop') {
  6373. const marked = this.markLoop(node);
  6374. anyMarked = anyMarked || marked;
  6375. } else {
  6376. for (const subBlock of node.blocks()) {
  6377. const marked = this.mark(subBlock);
  6378. anyMarked = anyMarked || marked;
  6379. }
  6380. }
  6381. const marked = this.markIfLive(node);
  6382. anyMarked = anyMarked || marked;
  6383. }
  6384. return anyMarked;
  6385. }
  6386. if (args.length === 1 && args[0] instanceof torch.Node) {
  6387. const [node] = args;
  6388. if (this._marked.has(node)) {
  6389. return false;
  6390. }
  6391. this._marked.add(node);
  6392. let curNode = node;
  6393. while (curNode && curNode.owningBlock()) {
  6394. this.mark(curNode);
  6395. curNode = curNode.owningBlock().owningNode();
  6396. }
  6397. for (const input of node.inputs()) {
  6398. if (!this._liveValues.has(input)) {
  6399. this._liveValues.add(input);
  6400. }
  6401. }
  6402. return true;
  6403. }
  6404. throw new python.Error('Not implemented.');
  6405. }
  6406. markIfLive(node) {
  6407. for (const output of node.outputs()) {
  6408. if (this._liveValues.has(output)) {
  6409. return this.mark(node);
  6410. }
  6411. }
  6412. if (this._useAliasDb) {
  6413. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6414. return this.mark(node);
  6415. }
  6416. }
  6417. return false;
  6418. }
  6419. sweep(block, recurse) {
  6420. const nodes = Array.from(block.nodes()).reverse();
  6421. for (const node of nodes) {
  6422. this.removeDeadBlockOutputs(node);
  6423. this.removeDeadLoopOutputs(node);
  6424. if (recurse) {
  6425. for (const block of node.blocks()) {
  6426. this.sweep(block, true);
  6427. }
  6428. }
  6429. if (!this._marked.has(node) && !node.hasUses()) {
  6430. node.destroy();
  6431. }
  6432. }
  6433. }
  6434. hasUntrackedMutation(node) {
  6435. if (!this._useAliasDb) {
  6436. if (node.kind() === 'prim::SetAttr') {
  6437. return true;
  6438. }
  6439. const schema = node.maybeSchema();
  6440. return schema && schema.is_mutable();
  6441. }
  6442. return this.getOrCreateAliasDb().writesToWildcard(node);
  6443. }
  6444. hasSideEffects(node) {
  6445. const it = this._memo.get(node);
  6446. if (it) {
  6447. return it;
  6448. }
  6449. const has_side_effects = node.hasSideEffects() ||
  6450. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6451. this.hasUntrackedMutation(node);
  6452. this._memo.set(node, has_side_effects);
  6453. return has_side_effects;
  6454. }
  6455. removeDeadBlockOutputs(node) {
  6456. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6457. return;
  6458. }
  6459. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6460. const i = i_1 - 1;
  6461. if (!node.outputs()[i].hasUses()) {
  6462. node.eraseOutput(i);
  6463. for (const b of node.blocks()) {
  6464. b.eraseOutput(i);
  6465. }
  6466. }
  6467. }
  6468. }
  6469. removeDeadLoopOutputs() {
  6470. }
  6471. getOrCreateAliasDb() {
  6472. if (!this._aliasDb) {
  6473. this._aliasDb = new torch._C.AliasDb(this._graph);
  6474. }
  6475. return this._aliasDb;
  6476. }
  6477. });
  6478. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6479. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6480. const [graph] = args;
  6481. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6482. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6483. worker.run(graph.block(), /*recurse=*/true);
  6484. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6485. const [block] = args;
  6486. const recurse = false;
  6487. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6488. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6489. worker.run(block, recurse);
  6490. } else {
  6491. throw new python.Error('Not implemented.');
  6492. }
  6493. });
  6494. this.registerFunction('torch._C.removeTupleNodes', () => {
  6495. });
  6496. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6497. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6498. const [graph] = args;
  6499. torch._C.LowerSimpleTuples(graph.block());
  6500. torch._C.EliminateDeadCode(graph);
  6501. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6502. const [block] = args;
  6503. for (const n of block.nodes()) {
  6504. torch._C.removeTupleNodes(n, false);
  6505. for (const b of n.blocks()) {
  6506. torch._C.LowerSimpleTuples(b);
  6507. }
  6508. }
  6509. } else {
  6510. throw new python.Error('Not implemented.');
  6511. }
  6512. });
  6513. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6514. torch._C.AT_ASSERT(lhs !== null);
  6515. torch._C.AT_ASSERT(rhs !== null);
  6516. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6517. return false;
  6518. }
  6519. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6520. return true;
  6521. }
  6522. const lnames = lhs.attributeNames();
  6523. const rnames = rhs.attributeNames();
  6524. lnames.sort();
  6525. rnames.sort();
  6526. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6527. return false;
  6528. }
  6529. for (const name of lnames) {
  6530. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6531. return false;
  6532. }
  6533. const kind = lhs.kindOf(name);
  6534. switch (kind) {
  6535. case 'i':
  6536. case 'f':
  6537. case 's':
  6538. case 't': {
  6539. if (lhs[kind](name) !== rhs[kind](name)) {
  6540. return false;
  6541. }
  6542. break;
  6543. }
  6544. case 'ival': {
  6545. if (lhs[kind](name) !== rhs[kind](name)) {
  6546. return false;
  6547. }
  6548. break;
  6549. }
  6550. default: {
  6551. throw new python.Error('Not implemented.');
  6552. }
  6553. }
  6554. }
  6555. return true;
  6556. });
  6557. this.registerFunction('torch._C.get_hash', (...args) => {
  6558. let hash = 0;
  6559. for (const value of args) {
  6560. if (typeof value === 'number') {
  6561. hash += (value | 0);
  6562. } else if (typeof value === 'string') {
  6563. hash += (value.length | 0);
  6564. } else if (Array.isArray(value)) {
  6565. for (const item of value) {
  6566. hash += torch._C.get_hash(item);
  6567. }
  6568. }
  6569. }
  6570. return hash;
  6571. });
  6572. this.registerFunction('torch._C.HashNode', (k) => {
  6573. torch._C.AT_ASSERT(k !== null);
  6574. let constant_hash = 0;
  6575. if (k.kind() === 'prim::Constant') {
  6576. const type = k.output().type();
  6577. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6578. constant_hash = k.i('value');
  6579. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6580. constant_hash = k.f('value');
  6581. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6582. constant_hash = k.c('value');
  6583. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6584. constant_hash = k.i('value');
  6585. }
  6586. }
  6587. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6588. });
  6589. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6590. if (lhs === null && rhs === null) {
  6591. return true;
  6592. }
  6593. if (lhs === null || rhs === null) {
  6594. return false;
  6595. }
  6596. if (lhs.kind() !== rhs.kind()) {
  6597. return false;
  6598. }
  6599. const lhs_outputs = lhs.outputs();
  6600. const rhs_outputs = rhs.outputs();
  6601. if (lhs_outputs.length !== rhs_outputs.length) {
  6602. return false;
  6603. }
  6604. for (let i = 0; i < lhs_outputs.length; i++) {
  6605. const lt = lhs_outputs[i].type();
  6606. const rt = rhs_outputs[i].type();
  6607. if (!lt.equals(rt)) {
  6608. return false;
  6609. }
  6610. }
  6611. const lhs_inputs = lhs.inputs();
  6612. const rhs_inputs = rhs.inputs();
  6613. if (lhs_inputs.length !== rhs_inputs.length) {
  6614. return false;
  6615. }
  6616. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6617. return false;
  6618. }
  6619. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6620. return false;
  6621. }
  6622. if (lhs.blocks().length !== rhs.blocks().length) {
  6623. return false;
  6624. }
  6625. for (let i = 0; i < lhs.blocks().length; i++) {
  6626. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6627. return false;
  6628. }
  6629. }
  6630. return true;
  6631. });
  6632. this.registerType('torch._C.NodeSet', class {
  6633. constructor() {
  6634. this._nodes = new Map();
  6635. }
  6636. insert(n) {
  6637. const key = torch._C.HashNode(n);
  6638. if (this._nodes.has(key)) {
  6639. this._nodes.get(key).push(n);
  6640. } else {
  6641. this._nodes.set(key, [n]);
  6642. }
  6643. }
  6644. get(n) {
  6645. const key = torch._C.HashNode(n);
  6646. if (this._nodes.has(key)) {
  6647. const nodes = this._nodes.get(key);
  6648. for (const node of nodes) {
  6649. if (torch._C.EqualNode(node, n)) {
  6650. return node;
  6651. }
  6652. }
  6653. }
  6654. return null;
  6655. }
  6656. has(n) {
  6657. return this.get(n) !== null;
  6658. }
  6659. });
  6660. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6661. const ty = stack.pop().type();
  6662. for (const candidate of types) {
  6663. if (ty.isSubtypeOf(candidate)) {
  6664. stack.push(new torch._C.IValue(true, 'Bool'));
  6665. stack.push(true);
  6666. return;
  6667. }
  6668. }
  6669. stack.push(new torch._C.IValue(false, 'Bool'));
  6670. });
  6671. this.registerType('torch._C.Tuple', class {
  6672. constructor(elements) {
  6673. this._elements = elements;
  6674. }
  6675. static create(elements) {
  6676. return new torch._C.Tuple(elements);
  6677. }
  6678. elements() {
  6679. return this._elements;
  6680. }
  6681. });
  6682. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6683. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6684. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6685. const tuple = torch._C.Tuple.create(elems.reverse());
  6686. stack.push(new torch._C.IValue(tuple));
  6687. });
  6688. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6689. let stack = [];
  6690. for (const input of n.inputs()) {
  6691. const ival = torch._C.toIValue(input);
  6692. if (ival) {
  6693. stack.push(ival);
  6694. } else {
  6695. return null;
  6696. }
  6697. }
  6698. switch (n.kind()) {
  6699. case 'prim::ListUnpack': {
  6700. if (stack.back().toList().size() !== n.outputs().length) {
  6701. return null;
  6702. }
  6703. torch._C.listUnpack(stack, n.outputs().length);
  6704. break;
  6705. }
  6706. case 'prim::TupleConstruct': {
  6707. const tt = n.output().type().expect(torch.TupleType);
  6708. if (tt.name()) {
  6709. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6710. } else {
  6711. torch._C.tupleConstruct(stack, n.inputs().length);
  6712. }
  6713. break;
  6714. }
  6715. case 'prim::ListConstruct': {
  6716. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6717. break;
  6718. }
  6719. case 'prim::DictConstruct': {
  6720. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6721. break;
  6722. }
  6723. case 'prim::CreateObject': {
  6724. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6725. break;
  6726. }
  6727. case 'prim::GetAttr': {
  6728. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6729. torch._C.push(stack, attr);
  6730. break;
  6731. }
  6732. case 'prim::isinstance': {
  6733. torch._C.isinstance(stack, n.tys('types'));
  6734. break;
  6735. }
  6736. default: {
  6737. const maybe_schema = n.maybeSchema();
  6738. if (maybe_schema && maybe_schema.is_vararg) {
  6739. return null;
  6740. }
  6741. // try
  6742. // {
  6743. // const op = n.getOperation();
  6744. // op(stack);
  6745. const [module, name] = n.kind().split('::');
  6746. const obj = torch.ops[module];
  6747. if (!obj) {
  6748. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6749. }
  6750. const fn = torch.ops[module].__getattr__(name);
  6751. if (!fn || !fn.__call__) {
  6752. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6753. }
  6754. const args = stack.map((v) => v.value);
  6755. const result = fn.__call__(...args);
  6756. if (result === undefined) {
  6757. stack = [];
  6758. } else if (result instanceof torch._C.IValue) {
  6759. stack = [result];
  6760. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6761. stack = result;
  6762. } else {
  6763. stack = [new torch._C.IValue(result)];
  6764. }
  6765. // } catch {
  6766. // stack = [];
  6767. // return null;
  6768. // }
  6769. break;
  6770. }
  6771. }
  6772. for (const v of stack) {
  6773. if (v.isTensor()) {
  6774. const t = v.toTensor();
  6775. if (t.defined() && t.requires_grad()) {
  6776. return null;
  6777. }
  6778. }
  6779. if (ignore_custom_classes) {
  6780. if (v.isCustomClass()) {
  6781. return null;
  6782. }
  6783. }
  6784. if (v.isCustomClass()) {
  6785. if (v.toObject().is_weak_compilation_ref()) {
  6786. continue;
  6787. }
  6788. if (!db) {
  6789. continue;
  6790. }
  6791. const n_non_const = n;
  6792. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6793. continue;
  6794. }
  6795. const obj = v.toObject();
  6796. obj.unsafe_make_weak_compilation_ref();
  6797. }
  6798. if (v.isObject()) {
  6799. if (!v.toObject().is_weak_compilation_ref()) {
  6800. return null;
  6801. }
  6802. }
  6803. }
  6804. return stack;
  6805. });
  6806. this.registerType('torch._C.ConstantPropagator', class {
  6807. constructor(graph, aliasing_types, ignore_custom_classes) {
  6808. this._made_change = false;
  6809. this._graph = graph;
  6810. this._aliasing_types = aliasing_types;
  6811. this._ignore_custom_classes = ignore_custom_classes;
  6812. }
  6813. static NoAliasDb(graph) {
  6814. return new torch._C.ConstantPropagator(graph, false, false);
  6815. }
  6816. run() {
  6817. this.ConstantPropagation(this._graph.block());
  6818. return this._made_change;
  6819. }
  6820. propagateNode(n) {
  6821. let outputs = [];
  6822. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6823. if (outputs_opt) {
  6824. outputs = outputs_opt;
  6825. const graph = n.owningGraph();
  6826. const guard = new torch._C.WithInsertPoint(n);
  6827. for (let i = 0; i < outputs.length; i++) {
  6828. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6829. if (new_output) {
  6830. this._made_change = true;
  6831. if (outputs[i].isNone()) {
  6832. new_output.setType(n.outputs()[i].type());
  6833. }
  6834. n.outputs()[i].replaceAllUsesWith(new_output);
  6835. }
  6836. }
  6837. guard.dispose();
  6838. }
  6839. }
  6840. removeLoopNode(n) {
  6841. const loop_input_offset = 2;
  6842. for (let i = 0; i < n.outputs().length; i++) {
  6843. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6844. }
  6845. this._made_change = true;
  6846. n.destroy();
  6847. }
  6848. loopWillNotRun(node) {
  6849. const [trip_count, start_cond] = node.inputs();
  6850. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6851. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6852. const loop_might_run = cond_val && iter_len > 0;
  6853. return !loop_might_run;
  6854. }
  6855. inlineIfBody(body) {
  6856. const n = body.owningNode();
  6857. for (const body_node of body.nodes()) {
  6858. body_node.moveBefore(n);
  6859. }
  6860. for (let i = 0; i < n.outputs().length; i++) {
  6861. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6862. }
  6863. n.destroy();
  6864. }
  6865. inlineIf(n) {
  6866. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6867. torch._C.AT_ASSERT(input_bool !== null);
  6868. const block_index = input_bool ? 0 : 1;
  6869. this.ConstantPropagation(n.blocks().at(block_index));
  6870. this.inlineIfBody(n.blocks().at(block_index));
  6871. this._made_change = true;
  6872. }
  6873. replaceAndRemoveIfOutput(n, i, replacement) {
  6874. n.outputs()[i].replaceAllUsesWith(replacement);
  6875. n.eraseOutput(i);
  6876. n.blocks().at(0).eraseOutput(i);
  6877. n.blocks().at(1).eraseOutput(i);
  6878. }
  6879. removeExtraIfOutputs(n) {
  6880. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6881. const [true_block, false_block] = n.blocks();
  6882. const graph = n.owningGraph();
  6883. const initial_outputs = true_block.outputs().length;
  6884. const guard = new torch._C.WithInsertPoint(n);
  6885. for (let i = 0; i < true_block.outputs().length;) {
  6886. const t_out = true_block.outputs()[i];
  6887. const f_out = false_block.outputs()[i];
  6888. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6889. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6890. continue;
  6891. }
  6892. const maybe_const = torch._C.toIValue(t_out);
  6893. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6894. const new_const = graph.insertConstant(maybe_const);
  6895. this.replaceAndRemoveIfOutput(n, i, new_const);
  6896. continue;
  6897. }
  6898. i++;
  6899. }
  6900. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6901. guard.dispose();
  6902. }
  6903. removeExtraLoopOutputs(node) {
  6904. const initial_outputs = node.outputs().length;
  6905. const [loop_body] = node.blocks();
  6906. const loop_input_offset = 2;
  6907. const loop_body_offset = 1;
  6908. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6909. const i = i_1 - 1;
  6910. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6911. const node_input = node.inputs()[loop_input_offset + i];
  6912. node.outputs().at(i).replaceAllUsesWith(node_input);
  6913. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6914. node.eraseOutput(i);
  6915. node.removeInput(loop_input_offset + i);
  6916. loop_body.eraseInput(loop_body_offset + i);
  6917. loop_body.eraseOutput(loop_body_offset + i);
  6918. }
  6919. }
  6920. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6921. }
  6922. noMutableValues(values) {
  6923. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6924. }
  6925. getOrCreateAliasDb() {
  6926. if (!this._aliasDb) {
  6927. this._aliasDb = new torch._C.AliasDb(this._graph);
  6928. }
  6929. return this._aliasDb;
  6930. }
  6931. supportedNode(n) {
  6932. torch._C.skip_list = torch._C.skip_list || new Set([
  6933. 'prim::If',
  6934. 'prim::Loop',
  6935. 'prim::Closure',
  6936. 'prim::Constant',
  6937. 'prim::AutogradZero',
  6938. 'prim::Uninitialized',
  6939. 'prim::Guard',
  6940. 'prim::profile',
  6941. 'prim::profile_ivalue',
  6942. 'prim::unchecked_unwrap_optional',
  6943. 'prim::awaitable',
  6944. 'aten::dequantize'
  6945. ]);
  6946. let no_mutation = false;
  6947. if (this._aliasing_types) {
  6948. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  6949. } else {
  6950. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  6951. }
  6952. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  6953. }
  6954. ConstantPropagation(...args) {
  6955. if (args[0] instanceof torch.Graph) {
  6956. throw new python.Error('Not implemented.');
  6957. } else if (args[0] instanceof torch.Block) {
  6958. const [block] = args;
  6959. for (const n of block.nodes()) {
  6960. this.ConstantPropagation(n);
  6961. }
  6962. } else if (args[0] instanceof torch.Node) {
  6963. const [n] = args;
  6964. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  6965. if (n.kind() === 'prim::If') {
  6966. if (constant_inputs) {
  6967. this.inlineIf(n);
  6968. } else {
  6969. this.ConstantPropagation(n.blocks());
  6970. this.removeExtraIfOutputs(n);
  6971. }
  6972. } else if (n.kind() === 'prim::Loop') {
  6973. if (this.loopWillNotRun(n)) {
  6974. this.removeLoopNode(n);
  6975. } else {
  6976. this.ConstantPropagation(n.blocks());
  6977. this.removeExtraLoopOutputs(n);
  6978. }
  6979. } else if (constant_inputs && this.supportedNode(n)) {
  6980. this.propagateNode(n);
  6981. } else {
  6982. this.ConstantPropagation(n.blocks()); // not implemented
  6983. }
  6984. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  6985. const [blocks] = args;
  6986. for (const block of blocks) {
  6987. this.ConstantPropagation(block);
  6988. }
  6989. } else {
  6990. throw new python.Error('Not implemented.');
  6991. }
  6992. }
  6993. });
  6994. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  6995. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  6996. const made_change = cp.run();
  6997. if (made_change) {
  6998. torch._C.EliminateDeadCode(graph);
  6999. }
  7000. return made_change;
  7001. });
  7002. this.registerType('torch._C.MutableTypePtrHelper', class {
  7003. constructor(mutable_type_cache) {
  7004. this._mutable_type_cache = mutable_type_cache;
  7005. }
  7006. mapTypeToAliasTypeSet(type) {
  7007. if (this._mutable_type_cache) {
  7008. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7009. if (result) {
  7010. return result;
  7011. }
  7012. }
  7013. return this.mapTypeToAliasTypeSetImpl(type);
  7014. }
  7015. mapTypeToAliasTypeSetImpl(type) {
  7016. if (type instanceof torch.ListType ||
  7017. type instanceof torch.DictType ||
  7018. type instanceof torch.ClassType ||
  7019. type instanceof torch.TensorType) {
  7020. return [torch._C.unshapedType(type)];
  7021. }
  7022. if (type instanceof torch.UnionType) {
  7023. const mutable_types = [];
  7024. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7025. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7026. if (maybe_inner_types) {
  7027. mutable_types.push(...maybe_inner_types);
  7028. }
  7029. }
  7030. if (mutable_types.length === 0) {
  7031. return null;
  7032. }
  7033. return mutable_types;
  7034. }
  7035. if (type instanceof torch.OptionalType) {
  7036. const inner = type.getElementType();
  7037. return this.mapTypeToAliasTypeSet(inner);
  7038. }
  7039. if (type instanceof torch.AnyType) {
  7040. return [torch._C.AliasTypeSet([type])];
  7041. }
  7042. if (type instanceof torch.FutureType) {
  7043. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7044. if (maybe_mut_types) {
  7045. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7046. }
  7047. return null;
  7048. }
  7049. if (type instanceof torch.AwaitType) {
  7050. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7051. if (maybe_mut_types) {
  7052. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7053. }
  7054. return null;
  7055. }
  7056. if (type instanceof torch.TupleType) {
  7057. const mutable_types = [];
  7058. for (const inner of type.elements()) {
  7059. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7060. if (maybe_inner_types) {
  7061. mutable_types.push(...maybe_inner_types);
  7062. }
  7063. }
  7064. if (mutable_types.length === 0) {
  7065. return null;
  7066. }
  7067. return [[torch.TupleType.create(mutable_types)]];
  7068. }
  7069. return null;
  7070. }
  7071. });
  7072. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7073. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7074. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7075. return true;
  7076. }
  7077. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7078. if (mutable_type_cache) {
  7079. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7080. }
  7081. return helper.mapTypeToAliasTypeSet(type) !== null;
  7082. });
  7083. this.registerType('torch._C.AliasDb', class {
  7084. constructor() {
  7085. this._writeIndex = new Map();
  7086. }
  7087. static isMutableType(...args) {
  7088. if (args[0] instanceof torch.Type) {
  7089. const [type] = args;
  7090. return torch._C.isMutableTypeImpl(type, null);
  7091. }
  7092. if (args[0] instanceof torch.Value) {
  7093. const [value] = args;
  7094. return torch._C.AliasDb.isMutableType(value.type());
  7095. }
  7096. throw new python.Error('Not implemented.');
  7097. }
  7098. writesToAlias(/* n, vs */) {
  7099. /*
  7100. const writtenTo = this.getWrites(n);
  7101. if (writtenTo.length === 0) {
  7102. return false;
  7103. }
  7104. MemoryLocations locs;
  7105. for (const v of vs) {
  7106. const it = elementMap_.find(v);
  7107. if (it != elementMap_.end()) {
  7108. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7109. if (writtenTo.intersects(vlocs)) {
  7110. return true;
  7111. }
  7112. }
  7113. }
  7114. */
  7115. return false;
  7116. }
  7117. writesToWildcard(n) {
  7118. if (!this._writeIndex.has(n)) {
  7119. return false;
  7120. }
  7121. const writes = this._writeIndex.get(n);
  7122. for (const pr of this._wildcardIndex) {
  7123. const [, wildcardElement] = pr;
  7124. if (writes.test(wildcardElement.index)) {
  7125. return true;
  7126. }
  7127. }
  7128. return false;
  7129. }
  7130. safeToChangeAliasingRelationship(a, b) {
  7131. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7132. return false;
  7133. }
  7134. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7135. }
  7136. });
  7137. this.registerFunction('torch._C.hasWriters', () => {
  7138. });
  7139. this.registerFunction('torch._C.escapesScope', () => {
  7140. });
  7141. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7142. constructor(graph) {
  7143. this._current = graph.block().nodes().front();
  7144. }
  7145. next() {
  7146. return null;
  7147. }
  7148. });
  7149. this.registerType('torch._C.ConcatCombiner', class {
  7150. constructor(graph) {
  7151. this._graph = graph;
  7152. this._aliasDb = new torch._C.AliasDb(graph);
  7153. this._combinable_concats = [];
  7154. }
  7155. collectOptimizableConcats() {
  7156. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7157. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7158. if (node.kind() === 'aten::cat') {
  7159. this.handleConcat(node);
  7160. }
  7161. }
  7162. }
  7163. combineConcats() {
  7164. if (this._combinable_concats.length === 0) {
  7165. return false;
  7166. }
  7167. const list_construct_inputs = this.getListConstructInputs();
  7168. for (const node_and_new_list of list_construct_inputs) {
  7169. const [node, inputs] = node_and_new_list;
  7170. const new_list_construct = this.createListConstruct(inputs);
  7171. const old_list_construct = node.input(0).node();
  7172. new_list_construct.output().setType(old_list_construct.output().type());
  7173. new_list_construct.insertBefore(node);
  7174. old_list_construct.replaceAllUsesWith(new_list_construct);
  7175. }
  7176. return true;
  7177. }
  7178. run() {
  7179. this.collectOptimizableConcats();
  7180. const changed = this.combineConcats();
  7181. if (changed) {
  7182. torch._C.EliminateDeadCode(this._graph);
  7183. }
  7184. return changed;
  7185. }
  7186. });
  7187. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7188. const changed = new torch._C.ConcatCombiner(graph).run();
  7189. return changed;
  7190. });
  7191. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7192. constructor(graph, disable_shape_peepholes) {
  7193. this._graph = graph;
  7194. this._shape_peepholes = !disable_shape_peepholes;
  7195. }
  7196. run() {
  7197. let changed = this.optimizeBlock(this._graph.block());
  7198. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7199. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7200. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7201. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7202. changed = changed || torch._C.CombineConcats(this._graph);
  7203. return changed;
  7204. }
  7205. optimizeBlock(block) {
  7206. let changed = false;
  7207. for (const node of block.nodes()) {
  7208. for (const sub_block of node.blocks()) {
  7209. changed = changed || this.optimizeBlock(sub_block);
  7210. }
  7211. if (node.kind() !== 'prim::Constant') {
  7212. const guard = new torch._C.WithInsertPoint(node);
  7213. for (const output of node.outputs()) {
  7214. if (output.type() instanceof torch.NoneType) {
  7215. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7216. changed = true;
  7217. }
  7218. }
  7219. guard.dispose();
  7220. }
  7221. if (node.kind() === 'prim::If') {
  7222. // throw new python.Error('Not implemented.');
  7223. /*
  7224. const n = new torch._C.IfView(node);
  7225. // this handles redundant short circuits like "x and True" or "x or
  7226. // False"
  7227. for (const auto i : c10::irange(n.outputs().length)) {
  7228. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7229. continue;
  7230. }
  7231. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7232. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7233. if (true_val && !false_val) {
  7234. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7235. changed = true;
  7236. }
  7237. }
  7238. for (let i = 0; i < n.outputs().length; ++i) {
  7239. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7240. const output_optional = n.outputs()[i].type();
  7241. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7242. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7243. if (unif) {
  7244. n.outputs()[i].setType(unif);
  7245. changed = true;
  7246. }
  7247. }
  7248. }
  7249. */
  7250. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7251. torch._C.AT_ASSERT(node.inputs().length === 2);
  7252. for (const check_none_index of [0, 1]) {
  7253. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7254. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7255. if (input_must_be_none && other_must_not_be_none) {
  7256. const guard = new torch._C.WithInsertPoint(node);
  7257. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7258. node.output().replaceAllUsesWith(output);
  7259. changed = true;
  7260. guard.dispose();
  7261. }
  7262. }
  7263. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7264. throw new python.Error('Not implemented.');
  7265. /*
  7266. // we are unwrapping an input that can't be None, remove the unwrap
  7267. const input = node.input();
  7268. if (input.mustNotBeNone()) {
  7269. node.output().replaceAllUsesWith(node.input());
  7270. changed = true;
  7271. }
  7272. */
  7273. } else if (node.kind() === 'prim::unchecked_cast') {
  7274. const input_type = torch._C.unshapedType(node.input().type());
  7275. const output_type = torch._C.unshapedType(node.output().type());
  7276. if (input_type.isSubtypeOf(output_type)) {
  7277. node.output().replaceAllUsesWith(node.input());
  7278. changed = true;
  7279. }
  7280. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7281. node.output().replaceAllUsesWith(node.input());
  7282. changed = true;
  7283. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7284. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7285. continue;
  7286. }
  7287. const inp_type = node.inputs()[0].type();
  7288. const immut_type = (type) => {
  7289. const kind = type.kind();
  7290. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7291. return handled_immutable_types.has(kind);
  7292. };
  7293. let non_throwing_type = false;
  7294. if (inp_type instanceof torch.ListType) {
  7295. non_throwing_type = immut_type(inp_type.getElementType());
  7296. } else if (inp_type instanceof torch.DictType) {
  7297. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7298. } else {
  7299. non_throwing_type = immut_type(inp_type);
  7300. }
  7301. if (non_throwing_type) {
  7302. const guard = new torch._C.WithInsertPoint(node);
  7303. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7304. changed = true;
  7305. guard.dispose();
  7306. }
  7307. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7308. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7309. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7310. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7311. }
  7312. }
  7313. return changed;
  7314. }
  7315. });
  7316. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7317. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7318. const changed = peephole.run();
  7319. if (changed) {
  7320. torch._C.EliminateDeadCode(graph.block());
  7321. }
  7322. return changed;
  7323. });
  7324. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7325. if (!cond) {
  7326. throw new python.Error('Assertion failed.');
  7327. }
  7328. });
  7329. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7330. if (!cond) {
  7331. throw new python.Error('Assertion failed.');
  7332. }
  7333. });
  7334. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7335. if (!cond) {
  7336. throw new python.Error('Assertion failed.');
  7337. }
  7338. });
  7339. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7340. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7341. for (let next_node = it.next(); next_node !== null;) {
  7342. const node = next_node;
  7343. next_node = it.next();
  7344. if (node.kind() === 'prim::EmptyListLiteral') {
  7345. if (node.hasUses()) {
  7346. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7347. }
  7348. const li = graph.createList(torch.TensorType.get(), []);
  7349. li.insertBefore(node);
  7350. node.replaceAllUsesWith(li);
  7351. }
  7352. node.destroy();
  7353. }
  7354. });
  7355. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7356. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7357. const [graph] = args;
  7358. const aliasDb = new torch._C.AliasDb(graph);
  7359. const constants = new torch._C.NodeSet();
  7360. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7361. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7362. const [block, constants, aliasDb] = args;
  7363. for (const node of block.nodes()) {
  7364. if (node.blocks().length > 0) {
  7365. for (const block of node.blocks()) {
  7366. torch._C.ConstantPooling(block, constants, aliasDb);
  7367. }
  7368. continue;
  7369. }
  7370. if (node.kind() !== 'prim::Constant') {
  7371. continue;
  7372. }
  7373. if (constants.has(node)) {
  7374. const existing = constants.get(node);
  7375. const old_ivalue = torch._C.toIValue(existing.output());
  7376. const new_ivalue = torch._C.toIValue(node.output());
  7377. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7378. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7379. continue;
  7380. }
  7381. node.replaceAllUsesWith(existing);
  7382. node.destroy();
  7383. continue;
  7384. } else {
  7385. constants.insert(node);
  7386. }
  7387. const [first_node] = node.owningGraph().block().nodes();
  7388. if (node !== first_node) {
  7389. node.moveBefore(first_node);
  7390. }
  7391. }
  7392. } else {
  7393. throw new python.Error('Not implemented.');
  7394. }
  7395. });
  7396. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7397. /*
  7398. const autocast_stack = [];
  7399. let incompatible_amp = null;
  7400. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7401. for (const node of block.nodes()) {
  7402. switch (node.kind()) {
  7403. case 'prim::CallFunction':
  7404. if (current_state() === initial_state) {
  7405. if (current_state()) {
  7406. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7407. }
  7408. break;
  7409. }
  7410. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7411. incompatible_amp = true;
  7412. break;
  7413. case 'prim::CallMethod':
  7414. if (current_state() === initial_state) {
  7415. if (current_state()) {
  7416. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7417. }
  7418. break;
  7419. }
  7420. if (node.input(0).type() instanceof torch.ClassType) {
  7421. const class_type = node.input(0).type();
  7422. const name = node.s('name');
  7423. const fn = class_type.getMethod(name);
  7424. if (!fn.isGraphFunction()) {
  7425. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7426. incompatible_amp = true;
  7427. }
  7428. } else {
  7429. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7430. incompatible_amp = true;
  7431. }
  7432. break;
  7433. case 'prim::Enter': {
  7434. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7435. if (autocast_scope) {
  7436. if (node.hasUses()) {
  7437. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7438. }
  7439. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7440. incompatible_amp = false;
  7441. autocast_stack.push(autocast_scope);
  7442. }
  7443. break;
  7444. }
  7445. case 'prim::Exit': {
  7446. if (torch._C.isAutocastNode(node.input(0))) {
  7447. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7448. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7449. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7450. incompatible_amp = false;
  7451. autocast_stack.pop();
  7452. }
  7453. break;
  7454. }
  7455. case 'aten::is_autocast_enabled': {
  7456. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7457. break;
  7458. }
  7459. case 'aten::is_autocast_cpu_enabled': {
  7460. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7461. break;
  7462. }
  7463. case 'aten::_convolution':
  7464. case 'aten::conv1d':
  7465. case 'aten::conv2d':
  7466. case 'aten::conv3d':
  7467. case 'aten::conv_tbc':
  7468. case 'aten::conv_transpose1d':
  7469. case 'aten::convolution':
  7470. case 'aten::cudnn_convolution':
  7471. case 'aten::cudnn_convolution_transpose':
  7472. case 'aten::prelu':
  7473. case 'aten::addmm':
  7474. case 'aten::addmv':
  7475. case 'aten::addr':
  7476. case 'aten::matmul':
  7477. case 'aten::mm':
  7478. case 'aten::mv':
  7479. case 'aten::linear':
  7480. case 'aten::addbmm':
  7481. case 'aten::baddbmm':
  7482. case 'aten::bmm':
  7483. case 'aten::chain_matmul':
  7484. case 'aten::_thnn_fused_lstm_cell':
  7485. case 'aten::_thnn_fused_gru_cell':
  7486. case 'aten::lstm_cell':
  7487. case 'aten::gru_cell':
  7488. case 'aten::rnn_tanh_cell':
  7489. case 'aten::rnn_relu_cell': {
  7490. if (!node.schema().is_mutable()) {
  7491. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7492. }
  7493. break;
  7494. }
  7495. case 'aten::native_layer_norm':
  7496. case 'aten::acos':
  7497. case 'aten::asin':
  7498. case 'aten::cosh':
  7499. case 'aten::erfinv':
  7500. case 'aten::exp':
  7501. case 'aten::expm1':
  7502. case 'aten::log':
  7503. case 'aten::log10':
  7504. case 'aten::log2':
  7505. case 'aten::log1p':
  7506. case 'aten::reciprocal':
  7507. case 'aten::rsqrt':
  7508. case 'aten::sinh':
  7509. case 'aten::tan':
  7510. case 'aten::pow':
  7511. case 'aten::softplus':
  7512. case 'aten::gelu':
  7513. case 'aten::layer_norm':
  7514. case 'aten::group_norm':
  7515. case 'aten::frobenius_norm':
  7516. case 'aten::nuclear_norm':
  7517. case 'aten::cosine_similarity':
  7518. case 'aten::cosine_embedding_loss':
  7519. case 'aten::nll_loss':
  7520. case 'aten::nll_loss2d':
  7521. case 'aten::hinge_embedding_loss':
  7522. case 'aten::kl_div':
  7523. case 'aten::l1_loss':
  7524. case 'aten::smooth_l1_loss':
  7525. case 'aten::mse_loss':
  7526. case 'aten::margin_ranking_loss':
  7527. case 'aten::multilabel_margin_loss':
  7528. case 'aten::soft_margin_loss':
  7529. case 'aten::triplet_margin_loss':
  7530. case 'aten::multi_margin_loss':
  7531. case 'aten::binary_cross_entropy_with_logits':
  7532. case 'aten::dist':
  7533. case 'aten::pdist':
  7534. case 'aten::cdist':
  7535. case 'aten::renorm':
  7536. case 'aten::logsumexp': {
  7537. if (!node.schema().is_mutable()) {
  7538. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7539. }
  7540. break;
  7541. }
  7542. case 'aten::prod':
  7543. case 'aten::log_softmax':
  7544. case 'aten::cumprod':
  7545. case 'aten::cumsum':
  7546. case 'aten::sum': {
  7547. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7548. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7549. }
  7550. break;
  7551. }
  7552. case 'aten::softmax': {
  7553. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7554. const context = current_state();
  7555. context.cpu_enabled = false;
  7556. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7557. }
  7558. break;
  7559. }
  7560. case 'aten::addcdiv':
  7561. case 'aten::addcmul':
  7562. case 'aten::atan2':
  7563. case 'aten::bilinear':
  7564. case 'aten::cat':
  7565. case 'aten::cross':
  7566. case 'aten::dot':
  7567. case 'aten::equal':
  7568. case 'aten::index_put':
  7569. case 'aten::stack':
  7570. case 'aten::tensordot':
  7571. case 'aten::add':
  7572. case 'aten::sub':
  7573. case 'aten::mul':
  7574. case 'aten::div': {
  7575. if (!node.schema().is_mutable()) {
  7576. torch._C.castInputsToWidestType(node, current_state());
  7577. }
  7578. break;
  7579. }
  7580. case 'aten::binary_cross_entropy': {
  7581. if (current_state()) {
  7582. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7583. }
  7584. break;
  7585. }
  7586. default: {
  7587. break;
  7588. }
  7589. }
  7590. for (const sub_block of node.blocks()) {
  7591. torch._C.handleBlock(sub_block, current_state());
  7592. }
  7593. }
  7594. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7595. */
  7596. });
  7597. this.registerFunction('torch._C.autocastEnabled', () => {
  7598. return true;
  7599. });
  7600. this.registerFunction('torch._C.Autocast', (graph) => {
  7601. if (torch._C.autocastEnabled()) {
  7602. const init = null;
  7603. /* AutocastContext init = {
  7604. at::autocast::is_autocast_enabled(at::kCUDA),
  7605. at::autocast::is_autocast_enabled(at::kCPU),
  7606. at::autocast::get_autocast_dtype(at::kCUDA),
  7607. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7608. torch._C.handleBlock(graph.block(), init);
  7609. }
  7610. });
  7611. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7612. disable_autocast = disable_autocast || false;
  7613. torch._C.Inline(graph);
  7614. torch._C.PeepholeOptimize(graph, true);
  7615. torch._C.ConstantPropagationImmutableTypes(graph);
  7616. if (!disable_autocast) {
  7617. torch._C.Autocast(graph);
  7618. }
  7619. torch._C.ConstantPooling(graph);
  7620. });
  7621. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7622. constructor(name, graph, function_creator, executor_execution_mode) {
  7623. super();
  7624. this._name = name;
  7625. this._graph = graph;
  7626. this._executor_execution_mode = executor_execution_mode || null;
  7627. this._function_creator = function_creator;
  7628. this._force_no_amp = false;
  7629. }
  7630. isGraphFunction() {
  7631. return true;
  7632. }
  7633. qualname() {
  7634. return this._name;
  7635. }
  7636. graph() {
  7637. return this._graph;
  7638. }
  7639. optimized_graph() {
  7640. const graph_ref = this._graph.copy();
  7641. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7642. return graph_ref;
  7643. }
  7644. ensure_defined() {
  7645. if (this._function_creator) {
  7646. const creator = this._function_creator;
  7647. this._function_creator = () => {
  7648. throw new python.Error('Recursive method call.');
  7649. };
  7650. creator(this);
  7651. this._function_creator = null;
  7652. }
  7653. this.check_single_output();
  7654. }
  7655. check_single_output() {
  7656. if (this.graph().outputs().length !== 1) {
  7657. throw new python.Error('Graph must have a single output.');
  7658. }
  7659. }
  7660. getSchema() {
  7661. this._schema = this._schema || this.defaultSchemaFor(this);
  7662. return this._schema;
  7663. }
  7664. setSchema(schema) {
  7665. this._schema = schema;
  7666. }
  7667. num_inputs() {
  7668. return this.graph().inputs().length;
  7669. }
  7670. unshapedType(type) {
  7671. if (type.isSubtypeOf(torch.TensorType.get())) {
  7672. return torch.TensorType.get();
  7673. }
  7674. const contained = type.containedTypes();
  7675. if (contained.length === 0) {
  7676. return type;
  7677. }
  7678. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7679. }
  7680. defaultSchemaFor(fn) {
  7681. const args = [];
  7682. const returns = [];
  7683. const g = fn.graph();
  7684. const num_inputs = fn.num_inputs();
  7685. for (let i = 0; i < num_inputs; i++) {
  7686. const v = g.inputs()[i];
  7687. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7688. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7689. args.push(argument);
  7690. }
  7691. const num_outputs = g.outputs().length;
  7692. for (let i = 0; i < num_outputs; i++) {
  7693. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7694. returns.push(argument);
  7695. }
  7696. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7697. }
  7698. });
  7699. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7700. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7701. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7702. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7703. __str__() {
  7704. return this._args.map((a) => a.__str__()).join('//');
  7705. }
  7706. });
  7707. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7708. this.registerType('torch.utils._sympy.functions.Where', class {});
  7709. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7710. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7711. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7712. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7713. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7714. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7715. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7716. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7717. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7718. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7719. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7720. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7721. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7722. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7723. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7724. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7725. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7726. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7727. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7728. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7729. static extract() {
  7730. }
  7731. });
  7732. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7733. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7734. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7735. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7736. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7737. this.registerType('torch.utils.data.dataset.Subset', class {});
  7738. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7739. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7740. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7741. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7742. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7743. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7744. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7745. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7746. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7747. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7748. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7749. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7750. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7751. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7752. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7753. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7754. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7755. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7756. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7757. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7758. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7759. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7760. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7761. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7762. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7763. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7764. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7765. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7766. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7767. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7768. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7769. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7770. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7771. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7772. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7773. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7774. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7775. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7776. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7777. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7778. this.registerType('torch._C._LegacyVariableBase', class {});
  7779. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7780. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7781. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7782. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7783. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7784. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7785. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7786. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7787. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7788. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7789. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7790. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7791. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7792. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7793. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7794. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7795. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7796. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7797. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7798. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7799. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7800. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7801. this.registerType('torch.distributions.beta.Beta', class {});
  7802. this.registerType('torch.distributions.binomial.Binomial', class {});
  7803. this.registerType('torch.distributions.categorical.Categorical', class {});
  7804. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7805. this.registerType('torch.distributions.constraints._Interval', class {});
  7806. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7807. this.registerType('torch.distributions.constraints._Real', class {});
  7808. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7809. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7810. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7811. this.registerType('torch.distributions.normal.Normal', class {});
  7812. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7813. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7814. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7815. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7816. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7817. this.registerType('torch.distributions.uniform.Uniform', class {});
  7818. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7819. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7820. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7821. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7822. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7823. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7824. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7825. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7826. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7827. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7828. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7829. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7830. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7831. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7832. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7833. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7834. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7835. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7836. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7837. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7838. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7839. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7840. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7841. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7842. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7843. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7844. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7845. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7846. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7847. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7848. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7849. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7850. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7851. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7852. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7853. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7854. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7855. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7856. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7857. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7858. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7859. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7860. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7861. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7862. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7863. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7864. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7865. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7866. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7867. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7868. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7869. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7870. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7871. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7872. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7873. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7874. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7875. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7876. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7877. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7878. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7879. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7880. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7881. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7882. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7883. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7884. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7885. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7886. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7887. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7888. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7889. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7890. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7891. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7892. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7893. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7894. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7895. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7896. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7897. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7898. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7899. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7900. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7901. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7902. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7903. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7904. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7905. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7906. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7907. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7908. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7913. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7915. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7916. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7917. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7918. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7919. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7920. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7921. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7922. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7923. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7924. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7925. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7926. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7927. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7928. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7929. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  7930. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7931. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  7932. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  7933. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  7934. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  7935. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  7936. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  7937. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  7938. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  7939. this.registerType('torch.nn.modules.module.PatchForward', class {});
  7940. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  7941. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  7942. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  7943. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  7944. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  7945. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  7946. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7947. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7948. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  7949. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  7950. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7951. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7952. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  7953. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  7954. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  7955. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  7956. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  7957. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  7958. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  7959. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  7960. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  7961. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  7962. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  7963. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7964. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7965. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  7966. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  7967. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  7968. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  7969. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  7970. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  7971. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  7972. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  7973. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  7974. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  7975. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  7976. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  7977. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  7978. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7979. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7980. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  7981. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  7982. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7983. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7984. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  7985. this.registerType('torch.nn.modules.rnn.GRU', class {});
  7986. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  7987. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  7988. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  7989. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  7990. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  7991. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  7992. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  7993. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  7994. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  7995. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  7996. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  7997. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  7998. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  7999. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8000. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8001. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8002. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8003. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8004. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8005. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8006. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8007. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8008. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8009. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8010. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8011. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8012. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8013. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8014. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8015. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8016. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8017. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8018. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8019. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8020. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8021. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8022. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8023. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8024. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8025. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8026. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8027. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8028. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8029. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8030. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8031. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8032. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8033. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8034. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8035. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8036. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8037. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8038. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8039. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8040. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8041. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8042. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8043. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8044. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8045. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8046. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8047. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8048. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8049. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8050. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8051. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8052. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8053. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8054. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8055. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8056. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8057. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8058. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8059. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8060. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8061. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8062. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8063. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8064. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8065. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8066. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8067. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8068. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8069. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8070. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8071. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8072. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8073. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8074. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8075. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8076. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8077. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8078. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8079. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8080. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8081. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8082. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8083. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8084. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8085. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8086. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8087. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8088. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8089. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8090. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8091. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8092. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8093. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8094. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8095. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8096. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8097. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8098. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8099. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8100. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8101. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8102. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8103. this.registerType('torch.optim.adamw.AdamW', class {});
  8104. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8105. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8106. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8107. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8108. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8109. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8110. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8111. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8112. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8113. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8114. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8115. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8116. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8117. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8118. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8119. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8120. this.registerType('torch.optim.sgd.SGD', class {});
  8121. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8122. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8123. torch.optim.RAdam = torch.optim.radam.RAdam;
  8124. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8125. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8126. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8127. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8128. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8129. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8130. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8131. this.registerFunction('torch.quantization.observer._with_args');
  8132. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8133. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8134. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8135. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8136. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8137. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8138. __enter__() {
  8139. return this;
  8140. }
  8141. __exit__(/* exc_type, exc_value, traceback */) {
  8142. }
  8143. });
  8144. this.registerFunction('torch.utils._pytree.tree_map');
  8145. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8146. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8147. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8148. this._expr = expr;
  8149. this.shape_env = shape_env;
  8150. this.pytype = pytype;
  8151. this._optimized_summation = optimized_summation;
  8152. this._hint = hint;
  8153. this.constant = constant;
  8154. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8155. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8156. }
  8157. __str__() {
  8158. return this._expr.__str__();
  8159. }
  8160. });
  8161. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8162. constructor() {
  8163. this.var_to_val = new Map();
  8164. this.var_to_stack = new Map();
  8165. }
  8166. add_var_to_val(expr, val) {
  8167. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8168. }
  8169. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8170. }
  8171. create_symintnode(sym, hint, source) {
  8172. let out = null;
  8173. let fx_node = null;
  8174. if (this._translation_validation_enabled && source !== null) {
  8175. throw new python.Error('Not implemented.');
  8176. } else {
  8177. fx_node = null;
  8178. }
  8179. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8180. out = builtins.int(sym);
  8181. if (hint !== null && out !== hint) {
  8182. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8183. }
  8184. } else {
  8185. // if free_unbacked_symbols(sym):
  8186. // hint = None
  8187. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8188. }
  8189. return out;
  8190. }
  8191. create_symboolnode(sym) {
  8192. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8193. }
  8194. });
  8195. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8196. /*
  8197. assert isinstance(sym, sympy.Symbol)
  8198. const name_str = sym.name.toLowerCase();
  8199. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8200. return name_str.startsWith(prefix_str[prefix])
  8201. }
  8202. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8203. */
  8204. return false;
  8205. });
  8206. this.registerType('torch.fx.proxy.TracerBase', class {
  8207. constructor() {
  8208. this.traced_func_name = 'forward';
  8209. }
  8210. });
  8211. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8212. trace(root /*, concrete_args */) {
  8213. let fn = null;
  8214. if (root instanceof torch.nn.Module) {
  8215. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8216. this.root = root;
  8217. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8218. this.root_module_name = root._get_name();
  8219. this.submodule_paths = new builtins.dict(root.named_modules());
  8220. } else {
  8221. this.root = new torch.nn.Module();
  8222. fn = root;
  8223. }
  8224. const tracer_cls = builtins.getattr(this, '__class__', null);
  8225. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8226. if (builtins.hasattr(this, '__code__')) {
  8227. const code = fn.__code__;
  8228. this.graph._co_fields = {
  8229. co_name: code.co_name,
  8230. co_filename: code.co_filename,
  8231. co_firstlineno: code.co_firstlineno,
  8232. };
  8233. }
  8234. return this.graph;
  8235. }
  8236. is_leaf_module(m /*, module_qualified_name */) {
  8237. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8238. }
  8239. });
  8240. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8241. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8242. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8243. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8244. return new graph_module_cls(...args);
  8245. });
  8246. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8247. let tracer_cls = body.get('_tracer_cls');
  8248. if (!tracer_cls) {
  8249. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8250. }
  8251. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8252. const cls_tracer = tracer_cls;
  8253. const KeepModules = class extends cls_tracer {
  8254. is_leaf_module() {
  8255. return true;
  8256. }
  8257. };
  8258. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8259. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8260. const graph = new KeepModules().trace(com, tracer_extras);
  8261. graph._tracer_cls = tracer_cls;
  8262. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8263. for (const [k, v] of body.items()) {
  8264. if (!builtins.hasattr(gm, k)) {
  8265. builtins.setattr(gm, k, v);
  8266. }
  8267. }
  8268. return gm;
  8269. });
  8270. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8271. globals = { ...globals };
  8272. const context = new python.Execution.Context(globals, null);
  8273. execution.exec(src, context);
  8274. const forward_fn = globals.forward;
  8275. delete globals.forward;
  8276. return forward_fn;
  8277. });
  8278. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8279. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8280. let fn_src = null;
  8281. if (body.has('_code')) {
  8282. fn_src = body.get('_code');
  8283. } else if (body.has('code')) {
  8284. fn_src = body.get('code');
  8285. } else {
  8286. fn_src = body._code || body.code;
  8287. }
  8288. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8289. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8290. });
  8291. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8292. const forward = importer.import_module(generated_module_name).forward;
  8293. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8294. });
  8295. this.registerType('torch.fx.graph.CodeGen', class {});
  8296. this.registerType('torch.fx.graph._Namespace', class {
  8297. constructor() {
  8298. this._obj_to_name = new Map();
  8299. this._unassociated_names = new Set();
  8300. this._used_names = new Set();
  8301. this._base_count = {};
  8302. }
  8303. create_name(candidate, obj) {
  8304. if (obj && this._obj_to_name.has(obj)) {
  8305. return self._obj_to_name.get(obj);
  8306. }
  8307. candidate = candidate || '_unnamed';
  8308. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8309. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8310. const match = candidate.match(/(.*)_(\d+)$"/);
  8311. let base = candidate;
  8312. let num = null;
  8313. if (match) {
  8314. [, base] = match;
  8315. num = parseInt(match[2], 10);
  8316. }
  8317. candidate = num ? `${base}_${num}` : base;
  8318. if (!num) {
  8319. num = this._base_count[base] || 0;
  8320. }
  8321. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8322. num += 1;
  8323. candidate = `${base}_${num}`;
  8324. }
  8325. this._used_names.add(candidate);
  8326. this._base_count[base] = num;
  8327. if (obj) {
  8328. this._obj_to_name[obj] = candidate;
  8329. } else {
  8330. this._unassociated_names.add(candidate);
  8331. }
  8332. return candidate;
  8333. }
  8334. _is_illegal_name(/* name, obj */) {
  8335. /*
  8336. if name in keyword.kwlist:
  8337. return True
  8338. if name in builtins.__dict__:
  8339. return obj is not builtins.__dict__[name]
  8340. if name in _custom_builtins:
  8341. return obj is not _custom_builtins[name].obj
  8342. */
  8343. return false;
  8344. }
  8345. associate_name_with_obj() {
  8346. }
  8347. });
  8348. this.registerType('torch.fx.node.Node', class {
  8349. constructor(graph, name, op, target, args, kwargs, return_type) {
  8350. this.graph = graph;
  8351. this.name = name;
  8352. this.op = op;
  8353. this.target = target;
  8354. this._input_nodes = new builtins.dict();
  8355. this.__update_args_kwargs(args, kwargs);
  8356. this.users = new builtins.dict();
  8357. this.type = return_type;
  8358. this._prev = this;
  8359. this._next = this;
  8360. this._erased = false;
  8361. this._repr_fn = null;
  8362. this.meta = new builtins.dict();
  8363. }
  8364. get args() {
  8365. return this._args;
  8366. }
  8367. get kwargs() {
  8368. return this._kwargs;
  8369. }
  8370. get next() {
  8371. return this._next;
  8372. }
  8373. prepend(x) {
  8374. x._remove_from_list();
  8375. const p = this._prev;
  8376. [p._next, x._prev] = [x, p];
  8377. [x._next, this._prev] = [this, x];
  8378. }
  8379. _remove_from_list() {
  8380. const [p, n] = [this._prev, this._next];
  8381. [p._next, n._prev] = [n, p];
  8382. }
  8383. __update_args_kwargs(new_args, new_kwargs) {
  8384. const update_users_and_input_nodes = (n) => {
  8385. if (n instanceof torch.fx.node.Node) {
  8386. this._input_nodes.setdefault(n);
  8387. n.users.setdefault(this);
  8388. }
  8389. return n;
  8390. };
  8391. const map_aggregate = (a, fn) => {
  8392. if (a instanceof builtins.tuple) {
  8393. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8394. if (!builtins.hasattr(a, '_fields')) {
  8395. return t;
  8396. }
  8397. throw new python.Error('Not implemented.');
  8398. // return type(a)(*t);
  8399. } else if (Array.isArray(a)) {
  8400. return a.map((elem) => map_aggregate(elem, fn));
  8401. } else if (a instanceof builtins.dict) {
  8402. const rv = new builtins.dict();
  8403. for (const [k, v] of a) {
  8404. rv.__setitem__(k, map_aggregate(v, fn));
  8405. }
  8406. return rv;
  8407. } else if (a instanceof builtins.slice) {
  8408. throw new python.Error('Not implemented.');
  8409. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8410. }
  8411. return fn(a);
  8412. };
  8413. for (const old_use of this._input_nodes.keys()) {
  8414. old_use.users.pop(this);
  8415. }
  8416. // object.__setattr__(self, "_input_nodes", {})
  8417. this._input_nodes = new builtins.dict();
  8418. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8419. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8420. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8421. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8422. }
  8423. });
  8424. torch.fx.Node = torch.fx.node.Node;
  8425. torch.fx.graph.Node = torch.fx.node.Node;
  8426. this.registerType('torch.fx.graph.Graph', class {
  8427. constructor(owning_module, tracer_cls, tracer_extras) {
  8428. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8429. this._used_names = new Map();
  8430. this._len = 0;
  8431. this._graph_namespace = new torch.fx.graph._Namespace();
  8432. this._owning_module = owning_module;
  8433. this._tracer_cls = tracer_cls;
  8434. this._tracer_extras = tracer_extras;
  8435. // this._codegen = CodeGen()
  8436. // this._co_fields = {}
  8437. }
  8438. get nodes() {
  8439. const array = new Array(this._len);
  8440. let node = this._root.next;
  8441. for (let i = 0; node !== this._root; i++) {
  8442. array[i] = node;
  8443. node = node.next;
  8444. }
  8445. return array;
  8446. }
  8447. placeholder(name, type_expr /*, default_value */) {
  8448. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8449. const kwargs = new builtins.dict();
  8450. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8451. }
  8452. create_node(op, target, args, kwargs, name, type_expr) {
  8453. args = args || new builtins.tuple();
  8454. kwargs = kwargs || new builtins.dict();
  8455. const candidate = name || this._target_to_str(target);
  8456. name = this._graph_namespace.create_name(candidate, null);
  8457. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8458. this._graph_namespace.associate_name_with_obj(name, n);
  8459. this._insert(n);
  8460. this._len += 1;
  8461. return n;
  8462. }
  8463. _insert(n) {
  8464. this._root.prepend(n);
  8465. }
  8466. output(result, type_expr) {
  8467. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8468. }
  8469. _target_to_str(target) {
  8470. if (typeof target === 'string') {
  8471. if (target.startsWith('__') && target.endsWith('__')) {
  8472. target = target.substring(2, target.length - 2);
  8473. }
  8474. } else {
  8475. target = target.__name__;
  8476. }
  8477. return this._snake_case(target);
  8478. }
  8479. _snake_case(s) {
  8480. const chars = [];
  8481. let prev_lower = false;
  8482. for (const c of s) {
  8483. const x = c.toLowerCase();
  8484. if (prev_lower && x !== c) {
  8485. chars.push('_');
  8486. } else {
  8487. prev_lower = true;
  8488. }
  8489. chars.push(x);
  8490. }
  8491. return chars.join('');
  8492. }
  8493. });
  8494. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8495. constructor(body) {
  8496. super();
  8497. for (const [k, v] of body.items()) {
  8498. builtins.setattr(this, k, v);
  8499. }
  8500. }
  8501. });
  8502. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8503. const parts = target.split('.');
  8504. const field = parts.pop();
  8505. for (const item of parts) {
  8506. const f = builtins.getattr(from_module, item);
  8507. let t = builtins.getattr(to_module, item, null);
  8508. if (f === t) {
  8509. return;
  8510. }
  8511. if (t === null) {
  8512. t = new torch.nn.modules.module.Module();
  8513. builtins.setattr(to_module, item, t);
  8514. }
  8515. from_module = f;
  8516. to_module = t;
  8517. }
  8518. const orig = builtins.getattr(from_module, field);
  8519. builtins.setattr(to_module, field, orig);
  8520. });
  8521. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8522. constructor(root, graph, class_name) {
  8523. super();
  8524. this.__class__.__name__ = class_name || 'GraphModule';
  8525. this.graph = graph;
  8526. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8527. for (const node of graph.nodes) {
  8528. if (node.op === 'get_attr' || node.op === 'call_module') {
  8529. torch.fx.graph_module._copy_attr(root, this, node.target);
  8530. }
  8531. }
  8532. }
  8533. }
  8534. });
  8535. torch.fx.Graph = torch.fx.graph.Graph;
  8536. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8537. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8538. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8539. return fn_or_name;
  8540. });
  8541. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8542. this.registerFunction('torchvision.datasets.folder.default_loader');
  8543. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8544. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8545. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8546. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8547. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8548. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8549. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8550. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8551. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8552. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8553. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8554. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8555. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8556. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8557. this.registerType('torchvision.ops.misc.Permute', class {});
  8558. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8559. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8560. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8561. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8562. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8563. this.registerType('torchvision.models._api.Weights', class {});
  8564. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8565. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8566. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8567. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8568. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8569. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8570. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8571. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8572. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8573. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8574. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8575. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8576. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8577. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8578. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8579. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8580. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8581. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8582. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8583. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8584. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8585. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8586. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8587. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8588. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8589. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8590. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8591. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8592. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8593. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8594. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8595. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8596. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8597. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8598. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8599. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8600. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8601. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8602. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8603. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8604. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8605. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8606. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8607. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8608. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8609. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8610. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8611. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8612. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8613. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8614. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8615. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8616. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8617. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8618. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8619. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8620. this.registerType('torchvision.models.googlenet.Inception', class {});
  8621. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8622. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8623. this.registerType('torchvision.models.inception.Inception3', class {});
  8624. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8625. this.registerType('torchvision.models.inception.InceptionA', class {});
  8626. this.registerType('torchvision.models.inception.InceptionB', class {});
  8627. this.registerType('torchvision.models.inception.InceptionC', class {});
  8628. this.registerType('torchvision.models.inception.InceptionD', class {});
  8629. this.registerType('torchvision.models.inception.InceptionE', class {});
  8630. this.registerFunction('torchvision.models.inception.inception_v3');
  8631. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8632. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8633. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8634. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8635. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8636. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8637. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8638. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8639. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8640. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8641. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8642. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8643. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8644. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8645. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8646. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8647. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8648. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8649. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8650. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8651. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8652. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8653. this.registerType('torchvision.models.regnet.RegNet', class {});
  8654. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8655. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8656. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8657. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8658. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8659. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8660. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8661. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8662. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8663. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8664. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8665. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8666. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8667. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8668. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8669. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8670. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8671. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8672. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8673. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8674. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8675. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8676. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8677. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8678. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8679. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8680. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8681. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8682. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8683. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8684. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8685. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8686. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8687. this.registerType('torchvision.models.resnet.ResNet', class {});
  8688. this.registerType('torchvision.models.vgg.VGG', class {});
  8689. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8690. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8691. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8692. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8693. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8694. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8695. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8696. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8697. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8698. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8699. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8700. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8701. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8702. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8703. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8704. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8705. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8706. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8707. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8708. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8709. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8710. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8711. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8712. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8713. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8714. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8715. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8716. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8717. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8718. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8719. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8720. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8721. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8722. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8723. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8724. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8725. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8726. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8727. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8728. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8729. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8730. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8731. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8732. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8733. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8734. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8735. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8736. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8737. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8738. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8739. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8740. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8741. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8742. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8743. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8744. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8745. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8746. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8747. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8748. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8749. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8750. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8751. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8752. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8753. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8754. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8755. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8756. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8757. this.registerFunction('torchvision.ops.boxes.box_iou');
  8758. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8759. this.registerFunction('builtins.annotate', (type, value) => {
  8760. if (type === builtins.int) {
  8761. return Number.isInteger(value) ? value : NaN;
  8762. }
  8763. if (type === builtins.float) {
  8764. return typeof value === 'number' ? value : NaN;
  8765. }
  8766. if (type === builtins.number) {
  8767. // if (pytorch.Utility.isTensor(value)) {
  8768. // value.resize_([]);
  8769. // }
  8770. }
  8771. return value;
  8772. });
  8773. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8774. return undefined;
  8775. });
  8776. this.registerFunction('builtins.range', (start, stop, step) => {
  8777. if (stop === undefined && step === undefined) {
  8778. if (Number.isInteger(start)) {
  8779. return Array(start).keys();
  8780. }
  8781. if (isNaN(start)) {
  8782. return [];
  8783. }
  8784. }
  8785. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8786. });
  8787. this.registerFunction('math.trunc');
  8788. builtins.xrange = builtins.range;
  8789. this.registerFunction('torch._C._nn.gelu');
  8790. this.registerFunction('torch._C._nn.avg_pool2d');
  8791. this.registerFunction('torch._C._nn.avg_pool3d');
  8792. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8793. this.registerFunction('torch._C._nn.softplus');
  8794. this.registerFunction('torch._native_multi_head_attention');
  8795. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8796. if (layout === torch.sparse_coo) {
  8797. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8798. }
  8799. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8800. });
  8801. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8802. return device;
  8803. });
  8804. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8805. device = torch._utils._get_restore_location(device);
  8806. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8807. });
  8808. this.registerFunction('torch.from_numpy', (obj) => {
  8809. const dtypes = new Map([
  8810. ['<f2', torch.float16],
  8811. ['<f4', torch.float32],
  8812. ['<f8', torch.float64],
  8813. ['<i2', torch.int16],
  8814. ['<i4', torch.int32],
  8815. ['<i8', torch.int64],
  8816. ]);
  8817. if (!dtypes.has(obj.dtype.str)) {
  8818. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8819. }
  8820. const dtype = dtypes.get(obj.dtype.str);
  8821. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8822. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8823. storage._set_cdata(obj.data);
  8824. const tensor = new torch.Tensor();
  8825. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8826. return tensor;
  8827. });
  8828. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8829. const tensor = torch.from_numpy(data);
  8830. // tensor = tensor.to(dtype, device)
  8831. tensor.requires_grad = requires_grad;
  8832. return tensor;
  8833. });
  8834. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  8835. const tensor = self.invoke('torch.Tensor', []);
  8836. tensor._layout = torch.sparse_coo;
  8837. tensor._indices = indices;
  8838. tensor._values = values;
  8839. tensor._shape = size;
  8840. return tensor;
  8841. });
  8842. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  8843. torch._C._set_tensor_metadata(tensor, metadata);
  8844. });
  8845. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  8846. return tensor;
  8847. });
  8848. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  8849. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  8850. });
  8851. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  8852. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  8853. const [, storage_type, , ,size] = storage;
  8854. storage = new storage_type(size);
  8855. }
  8856. const tensor = new torch.Tensor();
  8857. tensor.__setstate__([storage, storage_offset, size, stride]);
  8858. return tensor;
  8859. });
  8860. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  8861. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  8862. tensor.requires_grad = requires_grad;
  8863. if (metadata) {
  8864. torch._utils.set_tensor_metadata(tensor, metadata);
  8865. }
  8866. tensor.backward_hooks = backward_hooks;
  8867. return tensor;
  8868. });
  8869. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  8870. const t = new torch.Tensor(null, null, dtype);
  8871. t.set_(storage, storage_offset, size, stride);
  8872. if (metadata) {
  8873. torch._utils.set_tensor_metadata(t, metadata);
  8874. }
  8875. t._backward_hooks = backward_hooks;
  8876. return torch._utils._restore_device_fake_mode(t);
  8877. });
  8878. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  8879. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8880. param.backward_hooks = backward_hooks;
  8881. return param;
  8882. });
  8883. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  8884. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8885. param.backward_hooks = backward_hooks;
  8886. torch._utils._set_obj_state(param, state);
  8887. return param;
  8888. });
  8889. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  8890. const _set_obj_state = (obj, state) => {
  8891. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  8892. if (dict_state) {
  8893. for (const [k, v] of Object.entries(dict_state)) {
  8894. builtins.setattr(obj, k, v);
  8895. }
  8896. }
  8897. if (slots_state) {
  8898. for (const [k, v] of Object.entries(slots_state)) {
  8899. builtins.setattr(obj, k, v);
  8900. }
  8901. }
  8902. };
  8903. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8904. param._backward_hooks = backward_hooks;
  8905. _set_obj_state(param, state);
  8906. return param;
  8907. });
  8908. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  8909. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  8910. tensor.quantizer_params = quantizer_params;
  8911. return tensor;
  8912. });
  8913. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  8914. let dict_state = state;
  8915. let slots_state = null;
  8916. if (state instanceof self.builtins.tuple) {
  8917. if (state.length !== 2) {
  8918. throw new python.Error(`Invalid serialized state: '${state}'.`);
  8919. }
  8920. [dict_state, slots_state] = state;
  8921. }
  8922. if (dict_state) {
  8923. for (const [name, value] of Object.entries(dict_state)) {
  8924. builtins.setattr(obj, name, value);
  8925. }
  8926. }
  8927. if (slots_state) {
  8928. for (const [name, value] of Object.entries(slots_state)) {
  8929. builtins.setattr(obj, name, value);
  8930. }
  8931. }
  8932. return obj;
  8933. });
  8934. this.registerFunction('torch._set_item', (dict, key, value) => {
  8935. dict[key] = value;
  8936. });
  8937. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  8938. let ret = func(...args);
  8939. if (ret.__class__ !== new_type) {
  8940. // ret = ret.as_subclass(new_type);
  8941. }
  8942. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  8943. if (setstate === torch.Tensor.__setstate__) {
  8944. ret = torch._utils._set_obj_state(ret, state);
  8945. } else {
  8946. ret.__setstate__(state);
  8947. }
  8948. return ret;
  8949. });
  8950. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  8951. if (step === 0) {
  8952. throw new python.Error('range() arg 3 must not be zero');
  8953. }
  8954. if (step > 0 && lo < hi) {
  8955. return 1 + (hi - 1 - lo) / step;
  8956. } else if (step < 0 && lo > hi) {
  8957. return 1 + (lo - 1 - hi) / (0 - step);
  8958. }
  8959. return 0;
  8960. });
  8961. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  8962. this.registerOperator('aten::_unwrap_optional', (value) => {
  8963. return value;
  8964. });
  8965. this.registerFunction('torch.get_default_dtype', () => {
  8966. torch._default_type = torch._default_type || torch.float32;
  8967. return torch._default_type;
  8968. });
  8969. this.registerFunction('torch.set_default_dtype', (value) => {
  8970. torch._default_type = value;
  8971. });
  8972. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  8973. return value || torch.get_default_dtype();
  8974. });
  8975. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  8976. const shape = size;
  8977. dtype = torch._prims_common.dtype_or_default(dtype);
  8978. let storage = null;
  8979. if (size.every((d) => d instanceof torch.SymInt === false)) {
  8980. const size = shape.reduce((a, b) => a * b, 1);
  8981. storage = new torch.storage.TypedStorage(size, dtype);
  8982. }
  8983. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  8984. tensor.__setstate__([storage, 0, shape, stride]);
  8985. return tensor;
  8986. });
  8987. this.registerFunction('torch.all', (input) => {
  8988. if (Array.isArray(input) && input.length === 0) {
  8989. return true;
  8990. }
  8991. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  8992. });
  8993. this.registerFunction('torch.append', (list, value) => {
  8994. list.push(value);
  8995. return value;
  8996. });
  8997. this.registerFunction('torch.clear', (value) => {
  8998. if (value instanceof torch.Value) {
  8999. throw new python.Error('Invalid value.');
  9000. }
  9001. if (Object(value) === value) {
  9002. for (const key of Object.keys(value)) {
  9003. delete value[key];
  9004. }
  9005. }
  9006. });
  9007. this.registerFunction('torch.dict', (args) => {
  9008. const obj = {};
  9009. if (args) {
  9010. if (Array.isArray(args)) {
  9011. for (const [key, value] of args) {
  9012. obj[key] = value;
  9013. }
  9014. } else {
  9015. throw new python.Error("'torch.dict' arguments not supported.");
  9016. }
  9017. }
  9018. return obj;
  9019. });
  9020. this.registerOperator('aten::cosine_similarity', () => {
  9021. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9022. });
  9023. this.registerOperator('aten::extend', (list, value) => {
  9024. list.push(...value);
  9025. });
  9026. this.registerOperator('aten::insert', (list, index, value) => {
  9027. list.splice(index, 0, value);
  9028. return value;
  9029. });
  9030. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9031. return value.replace(oldvalue, newvalue);
  9032. });
  9033. this.registerOperator('aten::add', (left, right) => {
  9034. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9035. return left + right;
  9036. }
  9037. if (Array.isArray(left) && Array.isArray(right)) {
  9038. return left.concat(right);
  9039. }
  9040. if (typeof left === 'string' && typeof right === 'string') {
  9041. return left + right;
  9042. }
  9043. throw new python.Error('Unsupported aten::add expression type.');
  9044. });
  9045. this.registerOperator('aten::log', (x) => {
  9046. if (typeof x === 'number' || x instanceof Number) {
  9047. return Math.log(x);
  9048. }
  9049. throw new python.Error('Unsupported aten::log expression type.');
  9050. });
  9051. this.registerOperator('aten::dim', (tensor) => {
  9052. if (tensor && tensor.size) {
  9053. const size = tensor.size();
  9054. if (size) {
  9055. return size.length;
  9056. }
  9057. }
  9058. return NaN;
  9059. });
  9060. this.registerOperator('aten::numel', (tensor) => {
  9061. if (tensor && tensor.size) {
  9062. const size = tensor.size();
  9063. if (size) {
  9064. return size.reduce((a, b) => a * b, 1);
  9065. }
  9066. }
  9067. return NaN;
  9068. });
  9069. this.registerOperator('aten::eq', (left, right) => {
  9070. if (typeof left === 'string' && typeof right === 'string') {
  9071. return left === right;
  9072. }
  9073. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9074. if (isNaN(left) && isNaN(right)) {
  9075. return true;
  9076. }
  9077. return left === right;
  9078. }
  9079. if (left === undefined || right === undefined) {
  9080. return true;
  9081. }
  9082. if (Array.isArray(left) && Array.isArray(right)) {
  9083. return left.length === right.length && left.every((item, index) => item === right[index]);
  9084. }
  9085. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9086. });
  9087. this.registerOperator('aten::floor', (value) => {
  9088. return Math.floor(value);
  9089. });
  9090. this.registerOperator('aten::ceil', (value) => {
  9091. return Math.ceil(value);
  9092. });
  9093. this.registerOperator('aten::floordiv', (left, right) => {
  9094. return Math.floor(left / right);
  9095. });
  9096. this.registerOperator('aten::format', (...args) => {
  9097. const list = args.shift().split(/({}D?)/);
  9098. return list.map((text) => {
  9099. if (text === '{}' || text === '{}D') {
  9100. const arg = args.shift();
  9101. if (Array.isArray(arg)) {
  9102. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9103. }
  9104. return arg ? arg.toString() : '?';
  9105. }
  9106. return text;
  9107. }).join('');
  9108. });
  9109. this.registerOperator('aten::strip', (self, chars) => {
  9110. chars = chars || '\\n\\t\\f\\v';
  9111. const regex = new RegExp(`[${chars}]`, 'g');
  9112. return self.replace(regex, '');
  9113. });
  9114. this.registerOperator('aten::gt', (left, right) => {
  9115. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9116. if (!isNaN(left) && !isNaN(right)) {
  9117. return left > right;
  9118. }
  9119. }
  9120. if (isNaN(left) && !isNaN(right)) {
  9121. return true;
  9122. }
  9123. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9124. });
  9125. this.registerOperator('aten::ge', (left, right) => {
  9126. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9127. if (!isNaN(left) && !isNaN(right)) {
  9128. return left > right;
  9129. }
  9130. }
  9131. if (isNaN(left) && !isNaN(right)) {
  9132. return true;
  9133. }
  9134. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9135. });
  9136. this.registerOperator('aten::is_floating_point', (tensor) => {
  9137. const type = tensor.dtype.scalar_type();
  9138. return (type === 5 || type === 6 || type === 7);
  9139. });
  9140. this.registerOperator('aten::is_grad_enabled', () => {
  9141. return false;
  9142. });
  9143. this.registerOperator('aten::is_autocast_enabled', () => {
  9144. return false;
  9145. });
  9146. this.registerOperator('aten::isfinite');
  9147. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9148. });
  9149. this.registerFunction('torch.serialization._get_layout', (name) => {
  9150. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9151. return value instanceof torch.layout ? value : null;
  9152. });
  9153. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9154. return torch.load(b);
  9155. });
  9156. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9157. return data;
  9158. });
  9159. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9160. return data;
  9161. });
  9162. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9163. return data;
  9164. });
  9165. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9166. return data;
  9167. });
  9168. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9169. return self.builtins.CONSTANTS[`c${data}`];
  9170. });
  9171. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9172. return value;
  9173. });
  9174. this.registerOperator('aten::keys', (dict) => {
  9175. return Object.keys(dict);
  9176. });
  9177. this.registerOperator('aten::len', (value) => {
  9178. if (Array.isArray(value)) {
  9179. return value.length;
  9180. }
  9181. if (value && value.shape && value.__len__) {
  9182. return value.__len__();
  9183. }
  9184. return NaN;
  9185. });
  9186. this.registerOperator('aten::le', (left, right) => {
  9187. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9188. if (isNaN(left) || isNaN(right)) {
  9189. return false;
  9190. }
  9191. return left <= right;
  9192. }
  9193. if (left === undefined || right === undefined) {
  9194. return true;
  9195. }
  9196. throw new python.Error("Unsupported 'torch.le' expression type.");
  9197. });
  9198. this.registerOperator('aten::list', (args) => {
  9199. return args;
  9200. });
  9201. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9202. return size;
  9203. });
  9204. this.registerType('torch.PyTorchFileReader', class {
  9205. constructor(entries) {
  9206. let prefix = 0;
  9207. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9208. for (let set = new Set(); set && paths.length > 0;) {
  9209. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9210. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9211. prefix += set ? set.keys().next().value.length + 1 : 0;
  9212. }
  9213. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9214. this._version = 0;
  9215. const stream = this.get_record('.data/version') || this.get_record('version') || null;
  9216. if (stream) {
  9217. const decoder = new TextDecoder('utf-8');
  9218. const buffer = stream.peek();
  9219. const text = decoder.decode(buffer);
  9220. this._version = Number(text.split('\n').shift().trim());
  9221. }
  9222. }
  9223. has_record(name) {
  9224. return this._records.has(name);
  9225. }
  9226. get_record(name) {
  9227. return this._records.get(name);
  9228. }
  9229. get_all_records() {
  9230. return Array.from(this._records.keys());
  9231. }
  9232. version() {
  9233. return this._version;
  9234. }
  9235. });
  9236. this.registerFunction('torch.load', (f) => {
  9237. const legacy_load = (entries) => {
  9238. const deserialized_objects = {};
  9239. if (entries.has('storages')) {
  9240. const data = entries.get('storages');
  9241. const unpickler = new pickle.Unpickler(data);
  9242. const num_storages = unpickler.load();
  9243. for (let i = 0; i < num_storages; i++) {
  9244. const args = unpickler.load();
  9245. const [key, , storage_type] = args;
  9246. const obj = storage_type._new_with_file(unpickler);
  9247. deserialized_objects[key] = obj;
  9248. }
  9249. /*
  9250. let storage_views = unpickler.load();
  9251. for target_cdata, root_cdata, offset, size in storage_views:
  9252. root = deserialized_objects[root_cdata]
  9253. deserialized_objects[target_cdata] = root[offset:offset + size]
  9254. */
  9255. }
  9256. if (entries.has('tensors')) {
  9257. const data = entries.get('tensors');
  9258. const unpickler = new pickle.Unpickler(data);
  9259. const num_tensors = unpickler.load();
  9260. const int32 = (unpickler) => {
  9261. const buffer = unpickler.read(4);
  9262. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9263. };
  9264. const int64 = (unpickler) => {
  9265. const buffer = unpickler.read(8);
  9266. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9267. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9268. }
  9269. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9270. };
  9271. for (let i = 0; i < num_tensors; i++) {
  9272. const args = unpickler.load();
  9273. const [key, storage_id] = args;
  9274. const storage = deserialized_objects[storage_id];
  9275. const ndim = int32(unpickler);
  9276. unpickler.read(4);
  9277. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9278. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9279. const storage_offset = int64(unpickler);
  9280. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9281. deserialized_objects[key] = tensor;
  9282. }
  9283. }
  9284. const data = entries.get('pickle');
  9285. const unpickler = new pickle.Unpickler(data);
  9286. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9287. return unpickler.load();
  9288. };
  9289. const _legacy_load = () => {
  9290. const unpickler = new pickle.Unpickler(f);
  9291. unpickler.load(); // magic_number
  9292. const protocol_version = unpickler.load();
  9293. if (protocol_version !== 1001) {
  9294. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9295. }
  9296. const sys_info = unpickler.load();
  9297. if (sys_info.get('protocol_version') !== 1001) {
  9298. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9299. }
  9300. if (sys_info.get('little_endian') === false) {
  9301. throw new python.Error("Unsupported big-endian storage data.");
  9302. }
  9303. const module_source_map = new Map();
  9304. const deserialized_objects = new Map();
  9305. unpickler.persistent_load = (saved_id) => {
  9306. switch (saved_id[0]) {
  9307. case 'module': {
  9308. const [, module, ,source] = saved_id;
  9309. module_source_map.set(module, source);
  9310. return saved_id[1];
  9311. }
  9312. case 'storage': {
  9313. const [, storage_type, key, , size, view_metadata] = saved_id;
  9314. if (!deserialized_objects.has(key)) {
  9315. const obj = new storage_type(size);
  9316. deserialized_objects.set(key, obj);
  9317. }
  9318. if (view_metadata) {
  9319. const view_key = view_metadata.shift();
  9320. view_metadata.shift(); // view_offset
  9321. view_metadata.shift(); // view_size
  9322. if (!deserialized_objects.has(view_key)) {
  9323. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9324. deserialized_objects.set(view_key, view);
  9325. }
  9326. return deserialized_objects.get(view_key);
  9327. }
  9328. return deserialized_objects.get(key);
  9329. }
  9330. default: {
  9331. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9332. }
  9333. }
  9334. };
  9335. const obj = unpickler.load();
  9336. const deserialized_storage_keys = unpickler.load();
  9337. for (const deserialized_storage_key of deserialized_storage_keys) {
  9338. const storage = deserialized_objects.get(deserialized_storage_key);
  9339. storage._set_from_file(unpickler);
  9340. }
  9341. if (!obj) {
  9342. throw new python.Error('File format is not PyTorch.');
  9343. }
  9344. if (obj === 'None') {
  9345. throw new python.Error("File contains 'None' root object.");
  9346. }
  9347. return obj;
  9348. };
  9349. const _load = (entries) => {
  9350. if (f.has('constant.pkl')) {
  9351. throw python.Error("TorchScript 'torch.load' not supported.");
  9352. }
  9353. const loaded_storages = new Map();
  9354. const persistent_load = (saved_id) => {
  9355. switch (saved_id[0]) {
  9356. case 'storage': {
  9357. const [, storage_type, key, , numel] = saved_id;
  9358. if (!loaded_storages.has(key)) {
  9359. const storage = new storage_type(numel);
  9360. const name = `data/${key}`;
  9361. const stream = entries.get(name);
  9362. storage._set_cdata(stream);
  9363. loaded_storages.set(key, storage);
  9364. }
  9365. return loaded_storages.get(key);
  9366. }
  9367. default: {
  9368. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9369. }
  9370. }
  9371. };
  9372. const data_file = entries.get('data.pkl');
  9373. const unpickler = new pickle.Unpickler(data_file);
  9374. unpickler.persistent_load = persistent_load;
  9375. const result = unpickler.load();
  9376. return result;
  9377. };
  9378. if (f instanceof Map) {
  9379. const reader = new torch.PyTorchFileReader(f);
  9380. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9381. f = new Map(records);
  9382. if (f.has('pickle')) {
  9383. return legacy_load(f);
  9384. }
  9385. if (f.has('data.pkl')) {
  9386. return _load(f);
  9387. }
  9388. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9389. }
  9390. return _legacy_load(f);
  9391. });
  9392. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9393. return value;
  9394. });
  9395. this.registerOperator('prim::data', (tensor) => {
  9396. return tensor;
  9397. });
  9398. this.registerOperator('prim::device', (tensor) => {
  9399. return tensor.device;
  9400. });
  9401. this.registerOperator('prim::dtype', (tensor) => {
  9402. return tensor.dtype.scalar_type();
  9403. });
  9404. this.registerOperator('prim::is_quantized', (tensor) => {
  9405. return tensor.is_quantized;
  9406. });
  9407. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9408. return false;
  9409. });
  9410. this.registerOperator('prim::is_nested', (tensor) => {
  9411. return tensor.is_nested;
  9412. });
  9413. this.registerOperator('prim::is_sparse', (tensor) => {
  9414. return tensor.is_sparse;
  9415. });
  9416. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9417. return value;
  9418. });
  9419. this.registerOperator('prim::NumToTensor', (value) => {
  9420. const tensor = self.invoke('torch.Tensor', []);
  9421. tensor.value = value;
  9422. return tensor;
  9423. });
  9424. this.registerOperator('prim::min', (...args) => {
  9425. if (Array.isArray(args[0])) {
  9426. return Math.min.apply(null, args[0]);
  9427. }
  9428. return Math.min.apply(null, args);
  9429. });
  9430. this.registerOperator('prim::max', (...args) => {
  9431. if (Array.isArray(args[0])) {
  9432. return Math.max.apply(null, args[0]);
  9433. }
  9434. return Math.max.apply(null, args);
  9435. });
  9436. this.registerOperator('prim::shape', (tensor) => {
  9437. return tensor && tensor.size ? tensor.size() : undefined;
  9438. });
  9439. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9440. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9441. params.weight = weight;
  9442. params.bias = bias;
  9443. params.stride = stride;
  9444. params.padding = padding;
  9445. params.dilation = dilation;
  9446. params.groups = groups;
  9447. return params;
  9448. });
  9449. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9450. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9451. params.weight = weight;
  9452. params.bias = bias;
  9453. params.stride = stride;
  9454. params.padding = padding;
  9455. params.dilation = dilation;
  9456. params.groups = groups;
  9457. return params;
  9458. });
  9459. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9460. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9461. params.weight = weight;
  9462. params.bias = bias;
  9463. params.stride = stride;
  9464. params.padding = padding;
  9465. params.dilation = dilation;
  9466. params.groups = groups;
  9467. return params;
  9468. });
  9469. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9470. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9471. params.weight = weight;
  9472. params.bias = bias;
  9473. params.stride = stride;
  9474. params.padding = padding;
  9475. params.dilation = dilation;
  9476. params.groups = groups;
  9477. return params;
  9478. });
  9479. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9480. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9481. params.weight = weight;
  9482. params.bias = bias;
  9483. params.stride = stride;
  9484. params.padding = padding;
  9485. params.output_padding = output_padding;
  9486. params.dilation = dilation;
  9487. params.groups = groups;
  9488. return params;
  9489. });
  9490. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9491. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9492. params.weight = weight;
  9493. params.bias = bias;
  9494. params.stride = stride;
  9495. params.padding = padding;
  9496. params.output_padding = output_padding;
  9497. params.dilation = dilation;
  9498. params.groups = groups;
  9499. return params;
  9500. });
  9501. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9502. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9503. params.weight = weight;
  9504. params.bias = bias;
  9505. return params;
  9506. });
  9507. this.registerOperator('prim::RaiseException', (message) => {
  9508. throw new python.Error(message);
  9509. });
  9510. this.registerOperator('prim::TupleIndex', (t, i) => {
  9511. return t.elements()[i];
  9512. });
  9513. this.registerOperator('prim::TupleUnpack', (t) => {
  9514. return t.elements();
  9515. });
  9516. this.registerOperator('aten::is_scripting', () => {
  9517. return true;
  9518. });
  9519. this.registerOperator('aten::__and__', (left, right) => {
  9520. return left && right;
  9521. });
  9522. this.registerOperator('aten::__contains__', (dict, key) => {
  9523. return builtins.hasattr(dict, key);
  9524. });
  9525. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9526. return start + index * step;
  9527. });
  9528. this.registerOperator('aten::__is__', (left, right) => {
  9529. return left === right;
  9530. });
  9531. this.registerOperator('aten::__isnot__', (left, right) => {
  9532. return left !== right;
  9533. });
  9534. this.registerOperator('aten::__not__', (value) => {
  9535. if (Number.isInteger(value)) {
  9536. value = Boolean(value);
  9537. }
  9538. if (typeof value === 'boolean') {
  9539. return !value;
  9540. }
  9541. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9542. });
  9543. this.registerOperator('aten::log10', (value) => {
  9544. return Math.log10(value);
  9545. });
  9546. this.registerOperator('aten::device', (type, index) => {
  9547. return new torch.device(type, index);
  9548. });
  9549. this.registerOperator('aten::lt', (left, right) => {
  9550. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9551. return left < right;
  9552. }
  9553. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9554. });
  9555. this.registerOperator('aten::mul', (left, right) => {
  9556. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9557. return left * right;
  9558. }
  9559. if (isNaN(left) || isNaN(right)) {
  9560. return NaN;
  9561. }
  9562. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9563. return left.map((value) => value * right);
  9564. }
  9565. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9566. });
  9567. this.registerOperator('aten::div', (left, right) => {
  9568. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9569. return left / right;
  9570. }
  9571. if (isNaN(left) || isNaN(right)) {
  9572. return NaN;
  9573. }
  9574. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9575. });
  9576. this.registerFunction('torch.round', (value) => {
  9577. if (typeof value === 'number' || value instanceof Number) {
  9578. return Math.round(value);
  9579. }
  9580. if (isNaN(value)) {
  9581. return value;
  9582. }
  9583. throw new python.Error("Unsupported 'torch.round' expression type.");
  9584. });
  9585. this.registerOperator('aten::remainder', (left, right) => {
  9586. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9587. return left % right;
  9588. }
  9589. if (isNaN(left) || isNaN(right)) {
  9590. return NaN;
  9591. }
  9592. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9593. });
  9594. this.registerOperator('aten::ne', (left, right) => {
  9595. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9596. return left !== right;
  9597. }
  9598. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9599. if (isNaN(left) || isNaN(right)) {
  9600. return false;
  9601. }
  9602. return left !== right;
  9603. }
  9604. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9605. return false;
  9606. }
  9607. if (typeof left === 'string' && typeof right === 'string') {
  9608. return left !== right;
  9609. }
  9610. if (left === undefined || right === undefined) {
  9611. return true;
  9612. }
  9613. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9614. });
  9615. this.registerOperator('aten::neg', (value) => {
  9616. if (typeof value === 'number') {
  9617. return -value;
  9618. }
  9619. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9620. });
  9621. this.registerOperator('aten::pow', (left, right) => {
  9622. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9623. return Math.pow(left, right);
  9624. }
  9625. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9626. });
  9627. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9628. return -1;
  9629. });
  9630. this.registerFunction('torch.t', (tensor) => {
  9631. return tensor;
  9632. });
  9633. this.registerOperator('aten::size', (tensor, dim) => {
  9634. if (tensor && tensor.size) {
  9635. const size = tensor.size();
  9636. if (Array.isArray(size)) {
  9637. if (dim === undefined) {
  9638. return size;
  9639. }
  9640. if (Number.isInteger(dim)) {
  9641. if (dim >= 0 && dim < size.length) {
  9642. return size[dim];
  9643. }
  9644. if (dim < 0 && -dim < size.length) {
  9645. return size[size.length + dim];
  9646. }
  9647. }
  9648. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9649. }
  9650. }
  9651. if (Number.isInteger(dim)) {
  9652. return NaN;
  9653. }
  9654. return [];
  9655. });
  9656. this.registerFunction('aten::sqrt', (x) => {
  9657. return Math.sqrt(x);
  9658. });
  9659. this.registerOperator('aten::slice', (l, start, end, step) => {
  9660. if (!Array.isArray(l)) {
  9661. throw new python.Error('Slicing expected array');
  9662. }
  9663. step = step || 1;
  9664. if (step !== 1) {
  9665. throw new python.Error('Slicing only supports step=1');
  9666. }
  9667. start = Math.max(0, start >= 0 ? start : l.length + start);
  9668. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9669. return l.slice(start, end);
  9670. });
  9671. this.registerOperator('aten::sub', (left, right) => {
  9672. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9673. return left - right;
  9674. }
  9675. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9676. });
  9677. this.registerFunction('torch.sym_int');
  9678. this.registerFunction('torch.sym_float');
  9679. this.registerFunction('torch.sym_ite');
  9680. this.registerFunction('torch.sym_max');
  9681. this.registerFunction('torch.sym_min');
  9682. this.registerFunction('torch.sym_not');
  9683. this.registerFunction('torch.sym_sqrt');
  9684. this.registerFunction('torch.sym_sqrt');
  9685. this.registerFunction('torch.functional.einsum');
  9686. this.registerFunction('torch.functional.norm');
  9687. this.registerFunction('torch.functional.split');
  9688. this.registerFunction('torch.nn.init.constant_');
  9689. this.registerFunction('torch.nn.init.normal_');
  9690. this.registerFunction('torch.nn.init.xavier_uniform_');
  9691. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9692. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9693. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9694. this.registerFunction('torch.nn.functional.cross_entropy');
  9695. this.registerFunction('torch.nn.functional.elu');
  9696. this.registerFunction('torch.nn.functional.gelu');
  9697. this.registerFunction('torch.nn.functional.hardsigmoid');
  9698. this.registerFunction('torch.nn.functional.hardswish');
  9699. this.registerFunction('torch.nn.functional.hardtanh');
  9700. this.registerFunction('torch.nn.functional.interpolate');
  9701. this.registerFunction('torch.nn.functional.leaky_relu');
  9702. this.registerFunction('torch.nn.functional.l1_loss');
  9703. this.registerFunction('torch.nn.functional.linear');
  9704. this.registerFunction('torch.nn.functional.log_softmax');
  9705. this.registerFunction('torch.nn.functional._max_pool2d');
  9706. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9707. this.registerFunction('torch.nn.functional.mse_loss');
  9708. this.registerFunction('torch.nn.functional.pad');
  9709. this.registerFunction('torch.nn.functional.relu');
  9710. this.registerFunction('torch.nn.functional.relu6');
  9711. this.registerFunction('torch.nn.functional.sigmoid');
  9712. this.registerFunction('torch.nn.functional.silu');
  9713. this.registerFunction('torch.nn.functional.softmax');
  9714. this.registerFunction('torch.nn.functional.tanh');
  9715. this.registerFunction('torch.values', (dict) => {
  9716. return Object.values(dict);
  9717. });
  9718. this.registerFunction('torch.warn', () => {
  9719. });
  9720. this.registerType('torch._ops.OperatorBase', class {
  9721. constructor() {
  9722. this.functorch_table = {};
  9723. }
  9724. });
  9725. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9726. constructor(name, cacheable) {
  9727. super();
  9728. this._name = name;
  9729. this.__name__ = name;
  9730. this._ns = 'higher_order';
  9731. this.__module__ = 'torch.ops.higher_order';
  9732. this._cacheable = cacheable;
  9733. }
  9734. get namespace() {
  9735. return this._ns;
  9736. }
  9737. get name() {
  9738. return this._name;
  9739. }
  9740. });
  9741. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9742. constructor(name) {
  9743. super(name, false);
  9744. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9745. }
  9746. });
  9747. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9748. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9749. constructor(name) {
  9750. super(name, false);
  9751. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9752. }
  9753. });
  9754. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9755. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9756. constructor(name) {
  9757. super(name, false);
  9758. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9759. }
  9760. });
  9761. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  9762. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9763. constructor(name) {
  9764. super(name, false);
  9765. }
  9766. });
  9767. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  9768. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9769. constructor(name) {
  9770. super(name, false);
  9771. }
  9772. });
  9773. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  9774. this.registerType('torch.Type', class {
  9775. constructor(kind, annotation_str) {
  9776. this._kind = kind;
  9777. if (annotation_str) {
  9778. this._annotation_str = annotation_str;
  9779. }
  9780. }
  9781. static get(kind, annotation_str) {
  9782. torch.Type.cache = torch.Type.cache || new Map();
  9783. if (!annotation_str) {
  9784. if (!torch.Type.cache.has(kind)) {
  9785. torch.Type.cache.set(kind, new torch.Type(kind));
  9786. }
  9787. return torch.Type.cache.get(kind);
  9788. }
  9789. return new torch.Type(kind, annotation_str);
  9790. }
  9791. kind() {
  9792. return this._kind;
  9793. }
  9794. get annotation_str() {
  9795. return this._annotation_str;
  9796. }
  9797. equals(rhs) {
  9798. return this.kind() === rhs.kind();
  9799. }
  9800. isSubtypeOf(rhs) {
  9801. if (rhs.kind() === 'AnyType' || this === rhs) {
  9802. return true;
  9803. }
  9804. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  9805. return this.isSubtypeOf(rhs.getElementType());
  9806. }
  9807. if (rhs instanceof torch.UnionType) {
  9808. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  9809. }
  9810. if (rhs instanceof torch._C.DynamicType) {
  9811. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  9812. }
  9813. return this.equals(rhs);
  9814. }
  9815. containedTypes() {
  9816. return [];
  9817. }
  9818. containedType(i) {
  9819. return this.containedTypes()[i];
  9820. }
  9821. withContained(contained_types) {
  9822. const current_contained = this.containedTypes();
  9823. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  9824. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  9825. return this;
  9826. }
  9827. return this.createWithContained(contained_types);
  9828. }
  9829. createWithContained(/* createWithContained */) {
  9830. throw new python.Error('Not implemented.');
  9831. }
  9832. isUnionType() {
  9833. return false;
  9834. }
  9835. hasFreeVariables() {
  9836. return false;
  9837. }
  9838. is_module() {
  9839. return false;
  9840. }
  9841. expect(type) {
  9842. torch._C.AT_ASSERT(this instanceof type);
  9843. return this;
  9844. }
  9845. str() {
  9846. if (this instanceof torch._C.VarType && this._annotation_str) {
  9847. return this._annotation_str;
  9848. } else if (this._kind === 'ScalarTypeType') {
  9849. return 'ScalarType';
  9850. } else if (this._kind === 'QSchemeType') {
  9851. return 'QScheme';
  9852. } else if (this._kind) {
  9853. return this._kind;
  9854. }
  9855. throw new python.Error(`Not implemented '${this.kind()}'.`);
  9856. }
  9857. __str__() {
  9858. return this.str();
  9859. }
  9860. toString() {
  9861. return this.__str__();
  9862. }
  9863. });
  9864. this.registerType('torch.ClassType', class extends torch.Type {
  9865. constructor(qualified_name, cu, is_module) {
  9866. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  9867. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  9868. this._is_module = is_module;
  9869. this._attributes = [];
  9870. this._attributeTypes = [];
  9871. this._methods = [];
  9872. this._staticmethods = new Map();
  9873. this._forward_hooks = [];
  9874. this._forward_pre_hooks = [];
  9875. this._properties = [];
  9876. this._constants = new Map();
  9877. }
  9878. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  9879. return new torch.ClassType(qualifiedName, cu, is_module);
  9880. }
  9881. qualified_name() {
  9882. return this.annotation_str;
  9883. }
  9884. name() {
  9885. return this._name;
  9886. }
  9887. is_module() {
  9888. return this._is_module;
  9889. }
  9890. is_parameter(slot) {
  9891. return this._attributes[slot].is_parameter === true;
  9892. }
  9893. is_buffer(slot) {
  9894. return this._attributes[slot].is_buffer === true;
  9895. }
  9896. addMethod(method) {
  9897. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  9898. this._methods.push(method);
  9899. }
  9900. findMethod(name) {
  9901. for (const method of this._methods) {
  9902. if (name === method.name()) {
  9903. return method;
  9904. }
  9905. }
  9906. return null;
  9907. }
  9908. getMethod(name) {
  9909. const method = this.findMethod(name);
  9910. if (!method) {
  9911. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  9912. }
  9913. return method;
  9914. }
  9915. methods() {
  9916. return this._methods;
  9917. }
  9918. addStaticMethod(func) {
  9919. this._staticmethods.set(func.name, func);
  9920. }
  9921. findStaticMethod(name) {
  9922. return this._staticmethods.get(name);
  9923. }
  9924. findHook(name) {
  9925. let hook = this.findForwardHook(name);
  9926. if (hook === null) {
  9927. hook = this.findForwardPreHook(name);
  9928. }
  9929. return hook;
  9930. }
  9931. findForwardHook(name) {
  9932. for (const hook of this._forward_hooks) {
  9933. if (name === hook.name()) {
  9934. return hook;
  9935. }
  9936. }
  9937. return null;
  9938. }
  9939. findForwardPreHook(name) {
  9940. for (const pre_hook of this._forward_pre_hooks) {
  9941. if (name === pre_hook.name()) {
  9942. return pre_hook;
  9943. }
  9944. }
  9945. return null;
  9946. }
  9947. numAttributes() {
  9948. return this._attributes.length;
  9949. }
  9950. addAttribute(name, type, is_parameter, is_buffer) {
  9951. is_parameter = is_parameter || false;
  9952. is_buffer = is_buffer || false;
  9953. const slot = this._attributes.length;
  9954. this._attributes.push({ name, type, is_parameter, is_buffer });
  9955. this._attributeTypes.push(type);
  9956. return slot;
  9957. }
  9958. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  9959. is_parameter = is_parameter || false;
  9960. is_buffer = is_buffer || false;
  9961. const slot_idx = this.findAttributeSlot(name);
  9962. if (slot_idx === null) {
  9963. return this.addAttribute(name, ty, is_parameter, is_buffer);
  9964. }
  9965. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  9966. // const TypePtr& atype = getAttribute(*slot_idx);
  9967. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  9968. return slot_idx;
  9969. }
  9970. findAttributeSlot(name) {
  9971. for (let pos = 0; pos < this._attributes.length; pos++) {
  9972. if (name === this._attributes[pos].name) {
  9973. return pos;
  9974. }
  9975. }
  9976. return null;
  9977. }
  9978. findAttribute(name) {
  9979. const slot = this.findAttributeSlot(name);
  9980. if (slot !== null) {
  9981. return this._attributes[slot].type;
  9982. }
  9983. return null;
  9984. }
  9985. hasAttribute(name) {
  9986. return this._attributes.find((attr) => attr.name === name);
  9987. }
  9988. getAttribute(arg) {
  9989. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  9990. return this._attributes[slot].type;
  9991. }
  9992. getAttributeName(slot) {
  9993. return this._attributes[slot].name;
  9994. }
  9995. addConstant(name, value) {
  9996. this._constants.set(name, value);
  9997. }
  9998. hasConstant(name) {
  9999. return this._constants.has(name);
  10000. }
  10001. getProperty(name) {
  10002. for (const prop of this._properties) {
  10003. if (name === prop.name) {
  10004. return prop;
  10005. }
  10006. }
  10007. return null;
  10008. }
  10009. containedTypes() {
  10010. return this._attributeTypes;
  10011. }
  10012. createWithContained(contained_types) {
  10013. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10014. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10015. for (let i = 0; i < this._attributes.length; i++) {
  10016. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10017. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10018. }
  10019. for (const method of this.methods()) {
  10020. ptr.addMethod(method);
  10021. }
  10022. return ptr;
  10023. }
  10024. str() {
  10025. return this.qualified_name();
  10026. }
  10027. });
  10028. this.registerType('torch.EnumType', class extends torch.Type {
  10029. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10030. super('EnumType', qualified_class_name);
  10031. this._name = qualified_class_name;
  10032. this._value_type = value_type;
  10033. this._enum_names_values = enum_names_values;
  10034. this._cu = cu;
  10035. }
  10036. static create(qualified_class_name, value, enum_names_values, cu) {
  10037. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10038. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10039. }
  10040. torch._C.TORCH_CHECK(false);
  10041. return null;
  10042. }
  10043. name() {
  10044. return this._name;
  10045. }
  10046. get annotation_str() {
  10047. return this._name.qualifiedName();
  10048. }
  10049. enumNamesValues() {
  10050. return this._enum_names_values;
  10051. }
  10052. compilation_unit() {
  10053. return this._cu;
  10054. }
  10055. getValueType() {
  10056. return this._value_type;
  10057. }
  10058. equals(rhs) {
  10059. if (rhs instanceof torch.EnumType) {
  10060. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10061. }
  10062. return false;
  10063. }
  10064. isSubtypeOf(rhs) {
  10065. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10066. return true;
  10067. }
  10068. return super.isSubtypeOf(rhs);
  10069. }
  10070. });
  10071. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10072. if (args.length === 1) {
  10073. const [to_flatten] = args;
  10074. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10075. const to_fill = [];
  10076. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10077. to_flatten.splice(0, to_flatten.length);
  10078. to_flatten.push(...to_fill);
  10079. } else if (args.length === 2) {
  10080. const [reference, to_fill] = args;
  10081. for (const type of reference) {
  10082. torch._C.flattenUnion(type, to_fill);
  10083. }
  10084. torch._C.filterDuplicateSubtypes(to_fill);
  10085. torch._C.sortUnion(to_fill);
  10086. } else {
  10087. throw new python.Error('Not implemented.');
  10088. }
  10089. });
  10090. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10091. if (type instanceof torch.UnionType) {
  10092. for (const inner of type.containedTypes()) {
  10093. torch._C.flattenUnion(inner, to_fill);
  10094. }
  10095. } else if (type instanceof torch.OptionalType) {
  10096. const inner = type.getElementType();
  10097. torch._C.flattenUnion(inner, to_fill);
  10098. to_fill.push(torch.NoneType.get());
  10099. } else if (type instanceof torch.NumberType) {
  10100. to_fill.push(torch.IntType.get());
  10101. to_fill.push(torch.FloatType.get());
  10102. to_fill.push(torch.ComplexType.get());
  10103. } else {
  10104. to_fill.push(type);
  10105. }
  10106. });
  10107. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10108. if (types.length === 0) {
  10109. // return;
  10110. }
  10111. /*
  10112. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10113. // We don't want nested Optionals. Also, prematurely unifying to
  10114. // `Optional` could prevent us from coalescing other types
  10115. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10116. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10117. return null;
  10118. } else {
  10119. return unifyTypes(t1, t2, default_to_union=false);
  10120. }
  10121. };
  10122. size_t end_idx = types->size()-1;
  10123. for (size_t i = types->size()-1; i > 0; --i) {
  10124. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10125. std::optional<TypePtr> unified;
  10126. unified = get_supertype((*types)[i], (*types)[j]);
  10127. if (unified) {
  10128. (*types)[j] = *unified;
  10129. (*types)[i] = (*types)[end_idx];
  10130. --end_idx;
  10131. break;
  10132. }
  10133. if (j == 0) {
  10134. break;
  10135. }
  10136. }
  10137. }
  10138. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10139. */
  10140. });
  10141. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10142. /*
  10143. std::sort(types->begin(), types->end(),
  10144. [](const TypePtr& a, const TypePtr& b) -> bool {
  10145. if (a->kind() != b->kind()) {
  10146. return a->kind() < b->kind();
  10147. }
  10148. return a->str() < b->str();
  10149. });
  10150. */
  10151. });
  10152. this.registerType('torch.UnionType', class extends torch.Type {
  10153. constructor(reference, kind) {
  10154. super(kind || 'UnionType');
  10155. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10156. this._types = [];
  10157. torch._C.standardizeVectorForUnion(reference, this._types);
  10158. if (this._types.length === 1) {
  10159. throw new python.Error('Invalid union type reference.');
  10160. }
  10161. this._can_hold_none = false;
  10162. this._has_free_variables = false;
  10163. for (const type of this._types) {
  10164. if (type instanceof torch.NoneType) {
  10165. this._can_hold_none = true;
  10166. }
  10167. if (type.hasFreeVariables()) {
  10168. this._has_free_variables = true;
  10169. }
  10170. }
  10171. }
  10172. static create(reference) {
  10173. const union_type = new torch.UnionType(reference);
  10174. /*
  10175. bool int_found = false;
  10176. bool float_found = false;
  10177. bool complex_found = false;
  10178. bool nonetype_found = false;
  10179. const update_is_opt_flags = [&](const TypePtr& t) {
  10180. if (t == IntType::get()) {
  10181. int_found = true;
  10182. } else if (t == FloatType::get()) {
  10183. float_found = true;
  10184. } else if (t == ComplexType::get()) {
  10185. complex_found = true;
  10186. } else if (t == NoneType::get()) {
  10187. nonetype_found = true;
  10188. }
  10189. };
  10190. for (const auto& t : union_type->containedTypes()) {
  10191. update_is_opt_flags(t);
  10192. }
  10193. bool numbertype_found = int_found && float_found && complex_found;
  10194. if (nonetype_found) {
  10195. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10196. return OptionalType::create(NumberType::get());
  10197. }
  10198. if (union_type->containedTypes().size() == 2) {
  10199. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10200. ? union_type->containedTypes()[0]
  10201. : union_type->containedTypes()[1];
  10202. return OptionalType::create(not_none);
  10203. }
  10204. }
  10205. */
  10206. return union_type;
  10207. }
  10208. containedTypes() {
  10209. return this._types;
  10210. }
  10211. isUnionType() {
  10212. return true;
  10213. }
  10214. hasFreeVariables() {
  10215. return this._has_free_variables;
  10216. }
  10217. equals(rhs) {
  10218. if (rhs instanceof torch.UnionType) {
  10219. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10220. return false;
  10221. }
  10222. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10223. } else if (rhs instanceof torch.OptionalType) {
  10224. if (rhs.getElementType() === torch.NumberType.get()) {
  10225. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10226. }
  10227. const optional_lhs = this.toOptional();
  10228. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10229. } else if (rhs instanceof torch.NumberType) {
  10230. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10231. }
  10232. return false;
  10233. }
  10234. isSubtypeOf(rhs) {
  10235. const rhs_types = [];
  10236. if (rhs instanceof torch.UnionType) {
  10237. if (this.containedTypes() === rhs.containedTypes()) {
  10238. return true;
  10239. }
  10240. for (const typePtr of rhs.containedTypes()) {
  10241. rhs_types.push(typePtr);
  10242. }
  10243. } else if (rhs instanceof torch.OptionalType) {
  10244. rhs_types.push(torch.NoneType.get());
  10245. if (rhs.getElementType() === torch.NumberType.get()) {
  10246. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10247. rhs_types.push(...number_types);
  10248. } else {
  10249. rhs_types.push(rhs.getElementType());
  10250. }
  10251. } else if (rhs instanceof torch.NumberType) {
  10252. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10253. rhs_types.push(...number_types);
  10254. } else {
  10255. rhs_types.push(rhs);
  10256. }
  10257. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10258. }
  10259. });
  10260. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10261. constructor(contained) {
  10262. super([contained, torch.NoneType.get()], 'OptionalType');
  10263. let is_numbertype = false;
  10264. if (contained instanceof torch.UnionType) {
  10265. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10266. }
  10267. if (super.containedTypes().length === 2) {
  10268. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10269. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10270. this._contained = torch.NumberType.get();
  10271. this._types.splice(0, this._types.length);
  10272. this._types.push(torch.NumberType.get());
  10273. this._types.push(torch.NoneType.get());
  10274. } else {
  10275. const to_subtract = [torch.NoneType.get()];
  10276. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10277. this._contained = torch.UnionType.create([without_none]);
  10278. }
  10279. this._has_free_variables = contained.hasFreeVariables();
  10280. }
  10281. static create(elem) {
  10282. return new torch.OptionalType(elem);
  10283. }
  10284. getElementType() {
  10285. return this._contained;
  10286. }
  10287. equals(rhs) {
  10288. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10289. }
  10290. isSubtypeOf(rhs) {
  10291. if (rhs instanceof torch.OptionalType) {
  10292. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10293. } else if (rhs instanceof torch.UnionType) {
  10294. throw new python.Error('Not implemented.');
  10295. }
  10296. // return super.isSubtypeOf(rhs);
  10297. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10298. }
  10299. containedTypes() {
  10300. return [this._contained];
  10301. }
  10302. createWithContained(contained_types) {
  10303. torch._C.AT_ASSERT(contained_types.length === 1);
  10304. return torch.OptionalType.create(contained_types[0]);
  10305. }
  10306. subtractTypeSetFrom(to_subtract, from) {
  10307. const types = [];
  10308. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10309. for (const t of from) {
  10310. if (!should_subtract(t)) {
  10311. types.push(t);
  10312. }
  10313. }
  10314. if (types.length === 0) {
  10315. return null;
  10316. } else if (types.length === 1) {
  10317. return types[0];
  10318. }
  10319. return torch.UnionType.create(types);
  10320. }
  10321. str() {
  10322. return `${this.getElementType().str()}?`;
  10323. }
  10324. __str__() {
  10325. return `Optional[${this.getElementType().__str__()}]`;
  10326. }
  10327. });
  10328. this.registerType('torch.ListType', class extends torch.Type {
  10329. constructor(elem) {
  10330. super('ListType');
  10331. this._elem = elem;
  10332. }
  10333. static create(elem) {
  10334. return new torch.ListType(elem);
  10335. }
  10336. getElementType() {
  10337. return this._elem;
  10338. }
  10339. equals(rhs) {
  10340. if (rhs instanceof torch.ListType) {
  10341. return this.getElementType().equals(rhs.getElementType());
  10342. }
  10343. return false;
  10344. }
  10345. isSubtypeOf(rhs) {
  10346. if (super.isSubtypeOf(rhs)) {
  10347. return true;
  10348. }
  10349. if (rhs.kind() === 'AnyListType') {
  10350. return true;
  10351. }
  10352. return false;
  10353. }
  10354. containedTypes() {
  10355. return [this._elem];
  10356. }
  10357. createWithContained(contained_types) {
  10358. return new torch.ListType(contained_types[0]);
  10359. }
  10360. hasFreeVariables() {
  10361. return this.getElementType().hasFreeVariables();
  10362. }
  10363. str() {
  10364. return `${this.getElementType().str()}[]`;
  10365. }
  10366. __str__() {
  10367. return `List[${this.getElementType().__str__()}]`;
  10368. }
  10369. });
  10370. this.registerType('torch.FutureType', class extends torch.Type {
  10371. constructor(elem) {
  10372. super('FutureType');
  10373. this._elem = elem;
  10374. }
  10375. static create(elem) {
  10376. return new torch.FutureType(elem);
  10377. }
  10378. getElementType() {
  10379. return this._elem;
  10380. }
  10381. containedTypes() {
  10382. throw new python.Error('Not implemented.');
  10383. }
  10384. str() {
  10385. return `Future(${this.getElementType().str()})`;
  10386. }
  10387. __str__() {
  10388. return `Future[${this.getElementType().__str__()}]`;
  10389. }
  10390. });
  10391. this.registerType('torch.RRefType', class extends torch.Type {
  10392. constructor(elem) {
  10393. super('RRefType');
  10394. this._elem = elem;
  10395. }
  10396. static create(elem) {
  10397. return new torch.RRefType(elem);
  10398. }
  10399. getElementType() {
  10400. return this._elem;
  10401. }
  10402. containedTypes() {
  10403. throw new python.Error('Not implemented.');
  10404. }
  10405. str() {
  10406. return `RRef(${this.getElementType().str()})`;
  10407. }
  10408. __str__() {
  10409. return `RRef[${this.getElementType().__str__()}]`;
  10410. }
  10411. });
  10412. this.registerType('torch.AwaitType', class extends torch.Type {
  10413. constructor(elem) {
  10414. super('AwaitType');
  10415. this._elem = elem;
  10416. }
  10417. static get(elem) {
  10418. return new torch.AwaitType(elem);
  10419. }
  10420. getElementType() {
  10421. return this._elem;
  10422. }
  10423. containedTypes() {
  10424. throw new python.Error('Not implemented.');
  10425. }
  10426. str() {
  10427. return `Await(${this.getElementType().str()})`;
  10428. }
  10429. __str__() {
  10430. return `Await[${this.getElementType().__str__()}]`;
  10431. }
  10432. });
  10433. this.registerType('torch.TupleType', class extends torch.Type {
  10434. constructor(elements, annotation_str, schema) {
  10435. super('TupleType', annotation_str);
  10436. this._elements = elements;
  10437. this._has_free_variables = elements.some((v) => {
  10438. if (!v) {
  10439. throw new python.Error('Can not create tuple with None type');
  10440. }
  10441. return v.hasFreeVariables();
  10442. });
  10443. this._schema = schema;
  10444. }
  10445. static create(elements) {
  10446. return new torch.TupleType(elements, null, null);
  10447. }
  10448. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10449. const args = [];
  10450. for (let i = 0; i < field_names.length; i++) {
  10451. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10452. args.push(arg);
  10453. }
  10454. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10455. return new torch.TupleType(field_types, qualified_name, schema);
  10456. }
  10457. elements() {
  10458. return this._elements;
  10459. }
  10460. name() {
  10461. return this.annotation_str;
  10462. }
  10463. containedTypes() {
  10464. return this._elements;
  10465. }
  10466. createWithContained(createWithContained) {
  10467. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10468. }
  10469. hasFreeVariables() {
  10470. return this._has_free_variables;
  10471. }
  10472. schema() {
  10473. return this._schema;
  10474. }
  10475. str() {
  10476. if (this._schema) {
  10477. return `NamedTuple(...)`;
  10478. }
  10479. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10480. }
  10481. __str__() {
  10482. if (this.annotation_str) {
  10483. return this.annotation_str;
  10484. }
  10485. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10486. }
  10487. });
  10488. this.registerType('torch.AnyType', class extends torch.Type {
  10489. constructor() {
  10490. super('AnyType');
  10491. }
  10492. static get() {
  10493. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10494. return torch.AnyType.value;
  10495. }
  10496. str() {
  10497. return 'Any';
  10498. }
  10499. __str__() {
  10500. return 'Any';
  10501. }
  10502. });
  10503. this.registerType('torch.NoneType', class extends torch.Type {
  10504. constructor() {
  10505. super('NoneType');
  10506. }
  10507. static get() {
  10508. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10509. return torch.NoneType.value;
  10510. }
  10511. equals(rhs) {
  10512. return this.kind() === rhs.kind();
  10513. }
  10514. isSubtypeOf(rhs) {
  10515. if (rhs.kind() === 'OptionalType') {
  10516. return true;
  10517. }
  10518. return super.isSubtypeOf(rhs);
  10519. }
  10520. str() {
  10521. return 'NoneType';
  10522. }
  10523. __str__() {
  10524. return 'NoneType';
  10525. }
  10526. });
  10527. this.registerType('torch.TensorType', class extends torch.Type {
  10528. constructor() {
  10529. super('TensorType');
  10530. this._is_inferred = false;
  10531. }
  10532. static get() {
  10533. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10534. return torch.TensorType.value;
  10535. }
  10536. equals(rhs) {
  10537. return this.kind() === rhs.kind();
  10538. }
  10539. isInferredType() {
  10540. return this._is_inferred;
  10541. }
  10542. str() {
  10543. return 'Tensor';
  10544. }
  10545. __str__() {
  10546. return 'Tensor';
  10547. }
  10548. });
  10549. this.registerType('torch.NumberType', class extends torch.Type {
  10550. constructor() {
  10551. super('NumberType');
  10552. }
  10553. static get() {
  10554. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10555. return torch.NumberType.value;
  10556. }
  10557. str() {
  10558. return 'Scalar';
  10559. }
  10560. __str__() {
  10561. return 'number';
  10562. }
  10563. });
  10564. this.registerType('torch.BoolType', class extends torch.Type {
  10565. constructor() {
  10566. super('BoolType');
  10567. }
  10568. static get() {
  10569. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10570. return torch.BoolType.value;
  10571. }
  10572. equals(rhs) {
  10573. return this.kind() === rhs.kind();
  10574. }
  10575. str() {
  10576. return 'bool';
  10577. }
  10578. __str__() {
  10579. return 'bool';
  10580. }
  10581. });
  10582. this.registerType('torch.IntType', class extends torch.Type {
  10583. constructor() {
  10584. super('IntType');
  10585. }
  10586. static get() {
  10587. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10588. return torch.IntType.value;
  10589. }
  10590. equals(rhs) {
  10591. return this.kind() === rhs.kind();
  10592. }
  10593. isSubtypeOf(rhs) {
  10594. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10595. }
  10596. str() {
  10597. return 'int';
  10598. }
  10599. __str__() {
  10600. return 'int';
  10601. }
  10602. });
  10603. this.registerType('torch.SymIntType', class extends torch.Type {
  10604. constructor() {
  10605. super('SymIntType');
  10606. }
  10607. static get() {
  10608. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10609. return torch.SymIntType.value;
  10610. }
  10611. equals(rhs) {
  10612. return this.kind() === rhs.kind();
  10613. }
  10614. str() {
  10615. return 'SymInt';
  10616. }
  10617. __str__() {
  10618. return 'int';
  10619. }
  10620. });
  10621. this.registerType('torch.FloatType', class extends torch.Type {
  10622. constructor() {
  10623. super('FloatType');
  10624. }
  10625. static get() {
  10626. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10627. return torch.FloatType.value;
  10628. }
  10629. equals(rhs) {
  10630. return this.kind() === rhs.kind();
  10631. }
  10632. isSubtypeOf(rhs) {
  10633. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10634. }
  10635. str() {
  10636. return 'float';
  10637. }
  10638. __str__() {
  10639. return 'float';
  10640. }
  10641. });
  10642. this.registerType('torch.StringType', class extends torch.Type {
  10643. constructor() {
  10644. super('StringType');
  10645. }
  10646. static get() {
  10647. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10648. return torch.StringType.value;
  10649. }
  10650. equals(rhs) {
  10651. return this.kind() === rhs.kind();
  10652. }
  10653. str() {
  10654. return 'str';
  10655. }
  10656. __str__() {
  10657. return 'str';
  10658. }
  10659. });
  10660. this.registerType('torch.ComplexType', class extends torch.Type {
  10661. constructor() {
  10662. super('ComplexType');
  10663. }
  10664. static get() {
  10665. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10666. return torch.ComplexType.value;
  10667. }
  10668. equals(rhs) {
  10669. return this.kind() === rhs.kind();
  10670. }
  10671. isSubtypeOf(rhs) {
  10672. return this.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10673. }
  10674. str() {
  10675. return 'complex';
  10676. }
  10677. __str__() {
  10678. return 'complex';
  10679. }
  10680. });
  10681. this.registerType('torch.DictType', class extends torch.Type {
  10682. constructor(key, value) {
  10683. super('DictType');
  10684. this.types = [key, value];
  10685. }
  10686. static create(key, value) {
  10687. let kind = key.kind();
  10688. if (key instanceof torch._C.DynamicType) {
  10689. kind = key.dynamicKind();
  10690. }
  10691. switch (kind) {
  10692. case 'AnyType':
  10693. case 'IntType':
  10694. case 'BoolType':
  10695. case 'FloatType':
  10696. case 'ComplexType':
  10697. case 'StringType':
  10698. case 'TensorType':
  10699. case 'DeviceObjType':
  10700. return new torch.DictType(key, value);
  10701. default:
  10702. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10703. }
  10704. }
  10705. createWithContained(contained_types) {
  10706. if (contained_types.length !== 2) {
  10707. throw new python.Error('Expected 2 contained types.');
  10708. }
  10709. return torch.DictType.create(contained_types[0], contained_types[1]);
  10710. }
  10711. getKeyType() {
  10712. return this.types[0];
  10713. }
  10714. getValueType() {
  10715. return this.types[1];
  10716. }
  10717. hasFreeVariables() {
  10718. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10719. }
  10720. containedTypes() {
  10721. return this.types;
  10722. }
  10723. equals(rhs) {
  10724. if (rhs instanceof torch.DictType) {
  10725. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10726. }
  10727. return false;
  10728. }
  10729. str() {
  10730. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10731. }
  10732. __str__() {
  10733. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10734. }
  10735. });
  10736. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10737. constructor() {
  10738. super('DeviceObjType');
  10739. }
  10740. static get() {
  10741. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10742. return torch.DeviceObjType.value;
  10743. }
  10744. str() {
  10745. return 'Device';
  10746. }
  10747. __str__() {
  10748. return 'Device';
  10749. }
  10750. });
  10751. this.registerType('torch.StreamObjType', class extends torch.Type {
  10752. constructor() {
  10753. super('StreamObjType');
  10754. }
  10755. str() {
  10756. return 'Stream';
  10757. }
  10758. __str__() {
  10759. return 'Stream';
  10760. }
  10761. });
  10762. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10763. constructor() {
  10764. super('GeneratorType');
  10765. }
  10766. static get() {
  10767. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10768. return torch._C._GeneratorType.value;
  10769. }
  10770. str() {
  10771. return 'Generator';
  10772. }
  10773. __str__() {
  10774. return 'Generator';
  10775. }
  10776. });
  10777. this.registerType('torch.InterfaceType', class extends torch.Type {
  10778. constructor() {
  10779. super('InterfaceType');
  10780. }
  10781. });
  10782. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10783. constructor() {
  10784. super('DynamicType');
  10785. }
  10786. });
  10787. this.registerType('torch._C.FunctionType', class extends torch.Type {
  10788. constructor(func) {
  10789. super('FunctionType');
  10790. this._func = func;
  10791. }
  10792. static create(func) {
  10793. return new torch._C.FunctionType(func);
  10794. }
  10795. function() {
  10796. return this._func;
  10797. }
  10798. });
  10799. this.registerType('torch._C.VarType', class extends torch.Type {
  10800. constructor(name) {
  10801. super('VarType', name);
  10802. }
  10803. static create(name) {
  10804. return new torch._C.VarType(name);
  10805. }
  10806. name() {
  10807. return this._annotation_str;
  10808. }
  10809. hasFreeVariables() {
  10810. return true;
  10811. }
  10812. });
  10813. this.registerType('torch._C.AliasInfo', class {
  10814. constructor() {
  10815. this.is_write = false;
  10816. this.before_set = [];
  10817. this.after_set = [];
  10818. this.containedTypes = [];
  10819. }
  10820. addBeforeSet(value) {
  10821. this.before_set.push(value);
  10822. }
  10823. addAfterSet(value) {
  10824. this.after_set.push(value);
  10825. }
  10826. addContainedType(alias_info) {
  10827. this.containedTypes.push(alias_info);
  10828. }
  10829. str() {
  10830. const list = ['('];
  10831. list.push(this.before_set.join('|'));
  10832. if (this.after_set.length > 0) {
  10833. list.push(' -> ');
  10834. list.push(this.after_set.join('|'));
  10835. }
  10836. if (this.is_write) {
  10837. list.push('!');
  10838. }
  10839. list.push(')');
  10840. return list.join('');
  10841. }
  10842. });
  10843. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  10844. if (str.startsWith('"') && str.endsWith('"')) {
  10845. return str.slice(1, -1);
  10846. }
  10847. if (str.startsWith("'") && str.endsWith("'")) {
  10848. return str.slice(1, -1);
  10849. }
  10850. throw new python.Error(`Invalid string literal '${str}'.`);
  10851. // inline std::string parseStringLiteral(
  10852. });
  10853. this.registerType('torch._C.Token', class {
  10854. constructor() {
  10855. this.kind = '';
  10856. this.value = '';
  10857. }
  10858. text() {
  10859. return this.value;
  10860. }
  10861. });
  10862. this.registerType('torch._C.Lexer', class {
  10863. constructor(buffer) {
  10864. this.buffer = buffer;
  10865. this.position = 0;
  10866. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  10867. this.next();
  10868. }
  10869. cur() {
  10870. return this.next_tokens[0];
  10871. }
  10872. lookahead() {
  10873. if (!this.next_tokens[1].kind) {
  10874. this.position += this.cur().text().length;
  10875. this.lex(this.next_tokens[1]);
  10876. }
  10877. return this.next_tokens[1];
  10878. }
  10879. next() {
  10880. const [cur] = this.next_tokens;
  10881. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  10882. this.next_tokens[1].kind = '';
  10883. this.next_tokens[3] = cur;
  10884. const [token] = this.next_tokens;
  10885. if (token.kind) {
  10886. return cur;
  10887. }
  10888. this.position += cur.text().length;
  10889. this.lex(token);
  10890. return cur;
  10891. }
  10892. nextIf(kind) {
  10893. if (this.cur().kind !== kind) {
  10894. return false;
  10895. }
  10896. this.next();
  10897. return true;
  10898. }
  10899. expect(kind) {
  10900. if (this.cur().kind !== kind) {
  10901. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  10902. }
  10903. return this.next();
  10904. }
  10905. lex(token) {
  10906. while (this.buffer[this.position] === ' ') {
  10907. this.position += 1;
  10908. }
  10909. let i = this.position;
  10910. if (i >= this.buffer.length) {
  10911. token.kind = '\0';
  10912. token.value = '';
  10913. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  10914. token.kind = '...';
  10915. token.value = '...';
  10916. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  10917. this.kind = '[]';
  10918. this.value = '[]'; */
  10919. } 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] === '|') {
  10920. token.kind = this.buffer[i];
  10921. token.value = this.buffer[i];
  10922. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  10923. i += 1;
  10924. 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] === '_')) {
  10925. i += 1;
  10926. }
  10927. token.kind = 'id';
  10928. token.value = this.buffer.slice(this.position, i);
  10929. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  10930. token.kind = '->';
  10931. token.value = '->';
  10932. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  10933. i += 1;
  10934. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  10935. i += 1;
  10936. }
  10937. token.kind = '#';
  10938. token.value = this.buffer.slice(this.position, i);
  10939. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  10940. const quote = this.buffer[i];
  10941. i += 1;
  10942. while (i < this.buffer.length && this.buffer[i] !== quote) {
  10943. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  10944. }
  10945. i += 1;
  10946. token.kind = 'string';
  10947. token.value = this.buffer.slice(this.position, i);
  10948. } else {
  10949. throw new python.Error(`Unsupported token at '${this.position}'.`);
  10950. }
  10951. }
  10952. });
  10953. this.registerType('torch._C.SchemaTypeParser', class {
  10954. constructor(L, complete_tensor_types, allow_typevars) {
  10955. this.L = L;
  10956. this.complete_tensor_types = complete_tensor_types;
  10957. this._allow_typevars = allow_typevars;
  10958. }
  10959. parseType() {
  10960. const r = this.parseFakeAndRealType();
  10961. return { first: r[0], second: r[2] };
  10962. }
  10963. parseBaseType() {
  10964. const L = this.L;
  10965. const tok = L.cur();
  10966. const text = tok.text();
  10967. L.next();
  10968. switch (text) {
  10969. case 'Tensor': return torch.TensorType.get();
  10970. case 'bool': return torch.BoolType.get();
  10971. case 'int': return torch.IntType.get();
  10972. case 'float': return torch.FloatType.get();
  10973. case 'complex': return torch.ComplexType.get();
  10974. case 'str': return torch.StringType.get();
  10975. case 'SymInt': return torch.SymIntType.get();
  10976. case 'Scalar': return torch.NumberType.get();
  10977. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  10978. case 'Device': return torch.DeviceObjType.get();
  10979. case 'Layout': return torch.Type.get('Layout');
  10980. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  10981. case 'Generator': return torch._C._GeneratorType.get();
  10982. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  10983. case 'Any': return torch.AnyType.get();
  10984. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  10985. case 'Dimname': return torch.StringType.get();
  10986. case 'QScheme': return torch.Type.get('QSchemeType');
  10987. case 'Stream': return torch.StreamObjType.get();
  10988. case 'Storage': return torch.Type.get('Storage');
  10989. case 'AnyClassType': return torch.Type.get('AnyClassType');
  10990. case 'NoneType': return torch.NoneType.get();
  10991. default: throw new python.Error(`Unsupported type '${text}'.`);
  10992. }
  10993. }
  10994. parseFakeAndRealType() {
  10995. const L = this.L;
  10996. let fake_value = null;
  10997. let real_value = null;
  10998. let alias_info = null;
  10999. if (L.nextIf('(')) {
  11000. const types = [];
  11001. while (!L.nextIf(')')) {
  11002. const r = this.parseType();
  11003. types.push(r.first);
  11004. if (alias_info && r.second) {
  11005. alias_info.addContainedType(r.second);
  11006. }
  11007. L.nextIf(',');
  11008. }
  11009. real_value = torch.TupleType.create(types);
  11010. fake_value = real_value;
  11011. } else if (L.cur().text() === 'Future') {
  11012. L.next();
  11013. L.expect('(');
  11014. const p = this.parseType();
  11015. const subtype = p.first;
  11016. // const subalias = p.second;
  11017. L.expect(')');
  11018. real_value = torch.FutureType.create(subtype);
  11019. fake_value = real_value;
  11020. } else if (L.cur().text() === 'Await') {
  11021. L.next();
  11022. L.expect('(');
  11023. const p = this.parseType();
  11024. const subtype = p.first;
  11025. // const subalias = p.second;
  11026. L.expect(')');
  11027. real_value = torch.AwaitType.get(subtype);
  11028. fake_value = real_value;
  11029. } else if (L.cur().text() === 'RRef') {
  11030. L.next();
  11031. L.expect('(');
  11032. const p = this.parseType();
  11033. const subtype = p.first;
  11034. // const subalias = p.second;
  11035. L.expect(')');
  11036. real_value = torch.RRefType.create(subtype);
  11037. fake_value = real_value;
  11038. } else if (L.cur().text() === 'Tensor') {
  11039. L.next();
  11040. real_value = torch.TensorType.get();
  11041. fake_value = real_value;
  11042. alias_info = this.parseAliasAnnotation();
  11043. } else if (L.cur().text() === 'Dict') {
  11044. L.next();
  11045. L.expect('(');
  11046. const key_type = this.parseType().first;
  11047. L.expect(',');
  11048. const value_type = this.parseType().first;
  11049. L.expect(')');
  11050. alias_info = this.parseAliasAnnotation();
  11051. real_value = torch.DictType.create(key_type, value_type);
  11052. fake_value = real_value;
  11053. } else if (L.nextIf('Union')) {
  11054. L.next();
  11055. L.expect('(');
  11056. const types = [];
  11057. types.push(this.parseType().first);
  11058. while (L.cur().kind !== ')') {
  11059. L.expect(',');
  11060. types.push(this.parseType().first);
  11061. }
  11062. L.expect(')');
  11063. alias_info = this.parseAliasAnnotation();
  11064. real_value = new torch.UnionType(types);
  11065. fake_value = real_value;
  11066. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11067. fake_value = real_value = parseRefinedTensor();
  11068. alias_info = parseAliasAnnotation(); */
  11069. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11070. L.next();
  11071. L.expect('.');
  11072. const torch_tok = L.expect('id');
  11073. if (torch_tok.text() !== 'torch') {
  11074. throw new python.Error('Expected classes namespace.');
  11075. }
  11076. L.expect('.');
  11077. const classes_tok = L.expect('id');
  11078. if (classes_tok.text() !== 'classes') {
  11079. throw new python.Error('Expected classes namespace.');
  11080. }
  11081. L.expect('.');
  11082. const ns_tok = L.expect('id');
  11083. L.expect('.');
  11084. const class_tok = L.expect('id');
  11085. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11086. fake_value = real_value;
  11087. if (!fake_value) {
  11088. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11089. }
  11090. } else {
  11091. real_value = this.parseBaseType();
  11092. fake_value = real_value;
  11093. if (real_value.kind() === 'ScalarTypeType' ||
  11094. real_value.kind() === 'MemoryFormat' ||
  11095. real_value.kind() === 'Layout' ||
  11096. real_value.kind() === 'SymIntType') {
  11097. fake_value = torch.IntType.get();
  11098. }
  11099. alias_info = this.parseAliasAnnotation();
  11100. }
  11101. while (true) {
  11102. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11103. L.expect('[');
  11104. L.expect(']');
  11105. fake_value = torch.ListType.create(fake_value);
  11106. real_value = torch.ListType.create(real_value);
  11107. let container = this.parseAliasAnnotation();
  11108. if (alias_info) {
  11109. if (!container) {
  11110. container = new torch._C.AliasInfo();
  11111. container.is_write = alias_info.is_write;
  11112. }
  11113. container.addContainedType(alias_info);
  11114. }
  11115. alias_info = container;
  11116. } else if (L.nextIf('?')) {
  11117. fake_value = torch.OptionalType.create(fake_value);
  11118. real_value = torch.OptionalType.create(real_value);
  11119. } else {
  11120. break;
  11121. }
  11122. }
  11123. return [fake_value, real_value, alias_info];
  11124. }
  11125. parseAliasAnnotation() {
  11126. const L = this.L;
  11127. let alias_info = null;
  11128. if (L.nextIf('(')) {
  11129. alias_info = new torch._C.AliasInfo();
  11130. do {
  11131. alias_info.addBeforeSet(L.cur().text());
  11132. L.next();
  11133. if (L.nextIf('!')) {
  11134. alias_info.is_write = true;
  11135. }
  11136. }
  11137. while (L.nextIf('|'));
  11138. if (L.nextIf('->')) {
  11139. do {
  11140. alias_info.addAfterSet(L.cur().text());
  11141. L.next();
  11142. }
  11143. while (L.nextIf('|'));
  11144. }
  11145. L.expect(')');
  11146. }
  11147. return alias_info;
  11148. }
  11149. });
  11150. this.registerType('torch.Argument', class {
  11151. constructor(...args) {
  11152. // torch/aten/src/ATen/core/function_schema.h
  11153. this.N = null;
  11154. this.default_value = null;
  11155. this.kwarg_only = false;
  11156. this.alias_info = null;
  11157. if (args.length === 2) {
  11158. [this.name, this.type] = args;
  11159. this.real_type = this.type;
  11160. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11161. [this.name, this.type, this.real_type] = args;
  11162. } else if (args.length === 6) {
  11163. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11164. } else if (args.length === 7) {
  11165. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11166. } else {
  11167. throw new python.Error('Invalid arguments.');
  11168. }
  11169. const is_alias = this.alias_info && this.alias_info.is_write;
  11170. this.is_out = this.kwarg_only && is_alias;
  11171. }
  11172. has_default_value() {
  11173. return this.default_value !== undefined;
  11174. }
  11175. is_inferred_type() {
  11176. if (this.type instanceof torch.TensorType) {
  11177. return this.type.isInferredType();
  11178. }
  11179. return false;
  11180. }
  11181. str() {
  11182. const list = [];
  11183. const type = this.real_type;
  11184. const is_opt = type instanceof torch.OptionalType;
  11185. const unopt_type = is_opt ? type.getElementType() : type;
  11186. if (unopt_type instanceof torch.ListType) {
  11187. list.push(unopt_type.getElementType().str());
  11188. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11189. list.push(this.alias_info.containedTypes[0].str());
  11190. }
  11191. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11192. } else {
  11193. list.push(unopt_type.str());
  11194. }
  11195. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11196. list.push(this.alias_info.str());
  11197. }
  11198. if (is_opt) {
  11199. list.push('?');
  11200. }
  11201. if (this.name) {
  11202. list.push(' ');
  11203. list.push(this.name);
  11204. }
  11205. if (this.default_value !== undefined) {
  11206. const value = this.default_value;
  11207. if (value === null) {
  11208. list.push('=None');
  11209. } else if (typeof value === 'boolean') {
  11210. list.push('=');
  11211. list.push(value ? 'True' : 'False');
  11212. } else if (typeof value === 'string') {
  11213. list.push(`="${value}"`);
  11214. } else if (typeof value === 'number') {
  11215. list.push(`=${value}`);
  11216. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11217. list.push(`.`);
  11218. }
  11219. } else if (Array.isArray(value)) {
  11220. list.push(`=[${value.join(', ')}]`);
  11221. }
  11222. }
  11223. return list.join('');
  11224. }
  11225. });
  11226. torch._C.TypeKind = {
  11227. StringType: 'StringType',
  11228. NumberType: 'NumberType',
  11229. IntType: 'IntType',
  11230. BoolType: 'BoolType',
  11231. DynamicType: 'DynamicType',
  11232. OptionalType: 'OptionalType',
  11233. FloatType: 'FloatType',
  11234. ComplexType: 'ComplexType',
  11235. ListType: 'ListType',
  11236. };
  11237. this.registerType('torch._C.List', class extends Array {
  11238. constructor(type, elements) {
  11239. super(elements ? elements.length : 0);
  11240. if (Array.isArray(elements)) {
  11241. for (let i = 0; i < elements.length; i++) {
  11242. this[i] = elements[i];
  11243. }
  11244. }
  11245. this.type = type;
  11246. }
  11247. elementType() {
  11248. return this.type;
  11249. }
  11250. });
  11251. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11252. return new Map();
  11253. });
  11254. this.registerFunction('torch._C.string_to_type_lut', () => {
  11255. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11256. const map = new Map();
  11257. map.set('Tensor', torch.TensorType.get());
  11258. map.set('int', torch.IntType.get());
  11259. map.set('float', torch.FloatType.get());
  11260. map.set('bool', torch.BoolType.get());
  11261. map.set('complex', torch.ComplexType.get());
  11262. map.set('str', torch.StringType.get());
  11263. map.set('Device', torch.DeviceObjType.get());
  11264. map.set('number', torch.NumberType.get());
  11265. map.set('None', torch.NoneType.get());
  11266. map.set('NoneType', torch.NoneType.get());
  11267. map.set('Any', torch.AnyType.get());
  11268. map.set('list', torch.Type.get('AnyListType'));
  11269. map.set('tuple', torch.Type.get('AnyTupleType'));
  11270. torch._C.string_to_type_lut.basePythonTypes = map;
  11271. }
  11272. return torch._C.string_to_type_lut.basePythonTypes;
  11273. });
  11274. this.registerType('torch._C.ScriptTypeParser', class {
  11275. constructor(resolver) {
  11276. this._resolver = resolver;
  11277. }
  11278. parseSchemaFromDef(def, skip_self) {
  11279. const name = def.name;
  11280. const args = this.parseArgsFromDecl(def, skip_self);
  11281. const returns = this.parseReturnFromDecl(def);
  11282. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11283. }
  11284. parseArgsFromDecl(decl, skip_self) {
  11285. const retval = [];
  11286. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11287. throw new python.Error('Unsupported function argument.');
  11288. }
  11289. const params = decl.args.args.slice();
  11290. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11291. const start = skip_self ? 1 : 0;
  11292. for (let i = start; i < params.length; i++) {
  11293. const decl_arg = params[i];
  11294. const N = null;
  11295. const default_value = undefined;
  11296. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11297. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11298. retval.push(arg);
  11299. }
  11300. return retval;
  11301. }
  11302. parseReturnFromDecl(decl) {
  11303. if (!decl.returns) {
  11304. return [];
  11305. }
  11306. if (this.parseBroadcastList(decl.returns)) {
  11307. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11308. }
  11309. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11310. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11311. }
  11312. parseTypeFromExpr(expr) {
  11313. if (this._resolver) {
  11314. if (expr instanceof ast.Name) {
  11315. const type = this._resolver.resolveType(expr.id);
  11316. if (type) {
  11317. return type;
  11318. }
  11319. }
  11320. }
  11321. return this.parseTypeFromExprImpl(expr);
  11322. }
  11323. parseTypeFromExprImpl(expr) {
  11324. if (expr instanceof ast.Subscript) {
  11325. const value_name = this.parseBaseTypeName(expr.value);
  11326. if (!value_name) {
  11327. throw new python.Error('Subscripted type must be a type identifier.');
  11328. }
  11329. return this.subscriptToType(value_name, expr);
  11330. }
  11331. const name = this.parseBaseTypeName(expr);
  11332. if (name) {
  11333. const itr = torch._C.string_to_type_lut().get(name);
  11334. if (itr) {
  11335. return itr;
  11336. }
  11337. if (this._resolver) {
  11338. const typePtr = this._resolver.resolveType(name, expr);
  11339. if (typePtr) {
  11340. return typePtr;
  11341. }
  11342. }
  11343. }
  11344. throw new python.Error(`Unknown type name '${name}'.`);
  11345. }
  11346. parseBaseTypeName(expr) {
  11347. if (expr instanceof ast.Name) {
  11348. return expr.id;
  11349. } else if (expr instanceof ast.Constant && expr.value === null) {
  11350. return 'None';
  11351. } else if (expr instanceof ast.Attribute) {
  11352. const name = expr.attr;
  11353. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11354. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11355. return name;
  11356. }
  11357. return torch._C.collectQualname(expr);
  11358. }
  11359. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11360. }
  11361. parseBroadcastList(/* expr */) {
  11362. return null;
  11363. }
  11364. parseType(str) {
  11365. const expr = ast.parse(str);
  11366. return this.parseTypeFromExpr(expr.body[0].value);
  11367. }
  11368. subscriptToType(typeName, subscript) {
  11369. if (typeName === 'Tuple' || typeName === 'tuple') {
  11370. const subscript_expr_types = [];
  11371. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11372. for (const expr of elts) {
  11373. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11374. }
  11375. return torch.TupleType.create(subscript_expr_types);
  11376. } else if (typeName === 'List' || typeName === 'list') {
  11377. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11378. throw new python.Error('List type must have exactly one element type.');
  11379. }
  11380. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11381. return torch.ListType.create(elem_type);
  11382. } else if (typeName === 'Optional') {
  11383. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11384. throw new python.Error('Optional type must have exactly one element type.');
  11385. }
  11386. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11387. return torch.OptionalType.create(elem_type);
  11388. } else if (typeName === 'Union') {
  11389. const subscript_expr_types = [];
  11390. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11391. for (const expr of elts) {
  11392. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11393. }
  11394. return torch.UnionType.create(subscript_expr_types);
  11395. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11396. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11397. if (elts.length !== 1) {
  11398. throw new python.Error('Future type must have exactly one element type.');
  11399. }
  11400. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11401. return torch.FutureType.create(elem_type);
  11402. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11403. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11404. if (elts.length !== 1) {
  11405. throw new python.Error('Await type must have exactly one element type.');
  11406. }
  11407. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11408. return torch.AwaitType.create(elem_type);
  11409. } else if (typeName === 'RRef') {
  11410. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11411. if (elts.length !== 1) {
  11412. throw new python.Error('RRef type must have exactly one element type.');
  11413. }
  11414. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11415. return torch.RRefType.create(elem_type);
  11416. } else if (typeName === 'Dict' || typeName === 'dict') {
  11417. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11418. if (elts.length !== 2) {
  11419. throw new python.Error('Dict type must have exactly two element types.');
  11420. }
  11421. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11422. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11423. return torch.DictType.create(key_type, value_type);
  11424. }
  11425. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11426. }
  11427. });
  11428. this.registerFunction('torch._C.isTorch', (expr) => {
  11429. return expr instanceof ast.Name && expr.id === 'torch';
  11430. });
  11431. this.registerFunction('torch._C.collectQualname', (select) => {
  11432. const base = select.value;
  11433. if (base instanceof ast.Name) {
  11434. return `${base.id}.${select.attr}`;
  11435. }
  11436. const basename = torch._C.collectQualname(base);
  11437. return `${basename}.${select.attr}`;
  11438. });
  11439. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11440. constructor(overloadpacket, op, op_dk, schema, tags) {
  11441. super();
  11442. this._op = op;
  11443. this._op_dk = op_dk;
  11444. this._schema = schema;
  11445. this._overloadpacket = overloadpacket;
  11446. this._tags = tags;
  11447. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11448. this._name = this._schema.name;
  11449. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11450. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11451. this.__module__ = overloadpacket.__module__;
  11452. op.__module__ = overloadpacket.__module__;
  11453. this.__qualname__ = self._name;
  11454. this.__annotations__ = {};
  11455. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11456. let is_write = null;
  11457. for (const a of this._schema.arguments) {
  11458. if (a.alias_info) {
  11459. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11460. }
  11461. }
  11462. this.is_view = is_write !== null && !is_write;
  11463. }
  11464. name() {
  11465. return this._name;
  11466. }
  11467. });
  11468. this.registerType('torch._ops.OpOverloadPacket', class {
  11469. constructor(qualified_op_name, op_name, op, overload_names) {
  11470. this._qualified_op_name = qualified_op_name;
  11471. this.__name__ = op_name;
  11472. this._op = op;
  11473. this._overload_names = overload_names;
  11474. this._dir = [];
  11475. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11476. }
  11477. get _schemas() {
  11478. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11479. }
  11480. __getattr__(key) {
  11481. key = key === 'default' ? '' : key;
  11482. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11483. const [op_, op_dk_, tags] = op_dk_tags;
  11484. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11485. const overload = this._has_script_object_arg(schema) ?
  11486. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11487. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11488. builtins.setattr(self, key, overload);
  11489. this._dir.push(key);
  11490. return overload;
  11491. }
  11492. _has_script_object_arg(schema) {
  11493. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11494. }
  11495. __call__(...args) {
  11496. const fn = execution._operators.get(this._qualified_op_name);
  11497. if (!fn) {
  11498. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11499. }
  11500. return fn(...args);
  11501. }
  11502. });
  11503. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11504. constructor(name) {
  11505. super(`torch.ops.${name}`);
  11506. this.name = name;
  11507. this._dir = [];
  11508. }
  11509. __getattr__(op_name) {
  11510. const namespace_name = this.name;
  11511. const qualified_op_name = `${namespace_name}::${op_name}`;
  11512. const module_name = `${this.__module__}.${namespace_name}`;
  11513. let op = null;
  11514. let overload_names = null;
  11515. try {
  11516. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11517. } catch {
  11518. // continue regardless of error
  11519. }
  11520. if (!op) {
  11521. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11522. }
  11523. op.__module__ = module_name;
  11524. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11525. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11526. builtins.setattr(this, op_name, opoverloadpacket);
  11527. this._dir.push(op_name);
  11528. return opoverloadpacket;
  11529. }
  11530. _get_packet(qualname, op_module) {
  11531. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11532. if (op) {
  11533. // torch.jit._builtins._register_builtin(op, qualname);
  11534. }
  11535. op.__module__ = op_module;
  11536. return [op, overload_names];
  11537. }
  11538. });
  11539. this.registerType('torch._C.graph_node_list', class {
  11540. constructor(head) {
  11541. this.head = head;
  11542. }
  11543. front() {
  11544. return this.head.next;
  11545. }
  11546. end() {
  11547. return this.head.prev;
  11548. }
  11549. [Symbol.iterator]() {
  11550. let current = this.head.next;
  11551. const prev = this.head.prev;
  11552. return {
  11553. next() {
  11554. if (current !== prev) {
  11555. const value = current;
  11556. current = current.next;
  11557. return { value, done: false };
  11558. }
  11559. return { done: true };
  11560. }
  11561. };
  11562. }
  11563. });
  11564. this.registerType('torch.Graph', class {
  11565. constructor() {
  11566. this._next_unique = 0;
  11567. this._unique_names = new Map();
  11568. this._name_base_suffix = new Map();
  11569. this.all_nodes = new Set();
  11570. this.all_values = new Set();
  11571. this.all_blocks = new Set();
  11572. this._block = new torch.Block(this, null);
  11573. this._insert_before = this.return_node();
  11574. }
  11575. insert(opname, args, kwargs, range) {
  11576. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11577. }
  11578. create(kind, ...args) {
  11579. let inputs = null;
  11580. let num_outputs = 1;
  11581. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11582. [inputs, num_outputs] = args;
  11583. } else if (args.length === 1) {
  11584. if (typeof args[0] === 'number') {
  11585. [num_outputs] = args;
  11586. } else if (Array.isArray(args[0])) {
  11587. [inputs] = args;
  11588. }
  11589. }
  11590. const n = new torch.Node(this, kind);
  11591. if (inputs) {
  11592. for (const i of inputs) {
  11593. n.addInput(i);
  11594. }
  11595. }
  11596. for (let i = 0; i < num_outputs; i++) {
  11597. n.addOutput();
  11598. }
  11599. return n;
  11600. }
  11601. createClone(n, value_map, copy_blocks) {
  11602. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11603. const r = n.allocNewInstance(this);
  11604. for (const o of n.outputs()) {
  11605. r.addOutput().copyMetadata(o);
  11606. }
  11607. r.cloneFrom(n);
  11608. for (const i of n.inputs()) {
  11609. r.addInput(value_map(i));
  11610. }
  11611. if (copy_blocks) {
  11612. for (const b of n.blocks()) {
  11613. r.addBlock().cloneFrom(b, value_map);
  11614. }
  11615. }
  11616. return r;
  11617. }
  11618. createNone() {
  11619. const n = this.create('prim::Constant');
  11620. n.output().setType(torch.NoneType.get());
  11621. return n;
  11622. }
  11623. createUninitialized(typ) {
  11624. const n = this.create('prim::Uninitialized');
  11625. n.output().setType(typ);
  11626. return n;
  11627. }
  11628. createEnumValue(e) {
  11629. const enum_type = e.type().expect(torch.EnumType);
  11630. const n = this.create('prim::EnumValue', [e]);
  11631. n.output().setType(enum_type.getValueType());
  11632. return n;
  11633. }
  11634. createList(contained_type, values) {
  11635. const n = this.create('prim::ListConstruct', values);
  11636. for (const v of values) {
  11637. if (!v.type().isSubtypeOf(contained_type)) {
  11638. throw new python.Error('Invalid list item.');
  11639. }
  11640. }
  11641. n.output().setType(torch.ListType.create(contained_type));
  11642. return n;
  11643. }
  11644. createListUnpack(v, size) {
  11645. const list_type = v.type().expect(torch.ListType);
  11646. const elem_type = list_type.getElementType();
  11647. const n = this.create('prim::ListUnpack', [v], 0);
  11648. for (let i = 0; i < size; i++) {
  11649. n.addOutput().setType(elem_type);
  11650. }
  11651. return n;
  11652. }
  11653. createTuple(values, tuple_type) {
  11654. if (!tuple_type) {
  11655. const types = values.map((v) => v.type());
  11656. tuple_type = torch.TupleType.create(types);
  11657. }
  11658. const n = this.create('prim::TupleConstruct', values);
  11659. n.output().setType(tuple_type);
  11660. return n;
  11661. }
  11662. createTupleUnpack(v) {
  11663. const tt = v.type().expect(torch.TupleType);
  11664. const n = this.create('prim::TupleUnpack', [v], 0);
  11665. for (const element of tt.elements()) {
  11666. n.addOutput().setType(element);
  11667. }
  11668. return n;
  11669. }
  11670. createTupleIndex(tup, idx, output_type) {
  11671. const n = this.create('prim::TupleIndex', [tup, idx]);
  11672. n.output().setType(output_type);
  11673. return n;
  11674. }
  11675. createTupleSlice(tup, beg, step_size, num_values) {
  11676. const new_vals = [];
  11677. const tt = tup.type().expect(torch.TupleType);
  11678. let i = beg;
  11679. for (let j = 0; j < num_values; j++) {
  11680. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11681. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11682. new_vals.push(tupleIndex.output());
  11683. i += step_size;
  11684. }
  11685. const n = this.createTuple(new_vals);
  11686. return n;
  11687. }
  11688. createDict(key_type, value_type, keys, values) {
  11689. if (keys.length !== values.length) {
  11690. throw new python.Error('Invalid dictionary size.');
  11691. }
  11692. const n = this.create('prim::DictConstruct');
  11693. const length = keys.length;
  11694. for (let i = 0; i < length; i++) {
  11695. if (!keys[i].type().isSubtypeOf(key_type)) {
  11696. throw new python.Error('Invalid key.');
  11697. }
  11698. if (!values[i].type().isSubtypeOf(value_type)) {
  11699. throw new python.Error('Invalid value.');
  11700. }
  11701. n.addInput(keys[i]);
  11702. n.addInput(values[i]);
  11703. }
  11704. n.output().setType(torch.DictType.create(key_type, value_type));
  11705. return n;
  11706. }
  11707. createObject(type) {
  11708. const node = this.create('prim::CreateObject');
  11709. node.output().setType(type);
  11710. return node;
  11711. }
  11712. createIsInstance(v, types) {
  11713. const n = this.create('prim::isinstance', [v], 1);
  11714. n.tys_('types', types);
  11715. n.output().setType(torch.BoolType.get());
  11716. return n;
  11717. }
  11718. createSetAttr(obj, field, newValue) {
  11719. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11720. n.s_('name', field);
  11721. return n;
  11722. }
  11723. createGetAttr(obj, field) {
  11724. const n = this.create('prim::GetAttr', [obj]);
  11725. n.s_('name', field);
  11726. const classType = obj.type();
  11727. const outputType = classType.getAttribute(field);
  11728. n.output().setType(outputType);
  11729. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11730. return n;
  11731. }
  11732. createLoad(name, type) {
  11733. const n = this.create('prim::Load', [], 1);
  11734. n.s_('name', name);
  11735. n.output().setType(type);
  11736. return n;
  11737. }
  11738. createStore(name, v) {
  11739. const n = this.create('prim::Store', [v], 0);
  11740. n.s_('name', name);
  11741. return n;
  11742. }
  11743. inputs() {
  11744. return this._block.inputs();
  11745. }
  11746. outputs() {
  11747. return this._block.outputs();
  11748. }
  11749. nodes() {
  11750. return this._block.nodes();
  11751. }
  11752. param_node() {
  11753. return this._block.param_node();
  11754. }
  11755. return_node() {
  11756. return this._block.return_node();
  11757. }
  11758. block() {
  11759. return this._block;
  11760. }
  11761. addInput(name) {
  11762. return this._block.addInput(name);
  11763. }
  11764. insertNode(node) {
  11765. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11766. return node.insertBefore(this._insert_before);
  11767. }
  11768. insertConstant(val, loc, scope) {
  11769. return torch._C.insertConstant(this, val, loc, scope);
  11770. }
  11771. insertMethodCall(method_name, matched) {
  11772. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11773. .s_('name', method_name)
  11774. .output().setType(matched.return_types[0]);
  11775. return result;
  11776. }
  11777. insertUncheckedCast(v, type) {
  11778. const n = this.create('prim::unchecked_cast', [v]);
  11779. this.insertNode(n);
  11780. n.output().setType(type);
  11781. return n.output();
  11782. }
  11783. insertToList(v, type) {
  11784. let dim = 0;
  11785. let ptr = type;
  11786. while (ptr instanceof torch.ListType) {
  11787. ptr = ptr.getElementType();
  11788. dim += 1;
  11789. }
  11790. let elem_ty = 0;
  11791. if (ptr instanceof torch.IntType) {
  11792. elem_ty = 0;
  11793. } else if (ptr instanceof torch.FloatType) {
  11794. elem_ty = 1;
  11795. } else if (ptr instanceof torch.BoolType) {
  11796. elem_ty = 2;
  11797. } else if (ptr instanceof torch.ComplexType) {
  11798. elem_ty = 3;
  11799. } else {
  11800. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  11801. }
  11802. const dim_val = this.insertConstant(dim);
  11803. const elem_ty_val = this.insertConstant(elem_ty);
  11804. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  11805. n.output().setType(type);
  11806. return n.output();
  11807. }
  11808. insertFunctionCall(callee, matched) {
  11809. const func_name = callee.name();
  11810. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  11811. const inputs = [fn_constant, ...matched.inputs];
  11812. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  11813. return result;
  11814. }
  11815. insertPoint() {
  11816. return this._insert_before;
  11817. }
  11818. setInsertPoint(node) {
  11819. if (node instanceof torch.Block) {
  11820. node = node.return_node();
  11821. }
  11822. this._insert_before = node;
  11823. }
  11824. freeNode(n) {
  11825. this.all_nodes.delete(n);
  11826. }
  11827. freeValue(v) {
  11828. v.setDebugName('');
  11829. this.all_values.delete(v);
  11830. }
  11831. freeBlock(b) {
  11832. this.all_blocks.delete(b);
  11833. }
  11834. copy() {
  11835. const new_g = new torch.Graph();
  11836. new_g.cloneFrom(this);
  11837. return new_g;
  11838. }
  11839. cloneFrom(src) {
  11840. const env = (v) => {
  11841. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  11842. };
  11843. this.block().cloneFrom(src.block(), env);
  11844. }
  11845. set_op_version(version) {
  11846. this._op_version = version;
  11847. }
  11848. get_op_version() {
  11849. return this._op_version;
  11850. }
  11851. print(out, print_source_locations) {
  11852. out.write('graph(');
  11853. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  11854. out.write('):\n');
  11855. const groups = [];
  11856. for (const node of this.nodes()) {
  11857. node.print(out, 1, groups, print_source_locations);
  11858. }
  11859. out.write(' return (');
  11860. torch._C.printValueRefs(out, this.outputs());
  11861. out.write(')\n');
  11862. for (let i = 0; i < groups.length; i++) {
  11863. const fg = groups[i];
  11864. out.write('with ');
  11865. out.write(fg.kind());
  11866. out.write(`_${i} = `);
  11867. out.write(fg.g('Subgraph'));
  11868. }
  11869. return out;
  11870. }
  11871. toString() {
  11872. const out = new io.StringIO();
  11873. this.print(out, true);
  11874. return out.toString();
  11875. }
  11876. });
  11877. this.registerType('torch.Block', class {
  11878. constructor(graph, node) {
  11879. this._graph = graph;
  11880. this._input = graph.create('prim::Param', 0);
  11881. this._output = graph.create('prim::Return', 0);
  11882. this._owning_node = node;
  11883. this._input.next = this._output;
  11884. this._input.prev = this._output;
  11885. this._output.next = this._input;
  11886. this._output.prev = this._input;
  11887. this._graph.all_blocks.add(this);
  11888. this._output._owning_block = this;
  11889. // output_.topo_position_ = kUpperBound;
  11890. this._input._owning_block = this;
  11891. // input_.topo_position_ = kLowerBound;
  11892. }
  11893. inputs() {
  11894. return this._input.outputs();
  11895. }
  11896. outputs() {
  11897. return this._output.inputs();
  11898. }
  11899. nodes() {
  11900. return new torch._C.graph_node_list(this._input);
  11901. }
  11902. return_node() {
  11903. return this._output;
  11904. }
  11905. param_node() {
  11906. return this._input;
  11907. }
  11908. owningNode() {
  11909. return this._owning_node;
  11910. }
  11911. owningGraph() {
  11912. return this._graph;
  11913. }
  11914. addInput(name) {
  11915. const value = this._input.addOutput();
  11916. value.setDebugName(name || '');
  11917. return value;
  11918. }
  11919. registerOutput(value) {
  11920. this._output.addInput(value);
  11921. return this.outputs().length - 1;
  11922. }
  11923. appendNode(n) {
  11924. if (n._graph !== this._graph || n.inBlockList()) {
  11925. throw new python.Error('Node not in graph.');
  11926. }
  11927. n.insertBefore(this._output);
  11928. return n;
  11929. }
  11930. cloneFrom(src, value_map) {
  11931. const local_map = new Map();
  11932. const env = (v) => {
  11933. if (local_map.has(v)) {
  11934. return local_map.get(v);
  11935. }
  11936. return value_map(v);
  11937. };
  11938. const graph = this.owningGraph();
  11939. for (const input of src.inputs()) {
  11940. local_map.set(input, this.addInput().copyMetadata(input));
  11941. }
  11942. for (const node of src.nodes()) {
  11943. const new_node = this.appendNode(graph.createClone(node, env));
  11944. for (let i = 0; i < node.outputs().length; i++) {
  11945. const oo = node.outputs()[i];
  11946. const no = new_node.outputs()[i];
  11947. local_map.set(oo, no);
  11948. no.copyMetadata(oo);
  11949. }
  11950. }
  11951. for (const output of src.outputs()) {
  11952. this.registerOutput(env(output));
  11953. }
  11954. }
  11955. eraseOutput(i) {
  11956. this._output.removeInput(i);
  11957. }
  11958. destroy() {
  11959. this._output.removeAllInputs();
  11960. for (const n of this.nodes()) {
  11961. n.destroy();
  11962. }
  11963. this._output.destroy();
  11964. this._input.destroy();
  11965. this._graph.freeBlock(this);
  11966. }
  11967. });
  11968. this.registerType('torch.Node', class {
  11969. constructor(graph, kind) {
  11970. this._kind = kind;
  11971. this._graph = graph;
  11972. this._owning_block = null;
  11973. this._values = new Map();
  11974. this._inputs = [];
  11975. this._outputs = [];
  11976. this._blocks = [];
  11977. this._graph.all_nodes.add(this);
  11978. this._prev = null;
  11979. this._next = null;
  11980. this._source_range = null;
  11981. this._op = null;
  11982. }
  11983. owningGraph() {
  11984. return this._graph;
  11985. }
  11986. owningBlock() {
  11987. return this._owning_block;
  11988. }
  11989. kind() {
  11990. return this._kind;
  11991. }
  11992. schema() {
  11993. if (this._op) {
  11994. return this._op.schema();
  11995. }
  11996. // Node::schema() throws while torch.Node.schema() does not.
  11997. const op = this.maybeOperator();
  11998. if (op) {
  11999. return op.schema();
  12000. }
  12001. return null;
  12002. // return this.getOperator().schema();
  12003. }
  12004. hasNamedInput(name) {
  12005. for (const argument of this.schema().arguments) {
  12006. if (argument.name === name) {
  12007. return true;
  12008. }
  12009. }
  12010. return false;
  12011. }
  12012. matches(schema) {
  12013. if (torch._C.isBlockListedSchema(schema)) {
  12014. return false;
  12015. }
  12016. if (this.kind() !== schema.name) {
  12017. return false;
  12018. }
  12019. const actuals = this.inputs();
  12020. const formals = schema.arguments;
  12021. if (actuals.length < formals.length) {
  12022. return false;
  12023. }
  12024. const type_env = new Map();
  12025. for (let i = 0; i < formals.length; i++) {
  12026. let formal = formals[i].type;
  12027. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12028. if (!matched_type.success()) {
  12029. return false;
  12030. }
  12031. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12032. if (resolved) {
  12033. formal = resolved;
  12034. }
  12035. if (!actuals[i].type().isSubtypeOf(formal)) {
  12036. return false;
  12037. }
  12038. }
  12039. if (!schema.is_vararg && actuals.length !== formals.length) {
  12040. return false;
  12041. }
  12042. return true;
  12043. }
  12044. mustBeNone() {
  12045. return this._kind === 'prim::AutogradZero' ||
  12046. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12047. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12048. }
  12049. maybeSchema() {
  12050. const op = this.maybeOperator();
  12051. if (op) {
  12052. return op.schema();
  12053. }
  12054. return null;
  12055. }
  12056. maybeOperator() {
  12057. if (!this._op) {
  12058. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12059. for (const candidate of candidates) {
  12060. if (this.matches(candidate.schema())) {
  12061. this._op = candidate;
  12062. break;
  12063. }
  12064. }
  12065. }
  12066. return this._op;
  12067. }
  12068. getOperator() {
  12069. const maybe = this.maybeOperator();
  12070. if (maybe) {
  12071. return maybe;
  12072. }
  12073. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12074. }
  12075. getOperation() {
  12076. return this.getOperator().getOperation(this);
  12077. }
  12078. isNondeterministic() {
  12079. const schema = this.maybeSchema();
  12080. if (!this.kind().startsWith('aten::')) {
  12081. return false;
  12082. }
  12083. if (!schema) {
  12084. return false;
  12085. }
  12086. const schema_info = new torch._C.SchemaInfo(schema);
  12087. if (this.hasNamedInput('train')) {
  12088. throw new python.Error('Not Implemented.');
  12089. // const value = constant_as<bool>(this.namedInput("train"));
  12090. // if (value) {
  12091. // schema_info.addArgumentValue('train', value);
  12092. // }
  12093. }
  12094. return schema_info.is_nondeterministic();
  12095. }
  12096. hasSideEffects() {
  12097. switch (this._kind) {
  12098. case 'prim::PythonOp':
  12099. case 'prim::IgnoredPythonOp':
  12100. case 'prim::Print':
  12101. case 'prim::RaiseException':
  12102. case 'aten::warn':
  12103. case 'aten::save':
  12104. case 'aten::manual_seed':
  12105. case 'prim::AddStatValue':
  12106. case 'prim::TimePoint':
  12107. case 'prim::CallFunction':
  12108. case 'prim::CallMethod':
  12109. case 'prim::BailoutTemplate':
  12110. case 'prim::BailOut':
  12111. case 'prim::rpc_async':
  12112. case 'prim::rpc_sync':
  12113. case 'prim::rpc_remote':
  12114. case 'aten::wait':
  12115. case 'cuda::set_stream':
  12116. case 'cuda::_set_device':
  12117. case 'cuda::_current_device':
  12118. case 'cuda::synchronize':
  12119. case 'prim::Enter':
  12120. case 'prim::Exit':
  12121. return true;
  12122. default:
  12123. break;
  12124. }
  12125. const op = this.maybeOperator();
  12126. if (!op) {
  12127. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12128. return false;
  12129. }
  12130. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12131. torch._C.TORCH_INTERNAL_ASSERT(
  12132. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12133. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12134. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12135. }
  12136. switch (op.aliasAnalysisKind()) {
  12137. case 'PURE_FUNCTION':
  12138. case 'FROM_SCHEMA':
  12139. case 'INTERNAL_SPECIAL_CASE':
  12140. return false;
  12141. case 'CONSERVATIVE':
  12142. return true;
  12143. default:
  12144. break;
  12145. }
  12146. torch._C.TORCH_INTERNAL_ASSERT(false);
  12147. return false;
  12148. }
  12149. inputs() {
  12150. return this._inputs;
  12151. }
  12152. outputs() {
  12153. return this._outputs;
  12154. }
  12155. input(i) {
  12156. if (i === undefined) {
  12157. torch._C.AT_ASSERT(this._inputs.length === 1);
  12158. return this._inputs[0];
  12159. }
  12160. return this._inputs[i];
  12161. }
  12162. output(i) {
  12163. if (i === undefined) {
  12164. torch._C.AT_ASSERT(this._outputs.length === 1);
  12165. return this._outputs[0];
  12166. }
  12167. return this._outputs[i];
  12168. }
  12169. hasUses() {
  12170. for (const o of this.outputs()) {
  12171. if (o.uses().length > 0) {
  12172. return true;
  12173. }
  12174. }
  12175. return false;
  12176. }
  12177. blocks() {
  12178. return this._blocks;
  12179. }
  12180. insertInput(i, value) {
  12181. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12182. this._op = null;
  12183. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12184. const use = this.findUseForInput(use_itr);
  12185. use.offset += 1;
  12186. }
  12187. this._inputs.splice(i, 0, value);
  12188. value._uses.push(new torch.Use(this, i));
  12189. return value;
  12190. }
  12191. addInput(value) {
  12192. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12193. this._op = null;
  12194. const use = new torch.Use(this, this._inputs.length);
  12195. value.uses().push(use);
  12196. this._inputs.push(value);
  12197. return value;
  12198. }
  12199. addOutput() {
  12200. const value = new torch.Value(this, this._outputs.length);
  12201. this._outputs.push(value);
  12202. return value;
  12203. }
  12204. addBlock() {
  12205. this._op = null;
  12206. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12207. return this._blocks[this._blocks.length - 1];
  12208. }
  12209. get prev() {
  12210. return this._prev;
  12211. }
  12212. set prev(value) {
  12213. this._prev = value;
  12214. }
  12215. get next() {
  12216. return this._next;
  12217. }
  12218. set next(value) {
  12219. this._next = value;
  12220. }
  12221. insertBefore(n) {
  12222. if (!n.inBlockList()) {
  12223. throw new python.Error('Node not in block.');
  12224. }
  12225. this.insertAfter(n.prev);
  12226. return this;
  12227. }
  12228. insertAfter(n) {
  12229. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12230. torch._C.AT_ASSERT(n.owningBlock());
  12231. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12232. this._owning_block = n.owningBlock();
  12233. const next = n.next;
  12234. n.next = this;
  12235. this.prev = n;
  12236. this.next = next;
  12237. next.prev = this;
  12238. // this.assignTopoPosition();
  12239. return this;
  12240. }
  12241. allocNewInstance(g) {
  12242. return new torch.Node(g, this.kind());
  12243. }
  12244. cloneFrom(s) {
  12245. this._source_range = s._source_range;
  12246. if (s._scope && !s._scope.isBlank()) {
  12247. this._scope = s._scope;
  12248. }
  12249. this.copyAttributes(s);
  12250. this._callstack = s._callstack;
  12251. }
  12252. copyAttributes(rhs) {
  12253. this._values = new Map(rhs._values);
  12254. return this;
  12255. }
  12256. dropInput(i) {
  12257. torch._C.AT_ASSERT(i < this._inputs.length);
  12258. const input_node = this._inputs[i];
  12259. const use_it = this.findUseForInput(i);
  12260. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12261. this._inputs[i] = null;
  12262. return input_node;
  12263. }
  12264. eraseOutput(i) {
  12265. torch._C.AT_ASSERT(i < this._outputs.length);
  12266. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12267. this._op = null;
  12268. const n = this._outputs[i];
  12269. this._outputs.splice(i, 1);
  12270. this.owningGraph().freeValue(n);
  12271. for (let j = i; j < this._outputs.length; j++) {
  12272. this._outputs[j]._offset--;
  12273. }
  12274. }
  12275. eraseBlock(i) {
  12276. this._op = null;
  12277. const n = this._blocks[i];
  12278. this._blocks.splice(i, 1);
  12279. n.destroy();
  12280. }
  12281. findUseForInput(i) {
  12282. const input_uses = this._inputs[i]._uses;
  12283. for (const use_it of input_uses) {
  12284. if (use_it.user === this && use_it.offset === i) {
  12285. return use_it;
  12286. }
  12287. }
  12288. throw new python.Error('Input use not found.');
  12289. }
  12290. moveBefore(n) {
  12291. this.removeFromList();
  12292. this.insertBefore(n);
  12293. }
  12294. removeInput(i) {
  12295. this._op = null;
  12296. this.dropInput(i);
  12297. for (let j = i + 1; j < this._inputs.length; j++) {
  12298. const it = this.findUseForInput(j);
  12299. it.offset--;
  12300. }
  12301. this._inputs.splice(i, 1);
  12302. }
  12303. removeAllInputs() {
  12304. this._op = null;
  12305. for (let i = 0; i < this._inputs.length; i++) {
  12306. this.dropInput(i);
  12307. }
  12308. this._inputs = [];
  12309. }
  12310. inBlockList() {
  12311. return this.next !== null;
  12312. }
  12313. removeFromList() {
  12314. this._owning_block = null;
  12315. const next = this.next;
  12316. const prev = this.prev;
  12317. prev.next = next;
  12318. next.prev = prev;
  12319. this.next = null;
  12320. this.prev = null;
  12321. }
  12322. destroy() {
  12323. while (this.outputs().length > 0) {
  12324. this.eraseOutput(this.outputs().length - 1);
  12325. }
  12326. while (this.blocks().length > 0) {
  12327. this.eraseBlock(this.blocks().length - 1);
  12328. }
  12329. this.removeAllInputs();
  12330. if (this.inBlockList()) {
  12331. this.removeFromList();
  12332. }
  12333. this._graph.freeNode(this);
  12334. }
  12335. replaceAllUsesWith(n) {
  12336. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12337. const nOutputs = this.outputs().length;
  12338. for (let i = 0; i < nOutputs; i++) {
  12339. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12340. }
  12341. }
  12342. s_(name, value) {
  12343. this._values.set(name, [value, 's']);
  12344. return this;
  12345. }
  12346. s(name) {
  12347. return this._values.get(name)[0];
  12348. }
  12349. ss_(name, value) {
  12350. this._values.set(name, [value, 'ss']);
  12351. return this;
  12352. }
  12353. ss(name) {
  12354. return this._values.get(name)[0];
  12355. }
  12356. i_(name, value) {
  12357. this._values.set(name, [value, 'i']);
  12358. return this;
  12359. }
  12360. i(name) {
  12361. return this._values.get(name)[0];
  12362. }
  12363. f_(name, value) {
  12364. this._values.set(name, [value, 'f']);
  12365. return this;
  12366. }
  12367. f(name) {
  12368. return this._values.get(name)[0];
  12369. }
  12370. t_(name, value) {
  12371. this._values.set(name, [value, 't']);
  12372. return this;
  12373. }
  12374. t(name) {
  12375. return this._values.get(name)[0];
  12376. }
  12377. tys_(name, value) {
  12378. this._values.set(name, [value, 'tys']);
  12379. return this;
  12380. }
  12381. tys(name) {
  12382. return this._values.get(name)[0];
  12383. }
  12384. ival_(name, value) {
  12385. this._values.set(name, [value, 'ival']);
  12386. return this;
  12387. }
  12388. ival(name) {
  12389. return this._values.get(name)[0];
  12390. }
  12391. hasAttribute(name) {
  12392. return this._values.has(name);
  12393. }
  12394. hasAttributes() {
  12395. return this._values.size > 0;
  12396. }
  12397. attributeNames() {
  12398. return Array.from(this._values.keys());
  12399. }
  12400. kindOf(name) {
  12401. return this._values.get(name)[1];
  12402. }
  12403. setSourceRange(r) {
  12404. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12405. this._source_range = r;
  12406. return this;
  12407. }
  12408. sourceRange() {
  12409. if (this._source_range) {
  12410. return this._source_range;
  12411. }
  12412. return new torch._C.SourceRange();
  12413. }
  12414. print_attributes(out, ignore_subgraph) {
  12415. ignore_subgraph = ignore_subgraph || false;
  12416. out.write('[');
  12417. const names = this.attributeNames();
  12418. for (let i = 0; i < names.length; i++) {
  12419. const name = names[i];
  12420. if (ignore_subgraph && name === 'Subgraph') {
  12421. continue;
  12422. }
  12423. if (i > 0) {
  12424. out.write(', ');
  12425. }
  12426. out.write(`${name}=`);
  12427. this.printAttrValue(out, name);
  12428. }
  12429. out.write(']');
  12430. }
  12431. printTypeList(out, items) {
  12432. out.write('[');
  12433. for (let i = 0; i < items.length; i++) {
  12434. const item = items[i];
  12435. if (i++ > 0) {
  12436. out.write(', ');
  12437. }
  12438. out.write(item.str());
  12439. }
  12440. out.write(']');
  12441. }
  12442. printAttrValue(out, name) {
  12443. const kind = this.kindOf(name);
  12444. switch (kind) {
  12445. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12446. case 'ss': case 'ival': case 'ty':
  12447. out.write(this[kind](name));
  12448. break;
  12449. case 's':
  12450. out.write(`"${this.s(name)}"`);
  12451. break;
  12452. case 't':
  12453. out.write(`"{}"`);
  12454. break;
  12455. case 'ts': out.write('[<Tensors>]'); break;
  12456. case 'g': out.write('[<Graph>]'); break;
  12457. case 'gs': out.write('[<Graphs>]'); break;
  12458. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12459. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12460. }
  12461. }
  12462. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12463. print_source_locations = print_source_locations === false ? false : true;
  12464. print_attributes = print_attributes === false ? false : true;
  12465. print_scopes = print_scopes === false ? false : true;
  12466. print_body = print_body === false ? false : true;
  12467. const outs = this.outputs();
  12468. torch._C.indent(out, level);
  12469. torch._C.const_value_list_with_types(out, outs, ', ');
  12470. out.write(' = ');
  12471. if (this.kind() === 'prim::PythonOp') {
  12472. throw new python.Error('Not implemented.');
  12473. } else if (this.hasAttribute('Subgraph') && groups) {
  12474. throw new python.Error('Not implemented.');
  12475. } else {
  12476. out.write(this.kind());
  12477. if (print_attributes && this.hasAttributes()) {
  12478. this.print_attributes(out);
  12479. }
  12480. }
  12481. out.write('(');
  12482. torch._C.printValueRefs(out, this.inputs());
  12483. out.write(')');
  12484. if (print_scopes) {
  12485. //
  12486. }
  12487. if (print_source_locations) {
  12488. let r = this.sourceRange();
  12489. if (r.source()) {
  12490. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12491. if (orig) {
  12492. r = orig;
  12493. }
  12494. }
  12495. const file_line_col = r.file_line_col();
  12496. if (file_line_col !== null) {
  12497. const [filename, line, col] = file_line_col;
  12498. out.write(` # ${filename}:${line}:${col}`);
  12499. }
  12500. }
  12501. if (!print_body) {
  12502. return out;
  12503. }
  12504. out.write('\n');
  12505. for (let i = 0; i < this.blocks().length; i++) {
  12506. const b = this.blocks().at(i);
  12507. torch._C.indent(out, level + 1);
  12508. out.write(`block${i}(`);
  12509. torch._C.const_value_list_with_types(out, b.inputs());
  12510. out.write('):\n');
  12511. for (const nested of b.nodes()) {
  12512. nested.print(out, level + 2, groups);
  12513. }
  12514. torch._C.indent(out, level + 2);
  12515. out.write('-> (');
  12516. torch._C.printValueRefs(out, b.outputs());
  12517. out.write(')\n');
  12518. }
  12519. return out;
  12520. }
  12521. toString() {
  12522. const out = new io.StringIO();
  12523. this.print(out, 0, true);
  12524. return out.toString();
  12525. }
  12526. });
  12527. this.registerType('torch.Value', class {
  12528. constructor(node, offset) {
  12529. this._node = node;
  12530. this._offset = offset;
  12531. this._unique = node._graph._next_unique++;
  12532. this._uses = [];
  12533. this._node._graph.all_values.add(this);
  12534. }
  12535. unique() {
  12536. return this._unique;
  12537. }
  12538. node() {
  12539. return this._node;
  12540. }
  12541. owningGraph() {
  12542. return this._node.owningGraph();
  12543. }
  12544. uses() {
  12545. return this._uses;
  12546. }
  12547. hasUses() {
  12548. return this._uses.length > 0;
  12549. }
  12550. mustBeNone() {
  12551. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12552. }
  12553. mustNotBeNone() {
  12554. return this._node.kind() !== 'prim::AutogradAdd' &&
  12555. this.type() !== torch.NoneType.get() &&
  12556. !(this.type() instanceof torch.OptionalType) &&
  12557. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12558. }
  12559. isValidName(name) {
  12560. if (name.length === 0) {
  12561. return true;
  12562. }
  12563. if (torch._C.isNumber(name)) {
  12564. return false;
  12565. }
  12566. return true;
  12567. }
  12568. hasDebugName() {
  12569. return this._unique_name && this._unique_name.length > 0;
  12570. }
  12571. setDebugName(name) {
  12572. if (!this.isValidName(name)) {
  12573. throw new python.Error(`Invalid name '${name}'.`);
  12574. }
  12575. const names = this.node().owningGraph()._unique_names;
  12576. if (this.hasDebugName()) {
  12577. names.delete(this._unique_name);
  12578. this._unique_name = '';
  12579. }
  12580. if (!name) {
  12581. return this;
  12582. }
  12583. const old_owner_of_name = names.get(name);
  12584. if (old_owner_of_name) {
  12585. let suffix = 1;
  12586. let name_base = name;
  12587. const last_dot_pos = name.lastIndexOf('.');
  12588. if (last_dot_pos !== -1) {
  12589. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12590. suffix = Number(name.substring(last_dot_pos + 1));
  12591. name_base = name.substring(0, last_dot_pos);
  12592. }
  12593. }
  12594. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12595. if (names_suffixes.has(name_base)) {
  12596. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12597. }
  12598. let replacement_name = null;
  12599. do {
  12600. replacement_name = `${name_base}.${suffix++}`;
  12601. } while (names.has(replacement_name));
  12602. names_suffixes.set(name_base, suffix);
  12603. old_owner_of_name.setDebugName(replacement_name);
  12604. }
  12605. names.set(name, this);
  12606. this._unique_name = name;
  12607. return this;
  12608. }
  12609. debugName() {
  12610. if (this.hasDebugName()) {
  12611. return this._unique_name;
  12612. }
  12613. return this.unique().toString();
  12614. }
  12615. type() {
  12616. return this._type;
  12617. }
  12618. setType(type) {
  12619. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12620. if (type instanceof torch._C.DynamicType) {
  12621. type = type.fallback();
  12622. }
  12623. this._type = type;
  12624. for (const use of this._uses) {
  12625. use.user._op = null;
  12626. }
  12627. return this;
  12628. }
  12629. set value(value) { // remove
  12630. if (value instanceof torch.Value) {
  12631. throw new python.Error('Value cannot be a value.');
  12632. }
  12633. this._value = value;
  12634. }
  12635. get value() { // remove
  12636. return this._value;
  12637. }
  12638. replaceFirstUseWith(newValue) {
  12639. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12640. const [u] = this.uses();
  12641. u.user._inputs[u.offset] = newValue;
  12642. newValue._uses.push(u);
  12643. this._uses.shift();
  12644. }
  12645. replaceAllUsesWith(newValue) {
  12646. while (this.uses().length > 0) {
  12647. this.replaceFirstUseWith(newValue);
  12648. }
  12649. }
  12650. copyMetadata(from) {
  12651. this.setType(from.type());
  12652. if (from.hasDebugName()) {
  12653. this.setDebugName(from.debugName());
  12654. }
  12655. return this;
  12656. }
  12657. toString() {
  12658. return `${this.debugName()} : ${this.type().toString()}`;
  12659. }
  12660. });
  12661. this.registerType('torch.Use', class {
  12662. constructor(user, offset) {
  12663. this.user = user;
  12664. this.offset = offset;
  12665. }
  12666. });
  12667. this.registerType('torch._C.IValue', class {
  12668. constructor(value, tag) {
  12669. this.value = value;
  12670. if (tag) {
  12671. this.tag = tag;
  12672. } else if (value === undefined) {
  12673. this.tag = 'None';
  12674. this.value = null;
  12675. } else if (typeof value === 'boolean') {
  12676. this.tag = 'Bool';
  12677. } else if (typeof value === 'string') {
  12678. this.tag = 'String';
  12679. } else if (value instanceof torch.Tensor) {
  12680. this.tag = 'Tensor';
  12681. } else if (value instanceof torch.ScriptObject) {
  12682. this.tag = 'Object';
  12683. } else if (Array.isArray(value)) {
  12684. this.tag = 'GenericList';
  12685. } else if (value instanceof torch._C.Tuple) {
  12686. this.tag = 'Tuple';
  12687. } else if (value instanceof torch.device) {
  12688. this.tag = 'Device';
  12689. } else if (Number.isInteger(value)) {
  12690. this.tag = 'Int';
  12691. } else if (typeof value === 'number') {
  12692. this.tag = 'Double';
  12693. } else if (value instanceof torch._C.EnumHolder) {
  12694. this.tag = 'Enum';
  12695. } else {
  12696. throw new python.Error('Unsupported type.');
  12697. }
  12698. }
  12699. isNone() {
  12700. return this.tag === 'None';
  12701. }
  12702. isBool() {
  12703. return this.tag === 'Bool';
  12704. }
  12705. toBool() {
  12706. return this.value;
  12707. }
  12708. isObject() {
  12709. return this.tag === 'Object';
  12710. }
  12711. toObject() {
  12712. return this.value;
  12713. }
  12714. isTensor() {
  12715. return this.tag === 'Tensor';
  12716. }
  12717. toTensor() {
  12718. return this.value;
  12719. }
  12720. isDouble() {
  12721. return this.tag === 'Double';
  12722. }
  12723. toDouble() {
  12724. return this.value;
  12725. }
  12726. isComplexDouble() {
  12727. return this.tag === 'ComplexDouble';
  12728. }
  12729. isInt() {
  12730. return this.tag === 'Int';
  12731. }
  12732. toInt() {
  12733. if (this.isInt()) {
  12734. return this.value;
  12735. } else if (this.isSymInt()) {
  12736. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12737. }
  12738. throw new python.Error('Expected int.');
  12739. }
  12740. isString() {
  12741. return this.tag === 'String';
  12742. }
  12743. toStringRef() {
  12744. return this.value;
  12745. }
  12746. isList() {
  12747. return this.tag === 'GenericList';
  12748. }
  12749. toList() {
  12750. return this.value;
  12751. }
  12752. toListRef() {
  12753. return this.value;
  12754. }
  12755. isBoolList() {
  12756. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12757. }
  12758. isIntList() {
  12759. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12760. }
  12761. isDoubleList() {
  12762. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12763. }
  12764. isDevice() {
  12765. return this.tag === 'Device';
  12766. }
  12767. toDevice() {
  12768. return this.value;
  12769. }
  12770. isGenerator() {
  12771. return this.tag === 'Generator';
  12772. }
  12773. isStream() {
  12774. return this.tag === 'Stream';
  12775. }
  12776. isGenericDict() {
  12777. return this.tag === 'GenericDict';
  12778. }
  12779. isEnum() {
  12780. return this.tag === 'Enum';
  12781. }
  12782. toEnumHolder() {
  12783. return this.value;
  12784. }
  12785. isTuple() {
  12786. return this.tag === 'Tuple';
  12787. }
  12788. toTupleRef() {
  12789. return this.value;
  12790. }
  12791. isCustomClass() {
  12792. return torch._C.isCustomClass(this);
  12793. }
  12794. equals(rhs) {
  12795. switch (this.tag) {
  12796. case 'None': return rhs.isNone();
  12797. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  12798. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  12799. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  12800. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  12801. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  12802. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  12803. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  12804. case 'GenericList': {
  12805. if (rhs.isList()) {
  12806. const a = this.toList();
  12807. const b = rhs.toList();
  12808. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  12809. }
  12810. return false;
  12811. }
  12812. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  12813. }
  12814. }
  12815. is(rhs) {
  12816. return this.equals(rhs);
  12817. }
  12818. type() {
  12819. switch (this.tag) {
  12820. case 'None': return torch.NoneType.get();
  12821. case 'Bool': return torch.BoolType.get();
  12822. case 'Int': return torch.IntType.get();
  12823. case 'Double': return torch.FloatType.get();
  12824. case 'String': return torch.StringType.get();
  12825. case 'Device': return torch.DeviceObjType.get();
  12826. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  12827. case 'Enum': return this.toEnumHolder().type();
  12828. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  12829. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  12830. }
  12831. }
  12832. });
  12833. this.registerFunction('torch._C.indent', (out, level) => {
  12834. for (let i = 0; i < level; i++) {
  12835. out.write(' ');
  12836. }
  12837. return out;
  12838. });
  12839. this.registerFunction('torch._C.printValueRef', (out, n) => {
  12840. out.write(`%${n.debugName()}`);
  12841. });
  12842. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  12843. for (let i = 0; i < nodes.length; i++) {
  12844. const n = nodes[i];
  12845. if (i > 0) {
  12846. out.write(', ');
  12847. }
  12848. torch._C.printValueRef(out, n);
  12849. }
  12850. return out;
  12851. });
  12852. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  12853. for (let i = 0; i < values.length; i++) {
  12854. const n = values[i];
  12855. if (i > 0) {
  12856. out.write(delim);
  12857. }
  12858. torch._C.printValueRef(out, n);
  12859. out.write(' : ');
  12860. out.write(n.type().str());
  12861. }
  12862. });
  12863. this.register('torch.jit._script');
  12864. this.register('torch.jit._trace');
  12865. this.registerType('torch._C.Parser', class {
  12866. constructor(source) {
  12867. this.L = source;
  12868. }
  12869. parse() {
  12870. const p = ast.parse(this.L.text_str(), this.L.filename());
  12871. return p;
  12872. }
  12873. parseExp() {
  12874. const expr = ast.parse(this.L.text_str());
  12875. return expr.body[0].value;
  12876. }
  12877. });
  12878. this.registerType('torch._C.StringCordView', class {
  12879. });
  12880. this.registerType('torch._C.Source', class {
  12881. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  12882. if (text_view instanceof Uint8Array) {
  12883. const decoder = new TextDecoder('utf-8');
  12884. this._text_view = decoder.decode(text_view);
  12885. } else if (typeof text_view === 'string') {
  12886. this._text_view = text_view;
  12887. } else {
  12888. throw new python.Error('Invalid text view.');
  12889. }
  12890. this._filename = filename;
  12891. this._starting_line_no = starting_line_no;
  12892. this._gen_ranges = gen_ranges;
  12893. this.calc_line_start_offsets();
  12894. }
  12895. text_str() {
  12896. return this._text_view;
  12897. }
  12898. size() {
  12899. return this._text_view.length;
  12900. }
  12901. filename() {
  12902. return this._filename;
  12903. }
  12904. calc_line_start_offsets() {
  12905. let pos = 0;
  12906. this._line_starting_offsets = [0];
  12907. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  12908. pos += 1;
  12909. this._line_starting_offsets.push(pos);
  12910. }
  12911. }
  12912. offset_for_line(line) {
  12913. return this._line_starting_offsets[line];
  12914. }
  12915. lineno_for_offset(offset) {
  12916. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  12917. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  12918. }
  12919. lineno_to_source_lineno(lineno) {
  12920. if (this._filename) {
  12921. return lineno + this._starting_line_no;
  12922. }
  12923. return lineno;
  12924. }
  12925. findSourceRangeThatGenerated(range) {
  12926. if (!this._gen_ranges) {
  12927. return null;
  12928. }
  12929. return this._gen_ranges.findSourceRangeThatGenerated(range);
  12930. }
  12931. });
  12932. this.registerType('torch._C.SourceRange', class {
  12933. constructor(...args) {
  12934. if (args.length === 0) {
  12935. this._source_view = null;
  12936. } else if (args.length === 2) {
  12937. let node = null;
  12938. [this._source_view, node] = args;
  12939. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  12940. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  12941. } else if (args.length === 3) {
  12942. [this._source_view, this._start, this._end] = args;
  12943. } else {
  12944. throw new python.Error('Not implemented.');
  12945. }
  12946. }
  12947. source() {
  12948. return this._source_view;
  12949. }
  12950. file_line_col() {
  12951. if (!this._source_view || this.source().filename() === null) {
  12952. return null;
  12953. }
  12954. const lineno = this._source_view.lineno_for_offset(this._start);
  12955. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  12956. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  12957. }
  12958. start() {
  12959. return this._start;
  12960. }
  12961. toString() {
  12962. const loc = this.file_line_col();
  12963. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  12964. }
  12965. });
  12966. this.registerType('torch._C.QualifiedName', class {
  12967. constructor(...args) {
  12968. let name = null;
  12969. if (args.length === 1 && typeof args[0] === 'string') {
  12970. [name] = args;
  12971. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  12972. name = args[0].join('.');
  12973. } else {
  12974. name = `${args[0].qualifiedName()}.${args[1]}`;
  12975. }
  12976. const index = name.lastIndexOf('.');
  12977. this._qualifiedName = name;
  12978. this._prefix = index === -1 ? '' : name.substring(0, index);
  12979. this._name = index === -1 ? name : name.substring(index + 1);
  12980. }
  12981. qualifiedName() {
  12982. return this._qualifiedName; // "foo.bar.baz"
  12983. }
  12984. prefix() {
  12985. return this._prefix; // "foo.bar"
  12986. }
  12987. name() {
  12988. return this._name; // "baz"
  12989. }
  12990. atoms() {
  12991. return this._qualifiedName.split('.');
  12992. }
  12993. });
  12994. this.registerType('torch._C.Resolver', class {
  12995. resolveValue() {
  12996. throw new python.Error('Not implemented.');
  12997. }
  12998. resolveType() {
  12999. throw new python.Error('Not implemented.');
  13000. }
  13001. });
  13002. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13003. torch._C.customClasses = torch._C.customClasses || new Map();
  13004. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13005. const name = class_type.name().qualifiedName();
  13006. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13007. torch._C.customClasses.set(name, class_type);
  13008. });
  13009. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13010. torch._C.customClasses = torch._C.customClasses || new Map();
  13011. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13012. return ret;
  13013. });
  13014. this.registerFunction('torch._C.isCustomClass', (v) => {
  13015. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13016. });
  13017. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13018. constructor(cu, constant_table, source_loader, version) {
  13019. super();
  13020. this._cu = cu;
  13021. this._constant_table = constant_table;
  13022. this._source_loader = source_loader;
  13023. this._version = version;
  13024. this._loaded_sources = new Set();
  13025. this._sources = new Map();
  13026. const sources = this._sources;
  13027. ast.AST.prototype.range = function() {
  13028. if (!this._range) {
  13029. if (sources.has(this.filename)) {
  13030. const source_view = sources.get(this.filename);
  13031. this._range = new torch._C.SourceRange(source_view, this);
  13032. } else {
  13033. this._range = new torch._C.SourceRange();
  13034. }
  13035. }
  13036. return this._range;
  13037. };
  13038. this._to_be_defined = new Map();
  13039. this._env = new Map([
  13040. ['torch', new torch._C.BuiltinModule('aten', version)],
  13041. ['ops', new torch._C.OpsValue(version)],
  13042. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13043. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13044. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13045. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13046. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13047. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13048. ]);
  13049. }
  13050. loadType(name) {
  13051. const type_parser = new torch._C.ScriptTypeParser(this);
  13052. return type_parser.parseType(name.qualifiedName());
  13053. }
  13054. resolveType(name) {
  13055. name = new torch._C.QualifiedName(name);
  13056. return this.findNamedType(name);
  13057. }
  13058. resolveValue(name, m, loc) {
  13059. if (this._env.has(name)) {
  13060. return this._env.get(name);
  13061. }
  13062. const graph = m.graph();
  13063. switch (name) {
  13064. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13065. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13066. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13067. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13068. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13069. default: return null;
  13070. }
  13071. }
  13072. findNamedType(name) {
  13073. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13074. if (custom_class) {
  13075. return custom_class;
  13076. }
  13077. this.parseSourceIfNeeded(name.prefix());
  13078. const key = name.qualifiedName();
  13079. const it = this._to_be_defined.get(key);
  13080. if (it && it instanceof ast.ClassDef) {
  13081. this._to_be_defined.delete(key);
  13082. this.importNamedType(name.prefix(), it);
  13083. }
  13084. return this._cu.get_type(name);
  13085. }
  13086. importNamedType(qualifier, class_def) {
  13087. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13088. if (class_def.bases.length === 0) {
  13089. this.importClass(qualified_name, class_def, false);
  13090. return;
  13091. }
  13092. const superclass_name = class_def.bases[0].id;
  13093. if (superclass_name === 'Module') {
  13094. this.importClass(qualified_name, class_def, true);
  13095. } else if (superclass_name === 'NamedTuple') {
  13096. this.importNamedTuple(qualified_name, class_def);
  13097. } else if (superclass_name === 'Interface') {
  13098. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13099. } else if (superclass_name === 'ModuleInterface') {
  13100. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13101. } else if (superclass_name === 'Enum') {
  13102. this.importEnum(qualified_name, class_def);
  13103. } else {
  13104. throw new python.Error('TorchScript does not support class inheritance.');
  13105. }
  13106. }
  13107. importClass(qualified_classname, class_def, is_module) {
  13108. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13109. return;
  13110. }
  13111. const parameter_names = new Set();
  13112. const buffer_names = new Set();
  13113. const methods = [];
  13114. const method_resolvers = [];
  13115. const attributes = [];
  13116. const constants = [];
  13117. const pre_hook_names = new Set();
  13118. const pre_hook_def_map = new Map();
  13119. const hook_names = new Set();
  13120. const hook_def_map = new Map();
  13121. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13122. for (const stmt of class_def.body) {
  13123. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13124. let target = null;
  13125. let annotation = null;
  13126. let value = null;
  13127. if (stmt instanceof ast.Assign) {
  13128. [target] = stmt.targets;
  13129. value = stmt.value;
  13130. } else {
  13131. target = stmt.target;
  13132. annotation = stmt.annotation;
  13133. value = stmt.value;
  13134. }
  13135. if (target instanceof ast.Name) {
  13136. const name = this._cu.execution.identifier(target);
  13137. switch (name) {
  13138. case '__annotations__': {
  13139. continue;
  13140. }
  13141. case '__parameters__': {
  13142. for (const elt of value.elts) {
  13143. parameter_names.add(elt.value);
  13144. }
  13145. break;
  13146. }
  13147. case '__buffers__': {
  13148. for (const elt of value.elts) {
  13149. buffer_names.add(elt.value);
  13150. }
  13151. break;
  13152. }
  13153. case '__forward_pre_hooks__': {
  13154. for (const elt of value.elts) {
  13155. pre_hook_names.add(elt.value);
  13156. }
  13157. break;
  13158. }
  13159. case '__forward_hooks__': {
  13160. for (const elt of value.elts) {
  13161. hook_names.add(elt.value);
  13162. }
  13163. break;
  13164. }
  13165. default: {
  13166. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13167. if (fixed_up) {
  13168. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13169. } else if (value) {
  13170. constants.push({ name, value, annotation });
  13171. } else {
  13172. attributes.push({ name, value, annotation });
  13173. }
  13174. break;
  13175. }
  13176. }
  13177. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13178. const name = target.slice.value;
  13179. attributes.push({ name, value, annotation: stmt.value });
  13180. continue;
  13181. } else {
  13182. throw new python.Error('Unexpected statement kind in module metadata.');
  13183. }
  13184. } else if (stmt instanceof ast.FunctionDef) {
  13185. const def = stmt;
  13186. const def_name = def.name;
  13187. if (pre_hook_names.has(def_name)) {
  13188. pre_hook_def_map.set(def_name, def);
  13189. } else if (hook_names.has(def_name)) {
  13190. hook_def_map.set(def_name, def);
  13191. } else {
  13192. methods.push(def);
  13193. method_resolvers.push(this);
  13194. }
  13195. } else {
  13196. throw new python.Error('Unexpected statement kind in class body.');
  13197. }
  13198. }
  13199. const type_parser = new torch._C.ScriptTypeParser(this);
  13200. for (const assign of attributes) {
  13201. const name = assign.name;
  13202. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13203. const is_parameter = parameter_names.has(name);
  13204. const is_buffer = buffer_names.has(name);
  13205. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13206. }
  13207. for (const constant of constants) {
  13208. class_type.addConstant(constant.name, constant.value);
  13209. }
  13210. this._cu.register_type(class_type);
  13211. const self = new torch._C.SimpleSelf(class_type);
  13212. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13213. }
  13214. importEnum(qualified_name, enum_def) {
  13215. const names_values = [];
  13216. let value_type = null;
  13217. const set_or_check_type = (t) => {
  13218. if (!value_type) {
  13219. value_type = t;
  13220. } else if (value_type !== t) {
  13221. throw new python.Error('Enum class with varying value types are not supported.');
  13222. }
  13223. };
  13224. for (const stmt of enum_def.body) {
  13225. if (stmt instanceof ast.Assign === false) {
  13226. throw new python.Error('Unexpected statement in Enum class body.');
  13227. }
  13228. const assign = stmt;
  13229. const name = assign.targets[0].id;
  13230. let ivalue = null;
  13231. const rhs = assign.value;
  13232. switch (rhs.type) {
  13233. case 'str':
  13234. ivalue = new torch._C.IValue(rhs.value, 'String');
  13235. set_or_check_type(torch.StringType.get());
  13236. break;
  13237. case 'int':
  13238. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13239. set_or_check_type(torch.IntType.get());
  13240. break;
  13241. case 'float':
  13242. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13243. set_or_check_type(torch.FloatType.get());
  13244. break;
  13245. default:
  13246. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13247. }
  13248. names_values.push([name, ivalue]);
  13249. }
  13250. if (!value_type) {
  13251. throw new python.Error('No enum values defined.');
  13252. }
  13253. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13254. this._cu.register_type(enum_type);
  13255. }
  13256. importNamedTuple(qualified_name, named_tuple_def) {
  13257. const type_parser = new torch._C.ScriptTypeParser(this);
  13258. const field_names = [];
  13259. const field_types = [];
  13260. const field_defaults = [];
  13261. for (const stmt of named_tuple_def.body) {
  13262. if (stmt instanceof ast.AnnAssign === false) {
  13263. throw new python.Error('Unexpected statement in NamedTuple body.');
  13264. }
  13265. const assign = stmt;
  13266. const target = this._cu.execution.identifier(stmt.target);
  13267. // const annotation = this._cu.execution.type(stmt.annotation);
  13268. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13269. field_names.push(target);
  13270. // field_types.push(annotation);
  13271. field_types.push(type);
  13272. }
  13273. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13274. this._cu.register_type(tt);
  13275. }
  13276. importFunction(qualifier, def) {
  13277. const definitions = [def];
  13278. const resolvers = [this];
  13279. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13280. }
  13281. parseSourceIfNeeded(qualifier) {
  13282. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13283. return;
  13284. }
  13285. this._loaded_sources.add(qualifier);
  13286. const src = this._source_loader(qualifier);
  13287. if (!src) {
  13288. return;
  13289. }
  13290. this._sources.set(src.filename(), src);
  13291. const p = new torch._C.Parser(src);
  13292. const L = p.parse();
  13293. this.parsePossibleVersionNumber(p);
  13294. for (const stmt of L.body) {
  13295. if (stmt instanceof ast.ClassDef) {
  13296. const name = `${qualifier}.${stmt.name}`;
  13297. this._to_be_defined.set(name, stmt);
  13298. } else if (stmt instanceof ast.FunctionDef) {
  13299. const name = `${qualifier}.${stmt.name}`;
  13300. this._to_be_defined.set(name, stmt);
  13301. }
  13302. }
  13303. }
  13304. parsePossibleVersionNumber(/* p */) {
  13305. }
  13306. parseImports(/* p */) {
  13307. }
  13308. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13309. const replacements = new Map([
  13310. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13311. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13312. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13313. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13314. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13315. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13316. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13317. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13318. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13319. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13320. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13321. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13322. ]);
  13323. const mangleRe = /\.___torch_mangle_\d+/g;
  13324. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13325. if (replacements.has(demangled_classname)) {
  13326. const lhs = assign.target;
  13327. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13328. return null;
  13329. }
  13330. const type = assign.annotation.id;
  13331. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13332. if (lhs.id === attr_name && type === expected_type) {
  13333. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13334. const typename_expr = p.parseExp();
  13335. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13336. }
  13337. }
  13338. return null;
  13339. }
  13340. LEGACY_import_methods(mod, src) {
  13341. const self = new torch._C.SimpleSelf(mod.type());
  13342. const prefix = mod.type().name();
  13343. const p = new torch._C.Parser(src);
  13344. const L = p.parse();
  13345. this.parsePossibleVersionNumber(L);
  13346. this.parseImports(L);
  13347. const definitions = [];
  13348. const resolvers = [];
  13349. for (const def of L.body) {
  13350. if (def instanceof ast.FunctionDef) {
  13351. definitions.push(def);
  13352. resolvers.push(this);
  13353. }
  13354. }
  13355. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13356. }
  13357. findFunction(name) {
  13358. this.parseSourceIfNeeded(name.prefix());
  13359. const key = name.qualifiedName();
  13360. const it = this._to_be_defined.get(key);
  13361. if (it && it instanceof ast.FunctionDef) {
  13362. this._to_be_defined.delete(key);
  13363. this.importFunction(name.prefix(), it);
  13364. }
  13365. return this._cu.find_function(name);
  13366. }
  13367. });
  13368. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13369. constructor(otherResolver, functionTable) {
  13370. super();
  13371. this._otherResolver = otherResolver;
  13372. this._functionTable = functionTable;
  13373. }
  13374. resolveValue(name, m, loc) {
  13375. const it = this._functionTable.get(name);
  13376. if (it) {
  13377. return new torch._C.FunctionValue(it);
  13378. }
  13379. return this._otherResolver.resolveValue(name, m, loc);
  13380. }
  13381. resolveType(name, loc) {
  13382. return this._otherResolver.resolveType(name, loc);
  13383. }
  13384. });
  13385. this.registerType('torch._C.SourceRangeDeserializer', class {
  13386. constructor(text_table) {
  13387. this.cached_sources = new Map();
  13388. this._text_table = text_table || [];
  13389. }
  13390. deserialize(iv) {
  13391. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13392. const [file, start, end] = iv;
  13393. const source = this.deserialize_source(file);
  13394. return new torch._C.SourceRange(source, start, end);
  13395. }
  13396. deserialize_source(iv) {
  13397. const tup = iv;
  13398. if (this.cached_sources.has(tup)) {
  13399. return this.cached_sources.get(tup);
  13400. }
  13401. let source = null;
  13402. const tup_elems = tup;
  13403. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13404. if (this._text_table.length > 0) {
  13405. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13406. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13407. const filename = this._text_table[fnameIndex];
  13408. const pieces = [];
  13409. const strs = [];
  13410. for (const i of textIndex) {
  13411. pieces.push(this._text_table[i]);
  13412. strs.push(this._text_table[i]);
  13413. }
  13414. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13415. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13416. } else {
  13417. const [text, filename, starting_line_no] = tup_elems;
  13418. source = new torch._C.Source(text, filename, starting_line_no);
  13419. }
  13420. this.cached_sources.set(tup, source);
  13421. return source;
  13422. }
  13423. });
  13424. this.registerType('torch._C.SourceRangeUnpickler', class {
  13425. });
  13426. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13427. constructor (data) {
  13428. super();
  13429. this.data = data;
  13430. this.deserializer = null;
  13431. this.unpickled_records = null;
  13432. }
  13433. unpickle() {
  13434. if (this.unpickled_records) {
  13435. return;
  13436. }
  13437. const unpickler = new pickle.Unpickler(this.data);
  13438. const ivalues = unpickler.load();
  13439. torch._C.TORCH_CHECK(ivalues.length > 0);
  13440. this.unpickled_records = [];
  13441. let lines = null;
  13442. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13443. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13444. /* eslint-disable prefer-destructuring */
  13445. lines = ivalues[2];
  13446. /* eslint-enable prefer-destructuring */
  13447. } else {
  13448. this.deserializer = new torch._C.SourceRangeDeserializer();
  13449. lines = ivalues;
  13450. }
  13451. for (const tup_elems of lines) {
  13452. const [offset, range] = tup_elems;
  13453. const source_range = this.deserializer.deserialize(range);
  13454. this.unpickled_records.push([offset, source_range]);
  13455. }
  13456. }
  13457. findSourceRangeThatGenerated(range) {
  13458. this.unpickle();
  13459. const start = range.start();
  13460. const records = this.unpickled_records;
  13461. for (let i = 0; i < records.length; i++) {
  13462. const [offset, target] = records[i];
  13463. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13464. if (start >= offset && start < next) {
  13465. return target;
  13466. }
  13467. }
  13468. return null;
  13469. }
  13470. });
  13471. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13472. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13473. });
  13474. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13475. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13476. if (!reader.has_record(path)) {
  13477. return null;
  13478. }
  13479. const stream = reader.get_record(path);
  13480. let gen_ranges = null;
  13481. const debug_file = `${path}.debug_pkl`;
  13482. if (reader.has_record(debug_file)) {
  13483. const debug_stream = reader.get_record(debug_file);
  13484. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13485. }
  13486. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13487. });
  13488. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13489. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13490. this._compilation_unit = cu;
  13491. this._reader = reader;
  13492. this._storage_context = storage_context;
  13493. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13494. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13495. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13496. this._constant_table = [];
  13497. const SourceLoader = (qualifier) => {
  13498. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13499. };
  13500. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13501. }
  13502. deserialize() {
  13503. const execution = this._compilation_unit.execution;
  13504. const code_prefix = this._code_prefix;
  13505. for (const name of this._reader.get_all_records()) {
  13506. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13507. const file = name.substring(code_prefix.length);
  13508. const stream = this._reader.get_record(name);
  13509. const buffer = stream.peek();
  13510. execution.add(file, buffer);
  13511. }
  13512. }
  13513. const torch = execution.import('torch');
  13514. execution.builtins.torch = torch;
  13515. execution.builtins.Tensor = torch.Tensor;
  13516. execution.builtins.ops = torch.ops;
  13517. execution.builtins.inf = torch.inf;
  13518. execution.builtins.CONSTANTS = {};
  13519. execution._resolver = this._source_importer;
  13520. if (this._reader.has_record('model.json')) {
  13521. return this.LEGACY_deserialize();
  13522. }
  13523. const constants = this.readArchive('constants');
  13524. for (let i = 0; i < constants.length; i++) {
  13525. let val = constants[i];
  13526. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13527. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13528. const obj = torch.ScriptObject.create(type);
  13529. obj._ivalue = val;
  13530. val = obj;
  13531. }
  13532. execution.builtins.CONSTANTS[`c${i}`] = val;
  13533. this._constant_table.push(val);
  13534. }
  13535. const obj = this.readArchive('data');
  13536. const convertObject = (obj) => {
  13537. if (obj.__class__) {
  13538. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13539. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13540. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13541. for (let i = 0; i < type.numAttributes(); i++) {
  13542. const k = type.getAttributeName(i);
  13543. const t = type.getAttribute(i);
  13544. const v = obj[k];
  13545. if (t instanceof torch.ClassType) {
  13546. module.__setattr__(k, convertObject(v));
  13547. } else {
  13548. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13549. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13550. type._attributes[i].type = this._source_importer.resolveType(name);
  13551. }
  13552. module.__setattr__(k, obj[k]);
  13553. }
  13554. }
  13555. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13556. if (value && value.__class__ === builtins.method) {
  13557. module[key] = value;
  13558. }
  13559. }
  13560. return module;
  13561. }
  13562. throw new python.Error('Module class not found.');
  13563. };
  13564. return convertObject(obj);
  13565. }
  13566. LEGACY_deserialize() {
  13567. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13568. const execution = this._compilation_unit.execution;
  13569. const caffe2 = execution.proto.caffe2;
  13570. const torch = execution.import('torch');
  13571. const stream = this._reader.get_record('model.json');
  13572. const buffer = stream.peek();
  13573. const decoder = new TextDecoder('utf-8');
  13574. const content = decoder.decode(buffer);
  13575. const obj = JSON.parse(content);
  13576. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13577. const tensorTypeMap = new Map([
  13578. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13579. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13580. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13581. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13582. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13583. [caffe2.TensorProto.DataType.INT64, 'Long']
  13584. ]);
  13585. const tensor_table = (model.tensors || []).map((constant) => {
  13586. const key = constant.data.key;
  13587. if (!tensorTypeMap.has(constant.data_type)) {
  13588. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13589. }
  13590. const type = tensorTypeMap.get(constant.data_type);
  13591. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13592. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13593. const storage_type = execution.resolve(`torch.${type}Storage`);
  13594. const size = (shape || []).reduce((a, b) => a * b, 1);
  13595. const offset = parseInt(constant.offset, 10) || 0;
  13596. const storage = new storage_type(size);
  13597. const itemsize = storage.dtype.itemsize();
  13598. const stream = this._reader.get_record(key);
  13599. if (stream) {
  13600. const buffer = stream.peek();
  13601. const length = size * itemsize;
  13602. const data = buffer.slice(offset, offset + length);
  13603. storage._set_cdata(data);
  13604. }
  13605. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13606. tensor.name = key;
  13607. return tensor;
  13608. });
  13609. execution.builtins.CONSTANTS = {};
  13610. for (let i = 0; i < tensor_table.length; i++) {
  13611. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13612. }
  13613. const attributes = [];
  13614. if (this._reader.has_record('attributes.pkl')) {
  13615. const stream = this._reader.get_record('attributes.pkl');
  13616. const buffer = stream.peek();
  13617. const unpickler = new pickle.Unpickler(buffer);
  13618. const obj = unpickler.load();
  13619. attributes.push(...obj);
  13620. }
  13621. this._LEGACY_moduleStack = ['__torch__'];
  13622. const module_def = model.main_module;
  13623. for (const tensor of tensor_table) {
  13624. this._constant_table.push(tensor);
  13625. }
  13626. return this.LEGACY_convertModule(module_def);
  13627. }
  13628. LEGACY_convertModule(module_def) {
  13629. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13630. const numPushed = atoms.length;
  13631. for (const atom of atoms) {
  13632. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13633. this._LEGACY_moduleStack.push(sanitized);
  13634. }
  13635. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13636. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13637. for (const sub_def of module_def.submodules || []) {
  13638. const submodule = this.LEGACY_convertModule(sub_def);
  13639. module.register_module(sub_def.name, submodule);
  13640. }
  13641. for (const param_def of module_def.parameters || []) {
  13642. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13643. if (param_def.isBuffer) {
  13644. module.register_buffer(param_def.name, tensor);
  13645. } else {
  13646. module.register_parameter(param_def.name, tensor, false);
  13647. }
  13648. }
  13649. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13650. for (const attr_def of module_def.attributes || []) {
  13651. if (module.hasattr(attr_def.name)) {
  13652. continue;
  13653. }
  13654. throw new python.Error('Not implemented.');
  13655. // IValue ivalue;
  13656. // if (attr_def.id() >= 0) {
  13657. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13658. // }
  13659. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13660. }
  13661. if (module_def.torchscript_arena) {
  13662. const key = module_def.torchscript_arena.key;
  13663. const file = key.substring('code/'.length);
  13664. const name = file.replace(/\.py$/, '').split('/').join('.');
  13665. const code = execution.import(name);
  13666. if (code.forward.__class__ === execution.builtins.function) {
  13667. module.forward = code.forward;
  13668. }
  13669. }
  13670. // let gen_ranges = null;
  13671. if (module_def.torchscript_debug_arena) {
  13672. throw new python.Error('Not implemented.');
  13673. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13674. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13675. }
  13676. if (module_def.torchscript_arena) {
  13677. const filename = module_def.torchscript_arena.key;
  13678. const stream = this._reader.get_record(filename);
  13679. const data = stream.peek();
  13680. const src = new torch._C.Source(data, filename);
  13681. this._source_importer.LEGACY_import_methods(module, src);
  13682. }
  13683. if (module_def.get_state_attribute_id) {
  13684. throw new python.Error('Not implemented.');
  13685. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13686. }
  13687. /*
  13688. const module_type = module._ivalue().type();
  13689. const N = module_type.numAttributes();
  13690. for (let i = 0; i < N; ++i) {
  13691. const v = module._ivalue().getSlot(i);
  13692. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13693. torch._C.TORCH_CHECK(!v.isNone());
  13694. }
  13695. }
  13696. */
  13697. for (let i = 0; i < numPushed; i++) {
  13698. this._LEGACY_moduleStack.pop();
  13699. }
  13700. return module;
  13701. }
  13702. readArchive(archive_name) {
  13703. const type_resolver = (qn) => {
  13704. const cls = this._source_importer.loadType(qn);
  13705. return cls;
  13706. };
  13707. const ObjLoaderFunc = (/* type, ivalue */) => {
  13708. };
  13709. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13710. }
  13711. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13712. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13713. const stream = stream_reader.get_record(picklename);
  13714. if (!stream) {
  13715. throw new python.Error(`File '${picklename}' is not found.`);
  13716. }
  13717. const buffer = stream.peek();
  13718. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13719. const read_record = (name) => {
  13720. const stream = stream_reader.get_record(tensor_dir_path + name);
  13721. return stream.length <= 0x40000 ? stream.peek() : stream;
  13722. };
  13723. const execution = this._compilation_unit.execution;
  13724. const pickle = execution.__import__('pickle');
  13725. const Unpickler = class extends pickle.Unpickler {
  13726. find_class(module, name) {
  13727. return super.find_class(module, name);
  13728. }
  13729. };
  13730. const unpickler = new Unpickler(buffer);
  13731. unpickler.persistent_load = (saved_id) => {
  13732. if (saved_id[0] !== 'storage') {
  13733. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13734. }
  13735. const [, storage_type, key, , size] = saved_id;
  13736. if (storage_context && storage_context.has_storage(key)) {
  13737. return storage_context.get_storage(key);
  13738. }
  13739. const storage = new storage_type(size);
  13740. const storage_ptr = read_record(key);
  13741. storage._set_cdata(storage_ptr);
  13742. if (storage_context) {
  13743. storage_context.add_storage(key);
  13744. }
  13745. return storage;
  13746. };
  13747. return unpickler.load();
  13748. }
  13749. });
  13750. this.registerType('torch._C.WithInsertPoint', class {
  13751. constructor(...args) {
  13752. let n = null;
  13753. if (args.length === 1 && args[0] instanceof torch.Block) {
  13754. const [b] = args;
  13755. n = b.return_node();
  13756. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13757. [n] = args;
  13758. } else {
  13759. throw new python.Error('Invalid arguments.');
  13760. }
  13761. this._prev = n.owningGraph().insertPoint();
  13762. n.owningGraph().setInsertPoint(n);
  13763. }
  13764. dispose() {
  13765. this._prev.owningGraph().setInsertPoint(this._prev);
  13766. }
  13767. });
  13768. this.registerType('torch._C.Environment', class {
  13769. constructor(method, resolver, b, next) {
  13770. this.method = method;
  13771. this.resolver = resolver;
  13772. this.b = b;
  13773. this.next = next;
  13774. this.value_table = new Map();
  13775. this.type_table = new Map();
  13776. this.error_messages = new Map();
  13777. }
  13778. setVariableTypeError(name, msg) {
  13779. /* eslint-disable consistent-this */
  13780. let runner = this;
  13781. /* eslint-enable consistent-this */
  13782. while (runner.next) {
  13783. runner = runner.next;
  13784. }
  13785. runner.error_messages.set(name, msg);
  13786. }
  13787. insertLoad(name, type) {
  13788. const g = this.b.owningGraph();
  13789. const load = g.insertNode(g.createLoad(name, type));
  13790. if (torch._C.meaningfulName(name)) {
  13791. load.output().setDebugName(name);
  13792. }
  13793. return new torch._C.SimpleValue(load.output());
  13794. }
  13795. insertStore(name, loc, v, type) {
  13796. const g = this.b.owningGraph();
  13797. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  13798. this.type_table.set(name, type);
  13799. }
  13800. findInThisFrame(name) {
  13801. if (this.value_table.has(name)) {
  13802. return this.value_table.get(name);
  13803. }
  13804. if (this.type_table.has(name)) {
  13805. return this.insertLoad(name, this.type_table.get(name));
  13806. }
  13807. return null;
  13808. }
  13809. findInParentFrame(name) {
  13810. return this.next ? this.next.findInAnyFrame(name) : null;
  13811. }
  13812. setType(name, type) {
  13813. this.type_table.set(name, type);
  13814. }
  13815. findInAnyFrame(name) {
  13816. /* eslint-disable consistent-this */
  13817. const self = this;
  13818. /* eslint-enable consistent-this */
  13819. for (let runner = self; runner; runner = runner.next) {
  13820. const r = runner.findInThisFrame(name);
  13821. if (r) {
  13822. return r;
  13823. }
  13824. }
  13825. return null;
  13826. }
  13827. block() {
  13828. return this.b;
  13829. }
  13830. setVar(loc, name, value) {
  13831. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  13832. }
  13833. setSugaredVar(loc, name, value, annotated_type) {
  13834. let as_simple_value = torch._C.asSimple(value);
  13835. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  13836. as_simple_value.setDebugName(name);
  13837. }
  13838. const parent = this.findInParentFrame(name);
  13839. if (parent) {
  13840. if (annotated_type) {
  13841. throw new python.Error('Type already defined in an outer block.');
  13842. }
  13843. if (!as_simple_value) {
  13844. throw new python.Error('Only reassignments to first-class values are allowed.');
  13845. }
  13846. const simple_parent = torch._C.asSimple(parent);
  13847. if (!simple_parent) {
  13848. throw new python.Error('Only reassignments to first-class values are allowed.');
  13849. }
  13850. const parent_type = torch._C.unshapedType(simple_parent.type());
  13851. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  13852. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  13853. throw new python.Error('Incompatible types.');
  13854. }
  13855. }
  13856. if (as_simple_value) {
  13857. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  13858. throw new python.Error('Invalid type.');
  13859. }
  13860. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  13861. this.insertStore(name, loc, as_simple_value, value_store_type);
  13862. } else {
  13863. this.value_table.set(name, value);
  13864. }
  13865. }
  13866. getSugaredVar(ident, range, required) {
  13867. required = required || true;
  13868. let retval = this.findInAnyFrame(ident);
  13869. if (!retval) {
  13870. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  13871. ['print', new torch._C.PrintValue()],
  13872. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  13873. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  13874. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  13875. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  13876. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  13877. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  13878. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  13879. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  13880. ['range', torch._C.SpecialFormValue.create('prim::range')],
  13881. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  13882. ]);
  13883. if (torch._C.Environment.globals.has(ident)) {
  13884. retval = torch._C.Environment.globals.get(ident);
  13885. }
  13886. }
  13887. if (!retval) {
  13888. const type = this.resolver.resolveType(ident, range);
  13889. if (type instanceof torch.TupleType) {
  13890. retval = new torch.jit.NamedTupleConstructor(type);
  13891. }
  13892. }
  13893. if (!retval) {
  13894. retval = this.resolver.resolveValue(ident, this.method, range);
  13895. }
  13896. if (!retval) {
  13897. const type = this.resolver.resolveType(ident, range);
  13898. if (type instanceof torch.ClassType) {
  13899. retval = new torch.jit.ClassValue(type);
  13900. }
  13901. }
  13902. if (!retval && required) {
  13903. throw new python.Error(`The name '${ident}' is not defined.`);
  13904. }
  13905. return retval;
  13906. }
  13907. getVar(ident, range) {
  13908. return this.getSugaredVar(ident, range).asValue(range, this.method);
  13909. }
  13910. definedVariables() {
  13911. return Array.from(this.type_table.keys());
  13912. }
  13913. });
  13914. this.registerType('torch._C.Refinement', class {
  13915. constructor(identifier, type) {
  13916. this._identifier = identifier;
  13917. this._type = type;
  13918. }
  13919. identifier() {
  13920. return this._identifier;
  13921. }
  13922. type() {
  13923. return this._type;
  13924. }
  13925. });
  13926. this.registerType('torch._C.RefinementSet', class {
  13927. constructor(...args) {
  13928. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  13929. this._true_refinements = [args[0]];
  13930. this._false_refinements = [];
  13931. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  13932. this._true_refinements = [args[0]];
  13933. this._false_refinements = [args[1]];
  13934. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  13935. [this._true_refinements, this._false_refinements] = args;
  13936. } else {
  13937. throw new python.Error('Not implemented.');
  13938. }
  13939. }
  13940. Not() {
  13941. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  13942. }
  13943. activeRefinements() {
  13944. return this._true_refinements;
  13945. }
  13946. });
  13947. this.registerFunction('torch._C.CondValue', class {
  13948. constructor(...args) {
  13949. if (args.length === 3) {
  13950. [this._value, this._refinements, this._static_if] = args;
  13951. } else if (args.length === 4) {
  13952. const [g, loc, static_value, refinements] = args;
  13953. this._value = g.insertConstant(static_value, loc);
  13954. this._refinements = refinements;
  13955. this._static_if = static_value;
  13956. } else {
  13957. throw new python.Error('Invalid number of arguments.');
  13958. }
  13959. }
  13960. value() {
  13961. return this._value;
  13962. }
  13963. staticIf() {
  13964. return this._static_if;
  13965. }
  13966. refinements() {
  13967. return this._refinements;
  13968. }
  13969. });
  13970. this.registerFunction('torch._C.asSimple', (value) => {
  13971. if (value instanceof torch._C.SimpleValue) {
  13972. return value.getValue();
  13973. }
  13974. return null;
  13975. });
  13976. this.registerFunction('torch._C.isNumber', (str) => {
  13977. return /^[0-9]+$/.test(str);
  13978. });
  13979. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  13980. if (torch._C.isNumber(field)) {
  13981. return `_${field}`;
  13982. }
  13983. return field;
  13984. });
  13985. this.registerFunction('torch._C.meaningfulName', (name) => {
  13986. if (name.length === 0 && name[0] === '$') {
  13987. return false;
  13988. }
  13989. if (name[0] !== '_') {
  13990. return true;
  13991. }
  13992. return !/\d+/.test(name.slice(1));
  13993. });
  13994. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  13995. const key = `${val.value}:${val.tag}`;
  13996. const existing_constant = map.get(key);
  13997. if (existing_constant) {
  13998. return existing_constant;
  13999. }
  14000. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14001. const new_constant = graph.insertConstant(val, r);
  14002. map.set(key, new_constant);
  14003. guard.dispose();
  14004. return new_constant;
  14005. });
  14006. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14007. if (schema.overload_name) {
  14008. return `${schema.name}.${schema.overload_name}`;
  14009. }
  14010. return schema.name;
  14011. });
  14012. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14013. const value_map_func = (v) => value_map.get(v);
  14014. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14015. for (let i = 0; i < inputs.length; i++) {
  14016. value_map.set(callee.inputs()[i], inputs[i]);
  14017. }
  14018. for (const node of callee.nodes()) {
  14019. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14020. for (let i = 0; i < node.outputs().length; i++) {
  14021. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14022. }
  14023. }
  14024. const outputs = [];
  14025. for (const output of callee.outputs()) {
  14026. outputs.push(value_map_func(output));
  14027. }
  14028. return outputs;
  14029. });
  14030. this.registerType('TemplateEnv', class {
  14031. });
  14032. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14033. constructor() {
  14034. this.state = 'UNINITIALIZED';
  14035. this._builtins_by_name = new Map();
  14036. }
  14037. getAllBuiltinFunctionsFor(name) {
  14038. if (this.state === 'UNINITIALIZED') {
  14039. this.loadBuiltinFunctions();
  14040. this.state = 'INITIALIZED';
  14041. }
  14042. if (!this._builtins_by_name.has(name)) {
  14043. return [];
  14044. }
  14045. return this._builtins_by_name.get(name);
  14046. }
  14047. loadBuiltinFunctions() {
  14048. /*
  14049. for (const scalar of ['float', 'int', 'complex']) {
  14050. const env = new torch.C.TemplateEnv();
  14051. env.s('Scalar', scalar);
  14052. this.loadSource(scalar_operators_source.format(env), 'aten');
  14053. }
  14054. for (const scalar of ['float', 'int']) {
  14055. const env = new torch.C.TemplateEnv();
  14056. env.s('Scalar', scalar);
  14057. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14058. }
  14059. using str_pair = std::pair<std::string, std::string>;
  14060. const std::vector<str_pair> name_len = {
  14061. str_pair('single', '1'),
  14062. str_pair('pair', '2'),
  14063. str_pair('triple', '3'),
  14064. str_pair('quadruple', '4'),
  14065. };
  14066. for (const auto scalar : {'float', 'int'}) {
  14067. for (const auto& pair : name_len) {
  14068. const env = new torch.C.TemplateEnv();
  14069. env.s('Scalar', scalar);
  14070. env.s('name', pair.first);
  14071. env.s('Length', pair.second);
  14072. this.loadSource(_ntuple_ops.format(env), 'aten');
  14073. }
  14074. }
  14075. for (auto rhs : {'number', 'Tensor'}) {
  14076. at::jit::TemplateEnv env;
  14077. env.s('Rhs_Type', rhs);
  14078. this.loadSource(floordiv.format(env), 'aten');
  14079. }
  14080. this.loadSource(aten_ops, 'aten');
  14081. this.loadSource(aten_ops_additional, 'aten');
  14082. this.loadSource(tensor_properties, 'prim');
  14083. */
  14084. }
  14085. loadSource(/* source, the_namespace */) {
  14086. }
  14087. });
  14088. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14089. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14090. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14091. });
  14092. this.registerFunction('torch._C.get_operator_version_map', () => {
  14093. return new Map();
  14094. });
  14095. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14096. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14097. let arg_type = arg.type;
  14098. if (arg_type instanceof torch._C.DynamicType) {
  14099. arg_type = arg_type.fallback();
  14100. }
  14101. const argument_is_list = arg_type instanceof torch.ListType;
  14102. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14103. const arg_is_broadcasting_list = arg.N > 0;
  14104. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14105. });
  14106. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14107. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14108. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14109. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14110. return true;
  14111. }
  14112. return false;
  14113. });
  14114. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14115. if (opt_type instanceof torch._C.DynamicType) {
  14116. return torch._C.unwrapOptional(opt_type.fallback());
  14117. }
  14118. if (opt_type instanceof torch.OptionalType) {
  14119. return opt_type.getElementType();
  14120. }
  14121. return opt_type;
  14122. });
  14123. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14124. const possibleSchemas = [];
  14125. if (version === undefined) {
  14126. return possibleSchemas;
  14127. }
  14128. for (const entry of torch._C.get_operator_version_map()) {
  14129. const old_symbol_name = entry.first;
  14130. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14131. if (base_name === name) {
  14132. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14133. if (possibleUpgrader.has_value()) {
  14134. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14135. }
  14136. }
  14137. }
  14138. return possibleSchemas;
  14139. });
  14140. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14141. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14142. return current_version < latest_update;
  14143. });
  14144. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14145. const it = torch._C.get_operator_version_map().get(name);
  14146. if (it) {
  14147. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14148. }
  14149. return true;
  14150. });
  14151. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14152. if (values.length === 1) {
  14153. return values[0];
  14154. }
  14155. let named_tuple = null;
  14156. if (field_names) {
  14157. const types = values.map((v) => v.type());
  14158. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14159. }
  14160. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14161. });
  14162. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14163. const v_type = value.type();
  14164. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14165. return false;
  14166. }
  14167. const arg_type = torch._C.unwrapOptional(arg.type);
  14168. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14169. });
  14170. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14171. const list_type = list_type_;
  14172. if (list_type instanceof torch.ListType === false) {
  14173. return false;
  14174. }
  14175. if (type.isSubtypeOf(list_type_)) {
  14176. return true;
  14177. }
  14178. if (type instanceof torch.TupleType) {
  14179. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14180. }
  14181. return false;
  14182. });
  14183. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14184. for (let i = 0; i < kwargs.length; i++) {
  14185. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14186. return i;
  14187. }
  14188. if (kwargs[i].name() === name) {
  14189. return i;
  14190. }
  14191. }
  14192. return null;
  14193. });
  14194. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14195. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14196. const list_elements = [];
  14197. for (const named_value of varargs) {
  14198. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14199. if (!matched_value) {
  14200. return null;
  14201. }
  14202. list_elements.push(matched_value);
  14203. }
  14204. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14205. });
  14206. this.registerType('torch._C.MatchTypeReturn', class {
  14207. constructor(reason) {
  14208. this._reason = reason;
  14209. }
  14210. static Success() {
  14211. return new torch._C.MatchTypeReturn(null);
  14212. }
  14213. success() {
  14214. return this._reason === null;
  14215. }
  14216. });
  14217. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14218. if (!formal.hasFreeVariables()) {
  14219. if (formal instanceof torch._C.DynamicType) {
  14220. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14221. }
  14222. return torch._C.MatchTypeReturn.Success();
  14223. }
  14224. if (formal instanceof torch._C.VarType) {
  14225. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14226. if (it === null) {
  14227. type_env.set(formal.name(), actual);
  14228. return torch._C.MatchTypeReturn.Success();
  14229. } else if (torch._C.unifyTypes(it, actual)) {
  14230. return torch._C.MatchTypeReturn.Success();
  14231. }
  14232. return new torch._C.MatchTypeReturn('Cannot match var.');
  14233. } else if (formal instanceof torch.ListType) {
  14234. if (actual instanceof torch.ListType) {
  14235. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14236. if (!innerMatch.success()) {
  14237. return innerMatch;
  14238. }
  14239. return torch._C.MatchTypeReturn.Success();
  14240. } else if (actual instanceof torch.TupleType) {
  14241. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14242. if (maybe_tuple_unified) {
  14243. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14244. }
  14245. }
  14246. return new torch._C.MatchTypeReturn('Cannot match list.');
  14247. } else if (formal instanceof torch.TupleType) {
  14248. if (actual instanceof torch.TupleType) {
  14249. if (formal.elements().length !== actual.elements().length) {
  14250. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14251. }
  14252. for (let i = 0; i < formal.elements().length; i++) {
  14253. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14254. if (!result.success()) {
  14255. return result;
  14256. }
  14257. }
  14258. return torch._C.MatchTypeReturn.Success();
  14259. }
  14260. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14261. } else if (formal instanceof torch.FutureType) {
  14262. if (actual instanceof torch.FutureType) {
  14263. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14264. if (!innerMatch.success()) {
  14265. return innerMatch;
  14266. }
  14267. return torch._C.MatchTypeReturn.Success();
  14268. }
  14269. return new torch._C.MatchTypeReturn('Cannot match future.');
  14270. } else if (formal instanceof torch.AwaitType) {
  14271. if (actual instanceof torch.AwaitType) {
  14272. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14273. if (!innerMatch.success()) {
  14274. return innerMatch;
  14275. }
  14276. return torch._C.MatchTypeReturn.Success();
  14277. }
  14278. return new torch._C.MatchTypeReturn('Cannot match await.');
  14279. } else if (formal instanceof torch.RRefType) {
  14280. if (actual instanceof torch.RRefType) {
  14281. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14282. if (!innerMatch.success()) {
  14283. return innerMatch;
  14284. }
  14285. return torch._C.MatchTypeReturn.Success();
  14286. }
  14287. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14288. } else if (formal instanceof torch.OptionalType) {
  14289. if (actual instanceof torch.OptionalType) {
  14290. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14291. if (!optionedMatch.success()) {
  14292. return optionedMatch;
  14293. }
  14294. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14295. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14296. }
  14297. return torch._C.MatchTypeReturn.Success();
  14298. } else if (formal instanceof torch.DictType) {
  14299. if (actual instanceof torch.DictType) {
  14300. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14301. if (!key_match.success()) {
  14302. return key_match;
  14303. }
  14304. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14305. if (!value_match.success()) {
  14306. return value_match;
  14307. }
  14308. return torch._C.MatchTypeReturn.Success();
  14309. }
  14310. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14311. }
  14312. throw new python.Error('Unhandled free variable container.');
  14313. });
  14314. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14315. let value = named_value.value(graph);
  14316. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14317. const repeated = Array(arg.N).fill(value);
  14318. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14319. }
  14320. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14321. if (!matched.success()) {
  14322. if (failure_messages) {
  14323. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14324. }
  14325. return null;
  14326. }
  14327. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14328. if (!concrete_type) {
  14329. if (failure_messages) {
  14330. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14331. }
  14332. return null;
  14333. }
  14334. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14335. if (!value.type().isSubtypeOf(concrete_type)) {
  14336. if (failure_messages) {
  14337. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14338. }
  14339. return null;
  14340. }
  14341. return value;
  14342. });
  14343. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14344. if (concrete_type instanceof torch.OptionalType) {
  14345. const op = concrete_type;
  14346. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14347. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14348. }
  14349. }
  14350. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14351. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14352. }
  14353. if (value.type() instanceof torch.TupleType) {
  14354. const value_tuple = value.type();
  14355. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14356. const unpacked = torch._C.createTupleUnpack(value);
  14357. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14358. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14359. }
  14360. if (concrete_type instanceof torch.TupleType) {
  14361. const concrete_tuple = concrete_type;
  14362. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14363. concrete_tuple.elements().length === value_tuple.elements().length) {
  14364. const unpacked = torch._C.createTupleUnpack(value);
  14365. const converted = [];
  14366. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14367. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14368. }
  14369. value = graph.insertNode(graph.createTuple(converted)).output();
  14370. }
  14371. }
  14372. }
  14373. if (allow_conversions) {
  14374. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14375. const value_equals_number = value.type() === torch.NumberType.get();
  14376. const concrete_float = concrete_type === torch.FloatType.get();
  14377. const concrete_complex = concrete_type === torch.ComplexType.get();
  14378. const concrete_int = concrete_type === torch.IntType.get();
  14379. const concrete_number = concrete_type === torch.NumberType.get();
  14380. if (value_isa_tensor) {
  14381. if (concrete_float) {
  14382. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14383. } else if (concrete_complex) {
  14384. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14385. } else if (concrete_int) {
  14386. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14387. } else if (concrete_number) {
  14388. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14389. }
  14390. } else if (value_equals_number) {
  14391. if (concrete_float) {
  14392. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14393. } else if (concrete_complex) {
  14394. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14395. } else if (concrete_int) {
  14396. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14397. }
  14398. } else if (value.type() === torch.BoolType.get()) {
  14399. if (concrete_float) {
  14400. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14401. } else if (concrete_int || concrete_number) {
  14402. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14403. }
  14404. }
  14405. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14406. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14407. }
  14408. }
  14409. return value;
  14410. });
  14411. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14412. if (!type.hasFreeVariables()) {
  14413. if (type instanceof torch._C.DynamicType) {
  14414. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14415. }
  14416. return type;
  14417. }
  14418. if (type instanceof torch._C.VarType) {
  14419. return type_env.get(type.annotation_str);
  14420. }
  14421. const contained = type.containedTypes();
  14422. if (contained.length === 0) {
  14423. return type;
  14424. }
  14425. const new_contained = [];
  14426. for (const t of contained) {
  14427. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14428. if (!r) {
  14429. return null;
  14430. }
  14431. new_contained.push(r);
  14432. }
  14433. return type.withContained(new_contained);
  14434. });
  14435. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14436. if (torch._C.isBlockListedSchema(schema)) {
  14437. return null;
  14438. }
  14439. const err = null;
  14440. const type_env = new Map();
  14441. const positional_inputs = [];
  14442. const used_kwarg = kwargs.map(() => false);
  14443. const is_aten = schema.name.startsWith('aten::');
  14444. let used_args = 0;
  14445. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14446. const arg = schema.arguments[schema_i];
  14447. let actual_named_value = null;
  14448. if (arg.name === 'self' && self) {
  14449. actual_named_value = self;
  14450. self = null;
  14451. } else if (!arg.kwarg_only && used_args < args.length) {
  14452. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14453. const value = args[used_args].value(graph);
  14454. const actual_type = value.type();
  14455. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14456. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14457. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14458. if (!list) {
  14459. return null;
  14460. }
  14461. used_args = args.length;
  14462. positional_inputs.push(list);
  14463. continue;
  14464. }
  14465. }
  14466. actual_named_value = args[used_args];
  14467. used_args++;
  14468. } else {
  14469. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14470. if (Number.isInteger(kwarg_idx)) {
  14471. const nv = kwargs[kwarg_idx];
  14472. if (used_kwarg[kwarg_idx]) {
  14473. if (failure_messages) {
  14474. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14475. }
  14476. return null;
  14477. }
  14478. used_kwarg[kwarg_idx] = true;
  14479. actual_named_value = nv;
  14480. } else if (arg.has_default_value()) {
  14481. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14482. } else {
  14483. if (failure_messages) {
  14484. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14485. }
  14486. return null;
  14487. }
  14488. }
  14489. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14490. if (!positional) {
  14491. return null;
  14492. }
  14493. positional_inputs.push(positional);
  14494. }
  14495. if (self !== null) {
  14496. if (failure_messages) {
  14497. throw new python.Error('Provided self argument not used in schema.');
  14498. }
  14499. return null;
  14500. }
  14501. if (schema.is_vararg) {
  14502. for (; used_args < args.length; used_args++) {
  14503. positional_inputs.push(args[used_args].value(graph));
  14504. }
  14505. }
  14506. if (used_args < args.length) {
  14507. if (failure_messages) {
  14508. throw new python.Error('Too many positional arguments.');
  14509. }
  14510. return null;
  14511. }
  14512. for (let i = 0; i < kwargs.length; i++) {
  14513. const nv = kwargs[i];
  14514. if (!used_kwarg[i]) {
  14515. if (failure_messages) {
  14516. if (schema.argumentIndexWithName(nv.name()) === null) {
  14517. throw new python.Error('Keyword argument unknown.');
  14518. } else {
  14519. throw new python.Error('Keyword argument specified twice.');
  14520. }
  14521. }
  14522. return null;
  14523. }
  14524. }
  14525. const returns = schema.returns;
  14526. const return_types = returns.map((r) => {
  14527. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14528. if (!result) {
  14529. throw new python.Error('Unbound type variable.');
  14530. }
  14531. return result;
  14532. });
  14533. const return_has_field_names = returns.every((r) => !r.name);
  14534. let return_field_names = null;
  14535. if (return_has_field_names) {
  14536. return_field_names = returns.map((r) => r.name);
  14537. }
  14538. const schema_name = torch._C.getFullSchemaName(schema);
  14539. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14540. });
  14541. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14542. self = self || null;
  14543. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14544. if (result) {
  14545. return result;
  14546. }
  14547. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14548. });
  14549. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14550. self = self || null;
  14551. render_errors = render_errors || false;
  14552. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14553. if (schemas.length === 1) {
  14554. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14555. }
  14556. for (const allow_conversions of [false, true]) {
  14557. for (let i = 0; i < schemas.length; i++) {
  14558. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14559. if (matched_schema) {
  14560. return [i, matched_schema];
  14561. }
  14562. }
  14563. }
  14564. if (!render_errors) {
  14565. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14566. }
  14567. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14568. });
  14569. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14570. const variants = torch._C.getAllOperatorsFor(name);
  14571. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14572. const graph_version = graph.get_op_version();
  14573. const schemas = [];
  14574. const upgrader_schemas = [];
  14575. for (const op of variants) {
  14576. let found_upgrader = false;
  14577. const op_name = torch._C.getFullSchemaName(op.schema());
  14578. if (Number.isInteger(graph_version)) {
  14579. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14580. if (version_entry) {
  14581. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14582. if (old_schema_entry.has_value()) {
  14583. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14584. upgrader_schemas.push(old_schema);
  14585. found_upgrader = true;
  14586. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14587. throw new python.Error('Valid upgrader must be present.');
  14588. }
  14589. }
  14590. }
  14591. if (!found_upgrader) {
  14592. schemas.push(op.schema());
  14593. }
  14594. }
  14595. if (variants.length === 0) {
  14596. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14597. for (const old_schema_entry of oldSchemas) {
  14598. const old_schema = torch._C.parseSchema(old_schema_entry);
  14599. upgrader_schemas.push(old_schema);
  14600. }
  14601. }
  14602. for (const schema of upgrader_schemas) {
  14603. schemas.push(schema);
  14604. }
  14605. for (const method of builtin_functions) {
  14606. method.ensure_defined();
  14607. schemas.push(method.getSchema());
  14608. }
  14609. if (schemas.length === 0) {
  14610. const user_function_name = name;
  14611. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  14612. }
  14613. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14614. if (matched[0] < variants.length + upgrader_schemas.length) {
  14615. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14616. }
  14617. const fn = builtin_functions[matched.first - variants.size()];
  14618. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14619. });
  14620. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14621. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14622. for (const ret of matched_schema.return_types) {
  14623. n.addOutput().setType(ret);
  14624. }
  14625. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14626. n.getOperation();
  14627. } else {
  14628. n.setHistoricSchemaName(matched_schema.schema_name);
  14629. }
  14630. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14631. });
  14632. this.registerFunction('torch._C.unshapedType', (type) => {
  14633. if (type.isSubtypeOf(torch.TensorType.get())) {
  14634. return torch.TensorType.get();
  14635. }
  14636. const contained = type.containedTypes();
  14637. if (contained.length === 0) {
  14638. return type;
  14639. }
  14640. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14641. });
  14642. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14643. default_to_union = default_to_union || false;
  14644. type_hint = type_hint || null;
  14645. if (t1.isSubtypeOf(t2)) {
  14646. return t2;
  14647. } else if (t2.isSubtypeOf(t1)) {
  14648. return t1;
  14649. }
  14650. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14651. return t1.merge(t2);
  14652. }
  14653. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14654. return torch.OptionalType.create(t2);
  14655. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14656. return torch.OptionalType.create(t1);
  14657. }
  14658. if (t1 instanceof torch.OptionalType) {
  14659. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14660. if (elem) {
  14661. return torch.OptionalType.create(elem);
  14662. }
  14663. } else if (t2 instanceof torch.OptionalType) {
  14664. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14665. if (elem) {
  14666. return torch.OptionalType.create(elem);
  14667. }
  14668. }
  14669. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14670. if (t1.elements().size() !== t2.elements().size()) {
  14671. return null;
  14672. }
  14673. const elements = [];
  14674. for (let i = 0; i < t1.elements().length; i++) {
  14675. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14676. if (elem) {
  14677. elements.push(elem);
  14678. } else {
  14679. return null;
  14680. }
  14681. }
  14682. return torch.TupleType.create(elements);
  14683. }
  14684. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14685. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14686. if (elem) {
  14687. return torch.FutureType.create(elem);
  14688. }
  14689. }
  14690. const t1_unshaped = torch._C.unshapedType(t1);
  14691. const t2_unshaped = torch._C.unshapedType(t2);
  14692. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14693. return t2_unshaped;
  14694. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14695. return t1_unshaped;
  14696. }
  14697. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14698. return type_hint;
  14699. }
  14700. return null;
  14701. });
  14702. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14703. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14704. if (default_to_union && !unified) {
  14705. return torch.UnionType.create([t1, t2]);
  14706. }
  14707. return unified;
  14708. });
  14709. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14710. if (elements.length === 0) {
  14711. return null;
  14712. }
  14713. let [ret_type] = elements;
  14714. for (let i = 1; i < elements.length && ret_type; i++) {
  14715. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14716. if (!maybe_unified) {
  14717. return null;
  14718. }
  14719. ret_type = maybe_unified;
  14720. }
  14721. return ret_type;
  14722. });
  14723. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14724. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14725. });
  14726. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14727. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14728. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14729. ivalue.isDevice() || ivalue.isEnum()) {
  14730. return true;
  14731. }
  14732. if (ivalue.isTensor()) {
  14733. return torch._C.insertableTensor(ivalue.toTensor());
  14734. }
  14735. if (ivalue.isList() || ivalue.isTuple()) {
  14736. let elems = [];
  14737. if (ivalue.isTuple()) {
  14738. elems = ivalue.toTupleRef().elements();
  14739. } else {
  14740. elems = ivalue.toListRef();
  14741. }
  14742. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14743. }
  14744. if (ivalue.isGenericDict()) {
  14745. const dict = ivalue.toGenericDict();
  14746. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14747. }
  14748. return false;
  14749. });
  14750. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14751. loc = loc || null;
  14752. scope = scope || null;
  14753. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14754. if (value !== undefined) {
  14755. return value;
  14756. }
  14757. throw new python.Error('Unsupported value kind.');
  14758. });
  14759. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14760. if (val instanceof torch._C.IValue) {
  14761. const n = g.create('prim::Constant');
  14762. if (val.isTensor()) {
  14763. const ref = val.toTensor();
  14764. if (!torch._C.insertableTensor(val.toTensor())) {
  14765. n.destroy();
  14766. return null;
  14767. }
  14768. if (!ref.defined()) {
  14769. n.destroy();
  14770. return g.insertNode(g.createNone()).output();
  14771. }
  14772. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  14773. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  14774. n.t_('value', ref);
  14775. } else if (val.isInt()) {
  14776. n.i_('value', val.toInt());
  14777. n.output().setType(torch.IntType.get());
  14778. } else if (val.isDouble()) {
  14779. n.f_('value', val.toDouble());
  14780. n.output().setType(torch.FloatType.get());
  14781. } else if (val.isComplexDouble()) {
  14782. n.c_('value', val.toComplexDouble());
  14783. n.output().setType(torch.ComplexType.get());
  14784. } else if (val.isBool()) {
  14785. n.i_('value', val.toBool());
  14786. n.output().setType(torch.BoolType.get());
  14787. } else if (val.isList()) {
  14788. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  14789. if (fast_path_list || torch._C.insertableIValue(val)) {
  14790. n.ival_('value', val);
  14791. n.output().setType(val.type());
  14792. } else {
  14793. n.destroy();
  14794. return null;
  14795. }
  14796. } else if (val.isString()) {
  14797. n.s_('value', val.toStringRef());
  14798. n.output().setType(torch.StringType.get());
  14799. } else if (val.isDevice()) {
  14800. n.s_('value', val.toDevice().__str__());
  14801. n.output().setType(torch.DeviceObjType.get());
  14802. } else if (val.isGenerator()) {
  14803. n.ival_('value', val.toGenerator());
  14804. n.output().setType(torch._C_._GeneratorType.get());
  14805. } else if (val.isStream()) {
  14806. n.ival_('value', val);
  14807. n.output().setType(torch.StreamObjType.get());
  14808. } else if (val.isNone()) {
  14809. n.output().setType(torch.NoneType.get());
  14810. // n.ival_('value', null); // remove
  14811. } else if (val.isTuple()) {
  14812. if (torch._C.insertableIValue(val)) {
  14813. n.ival_('value', val);
  14814. n.output().setType(val.type());
  14815. } else {
  14816. n.destroy();
  14817. return null;
  14818. }
  14819. } else if (val.isObject()) {
  14820. const ref = val.toObjectRef();
  14821. // see: [Constant Object Weak CompilationUnit Reference]
  14822. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  14823. n.ival_('value', val);
  14824. n.output().setType(val.type());
  14825. } else {
  14826. n.destroy();
  14827. return null;
  14828. }
  14829. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  14830. n.ival_('value', val);
  14831. n.output().setType(val.type());
  14832. } else {
  14833. n.destroy();
  14834. return null;
  14835. }
  14836. if (loc) {
  14837. n.setSourceRange(loc);
  14838. }
  14839. if (scope) {
  14840. n.setScope(scope);
  14841. }
  14842. return g.insertNode(n).output();
  14843. }
  14844. const n = g.create('prim::Constant');
  14845. let type = null;
  14846. if (val === null) {
  14847. n.ival_('value', val);
  14848. type = torch.NoneType.get();
  14849. } else if (typeof val === 'string') {
  14850. n.s_('value', val);
  14851. type = torch.StringType.get();
  14852. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  14853. n.ss_('value', val);
  14854. type = torch.ListType.create(torch.StringType.get());
  14855. } else if (typeof val === 'boolean') {
  14856. n.i_('value', val === true ? 1 : 0);
  14857. type = torch.BoolType.get();
  14858. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  14859. n.i_('value', val);
  14860. type = torch.IntType.get();
  14861. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  14862. n.f_('value', val);
  14863. type = torch.FloatType.get();
  14864. } else if (val instanceof torch.Tensor) {
  14865. n.t_('value', val);
  14866. type = torch.TensorType.get();
  14867. } else if (val instanceof torch.ScriptObject) {
  14868. n.ival_('value', val);
  14869. type = val.type();
  14870. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  14871. n.ival_('value', val);
  14872. type = torch.ListType.create(torch.IntType.get());
  14873. } else {
  14874. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  14875. }
  14876. if (type) {
  14877. n.output().setType(type);
  14878. }
  14879. if (loc) {
  14880. n.setSourceRange(loc);
  14881. }
  14882. if (scope) {
  14883. n.setScope(scope);
  14884. }
  14885. return g.insertNode(n).output();
  14886. });
  14887. this.registerFunction('torch._C.toIValue', (v) => {
  14888. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  14889. return null;
  14890. }
  14891. const node = v.node();
  14892. const type = v.type();
  14893. if (type.isSubtypeOf(torch.TensorType.get())) {
  14894. return new torch._C.IValue(node.t('value'), 'Tensor');
  14895. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  14896. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  14897. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  14898. return new torch._C.IValue(node.i('value'), 'Int');
  14899. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  14900. return new torch._C.IValue(node.f('value'), 'Double');
  14901. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'c') {
  14902. return new torch._C.IValue(node.c('value'), 'Complex');
  14903. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  14904. let list = node.ival('value');
  14905. list = list.isList ? list : new torch._C.IValue(list); // remove
  14906. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  14907. return list;
  14908. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  14909. const dict = node.ival('value');
  14910. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  14911. return dict;
  14912. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  14913. const tup = node.ival('value');
  14914. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  14915. return tup;
  14916. } else if (type === torch.StringType.get()) {
  14917. const s = new torch._C.IValue(node.s('value'), 'String');
  14918. return s;
  14919. } else if (type === torch.DeviceObjType.get()) {
  14920. const d = new torch.device(node.s('value'));
  14921. return new torch._C.IValue(d);
  14922. } else if (type === torch._C._GeneratorType.get()) {
  14923. throw new python.Error('Not implemented.');
  14924. // const generator = node.ival('value').toGenerator();
  14925. // return generator;
  14926. } else if (type === torch.StreamObjType.get()) {
  14927. throw new python.Error('Not implemented.');
  14928. // const s = node.ival('value').toStream();
  14929. // return s;
  14930. } else if (node.mustBeNone()) {
  14931. return new torch._C.IValue();
  14932. } else if (type.kind() === 'EnumType') {
  14933. const enum_val = node.ival('value');
  14934. return enum_val;
  14935. } else if (type instanceof torch.ClassType && !type.is_module()) {
  14936. const class_val = node.ival('value');
  14937. return new torch._C.IValue(class_val, 'Object');
  14938. }
  14939. throw new python.Error('Unsupported constant literal.');
  14940. });
  14941. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  14942. const ivalue = torch._C.toIValue(v);
  14943. if (ivalue) {
  14944. return ivalue[target]();
  14945. }
  14946. return default_value === undefined ? null : default_value;
  14947. });
  14948. this.registerType('torch._C.NamedValue', class {
  14949. constructor(...args) {
  14950. if (args.length === 1) {
  14951. if (args[0] instanceof torch.Value) {
  14952. [this._value] = args;
  14953. } else {
  14954. [this._ivalue] = args;
  14955. }
  14956. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  14957. [this._loc, this._name, this._value] = args;
  14958. } else {
  14959. throw new python.Error('Invalid argument.');
  14960. }
  14961. }
  14962. name() {
  14963. return this._name;
  14964. }
  14965. value(g) {
  14966. if (!this._value) {
  14967. return torch._C.insertConstant(g, this._ivalue);
  14968. }
  14969. return this._value;
  14970. }
  14971. type() {
  14972. if (this._value) {
  14973. return this._value.type();
  14974. }
  14975. return this._ivalue.type();
  14976. }
  14977. });
  14978. this.registerType('torch._C.SugaredValue', class {
  14979. kind() {
  14980. throw new python.Error('Not implemented.');
  14981. }
  14982. shouldEmitUnrolled() {
  14983. return this.staticLen() !== null;
  14984. }
  14985. });
  14986. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  14987. constructor(value) {
  14988. super();
  14989. this._value = value;
  14990. }
  14991. kind() {
  14992. return `value of type '${this._value.type().annotation_str}'`;
  14993. }
  14994. asValue(/* range, m */) {
  14995. return this._value;
  14996. }
  14997. getValue() {
  14998. return this._value;
  14999. }
  15000. asTuple(loc, m, size_hint) {
  15001. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15002. if (this._value.type() instanceof torch.TupleType) {
  15003. const outputs = torch._C.createTupleUnpack(this._value);
  15004. return outputs.map((v) => make_simple_value(v));
  15005. } else if (this._value.type() instanceof torch.ListType) {
  15006. if (!size_hint) {
  15007. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15008. }
  15009. const graph = this._value.owningGraph();
  15010. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15011. return unpack.outputs().map((v) => make_simple_value(v));
  15012. } else if (this._value.type().kind() === 'AnyTupleType') {
  15013. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15014. }
  15015. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15016. }
  15017. attr(loc, m, field) {
  15018. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15019. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15020. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15021. }
  15022. }
  15023. if (this._value.type() instanceof torch.TupleType) {
  15024. throw new python.Error('Not implemented.');
  15025. }
  15026. if (this._value.type() instanceof torch.AwaitType) {
  15027. throw new python.Error('Not implemented.');
  15028. }
  15029. if (this._value.type() instanceof torch.ClassType) {
  15030. const classType = this._value.type();
  15031. if (classType.findMethod(field)) {
  15032. return new torch._C.MethodValue(this.getValue(), [field]);
  15033. }
  15034. if (classType.hasAttribute(field)) {
  15035. const g = m.graph();
  15036. const n = g.insertNode(g.createGetAttr(this._value, field));
  15037. return new torch._C.SimpleValue(n.output());
  15038. }
  15039. const prop = classType.getProperty(field);
  15040. if (prop) {
  15041. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15042. }
  15043. } else if (this._value.type() instanceof torch.InterfaceType) {
  15044. throw new python.Error('Not implemented.');
  15045. } else if (this._value.type() instanceof torch.EnumType) {
  15046. const g = m.graph();
  15047. if (field === 'name') {
  15048. const n = g.insertNode(g.createEnumName(this._value));
  15049. return new torch._C.SimpleValue(n.output());
  15050. }
  15051. if (field === 'value') {
  15052. const n = g.insertNode(g.createEnumValue(this._value));
  15053. return new torch._C.SimpleValue(n.output());
  15054. }
  15055. }
  15056. if (field === 'type') {
  15057. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15058. if (builtin) {
  15059. return builtin;
  15060. }
  15061. }
  15062. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15063. if (builtin) {
  15064. return builtin;
  15065. }
  15066. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15067. return torch._C.SpecialFormValue.create('prim::tolist');
  15068. }
  15069. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15070. return torch._C.SpecialFormValue.create('aten::index');
  15071. }
  15072. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15073. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15074. if (builtin) {
  15075. return builtin;
  15076. }
  15077. }
  15078. throw new python.Error('Object has no attribute or method.');
  15079. }
  15080. setAttr(loc, m, field, newValue) {
  15081. const type = this._value.type();
  15082. if (type instanceof torch.ClassType === false) {
  15083. throw new python.Error('Cannot set attribute on non-class type.');
  15084. }
  15085. const classType = type;
  15086. let expectedType = classType.findAttribute(field);
  15087. if (!expectedType) {
  15088. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15089. if (isInitializing) {
  15090. if (this.isRecursive(classType, newValue.type())) {
  15091. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15092. }
  15093. classType.addAttribute(field, newValue.type());
  15094. expectedType = newValue.type();
  15095. const insertPoint = m.graph().insertPoint();
  15096. const topLevelBlock = m.graph().block();
  15097. if (insertPoint.owningBlock() !== topLevelBlock) {
  15098. throw new python.Error('First assignment cannot be in a control-flow block.');
  15099. }
  15100. } else {
  15101. const prop = classType.getProperty(field);
  15102. if (prop && prop.setter) {
  15103. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15104. return;
  15105. }
  15106. if (prop && !prop.setter) {
  15107. throw new python.Error('Tried to set read-only attribute.');
  15108. }
  15109. throw new python.Error('Tried to set nonexistent attribute.');
  15110. }
  15111. }
  15112. torch._C.AT_ASSERT(expectedType);
  15113. const newType = newValue.type();
  15114. if (!newType.isSubtypeOf(expectedType)) {
  15115. throw new python.Error('Wrong type for attribute assignment.');
  15116. }
  15117. const g = m.graph();
  15118. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15119. }
  15120. getitem(loc, m, idx, type_hint) {
  15121. const val = this.getValue();
  15122. const val_type = val.type();
  15123. const g = m.graph();
  15124. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15125. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15126. } else if (val_type instanceof torch.DictType) {
  15127. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15128. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15129. 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));
  15130. } else if (val_type instanceof torch.ClassType) {
  15131. const class_type = val_type;
  15132. if (class_type.is_module() && type_hint) {
  15133. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15134. res.setType(type_hint);
  15135. return new torch._C.SimpleValue(res);
  15136. }
  15137. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15138. }
  15139. throw new python.Error('Object is not subscriptable.');
  15140. }
  15141. });
  15142. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15143. constructor(self, method_names) {
  15144. super();
  15145. this._self = self;
  15146. this._method_names = method_names;
  15147. }
  15148. call(loc, f, args, kwargs /*, n_binders */) {
  15149. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15150. const schemas = [];
  15151. for (const method_name of this._method_names) {
  15152. const type = this._self.type();
  15153. if (type instanceof torch.ClassType) {
  15154. const class_type = type;
  15155. const method = class_type.getMethod(method_name);
  15156. method.ensure_defined();
  15157. schemas.push(method.getSchema());
  15158. } else if (type instanceof torch.InterfaceType) {
  15159. const interface_type = type;
  15160. schemas.push(interface_type.getMethod(method_name));
  15161. } else {
  15162. throw new python.Error('Method constructed that is not a class or interface.');
  15163. }
  15164. }
  15165. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15166. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15167. output.node().setSourceRange(loc);
  15168. return new torch._C.SimpleValue(output);
  15169. }
  15170. });
  15171. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15172. constructor(type) {
  15173. super();
  15174. this._type = type;
  15175. }
  15176. attr(loc, m, field) {
  15177. const hook = this._type.findHook(field);
  15178. if (hook) {
  15179. return new torch._C.FunctionValue(hook);
  15180. }
  15181. if (field !== '__new__') {
  15182. throw new python.Error('Tried to lookup unknown attribute on class.');
  15183. }
  15184. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15185. }
  15186. });
  15187. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15188. constructor(type) {
  15189. super();
  15190. this._type = type;
  15191. }
  15192. call(loc, m, args, kwargs /*, n_binders */) {
  15193. const g = m.graph();
  15194. const schema = this._type.schema();
  15195. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15196. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15197. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15198. self.setType(this._type);
  15199. return new torch._C.SimpleValue(self);
  15200. }
  15201. });
  15202. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15203. constructor(enum_type) {
  15204. super();
  15205. this._enum_type = enum_type;
  15206. }
  15207. attr(loc, m, field) {
  15208. const names_values = this._enum_type.enumNamesValues();
  15209. const it = names_values.find((nv) => nv[0] === field);
  15210. if (it === null) {
  15211. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15212. }
  15213. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15214. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15215. }
  15216. });
  15217. this.registerType('torch._C.EnumHolder', class {
  15218. constructor(type, name, value) {
  15219. this._type = type;
  15220. this._name = name;
  15221. this._value = value;
  15222. }
  15223. name() {
  15224. return this._name;
  15225. }
  15226. type() {
  15227. return this._type;
  15228. }
  15229. });
  15230. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15231. constructor(...args) {
  15232. super();
  15233. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15234. this._callees = [args[0]];
  15235. } else {
  15236. throw new python.Error('Not implemented.');
  15237. }
  15238. }
  15239. call(loc, f, args, kwargs /*, n_binders */) {
  15240. const schemas = [];
  15241. for (const callee of this._callees) {
  15242. callee.ensure_defined();
  15243. schemas.push(callee.getSchema());
  15244. }
  15245. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15246. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15247. output.node().setSourceRange(loc);
  15248. return new torch._C.SimpleValue(output);
  15249. }
  15250. });
  15251. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15252. });
  15253. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15254. call(loc, m, args, kwargs /*, n_binders */) {
  15255. const g = m.graph();
  15256. if (kwargs.length > 0) {
  15257. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15258. }
  15259. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15260. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15261. return new torch._C.NoneValue();
  15262. }
  15263. });
  15264. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15265. constructor(form) {
  15266. super();
  15267. this._form = form;
  15268. }
  15269. form() {
  15270. return this._form;
  15271. }
  15272. static create(form) {
  15273. return new torch._C.SpecialFormValue(form);
  15274. }
  15275. });
  15276. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15277. return new torch._C.MagicMethod(name, base);
  15278. });
  15279. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15280. constructor(symbol, self) {
  15281. super();
  15282. this.symbol = symbol;
  15283. this.self = self;
  15284. }
  15285. call(loc, m, args, kwargs /*, n_binders */) {
  15286. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15287. }
  15288. static tryCreate(symbol, self) {
  15289. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15290. if (!self) {
  15291. return new torch._C.BuiltinFunction(symbol, null);
  15292. }
  15293. const index = op.schema().argumentIndexWithName('self');
  15294. if (index) {
  15295. const type_env = new Map();
  15296. const formal_type = op.schema().arguments()[index].type();
  15297. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15298. if (!matched.success()) {
  15299. continue;
  15300. }
  15301. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15302. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15303. continue;
  15304. }
  15305. return new torch._C.BuiltinFunction(symbol, self);
  15306. }
  15307. }
  15308. return null;
  15309. }
  15310. });
  15311. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15312. constructor(name, version) {
  15313. super();
  15314. this.name = name;
  15315. this.version = version || null;
  15316. }
  15317. attr(loc, m, field) {
  15318. if (field === 'autograd') {
  15319. return new torch._C.BuiltinModule('aten', this.version);
  15320. }
  15321. const sym = `${this.name}::${field}`;
  15322. return new torch._C.BuiltinFunction(sym, null);
  15323. }
  15324. });
  15325. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15326. constructor(version) {
  15327. super();
  15328. this._version = version;
  15329. }
  15330. attr(loc, m, field) {
  15331. return new torch._C.BuiltinModule(field, this._version);
  15332. }
  15333. });
  15334. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15335. constructor(constants) {
  15336. super();
  15337. this._constants = constants;
  15338. this.non_holding_object_cache = new Map();
  15339. }
  15340. attr(loc, m, field) {
  15341. const offset = parseInt(field.substring(1), 10);
  15342. if (!Number.isInteger(offset)) {
  15343. throw new python.Error(`Invalid constant identifier '${field}.`);
  15344. }
  15345. if (offset < 0 || offset >= this._constants.length) {
  15346. throw new python.Error('Invalid constant index.');
  15347. }
  15348. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15349. let value = null;
  15350. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15351. const obj = ivalue.toObject();
  15352. if (!this.non_holding_object_cache.has(obj)) {
  15353. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15354. }
  15355. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15356. } else {
  15357. value = m.graph().insertConstant(this._constants[offset], loc);
  15358. }
  15359. value.setType(torch._C.unshapedType(value.type()));
  15360. return new torch._C.SimpleValue(value);
  15361. }
  15362. });
  15363. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15364. constructor(type, method) {
  15365. super(method, null);
  15366. this._type = type;
  15367. }
  15368. call(loc, m, args, kwargs, n_binders) {
  15369. if (args.length === 1 && kwargs.length === 0) {
  15370. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15371. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15372. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15373. const v = args[0].value(m.graph());
  15374. if (v.type().isSubtypeOf(this._type)) {
  15375. return new torch._C.SimpleValue(v);
  15376. } 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)) {
  15377. const len = len_op.call(loc, m, [v], [], 1);
  15378. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15379. }
  15380. }
  15381. return super.call(loc, m, args, kwargs, n_binders);
  15382. }
  15383. });
  15384. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15385. constructor(desugared_name, base) {
  15386. super();
  15387. this._base_value = base;
  15388. this._desugared_name = desugared_name;
  15389. }
  15390. call(loc, m, args, kwargs, n_binders) {
  15391. if (args.length > 0) {
  15392. const self = args[0].value(m.graph());
  15393. if (self.type() instanceof torch.ClassType) {
  15394. return new torch._C.SimpleValue(self)
  15395. .attr(loc, m, this._desugared_name)
  15396. .call(loc, m, args.slice(1), kwargs, n_binders);
  15397. }
  15398. }
  15399. if (!this._base_value) {
  15400. throw new python.Error('Invalid magic method.');
  15401. }
  15402. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15403. }
  15404. });
  15405. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15406. constructor(loc, m, inputs, static_len) {
  15407. super();
  15408. static_len = static_len || null;
  15409. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15410. throw new python.Error('Invalid range inputs.');
  15411. }
  15412. const g = m.graph();
  15413. if (inputs.length === 1) {
  15414. [this._end] = inputs;
  15415. this._start = g.insertConstant(0, loc);
  15416. this._step = g.insertConstant(1, loc);
  15417. this._has_only_end = true;
  15418. } else {
  15419. [this._start, this._end] = inputs;
  15420. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15421. this._has_only_end = false;
  15422. }
  15423. this._static_len = static_len;
  15424. }
  15425. staticLen() {
  15426. return this._static_len;
  15427. }
  15428. iter() {
  15429. return this;
  15430. }
  15431. len(loc, m) {
  15432. if (this._static_len) {
  15433. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15434. }
  15435. if (this._has_only_end) {
  15436. return this._end;
  15437. }
  15438. const g = m.graph();
  15439. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15440. }
  15441. getitem(loc, m, idx /*, type_hint */) {
  15442. if (this._has_only_end) {
  15443. return new torch._C.SimpleValue(idx);
  15444. }
  15445. const g = m.graph();
  15446. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15447. }
  15448. });
  15449. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15450. });
  15451. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15452. constructor(name, si) {
  15453. super();
  15454. this._basename = name;
  15455. this._si = si;
  15456. }
  15457. attr(loc, m, name) {
  15458. const fullName = new torch._C.QualifiedName(this._basename, name);
  15459. const serializable_type = this._si.findNamedType(fullName);
  15460. if (serializable_type) {
  15461. if (serializable_type instanceof torch.ClassType) {
  15462. return new torch._C.ClassValue(serializable_type);
  15463. } else if (serializable_type instanceof torch.TupleType) {
  15464. return new torch._C.NamedTupleConstructor(serializable_type);
  15465. } else if (serializable_type instanceof torch.EnumType) {
  15466. return new torch._C.SugaredEnumClass(serializable_type);
  15467. }
  15468. }
  15469. const fn = this._si.findFunction(fullName);
  15470. if (fn) {
  15471. return new torch._C.FunctionValue(fn);
  15472. }
  15473. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15474. }
  15475. });
  15476. this.registerType('torch.package.PackageImporter', class {
  15477. constructor(reader) {
  15478. this.zip_reader = reader;
  15479. }
  15480. load_pickle(module, resource) {
  15481. const name = `${module.replace(/\./, '/')}/${resource}`;
  15482. const stream = this.zip_reader.get_record(name);
  15483. const loaded_reduces = new Map();
  15484. this.storage_context = new torch._C.DeserializationStorageContext();
  15485. const unpickler = new pickle.Unpickler(stream);
  15486. unpickler.persistent_load = (saved_id) => {
  15487. switch (saved_id[0]) {
  15488. case 'storage': {
  15489. const [, storage_type, key, , size] = saved_id;
  15490. if (!this.storage_context.has_storage(key)) {
  15491. const storage = new storage_type(size);
  15492. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15493. const buffer = stream.peek();
  15494. storage._set_cdata(buffer);
  15495. this.storage_context.add_storage(key, storage);
  15496. }
  15497. return this.storage_context.get_storage(key);
  15498. }
  15499. case 'reduce_package': {
  15500. if (saved_id.length === 2) {
  15501. const [, func, args] = saved_id;
  15502. return execution.invoke(func, args);
  15503. }
  15504. const [, reduce_id, func, args] = saved_id;
  15505. if (!loaded_reduces.has(reduce_id)) {
  15506. const value = execution.invoke(func, [this].concat(args));
  15507. loaded_reduces.set(reduce_id, value);
  15508. }
  15509. return loaded_reduces.get(reduce_id);
  15510. }
  15511. default: {
  15512. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15513. }
  15514. }
  15515. };
  15516. const obj = unpickler.load();
  15517. this.storage_context = null;
  15518. return obj;
  15519. }
  15520. import_module(name) {
  15521. return execution.import(name);
  15522. }
  15523. });
  15524. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15525. const cu = new torch.jit.CompilationUnit();
  15526. cu.execution = execution;
  15527. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15528. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15529. module.forward = cpp_module.forward; // remove
  15530. return module;
  15531. });
  15532. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15533. switch (arguments.length) {
  15534. case 4: {
  15535. const [device, extra_files] = args;
  15536. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15537. return deserializer.deserialize(device, extra_files);
  15538. }
  15539. case 5: {
  15540. const [storage_context, device, ts_id] = args;
  15541. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15542. return deserializer.deserialize(device, null);
  15543. }
  15544. default: {
  15545. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15546. }
  15547. }
  15548. });
  15549. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15550. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15551. });
  15552. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15553. if (value instanceof torch.Node) {
  15554. const n = value;
  15555. if (n.kind() === 'prim::CallFunction') {
  15556. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15557. const function_constant = n.input(0).node();
  15558. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15559. return torch._C.tryToGraphFunction(fun_type.function());
  15560. }
  15561. if (n.kind() === 'prim::CallMethod') {
  15562. const name = n.s('name');
  15563. const class_type = n.input(0).type();
  15564. if (class_type instanceof torch.ClassType) {
  15565. const fn = class_type.getMethod(name);
  15566. return torch._C.tryToGraphFunction(fn);
  15567. }
  15568. }
  15569. return null;
  15570. } else if (value instanceof torch._C.Function) {
  15571. const fn = value;
  15572. if (!fn.isGraphFunction()) {
  15573. return null;
  15574. }
  15575. return fn;
  15576. }
  15577. throw new python.Error('Not implemented.');
  15578. });
  15579. this.registerType('torch._C.ModuleInstanceInfo', class {
  15580. constructor(module_type, instance_name) {
  15581. this._module_type = module_type;
  15582. this._instance_name = instance_name;
  15583. }
  15584. });
  15585. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15586. torch._C.TORCH_CHECK(step !== 0);
  15587. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15588. if (start._ === Number.MAX_SAFE_INTEGER) {
  15589. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15590. }
  15591. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15592. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15593. }
  15594. if (start._ < 0) {
  15595. start._ += length;
  15596. if (start._ < 0) {
  15597. start._ = (step < 0) ? -1 : 0;
  15598. }
  15599. } else if (start._ >= length) {
  15600. start._ = (step < 0) ? length - 1 : length;
  15601. }
  15602. if (stop._ < 0) {
  15603. stop._ += length;
  15604. if (stop._ < 0) {
  15605. stop._ = (step < 0) ? -1 : 0;
  15606. }
  15607. } else if (stop._ >= length) {
  15608. stop._ = (step < 0) ? length - 1 : length;
  15609. }
  15610. if (step < 0) {
  15611. if (stop._ < start._) {
  15612. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15613. }
  15614. } else if (start._ < stop._) {
  15615. return Math.floor((stop._ - start._ - 1) / step + 1);
  15616. }
  15617. return 0;
  15618. });
  15619. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15620. if (v.node().kind() === 'prim::TupleConstruct') {
  15621. return v.node().inputs();
  15622. }
  15623. const g = v.owningGraph();
  15624. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15625. });
  15626. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15627. /*
  15628. const new_node_cs = new_node.callstack();
  15629. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15630. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15631. if (new_node_cs) {
  15632. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15633. } else {
  15634. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15635. }
  15636. }
  15637. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15638. for (const block of new_node.blocks()) {
  15639. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15640. }
  15641. */
  15642. });
  15643. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15644. if (arg === undefined || typeof arg === 'boolean') {
  15645. const inline_optimized_graph = arg === undefined ? true : arg;
  15646. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15647. return torch._C.inlineCallTo(to_replace, callee, graph);
  15648. }
  15649. if (arg instanceof torch.Graph === false) {
  15650. throw new python.Error('Invalid argument.');
  15651. }
  15652. const callee_graph = arg;
  15653. const guard = new torch._C.WithInsertPoint(to_replace);
  15654. const value_map = new Map();
  15655. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15656. const new_callstack_entries = new Map();
  15657. let module_instance_info = null;
  15658. if (to_replace.kind() === 'prim::CallMethod') {
  15659. const class_type_ptr = to_replace.input(0).type();
  15660. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15661. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15662. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15663. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15664. } else {
  15665. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15666. }
  15667. }
  15668. const updated_nodes = new Set();
  15669. for (const kv of value_map) {
  15670. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15671. if (is_graph_input === -1) {
  15672. continue;
  15673. }
  15674. const new_node = kv[1].node();
  15675. if (updated_nodes.has(new_node)) {
  15676. continue;
  15677. }
  15678. updated_nodes.add(new_node);
  15679. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15680. }
  15681. const old_outputs = to_replace.outputs();
  15682. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15683. for (let i = 0; i < old_outputs.length; i++) {
  15684. if (old_outputs[i].hasDebugName()) {
  15685. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15686. }
  15687. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15688. }
  15689. to_replace.destroy();
  15690. guard.dispose();
  15691. return new_outputs;
  15692. });
  15693. this.registerFunction('torch._C.inlineCalls', (block) => {
  15694. for (const cur of block.nodes()) {
  15695. switch (cur.kind()) {
  15696. case 'prim::CallFunction': {
  15697. const graphFunction = torch._C.tryToGraphFunction(cur);
  15698. if (graphFunction) {
  15699. const function_constant = cur.input(0).node();
  15700. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15701. cur.removeInput(0);
  15702. let g = null;
  15703. const fallback = function_constant.hasAttribute('fallback');
  15704. if (fallback && graphFunction.get_executor().isOptimized()) {
  15705. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15706. if (!exec_plans.empty()) {
  15707. g = exec_plans.begin().second.graph;
  15708. torch._C.Inline(g);
  15709. }
  15710. }
  15711. if (g === null) {
  15712. g = graphFunction.optimized_graph();
  15713. }
  15714. torch._C.inlineCallTo(cur, graphFunction, g);
  15715. }
  15716. break;
  15717. }
  15718. case 'prim::CallMethod': {
  15719. const graphFunction = torch._C.tryToGraphFunction(cur);
  15720. if (graphFunction) {
  15721. torch._C.inlineCallTo(cur, graphFunction);
  15722. }
  15723. break;
  15724. }
  15725. default: {
  15726. for (const b of cur.blocks()) {
  15727. torch._C.inlineCalls(b);
  15728. }
  15729. }
  15730. }
  15731. }
  15732. });
  15733. this.registerFunction('torch._C.Inline', (graph) => {
  15734. torch._C.inlineCalls(graph.block());
  15735. });
  15736. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15737. torch._C.Inline(graph);
  15738. });
  15739. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15740. });
  15741. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15742. const cu = new torch.jit.CompilationUnit();
  15743. cu.execution = execution;
  15744. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15745. return torch.jit._script.wrap_cpp_module(cpp_module);
  15746. });
  15747. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15748. const init_fn = (script_module) => {
  15749. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15750. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15751. }
  15752. };
  15753. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15754. });
  15755. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15756. has_storage(name) {
  15757. return this.has(name);
  15758. }
  15759. get_storage(name) {
  15760. return this.get(name);
  15761. }
  15762. add_storage(name, storage) {
  15763. return this.set(name, storage);
  15764. }
  15765. });
  15766. this.registerType('torch.ScriptFunction', class {
  15767. constructor(name, graph /*, function_creator */) {
  15768. this._name = name;
  15769. this._graph = graph;
  15770. }
  15771. });
  15772. this.registerType('torch.ScriptMethod', class {
  15773. constructor(owner, value) {
  15774. this._owner = owner;
  15775. this._function = value;
  15776. }
  15777. get name() {
  15778. return this._function.name();
  15779. }
  15780. get owner() {
  15781. return this._owner;
  15782. }
  15783. __call__(/* args, kwargs */) {
  15784. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  15785. }
  15786. get graph() {
  15787. return this._function.graph();
  15788. }
  15789. get schema() {
  15790. // return this.function().getSchema();
  15791. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  15792. }
  15793. get code() {
  15794. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  15795. }
  15796. get code_with_constants() {
  15797. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  15798. }
  15799. });
  15800. this.registerType('torch.ScriptObject', class {
  15801. constructor(type) {
  15802. this._typ = type;
  15803. this._ivalue = {};
  15804. }
  15805. static create(type) {
  15806. if (type.is_module()) {
  15807. return new torch.ScriptModule(type);
  15808. }
  15809. return new torch.ScriptObject(type);
  15810. }
  15811. type() {
  15812. return this._typ;
  15813. }
  15814. _type() {
  15815. return this._typ; // torch.ClassType
  15816. }
  15817. __setstate__(state) {
  15818. const [attrs, qualname] = state;
  15819. this._typ = torch._C.getCustomClass(qualname);
  15820. if (!this._typ) {
  15821. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  15822. }
  15823. for (let i = 0; i < this._typ.numAttributes(); i++) {
  15824. const name = this._typ.getAttributeName(i);
  15825. this.__setattr__(name, attrs[i]);
  15826. }
  15827. }
  15828. find_method(basename) {
  15829. for (const fn of this.type().methods()) {
  15830. if (fn.name() === basename) {
  15831. return new torch.ScriptMethod(this /* _value() */, fn);
  15832. }
  15833. }
  15834. return null;
  15835. }
  15836. _get_method(name) {
  15837. const method = this.find_method(name);
  15838. if (method) {
  15839. return method;
  15840. }
  15841. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  15842. return null;
  15843. }
  15844. _has_method(name) {
  15845. return this.find_method(name) ? true : false;
  15846. }
  15847. _method_names() {
  15848. return this.type().methods().map((fn) => fn.name());
  15849. }
  15850. __setattr__(name, value) {
  15851. // if (this._type.hasContant(name))
  15852. this._ivalue[name] = value;
  15853. }
  15854. __getattr__(name) {
  15855. return this._ivalue[name];
  15856. }
  15857. hasattr(name) {
  15858. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  15859. }
  15860. getattr(name) {
  15861. return this.__getattr__(name);
  15862. }
  15863. _properties() {
  15864. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  15865. }
  15866. is_weak_compilation_ref() {
  15867. return true; // not implemented
  15868. }
  15869. });
  15870. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  15871. constructor(...args) {
  15872. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  15873. const [class_name, cu, shouldMangle] = args;
  15874. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  15875. } else {
  15876. super(...args);
  15877. }
  15878. }
  15879. get qualified_name() {
  15880. return this.type().qualified_name();
  15881. }
  15882. get code_with_constants() {
  15883. const const_map = {};
  15884. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  15885. return [null, const_map];
  15886. }
  15887. get graph() {
  15888. if (!this._graph) {
  15889. const fn = this._typ.getMethod('forward');
  15890. this._graph = fn.graph();
  15891. }
  15892. return this._graph;
  15893. }
  15894. static create_module_object(class_name, cu, shouldMangle) {
  15895. shouldMangle = shouldMangle || false;
  15896. if (!class_name.prefix()) {
  15897. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  15898. }
  15899. if (shouldMangle && cu.get_class(class_name)) {
  15900. class_name = cu.mangle(class_name);
  15901. }
  15902. const cls = torch.ClassType.create(class_name, cu, true);
  15903. cu.register_type(cls);
  15904. return [cls, cu];
  15905. }
  15906. register_module(name, module) {
  15907. this.type().addOrCheckAttribute(name, module.type());
  15908. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  15909. }
  15910. register_buffer(name, v) {
  15911. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  15912. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  15913. }
  15914. register_parameter(name, v, is_buffer) {
  15915. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  15916. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  15917. }
  15918. register_attribute(name, t, v, is_param, is_buffer) {
  15919. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  15920. // _ivalue()->setAttr(name, v);
  15921. }
  15922. });
  15923. this.registerType('torch.ModuleDict', class {
  15924. constructor(mod) {
  15925. this._module = mod;
  15926. }
  15927. items() {
  15928. const result = new Map();
  15929. const type = this._module.type();
  15930. for (let i = 0; i < type.numAttributes(); i++) {
  15931. const k = type.getAttributeName(i);
  15932. const t = type.getAttribute(i);
  15933. if (t && t.is_module()) {
  15934. result.set(k, this._module.__getattr__(k));
  15935. }
  15936. }
  15937. return result;
  15938. }
  15939. });
  15940. this.registerType('torch.ParameterDict', class {
  15941. constructor(mod) {
  15942. this._module = mod;
  15943. }
  15944. items() {
  15945. const result = new Map();
  15946. const type = this._module.type();
  15947. for (let i = 0; i < type.numAttributes(); i++) {
  15948. if (type.is_parameter(i)) {
  15949. const k = type.getAttributeName(i);
  15950. const v = this._module.__getattr__(k);
  15951. if (v instanceof torch.Tensor) {
  15952. result.set(k, v);
  15953. }
  15954. }
  15955. }
  15956. return result;
  15957. }
  15958. });
  15959. this.registerType('torch.BufferDict', class {
  15960. constructor(mod) {
  15961. this._module = mod;
  15962. }
  15963. items() {
  15964. const result = new Map();
  15965. const type = this._module.type();
  15966. for (let i = 0; i < type.numAttributes(); i++) {
  15967. if (type.is_buffer(i)) {
  15968. const t = type.getAttribute(i);
  15969. if (t.isSubtypeOf(torch.TensorType.get())) {
  15970. const k = type.getAttributeName(i);
  15971. const v = this._module.__getattr__(k);
  15972. result.set(k, v);
  15973. }
  15974. }
  15975. }
  15976. return result;
  15977. }
  15978. });
  15979. this.registerType('torch._C.to_ir', class {
  15980. constructor(def, _resolver, self, method) {
  15981. this.method = method;
  15982. this.graph = method.graph();
  15983. this.resolver = _resolver;
  15984. this.integral_constants = new Map();
  15985. this.fp_constants = new Map();
  15986. this.complex_constants = new Map();
  15987. this.exit_blocks = new Set();
  15988. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  15989. this._loop_status = 'NOT_IN_LOOP';
  15990. this.environment_stack = null;
  15991. this._def_stack = [];
  15992. this._temp_name_count = 0;
  15993. torch._C.AT_ASSERT(this.resolver);
  15994. this.pushFrame(this.graph.block(), true);
  15995. if (self && def && def.args.args.length === 0) {
  15996. throw new python.Error('Method must have a self argument.');
  15997. }
  15998. method.setSchema(this.emitDef(def, self, this.graph.block()));
  15999. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16000. torch._C.ConvertToSSA(this.graph);
  16001. torch._C.CanonicalizeModifiedLoops(this.graph);
  16002. torch._C.NormalizeOps(this.graph.block());
  16003. torch._C.runCleanupPasses(this.graph);
  16004. }
  16005. pushFrame(b, starts_def) {
  16006. starts_def = starts_def || false;
  16007. if (starts_def) {
  16008. this._def_stack.push({});
  16009. }
  16010. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16011. }
  16012. popFrame(ends_def) {
  16013. const old_frame = this.environment_stack;
  16014. this.environment_stack = this.environment_stack.next;
  16015. if (ends_def) {
  16016. this._def_stack.pop();
  16017. }
  16018. return old_frame;
  16019. }
  16020. emitDef(def, self, block) {
  16021. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16022. if (schema.returns.length === 1) {
  16023. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16024. }
  16025. const args = this.emitFormalArguments(def, self, schema, block);
  16026. this.emitStatements(def.body);
  16027. this.handleMaybeNoReturn(def, block);
  16028. const returns = [this.emitOutput(def, schema, block)];
  16029. return new torch.FunctionSchema(def.name, '', args, returns);
  16030. }
  16031. emitFormalArguments(def, self, schema, block) {
  16032. const args = [];
  16033. const params = def.args.args;
  16034. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16035. if (schema.arguments.length !== expected_annotation_size) {
  16036. throw new python.Error('Invalid formal arguments.');
  16037. }
  16038. let it = 0;
  16039. if (self) {
  16040. const param = params[it];
  16041. const name = param.arg;
  16042. const new_input = block.addInput().setDebugName(name);
  16043. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16044. args.push(new torch.Argument(name, new_input.type()));
  16045. it++;
  16046. }
  16047. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16048. let arg_annotation_idx = 0;
  16049. for (; it < params.length; it++) {
  16050. const param = params[it];
  16051. const name = param.arg;
  16052. const new_input = block.addInput();
  16053. if (torch._C.meaningfulName(name)) {
  16054. new_input.setDebugName(name);
  16055. }
  16056. let arg = schema.arguments[arg_annotation_idx++];
  16057. if (shouldDeriveType) {
  16058. if (schema.arguments.length === 1) {
  16059. throw new python.Error('Invalid schema.');
  16060. }
  16061. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16062. arg = arg.cloneWithType(inferredStateType);
  16063. }
  16064. args.push(arg);
  16065. new_input.setType(arg.type);
  16066. this.environment_stack.setVar(param.range(), name, new_input);
  16067. }
  16068. return args;
  16069. }
  16070. emitOutput(range, schema, block) {
  16071. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16072. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16073. block.registerOutput(placeholder_return);
  16074. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16075. }
  16076. emitStatements(stmts) {
  16077. for (let i = 0; i < stmts.length; i++) {
  16078. const stmt = stmts[i];
  16079. if (stmt instanceof ast.If) {
  16080. this.emitIf(stmt);
  16081. } else if (stmt instanceof ast.While) {
  16082. this.emitWhile(stmt);
  16083. } else if (stmt instanceof ast.For) {
  16084. this.emitFor(stmt);
  16085. } else if (stmt instanceof ast.Assign) {
  16086. this.emitAssignment(stmt);
  16087. } else if (stmt instanceof ast.AnnAssign) {
  16088. this.emitAssignment(stmt);
  16089. } else if (stmt instanceof ast.Expr) {
  16090. this.emitSugaredExpr(stmt.value, 0);
  16091. } else if (stmt instanceof ast.Return) {
  16092. this.emitReturn(stmt);
  16093. } else if (stmt instanceof ast.Pass) {
  16094. // pass
  16095. } else if (stmt instanceof ast.With) {
  16096. this.emitWith(stmt);
  16097. } else {
  16098. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16099. }
  16100. if (this.exit_blocks.has(this.environment_stack.block())) {
  16101. return;
  16102. }
  16103. }
  16104. }
  16105. emitWith(stmt) {
  16106. const targets = stmt.items;
  16107. const entered = [];
  16108. for (const target of targets) {
  16109. const e = target.context_expr;
  16110. const rhs = this.emitExpr(e);
  16111. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16112. entered.push(rhs);
  16113. if (rhs.type() instanceof torch.ClassType === false) {
  16114. throw new python.Error('With item expression must return an object.');
  16115. }
  16116. const rhsClass = rhs.type();
  16117. const enterMethod = rhsClass.findMethod('__enter__');
  16118. const exitMethod = rhsClass.findMethod('__exit__');
  16119. if (!enterMethod || !exitMethod) {
  16120. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16121. }
  16122. const enterSchema = enterMethod.getSchema();
  16123. if (enterSchema.arguments.length !== 1) {
  16124. throw new python.Error('__enter__ must have only one argument and one return value.');
  16125. }
  16126. const exitSchema = exitMethod.getSchema();
  16127. if (exitSchema.arguments.length === 4) {
  16128. for (let i = 1; i < 4; i++) {
  16129. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16130. throw new python.Error('Argument of __exit__ must have Any type.');
  16131. }
  16132. }
  16133. } else {
  16134. throw new python.Error('__exit__ must have four arguments');
  16135. }
  16136. n.output(0).setType(enterSchema.returns[0].type);
  16137. if (target.optional_vars) {
  16138. throw new python.Error('Not implemented.');
  16139. // Var i = target.var().get();
  16140. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16141. }
  16142. }
  16143. this.emitStatements(stmt.body);
  16144. while (entered.length > 0) {
  16145. const input = entered.pop();
  16146. const n = this.graph.create('prim::Exit');
  16147. this.graph.insertNode(n);
  16148. n.addInput(input);
  16149. }
  16150. }
  16151. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16152. let max_trip_count_val = null;
  16153. if (iter_val === null) {
  16154. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16155. } else {
  16156. max_trip_count_val = iter_val.len(range, this.method);
  16157. }
  16158. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16159. const body_block = n.addBlock();
  16160. {
  16161. const condition_block = n.addBlock();
  16162. this.pushFrame(condition_block);
  16163. let out = null;
  16164. if (cond) {
  16165. const insert = new torch._C.WithInsertPoint(condition_block);
  16166. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16167. insert.dispose();
  16168. } else {
  16169. const insert = new torch._C.WithInsertPoint(n);
  16170. out = this.graph.insertConstant(true, range);
  16171. insert.dispose();
  16172. }
  16173. condition_block.registerOutput(out);
  16174. this.popFrame();
  16175. }
  16176. n.addInput(max_trip_count_val);
  16177. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16178. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16179. {
  16180. this.pushFrame(body_block);
  16181. const guard = new torch._C.WithInsertPoint(body_block);
  16182. if (iter_val !== null && targets) {
  16183. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16184. const sv = new torch._C.SimpleValue(cur_elem);
  16185. const target_exprs = targets;
  16186. this.validateAssignLhsExpr(target_exprs, range);
  16187. if (target_exprs.length > 1) {
  16188. throw new python.Error('Not implemented.');
  16189. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16190. // target_exprs = ListExpr.create(range, [tl]);
  16191. }
  16192. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16193. }
  16194. emit_body();
  16195. this.popFrame();
  16196. guard.dispose();
  16197. }
  16198. loop_guard.dispose();
  16199. }
  16200. emitFor(...args) {
  16201. if (args.length === 1 && args[0] instanceof ast.For) {
  16202. const [stmt] = args;
  16203. const emit_body = () => this.emitStatements(stmt.body);
  16204. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16205. } else if (args.length === 4) {
  16206. const [targets, itrs, loc, emit_body] = args;
  16207. if (itrs instanceof ast.Tuple) {
  16208. throw new python.Error('List of iterables is not supported currently.');
  16209. }
  16210. const sv = this.emitSugaredExpr(itrs, 1);
  16211. const iterable = sv.iter(loc, this.method);
  16212. if (iterable.shouldEmitUnrolled()) {
  16213. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16214. } else {
  16215. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16216. }
  16217. } else {
  16218. throw new python.Error('Not implemented.');
  16219. }
  16220. }
  16221. emitWhile(stmt) {
  16222. const cond = stmt.test;
  16223. const emit_body = () => this.emitStatements(stmt.body);
  16224. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16225. }
  16226. emitIsInstance(obj, classinfo) {
  16227. const lhs_val = this.emitExpr(obj);
  16228. const lhs_types = [];
  16229. const rhs_types = [];
  16230. const gather_rhs = (expr) => {
  16231. if (expr instanceof ast.Tuple) {
  16232. for (const e of expr.elts) {
  16233. gather_rhs(e);
  16234. }
  16235. return;
  16236. }
  16237. const type = this._typeParser.parseTypeFromExpr(expr);
  16238. rhs_types.push(type);
  16239. };
  16240. lhs_types.push(lhs_val.type());
  16241. gather_rhs(classinfo);
  16242. torch._C.standardizeVectorForUnion(lhs_types);
  16243. torch._C.standardizeVectorForUnion(rhs_types);
  16244. let refinement = new torch._C.RefinementSet([], []);
  16245. let unified_true = null;
  16246. let unified_false = null;
  16247. const isinstance_types = [];
  16248. const not_isinstance_types = [];
  16249. let true_refinements = [];
  16250. let false_refinements = [];
  16251. let all_lhs_subtype_some_rhs = true;
  16252. for (const lhs_type of lhs_types) {
  16253. if (lhs_type === torch.AnyType.get()) {
  16254. isinstance_types.push(...rhs_types);
  16255. not_isinstance_types.push(torch.AnyType.get());
  16256. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16257. all_lhs_subtype_some_rhs = false;
  16258. }
  16259. break;
  16260. }
  16261. const get_smaller_type = (t1, t2) => {
  16262. if (t1.isSubtypeOf(t2)) {
  16263. return t1;
  16264. } else if (t2.isSubtypeOf(t1)) {
  16265. return t2;
  16266. }
  16267. return null;
  16268. };
  16269. let found_refinement = null;
  16270. for (const rhs_type of rhs_types) {
  16271. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16272. if (!maybe_smaller_type) {
  16273. continue;
  16274. } else if (maybe_smaller_type === lhs_type) {
  16275. found_refinement = lhs_type;
  16276. } else if (maybe_smaller_type === rhs_type) {
  16277. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16278. }
  16279. }
  16280. if (found_refinement) {
  16281. if (found_refinement === lhs_type) {
  16282. all_lhs_subtype_some_rhs &= true;
  16283. }
  16284. isinstance_types.push(found_refinement);
  16285. } else {
  16286. not_isinstance_types.push(lhs_type);
  16287. all_lhs_subtype_some_rhs = false;
  16288. }
  16289. }
  16290. if (isinstance_types.length > 0) {
  16291. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16292. }
  16293. if (obj instanceof ast.Name && unified_true) {
  16294. const ident = obj.id;
  16295. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16296. }
  16297. if (not_isinstance_types.length > 0) {
  16298. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16299. }
  16300. if (obj instanceof ast.Name && unified_false) {
  16301. const ident = obj.id;
  16302. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16303. }
  16304. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16305. const is_statically_false = isinstance_types.length === 0;
  16306. if (all_lhs_subtype_some_rhs) {
  16307. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16308. }
  16309. if (is_statically_false) {
  16310. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16311. }
  16312. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16313. return new torch._C.CondValue(result, refinement, null);
  16314. }
  16315. emitIf(stmt) {
  16316. const cond_value = this.emitCondExpr(stmt.test);
  16317. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16318. }
  16319. emitCondExpr(expr) {
  16320. /*
  16321. switch (expr.kind()) {
  16322. case TK_AND:
  16323. case TK_OR: {
  16324. const binop = BinOp(expr);
  16325. return emitShortCircuitLogical(
  16326. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16327. }
  16328. case TK_NOT: {
  16329. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16330. Value* result = emitBuiltinCall(
  16331. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16332. std::optional<bool> static_if;
  16333. if (v.staticIf()) {
  16334. static_if = !*v.staticIf();
  16335. }
  16336. return CondValue(result, v.refinements().Not(), static_if);
  16337. } break;
  16338. case TK_IS:
  16339. case TK_ISNOT: {
  16340. // meta programming on AST for is/is not cases and emit branches base on
  16341. const cond_op = BinOp(expr);
  16342. Value* lhs_val = emitExpr(cond_op.lhs());
  16343. Value* rhs_val = emitExpr(cond_op.rhs());
  16344. const lhs_none = canBeNone(lhs_val);
  16345. const rhs_none = canBeNone(rhs_val);
  16346. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16347. // AA, -> statically IS always holds, IS_NOT never holds
  16348. // AN , NA-> statically IS_NOT always holds, IS never holds
  16349. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16350. bool its_is = expr.kind() == TK_IS;
  16351. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16352. return CondValue(*graph, expr.range(), its_is, {});
  16353. } else if (
  16354. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16355. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16356. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16357. return CondValue(*graph, expr.range(), !its_is, {});
  16358. } else {
  16359. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16360. Value* cond_value = emitBuiltinCall(
  16361. expr.get()->range(),
  16362. *method.graph(),
  16363. kind,
  16364. {lhs_val, rhs_val},
  16365. {});
  16366. const refinements = RefinementSet(findIsNoneRefinements(
  16367. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16368. return CondValue(cond_value, refinements, null);
  16369. }
  16370. } break;
  16371. */
  16372. if (expr instanceof ast.UnaryOp) {
  16373. throw new python.Error('Not implemented.');
  16374. }
  16375. if (expr instanceof ast.Call) {
  16376. const apply = expr;
  16377. const callee = expr.func;
  16378. if (callee instanceof ast.Name) {
  16379. if (callee.id === 'isinstance') {
  16380. this.checkApplyNumInputs(apply, 2);
  16381. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16382. }
  16383. if (callee.id === 'hasattr') {
  16384. this.checkApplyNumInputs(apply, 2);
  16385. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16386. }
  16387. const sv = this.emitSugaredExpr(callee, 1);
  16388. if (sv instanceof torch._C.SpecialFormValue) {
  16389. if (sv.form() === 'prim::isinstance') {
  16390. this.checkApplyNumInputs(apply, 2);
  16391. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16392. }
  16393. }
  16394. }
  16395. }
  16396. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16397. let static_if = null;
  16398. const kind = expr_out.node().kind();
  16399. if (kind === 'aten::is_scripting') {
  16400. static_if = true;
  16401. } else if (kind === 'aten::has_torch_function') {
  16402. static_if = false;
  16403. }
  16404. const maybe_ivalue = torch._C.toIValue(expr_out);
  16405. if (maybe_ivalue) {
  16406. static_if = maybe_ivalue.toBool();
  16407. }
  16408. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16409. }
  16410. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16411. if (cond_value.staticIf() !== null) {
  16412. if (cond_value.staticIf()) {
  16413. this.insertRefinements(loc, cond_value.refinements());
  16414. this.emitStatements(trueBranch);
  16415. } else {
  16416. this.insertRefinements(loc, cond_value.refinements().Not());
  16417. this.emitStatements(falseBranch);
  16418. }
  16419. return;
  16420. }
  16421. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16422. n.addInput(cond_value.value());
  16423. const true_block = n.addBlock();
  16424. const false_block = n.addBlock();
  16425. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16426. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16427. const true_exits = this.exit_blocks.has(true_block);
  16428. const false_exits = this.exit_blocks.has(false_block);
  16429. if (true_exits && false_exits) {
  16430. this.exit_blocks.add(n.owningBlock());
  16431. }
  16432. const mutated_variables = new Set();
  16433. for (const v of save_true.definedVariables()) {
  16434. const insert = new torch._C.WithInsertPoint(false_block);
  16435. if (save_false.findInAnyFrame(v) || false_exits) {
  16436. mutated_variables.add(v);
  16437. } else {
  16438. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16439. }
  16440. insert.dispose();
  16441. }
  16442. for (const v of save_false.definedVariables()) {
  16443. const insert = new torch._C.WithInsertPoint(true_block);
  16444. if (save_true.findInAnyFrame(v) || true_exits) {
  16445. mutated_variables.add(v);
  16446. } else {
  16447. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16448. }
  16449. insert.dispose();
  16450. }
  16451. for (const x of mutated_variables) {
  16452. let tv = null;
  16453. let fv = null;
  16454. {
  16455. const insert = new torch._C.WithInsertPoint(true_block);
  16456. if (!true_exits) {
  16457. tv = save_true.getVar(x, loc);
  16458. }
  16459. insert.dispose();
  16460. }
  16461. {
  16462. const insert = new torch._C.WithInsertPoint(false_block);
  16463. if (!false_exits) {
  16464. fv = save_false.getVar(x, loc);
  16465. }
  16466. insert.dispose();
  16467. }
  16468. if (true_exits && false_exits) {
  16469. continue;
  16470. } else if (true_exits) {
  16471. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16472. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16473. } else if (false_exits) {
  16474. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16475. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16476. }
  16477. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16478. let full_type = null;
  16479. if (maybe_sugared_x) {
  16480. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16481. if (maybe_simple) {
  16482. full_type = maybe_simple.type();
  16483. }
  16484. }
  16485. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16486. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16487. if (!unified) {
  16488. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16489. throw new python.Error('Type mismatch.');
  16490. } else {
  16491. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16492. continue;
  16493. }
  16494. }
  16495. this.environment_stack.setType(x, unified);
  16496. }
  16497. }
  16498. emitSingleIfBranch(b, branch, refinements) {
  16499. this.pushFrame(b);
  16500. const guard = new torch._C.WithInsertPoint(b);
  16501. this.insertRefinements(branch, refinements);
  16502. this.emitStatements(branch);
  16503. const frame = this.popFrame();
  16504. guard.dispose();
  16505. return frame;
  16506. }
  16507. create(kind, loc, n_outputs) {
  16508. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16509. }
  16510. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16511. is_dict_constructor = is_dict_constructor || false;
  16512. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16513. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16514. if (!is_dict_constructor && candidate_types.length === 0) {
  16515. throw new python.Error("No matching types found in Union type annotation.");
  16516. } else if (candidate_types.length === 1) {
  16517. [refined_type_hint_ptr._] = candidate_types;
  16518. } else {
  16519. all_candidates._ = candidate_types;
  16520. }
  16521. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16522. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16523. }
  16524. if (is_dict_constructor) {
  16525. return;
  16526. }
  16527. if (all_candidates._.length === 0) {
  16528. if (type_match(refined_type_hint_ptr._)) {
  16529. do_if_match();
  16530. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16531. do_if_anytype();
  16532. } else {
  16533. throw new python.Error('Invalid annotation type.');
  16534. }
  16535. }
  16536. }
  16537. emitToBool(loc, v) {
  16538. let out = null;
  16539. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16540. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16541. if (!out) {
  16542. throw new python.Error('Could not cast value to bool.');
  16543. }
  16544. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16545. throw new python.Error('Expected a bool expression for condition.');
  16546. }
  16547. return out;
  16548. }
  16549. emitUnaryOp(tree, magicMethod, opSymbol) {
  16550. const inputs = [tree.operand];
  16551. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16552. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16553. if (val.node().kind() !== opSymbol) {
  16554. return val;
  16555. }
  16556. const maybe_out_stack = this.runNodeIfInputsAreConstant(val.node());
  16557. if (!maybe_out_stack) {
  16558. return val;
  16559. }
  16560. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16561. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16562. }
  16563. emitAssignment(stmt) {
  16564. if (stmt instanceof ast.AnnAssign) {
  16565. return this.emitSingleAssignment(stmt);
  16566. }
  16567. if (stmt.targets.length === 1) {
  16568. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16569. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16570. for (const [key, value] of entries) {
  16571. assign[key] = value;
  16572. }
  16573. return this.emitSingleAssignment(assign);
  16574. }
  16575. if (stmt.targets.length <= 1) {
  16576. throw new python.Error('Invalid assignment.');
  16577. }
  16578. throw new python.Error('Not implemented.');
  16579. /*
  16580. const tmp_name = this.createTempName('$tmp_assign_');
  16581. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16582. const ident = new ast.Name(tmp_name);
  16583. for (const expr of lhs_list) {
  16584. const assign = new ast.Assign(targets, value, ctx);
  16585. this.emitSingleAssignment(Assign.create(stmt,
  16586. List<Expr>.create(expr.range(), [expr]),
  16587. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16588. Maybe<Expr>::create(stmt.range())));
  16589. }
  16590. */
  16591. }
  16592. emitSingleAssignment(stmt) {
  16593. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16594. const rhs = stmt.value;
  16595. const lhs = stmt.target;
  16596. if (lhs instanceof ast.Name) {
  16597. let type = null;
  16598. if (stmt.annotation) {
  16599. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16600. }
  16601. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16602. // BC HACK
  16603. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16604. } else if (lhs instanceof ast.Tuple) {
  16605. this.emitTupleAssign(lhs, rhs);
  16606. } else if (lhs instanceof ast.Attribute) {
  16607. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16608. } else {
  16609. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16610. }
  16611. }
  16612. emitSelectAssign(lhs, rhs, type, loc) {
  16613. if (!rhs) {
  16614. throw new python.Error('Expected RHS for assignment.');
  16615. }
  16616. let type_hint = null;
  16617. if (type) {
  16618. type_hint = this._typeParser.parseTypeFromExpr(type);
  16619. }
  16620. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16621. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16622. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16623. }
  16624. emitTupleAssign(...args) {
  16625. if (args.length === 2) {
  16626. const [tl, rhs] = args;
  16627. let n_binders = tl.elts.length;
  16628. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16629. if (starred_unpack) {
  16630. n_binders--;
  16631. }
  16632. const output = this.emitSugaredExpr(rhs, n_binders);
  16633. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16634. } else if (args.length === 5) {
  16635. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16636. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16637. if (outputs.length < n_binders) {
  16638. throw new python.Error('Not enough values to unpack.');
  16639. }
  16640. if (outputs.length > n_binders && !starred_unpack) {
  16641. throw new python.Error('Too many values to unpack.');
  16642. }
  16643. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16644. } else {
  16645. throw new python.Error('Not implemented.');
  16646. }
  16647. }
  16648. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16649. let i = 0;
  16650. for (const assignee of lhs_exprs) {
  16651. if (assignee instanceof ast.Subscript) {
  16652. throw new python.Error('Not implemented.');
  16653. /*
  16654. this.emitSubscriptAssign(
  16655. rhs_loc,
  16656. Subscript(assignee),
  16657. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16658. i++;
  16659. */
  16660. } else if (assignee instanceof ast.Name) {
  16661. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16662. i++;
  16663. } else if (assignee instanceof ast.Starred) {
  16664. throw new python.Error('Not implemented.');
  16665. /*
  16666. const var = Starred(assignee).expr();
  16667. if (var.kind() != TK_VAR) {
  16668. throw(
  16669. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16670. }
  16671. size_t n_matched = outputs.size() - n_binders;
  16672. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16673. const values = fmap(
  16674. outputs_ref.slice(i, n_matched),
  16675. [&](const std::shared_ptr<SugaredValue>& v) {
  16676. return v.asValue(assignee.range(), method);
  16677. });
  16678. const tup = graph.insertNode(graph.createTuple(values)).output();
  16679. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16680. i += n_matched;
  16681. */
  16682. } else if (assignee instanceof ast.Tuple) {
  16683. throw new python.Error('Not implemented.');
  16684. /*
  16685. // recursively emit tuple assignments on tuple literal input
  16686. TupleLiteral sub_tl = TupleLiteral(assignee);
  16687. size_t sub_n_binders = sub_tl.inputs().length;
  16688. bool sub_starred_unpack =
  16689. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16690. if (sub_starred_unpack)
  16691. sub_n_binders--;
  16692. emitTupleAssign(
  16693. sub_tl,
  16694. outputs.at(i),
  16695. rhs_loc,
  16696. sub_n_binders,
  16697. sub_starred_unpack);
  16698. i++;
  16699. */
  16700. } else if (assignee instanceof ast.Attribute) {
  16701. throw new python.Error('Not implemented.');
  16702. /*
  16703. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16704. i++;
  16705. */
  16706. } else {
  16707. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16708. }
  16709. }
  16710. }
  16711. emitReturn(stmt) {
  16712. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16713. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16714. if (declared_return_type) {
  16715. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16716. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16717. }
  16718. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16719. throw new python.Error(`Invalid return type.`);
  16720. }
  16721. } else {
  16722. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16723. if (!declared_return_type) {
  16724. declared_return_type = actual_return.type();
  16725. }
  16726. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16727. if (!merged_return_type) {
  16728. throw new python.Error(`Invalid return type.`);
  16729. }
  16730. declared_return_type = merged_return_type;
  16731. }
  16732. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16733. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16734. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16735. }
  16736. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16737. this.exit_blocks.add(this.environment_stack.block());
  16738. }
  16739. getNamedValues(trees, maybe_unpack) {
  16740. const values = [];
  16741. for (const tree of trees) {
  16742. if (maybe_unpack && tree instanceof ast.Starred) {
  16743. throw new python.Error('Starred argument not supported.');
  16744. } else {
  16745. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16746. }
  16747. }
  16748. return values;
  16749. }
  16750. getValues(trees, maybe_unpack) {
  16751. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16752. }
  16753. emitExpr(tree, type_hint) {
  16754. type_hint = type_hint || null;
  16755. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16756. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16757. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16758. }
  16759. return out_val;
  16760. }
  16761. emitSugaredExpr(tree, n_binders, type_hint) {
  16762. if (tree instanceof ast.Name) { // TK_VAR
  16763. return this.environment_stack.getSugaredVar(tree.id);
  16764. } else if (tree instanceof ast.Attribute) {
  16765. const sv = this.emitSugaredExpr(tree.value, 1);
  16766. return sv.attr(tree.range(), this.method, tree.attr);
  16767. } else if (tree instanceof ast.Call) { // TK_APPLY
  16768. return this.emitApplyExpr(tree, n_binders, type_hint);
  16769. } if (tree instanceof ast.Subscript) {
  16770. return this.emitSubscript(tree, type_hint);
  16771. }
  16772. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  16773. }
  16774. emitApplyExpr(apply, n_binders, type_hint) {
  16775. type_hint = type_hint || null;
  16776. const sv = this.emitSugaredExpr(apply.func, 1);
  16777. const loc = apply.func.range();
  16778. if (sv instanceof torch._C.SpecialFormValue) {
  16779. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  16780. }
  16781. const args = this.getNamedValues(apply.args, true);
  16782. const kwargs = this.emitAttributes(apply.keywords);
  16783. return sv.call(loc, this.method, args, kwargs, n_binders);
  16784. }
  16785. emitAttributes(attributes) {
  16786. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  16787. }
  16788. emitApplySpecialForm(form, apply, sv, type_hint) {
  16789. switch (form) {
  16790. case 'prim::fork': {
  16791. throw new python.Error('Not implemented.');
  16792. }
  16793. case 'prim::awaitable': {
  16794. throw new python.Error('Not implemented.');
  16795. }
  16796. case 'prim::annotate': {
  16797. this.checkApplyNumInputs(apply, 2);
  16798. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16799. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  16800. if (!expr.type().isSubtypeOf(type)) {
  16801. throw new python.Error('Invalid expression type.');
  16802. }
  16803. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  16804. const none = this.graph.createNone();
  16805. none.output().setType(type);
  16806. this.graph.insertNode(none);
  16807. expr = none.output();
  16808. }
  16809. return new torch._C.SimpleValue(expr);
  16810. }
  16811. case 'prim::unchecked_cast': {
  16812. this.checkApplyNumInputs(apply, 2);
  16813. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16814. let v = this.emitExpr(apply.args[1]);
  16815. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  16816. v = this.graph.insertUncheckedCast(v, type);
  16817. }
  16818. return new torch._C.SimpleValue(v);
  16819. }
  16820. case 'prim::GetAttr': {
  16821. this.checkApplyNumInputsRange(apply, 2, 3);
  16822. const obj = this.emitSugaredExpr(apply.args[0], 1);
  16823. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  16824. throw new python.Error('Invalid argument.');
  16825. }
  16826. const name = apply.args[1].value;
  16827. if (apply.args.length === 2) {
  16828. return obj.attr(apply, this.method, name);
  16829. } else if (obj.hasAttr(apply, this.method, name)) {
  16830. return obj.attr(apply, this.method, name);
  16831. }
  16832. return this.emitSugaredExpr(apply.inputs()[2], 1);
  16833. }
  16834. case 'prim::Uninitialized': {
  16835. this.checkApplyNumInputs(apply, 1);
  16836. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16837. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  16838. return new torch._C.SimpleValue(out.output());
  16839. }
  16840. case 'prim::TupleConstruct': {
  16841. throw new python.Error('Not implemented.');
  16842. }
  16843. case 'prim::isinstance': {
  16844. this.checkApplyNumInputs(apply, 2);
  16845. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  16846. return new torch._C.SimpleValue(result.value());
  16847. }
  16848. case 'prim::tolist': {
  16849. const value = apply.func.value;
  16850. const operand = this.emitSugaredExpr(value, 1);
  16851. if (!type_hint) {
  16852. throw new python.Error('Expected type hint for result of tolist().');
  16853. }
  16854. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  16855. }
  16856. case 'prim::HasAttr': {
  16857. throw new python.Error('Not implemented.');
  16858. }
  16859. case 'prim::CreateObject': {
  16860. if (apply.args.length !== 1) {
  16861. throw python.Error('Only one argument to __new__ allowed.');
  16862. }
  16863. const arg = this.emitSugaredExpr(apply.args[0], 1);
  16864. if (arg instanceof torch._C.ClassValue === false) {
  16865. throw python.Error('Expected class value as argument to __new__.');
  16866. }
  16867. const class_arg = arg;
  16868. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  16869. createNode.setSourceRange(apply.range());
  16870. return new torch._C.SimpleValue(createNode.output());
  16871. }
  16872. case 'prim::range': {
  16873. const input_vals = this.getValues(apply.args, true);
  16874. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  16875. }
  16876. case 'prim::enumerate': {
  16877. throw new python.Error('Not implemented.');
  16878. }
  16879. case 'prim::zip': {
  16880. throw new python.Error('Not implemented.');
  16881. }
  16882. case 'prim::list': {
  16883. throw new python.Error('Not implemented.');
  16884. }
  16885. case 'prim::dict': {
  16886. throw new python.Error('Not implemented.');
  16887. }
  16888. case 'aten::index': {
  16889. throw new python.Error('Not implemented.');
  16890. }
  16891. default: {
  16892. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  16893. }
  16894. }
  16895. }
  16896. emitSimpleExpr(tree, type_hint) {
  16897. if (tree instanceof ast.Constant) {
  16898. if (tree.value === true) {
  16899. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  16900. } else if (tree.value === false) {
  16901. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  16902. } else if (tree.value === null) {
  16903. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  16904. } else if (typeof tree.value === 'string') {
  16905. return this.emitStringLiteral(tree);
  16906. }
  16907. return this.emitConst(tree);
  16908. } else if (tree instanceof ast.List) {
  16909. return this.emitListLiteral(tree, type_hint);
  16910. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  16911. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  16912. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  16913. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  16914. } else if (tree instanceof ast.BinOp) {
  16915. return this.emitBinaryOp(tree);
  16916. } else if (tree instanceof ast.Dict) {
  16917. return this.emitDictLiteral(tree, type_hint);
  16918. } else if (tree instanceof ast.Tuple) {
  16919. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  16920. return this.graph.insertNode(this.graph.createTuple(values)).output();
  16921. }
  16922. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  16923. }
  16924. getNodeKind(kind /*, ninputs */) {
  16925. if (kind instanceof ast.Add) {
  16926. return 'aten::add';
  16927. } else if (kind instanceof ast.Sub) {
  16928. return 'aten::sub';
  16929. } else if (kind instanceof ast.Mult) {
  16930. return 'aten::mul';
  16931. }
  16932. /*
  16933. case TK_UNARY_MINUS: return 'aten::neg';
  16934. case TK_POW: return 'aten::pow';
  16935. case '@': return 'aten::matmul';
  16936. case TK_STARRED: return 'prim::Starred';
  16937. case '/': return 'aten::div';
  16938. case '%': return 'aten::remainder';
  16939. case TK_NE: return 'aten::ne';
  16940. case TK_EQ: return 'aten::eq';
  16941. case '<': return 'aten::lt';
  16942. case '>': return 'aten::gt';
  16943. case TK_LE: return 'aten::le';
  16944. case TK_GE: return 'aten::ge';
  16945. case TK_AND: return 'aten::__and__';
  16946. case TK_OR: return 'aten::__or__';
  16947. case TK_IS: return 'aten::__is__';
  16948. case TK_ISNOT: return 'aten::__isnot__';
  16949. case TK_NOT: return 'aten::__not__';
  16950. case TK_FLOOR_DIV: return 'aten::floordiv';
  16951. case TK_LSHIFT: return 'aten::__lshift__';
  16952. case TK_RSHIFT: return 'aten::__rshift__';
  16953. case '&': return 'aten::__and__';
  16954. case '|': return 'aten::__or__';
  16955. case '^': return 'aten::__xor__';
  16956. case TK_IN: return 'aten::__contains__';
  16957. */
  16958. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  16959. }
  16960. getOperatorOverload(kind /*, ninputs */) {
  16961. if (kind instanceof ast.Add) {
  16962. return '__add__';
  16963. } else if (kind instanceof ast.Sub) {
  16964. return '__sub__';
  16965. } else if (kind instanceof ast.Mult) {
  16966. return '__mul__';
  16967. }
  16968. /*
  16969. case TK_UNARY_MINUS: return "__neg__";
  16970. case '~': return "__invert__";
  16971. case TK_POW: return "__pow__";
  16972. case '/': return "__truediv__";
  16973. case '%': return "__mod__";
  16974. case TK_NE: return "__ne__";
  16975. case TK_EQ: return "__eq__";
  16976. case '<': return "__lt__";
  16977. case '>': return "__gt__";
  16978. case TK_LE: return "__le__";
  16979. case TK_GE: return "__ge__";
  16980. case '&': return "__and__";
  16981. case '|': return "__or__";
  16982. case '^': return "__xor__";
  16983. case TK_IN: return "__contains__";
  16984. case TK_LSHIFT: return "__lshift__";
  16985. case TK_RSHIFT: return "__rshift__";
  16986. */
  16987. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  16988. }
  16989. emitBinaryOp(tree) {
  16990. const inputs = [tree.left, tree.right];
  16991. const kind = this.getNodeKind(tree.op, inputs.length);
  16992. const overload = this.getOperatorOverload(tree.op, inputs.length);
  16993. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16994. if (tree.op instanceof ast.In) {
  16995. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  16996. throw new python.Error('Not implemented.');
  16997. }
  16998. if (named_values[0].type() instanceof torch.TupleType &&
  16999. named_values[1].type() instanceof torch.TupleType &&
  17000. kind === 'aten::add') {
  17001. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17002. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17003. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17004. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17005. }
  17006. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17007. }
  17008. emitDictLiteral(dl, type_hint) {
  17009. const key_trees = dl.keys;
  17010. const value_trees = dl.values;
  17011. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17012. const keys = [];
  17013. const values = [];
  17014. let rhs_value_type = null;
  17015. for (let i = 0; i < key_trees.length; i++) {
  17016. keys.push(this.emitExpr(key_trees[i]));
  17017. values.push(this.emitExpr(value_trees[i]));
  17018. if (i === 0) {
  17019. rhs_value_type = values[i].type();
  17020. } else {
  17021. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17022. throw new python.Error('Dict keys must contain only a single type.');
  17023. }
  17024. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17025. }
  17026. }
  17027. const refined_type_hint = { _: type_hint };
  17028. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17029. const all_candidates = { _: [] };
  17030. const default_refined_type_hint_setter = () => {
  17031. if (keys.length === 0) {
  17032. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17033. } else {
  17034. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17035. if (rhs_value_type instanceof torch.UnionType) {
  17036. throw new python.Error('Dict values consist of heterogeneous types.');
  17037. }
  17038. }
  17039. };
  17040. if (type_hint) {
  17041. const type_match = (t) => t instanceof torch.DictType;
  17042. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17043. if (all_candidates._.length > 0 && values.length === 0) {
  17044. throw new python.Error('Cannot assign an empty dict.');
  17045. }
  17046. } else {
  17047. default_refined_type_hint_setter();
  17048. }
  17049. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17050. if (values.length > 0) {
  17051. if (all_candidates._.length > 0) {
  17052. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17053. }
  17054. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17055. throw new python.Error('Type annotation does not match key type.');
  17056. }
  17057. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17058. throw new python.Error('Type annotation does not match value type.');
  17059. }
  17060. }
  17061. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17062. if (annotated_union_type) {
  17063. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17064. n.output().setType(annotated_union_type);
  17065. result = n;
  17066. }
  17067. return result.output();
  17068. }
  17069. emitStringLiteral(c) {
  17070. return torch._C.insertConstant(this.graph, c.value, c.range());
  17071. }
  17072. emitConst(c) {
  17073. if (c.type === 'int') {
  17074. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17075. } else if (c.type === 'complex') {
  17076. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17077. } else if (c.type === 'float') {
  17078. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17079. }
  17080. throw new python.Error(`Unsupported constant type.`);
  17081. }
  17082. emitListLiteral(ll, type_hint) {
  17083. type_hint = type_hint || null;
  17084. const values = this.getValues(ll.elts, true);
  17085. if (values.length === 0 && type_hint === null) {
  17086. throw new python.Error('Not implemented.');
  17087. }
  17088. let inferred_elem_type = torch.TensorType.get();
  17089. const refined_type_hint = { _: type_hint };
  17090. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17091. const all_candidates = { _: [] };
  17092. if (refined_type_hint._) {
  17093. const do_if_type_match = () => {
  17094. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17095. };
  17096. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17097. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17098. if (all_candidates._.length > 0 && values.len === 0) {
  17099. throw new python.Error('Cannot assign an empty list.');
  17100. }
  17101. }
  17102. if (values.length !== 0) {
  17103. const types = values.map((v) => v.type());
  17104. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17105. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17106. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17107. throw new python.Error('Not implemented.');
  17108. }
  17109. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17110. throw new python.Error('Not implemented.');
  17111. }
  17112. if (all_candidates._.length !== 0) {
  17113. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17114. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17115. }
  17116. if (!refined_type_hint._) {
  17117. inferred_elem_type = unified_elem_type;
  17118. }
  17119. }
  17120. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17121. if (annotated_union_type) {
  17122. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17123. n.output().setType(annotated_union_type);
  17124. result = n;
  17125. }
  17126. return result.output();
  17127. }
  17128. insertRefinements(loc, ref) {
  17129. for (const r of ref.activeRefinements()) {
  17130. const v = this.environment_stack.getVar(r.identifier(), loc);
  17131. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17132. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17133. }
  17134. }
  17135. shouldDeriveSetStateType(def, schema) {
  17136. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17137. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17138. if (!shouldInfer) {
  17139. return false;
  17140. }
  17141. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17142. throw new python.Error(`Invalid '__setstate' method.`);
  17143. }
  17144. return true;
  17145. }
  17146. checkApplyNumInputs(apply, expected_inputs) {
  17147. if (apply.args.length !== expected_inputs) {
  17148. throw new python.Error('Invalid number of arguments.');
  17149. }
  17150. if (apply.keywords.length > 0) {
  17151. throw new python.Error('Invalid number of keyword arguments.');
  17152. }
  17153. }
  17154. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17155. const position_arg_size = apply.args.length;
  17156. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17157. throw new python.Error('Invalid number of arguments.');
  17158. }
  17159. if (apply.keywords.length > 0) {
  17160. throw new python.Error('Invalid number of keyword arguments.');
  17161. }
  17162. }
  17163. validateAssignLhsExpr(lhs /*, r */) {
  17164. let num_normal_assign = 0;
  17165. let num_starred = 0;
  17166. for (const assignee of lhs) {
  17167. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17168. num_normal_assign++;
  17169. } else if (assignee instanceof ast.Starred) {
  17170. num_starred++;
  17171. } else {
  17172. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17173. }
  17174. }
  17175. if (num_starred > 1) {
  17176. throw new python.Error('Only one starred expression is allowed.');
  17177. }
  17178. if (num_starred > 0 && num_normal_assign === 0) {
  17179. throw new python.Error('Invalid starred expression.');
  17180. }
  17181. return num_starred;
  17182. }
  17183. createTempName(prefix) {
  17184. return `${prefix}${this._temp_name_count++}`;
  17185. }
  17186. handleMaybeNoReturn(def, block) {
  17187. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17188. if (this.exit_blocks.size === 0) {
  17189. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17190. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17191. }
  17192. const b = new torch._C.WithInsertPoint(block.nodes()[-1]);
  17193. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17194. b.dispose();
  17195. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17196. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17197. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17198. }
  17199. }
  17200. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17201. let adj_index = input_index;
  17202. const tuple_len = tuple_type.elements().length;
  17203. if (input_index < 0) {
  17204. adj_index = tuple_len + input_index;
  17205. }
  17206. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17207. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17208. }
  17209. return adj_index;
  17210. }
  17211. emitTupleIndex(loc, tuple_val, idx_val) {
  17212. const tuple_typ = tuple_val.type();
  17213. const elems = tuple_typ.elements();
  17214. let output_type = null;
  17215. if (idx_val.type() !== torch.IntType.get()) {
  17216. throw new python.Error('Tuple index must be an integer.');
  17217. }
  17218. const idx = torch._C.toIValue(idx_val);
  17219. if (idx) {
  17220. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17221. output_type = elems[adj_index];
  17222. } else {
  17223. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17224. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17225. }
  17226. [output_type] = elems;
  17227. }
  17228. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17229. }
  17230. getSliceInd(idx_val, loc) {
  17231. const ivalue = torch._C.toIValue(idx_val);
  17232. if (ivalue && ivalue.isInt()) {
  17233. return ivalue.toInt();
  17234. }
  17235. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17236. }
  17237. emitTupleSlice(loc, tuple_val, tuple_args) {
  17238. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17239. const tuple_len = tuple_type.elements().length;
  17240. const [beg_val, end_val, step] = tuple_args;
  17241. let step_size = 1;
  17242. if (step) {
  17243. const val = torch._C.toIValue(step.value(this.graph));
  17244. torch._C.TORCH_CHECK(val.isInt());
  17245. step_size = val.toInt();
  17246. }
  17247. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17248. if (beg_val) {
  17249. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17250. }
  17251. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17252. if (end_val) {
  17253. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17254. }
  17255. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17256. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17257. }
  17258. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17259. const args = [];
  17260. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17261. if (dim) {
  17262. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17263. args.emplace_back(new torch._C.NamedValue(dim));
  17264. } else {
  17265. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17266. }
  17267. if (sliceable.type() instanceof torch.TupleType) {
  17268. const tuple_args = [];
  17269. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17270. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17271. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17272. return this.emitTupleSlice(loc, args[0], tuple_args);
  17273. }
  17274. if (!step) {
  17275. step = this.graph.insertConstant(1, loc);
  17276. }
  17277. args.push(new torch._C.NamedValue(loc, 'start', start));
  17278. args.push(new torch._C.NamedValue(loc, 'end', end));
  17279. args.push(new torch._C.NamedValue(loc, 'step', step));
  17280. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17281. }
  17282. emitSlice(loc, input, dim, slice) {
  17283. let start = null;
  17284. let end = null;
  17285. let step = null;
  17286. if (slice.lower) {
  17287. start = this.emitExpr(slice.lower);
  17288. }
  17289. if (slice.upper) {
  17290. end = this.emitExpr(slice.upper);
  17291. }
  17292. if (slice.step) {
  17293. step = this.emitExpr(slice.step);
  17294. }
  17295. return this.emitSliceOp(loc, input, dim, start, end, step);
  17296. }
  17297. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17298. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17299. const slice_exp = subscript_exprs;
  17300. let maybe_dim = null;
  17301. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17302. maybe_dim = this.graph.insertConstant(0, loc);
  17303. }
  17304. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17305. }
  17306. emitSubscript(subscript, type_hint) {
  17307. type_hint = type_hint === undefined ? null : type_hint;
  17308. const sv = this.emitSugaredExpr(subscript.value, 1);
  17309. const subscript_exprs = subscript.slice;
  17310. const range = subscript.range();
  17311. const val_range = subscript.value;
  17312. if (subscript_exprs instanceof ast.Tuple) {
  17313. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17314. }
  17315. if (subscript_exprs instanceof ast.Slice) {
  17316. if (sv.kind() === 'module') {
  17317. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17318. const [slice] = subscript_exprs;
  17319. const tuple_args = [];
  17320. if (slice.start().present()) {
  17321. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17322. tuple_args.push(begin);
  17323. } else {
  17324. tuple_args.push(null);
  17325. }
  17326. if (slice.end().present()) {
  17327. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17328. tuple_args.push(end);
  17329. } else {
  17330. tuple_args.push(null);
  17331. }
  17332. if (slice.step().present()) {
  17333. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17334. tuple_args.push(step);
  17335. } else {
  17336. tuple_args.push(null);
  17337. }
  17338. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17339. return new torch._C.SimpleValue(tupleSliceValue);
  17340. }
  17341. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17342. }
  17343. const sliceable = sv.asValue(val_range, this.method);
  17344. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17345. if (subscript_sv instanceof torch._C.SliceValue) {
  17346. const slice_value = subscript_sv;
  17347. let dim = null;
  17348. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17349. dim = this.method.graph().insertConstant(0, val_range);
  17350. }
  17351. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17352. return new torch._C.SimpleValue(sliced);
  17353. }
  17354. const idx = subscript_sv.asValue(val_range, this.method);
  17355. if (sliceable.type() instanceof torch.TupleType) {
  17356. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17357. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17358. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17359. }
  17360. return sv.getitem(range, this.method, idx, type_hint);
  17361. }
  17362. });
  17363. this.registerType('torch.jit.CompilationUnit', class {
  17364. constructor() {
  17365. this._functions = new Map();
  17366. this._classes = new Map();
  17367. }
  17368. register_type(namedType) {
  17369. this._classes.set(namedType.annotation_str, namedType);
  17370. }
  17371. register_function(fn) {
  17372. const name = fn.qualname().qualifiedName();
  17373. torch._C.TORCH_CHECK(!this._functions.has(name));
  17374. this._functions.set(name, fn);
  17375. return fn;
  17376. }
  17377. define(...args) {
  17378. if (Array.isArray(args[1])) {
  17379. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17380. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17381. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17382. const functions = [];
  17383. const function_table = new Map();
  17384. const record_function = (fn) => {
  17385. function_table.set(fn.name(), fn);
  17386. functions.push(fn);
  17387. this.register_function(fn);
  17388. };
  17389. for (let i = 0; i < properties.length; i++) {
  17390. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17391. const getter_fn = property_fns.getGetter();
  17392. const setter_fn = property_fns.getSetter();
  17393. record_function(getter_fn);
  17394. if (setter_fn) {
  17395. record_function(setter_fn);
  17396. }
  17397. }
  17398. for (let i = 0; i < definitions.length; i++) {
  17399. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17400. record_function(fn);
  17401. }
  17402. for (const [name, fn] of function_table) {
  17403. if (name === '__init__') {
  17404. fn.ensure_defined();
  17405. }
  17406. }
  17407. for (const fn of functions) {
  17408. fn.ensure_defined();
  17409. }
  17410. return functions;
  17411. } else if (args[1] instanceof ast.FunctionDef) {
  17412. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17413. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17414. const creator = (method) => {
  17415. return new torch._C.to_ir(def, _resolver, self, method);
  17416. };
  17417. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17418. if (shouldMangle && this.find_function(name)) {
  17419. name = this.mangle(name);
  17420. }
  17421. const graph = new torch.Graph();
  17422. graph.set_op_version(operator_set_version);
  17423. const fn = new torch._C.GraphFunction(name, graph, creator);
  17424. fn.__ast__ = def; // remove
  17425. if (self) {
  17426. if (type === 'hook') {
  17427. self.getClassType().addForwardHook(fn);
  17428. } else if (type === 'prehook') {
  17429. self.getClassType().addPreHook(fn);
  17430. } else {
  17431. self.getClassType().addMethod(fn);
  17432. }
  17433. }
  17434. return fn;
  17435. }
  17436. throw new python.Error('Invalid arguments.');
  17437. }
  17438. get_type(name) {
  17439. return this._classes.get(name.qualifiedName());
  17440. }
  17441. get_class(name) {
  17442. return this.get_type(name);
  17443. }
  17444. find_function(name) {
  17445. const key = name.qualifiedName();
  17446. return this._functions.get(key);
  17447. }
  17448. });
  17449. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17450. const ctrl = new torch._C.ControlFlowLoadStores();
  17451. ctrl.run(graph);
  17452. const exit_vars = new torch._C.LoopContinuations();
  17453. exit_vars.run(graph);
  17454. torch._C.InlineLoopCondition(graph);
  17455. const erase_loads_stores = new torch._C.EraseLoadStores();
  17456. erase_loads_stores.run(graph);
  17457. torch._C.TransformExits(graph);
  17458. });
  17459. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17460. /*
  17461. LoopView loop(n);
  17462. if (loop.loopType() != LoopView::ModifiedLoop) {
  17463. return;
  17464. }
  17465. const g = n.owningGraph();
  17466. WithInsertPoint node_insert(n);
  17467. const zero = g.insertConstant(0);
  17468. const one = g.insertConstant(1);
  17469. const max_trip_count = loop.maxTripCount();
  17470. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17471. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17472. const inp_condition = toIValue(loop.inputCond());
  17473. if (inp_condition == null || inp_condition.toBool() == false) {
  17474. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17475. }
  17476. loop.replaceInputCondition(condition);
  17477. n.addOutput().setType(IntType::get());
  17478. WithInsertPoint loop_insert(loop.bodyBlock());
  17479. n.addInput(zero);
  17480. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17481. // unset unique name for jitter, its replacement does not have a name
  17482. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17483. const inc_iter = g.insert(aten::add, {new_iter, one});
  17484. loop.bodyBlock().registerOutput(inc_iter);
  17485. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17486. const loop_continue = loop.nextCond();
  17487. const new_condition =
  17488. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17489. loop.bodyBlock().eraseOutput(0);
  17490. loop.bodyBlock().insertOutput(0, new_condition);
  17491. */
  17492. });
  17493. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17494. for (const n of block.nodes()) {
  17495. for (const b of n.blocks()) {
  17496. torch._C.canonicalizeModifiedLoops(b);
  17497. }
  17498. if (n.kind() === 'prim::Loop') {
  17499. torch._C.canonicalizeModifiedLoop(n);
  17500. }
  17501. }
  17502. });
  17503. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17504. torch._C.canonicalizeModifiedLoops(graph.block());
  17505. });
  17506. this.registerType('torch._C.MiniEnvironment', class {
  17507. constructor(b, next) {
  17508. this.next = next || null;
  17509. this.table = new Map();
  17510. }
  17511. setVar(name, value) {
  17512. this.table.set(name, value);
  17513. }
  17514. definedVariables() {
  17515. const result = Array.from(this.table.keys());
  17516. return result.sort();
  17517. }
  17518. findInThisFrame(name) {
  17519. if (this.table.has(name)) {
  17520. return this.table.get(name);
  17521. }
  17522. return null;
  17523. }
  17524. findInAnyFrame(name) {
  17525. /* eslint-disable consistent-this */
  17526. const self = this;
  17527. /* eslint-enable consistent-this */
  17528. for (let runner = self; runner; runner = runner.next) {
  17529. const r = runner.findInThisFrame(name);
  17530. if (r) {
  17531. return r;
  17532. }
  17533. }
  17534. return null;
  17535. }
  17536. });
  17537. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17538. });
  17539. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17540. });
  17541. this.registerType('torch._C.ControlFlowLoadStores', class {
  17542. constructor() {
  17543. this.environment_stack = null;
  17544. }
  17545. pushFrame(b) {
  17546. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17547. }
  17548. popFrame() {
  17549. const old_frame = this.environment_stack;
  17550. this.environment_stack = this.environment_stack.next;
  17551. return old_frame;
  17552. }
  17553. addBlockInput(b, type, name) {
  17554. const g = b.owningGraph();
  17555. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17556. }
  17557. addBlockOutput(exit_block, type, name) {
  17558. const insert = new torch._C.WithInsertPoint(exit_block);
  17559. const g = exit_block.owningGraph();
  17560. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17561. exit_block.registerOutput(block_exit);
  17562. insert.dispose();
  17563. }
  17564. addNodeOutput(n, type, name) {
  17565. const out = n.addOutput().setType(type);
  17566. if (torch._C.meaningfulName(name)) {
  17567. out.setDebugName(name);
  17568. }
  17569. const g = n.owningGraph();
  17570. g.createStore(name, out).insertAfter(n);
  17571. }
  17572. addNodeInput(n, type, name) {
  17573. const g = n.owningGraph();
  17574. const inp = g.createLoad(name, type).insertBefore(n).output();
  17575. n.addInput(inp);
  17576. }
  17577. addIfLoadStores(n) {
  17578. const [true_block, false_block] = n.blocks();
  17579. const true_vars = this.addControlFlowLoadStores(true_block);
  17580. const false_vars = this.addControlFlowLoadStores(false_block);
  17581. const mutated_variables = new Set();
  17582. for (const v of true_vars.definedVariables()) {
  17583. if (false_vars.findInAnyFrame(v)) {
  17584. mutated_variables.add(v);
  17585. }
  17586. }
  17587. for (const v of false_vars.definedVariables()) {
  17588. if (true_vars.findInAnyFrame(v)) {
  17589. mutated_variables.add(v);
  17590. }
  17591. }
  17592. for (const x of mutated_variables) {
  17593. const true_type = true_vars.findInAnyFrame(x);
  17594. const false_type = false_vars.findInAnyFrame(x);
  17595. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17596. this.addBlockOutput(true_block, true_type, x);
  17597. this.addBlockOutput(false_block, false_type, x);
  17598. this.addNodeOutput(n, unified, x);
  17599. }
  17600. }
  17601. addLoopLoadStores(n) {
  17602. const [body_block] = n.blocks();
  17603. const loop_vars = this.addControlFlowLoadStores(body_block);
  17604. for (const name of loop_vars.definedVariables()) {
  17605. const parent_type = this.environment_stack.findInAnyFrame(name);
  17606. if (!parent_type) {
  17607. continue;
  17608. }
  17609. const block_type = loop_vars.findInThisFrame(name);
  17610. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17611. this.addNodeInput(n, parent_type, name);
  17612. this.addBlockInput(body_block, unified_type, name);
  17613. this.addBlockOutput(body_block, block_type, name);
  17614. this.addNodeOutput(n, unified_type, name);
  17615. }
  17616. }
  17617. addControlFlowLoadStores(block) {
  17618. this.pushFrame(block);
  17619. for (const n of block.nodes()) {
  17620. switch (n.kind()) {
  17621. case 'prim::If': {
  17622. this.addIfLoadStores(n);
  17623. break;
  17624. }
  17625. case 'prim::Loop': {
  17626. this.addLoopLoadStores(n);
  17627. break;
  17628. }
  17629. case 'prim::Closure': {
  17630. for (const b of n.blocks()) {
  17631. this.addControlFlowLoadStores(b);
  17632. }
  17633. break;
  17634. }
  17635. case 'prim::Store': {
  17636. this.environment_stack.setVar(n.s('name'), n.input().type());
  17637. break;
  17638. }
  17639. case 'prim::ComprehensionScope': {
  17640. this.addControlFlowLoadStores(n.blocks().at(0));
  17641. break;
  17642. }
  17643. default: {
  17644. break;
  17645. }
  17646. }
  17647. }
  17648. return this.popFrame();
  17649. }
  17650. run(graph) {
  17651. this.addControlFlowLoadStores(graph.block());
  17652. }
  17653. });
  17654. this.registerType('torch._C.LoopContinuations', class {
  17655. constructor() {
  17656. this._graph = null;
  17657. this._false_val = null;
  17658. this._curr_loop = null;
  17659. }
  17660. assignExitContinuations(block) {
  17661. for (const n of block.nodes()) {
  17662. switch (n.kind()) {
  17663. case 'prim::If': {
  17664. this.assignExitContinuations(n.blocks().at(0));
  17665. this.assignExitContinuations(n.blocks().at(1));
  17666. break;
  17667. }
  17668. case 'prim::Closure': {
  17669. const closure_block = new torch._C.LoopContinuations();
  17670. closure_block.run(n.blocks().at(0));
  17671. break;
  17672. }
  17673. case 'prim::Loop': {
  17674. const prev_loop = this._curr_loop;
  17675. this._curr_loop = n;
  17676. this.assignExitContinuations(n.blocks().at(0));
  17677. this._curr_loop = prev_loop;
  17678. break;
  17679. }
  17680. case 'prim::ContinueStmt': {
  17681. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17682. const header_block = loop_continuation.addBlock();
  17683. const [, pre_header] = this._curr_loop.blocks();
  17684. header_block.cloneFrom(pre_header, (v) => v);
  17685. this.InlineBlockBeforeNode(n, header_block);
  17686. loop_continuation.addInput(header_block.outputs()[0]);
  17687. loop_continuation.eraseBlock(0);
  17688. this.addLoopCarriedOutputs(loop_continuation);
  17689. n.destroy();
  17690. break;
  17691. }
  17692. case 'prim::BreakStmt': {
  17693. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17694. loop_exit.addInput(this._false_val);
  17695. this.addLoopCarriedOutputs(loop_exit);
  17696. n.destroy();
  17697. break;
  17698. }
  17699. default: {
  17700. break;
  17701. }
  17702. }
  17703. }
  17704. }
  17705. run(...args) {
  17706. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17707. const [graph] = args;
  17708. this.run(graph.block());
  17709. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17710. const [b] = args;
  17711. {
  17712. this._graph = b.owningGraph();
  17713. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17714. this._false_val = this._graph.insertConstant(false);
  17715. guard.dispose();
  17716. }
  17717. this.assignExitContinuations(b);
  17718. } else {
  17719. throw new python.Error('Not implemented.');
  17720. }
  17721. }
  17722. });
  17723. this.registerType('torch._C.LoopView', class {
  17724. constructor(node) {
  17725. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17726. this._node = node;
  17727. }
  17728. bodyBlock() {
  17729. return this._node.blocks().at(0);
  17730. }
  17731. nextCond() {
  17732. return this.bodyBlock().outputs()[0];
  17733. }
  17734. carriedOutputs() {
  17735. return this._node.outputs();
  17736. }
  17737. bodyCarriedInputs() {
  17738. return this.bodyBlock().inputs().slice(1);
  17739. }
  17740. bodyCarriedOutputs() {
  17741. return this.bodyBlock().outputs().slice(1);
  17742. }
  17743. });
  17744. this.registerType('torch._C.WithLoopStatus', class {
  17745. constructor(to_ir, new_status) {
  17746. this._to_ir = to_ir;
  17747. this._prev = this._to_ir._loop_status;
  17748. this._to_ir._loop_status = new_status;
  17749. }
  17750. dispose() {
  17751. this._to_ir._loop_status = this._prev;
  17752. }
  17753. });
  17754. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17755. for (const block_node of block.nodes()) {
  17756. block_node.moveBefore(before_node);
  17757. }
  17758. });
  17759. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  17760. if (args.length === 1 && args[0] instanceof torch.Block) {
  17761. const [block] = args;
  17762. for (const n of block.nodes()) {
  17763. for (const b of n.blocks()) {
  17764. torch._C.inlineLoopCondition(b);
  17765. }
  17766. if (n.kind() === 'prim::Loop') {
  17767. torch._C.inlineLoopCondition(n);
  17768. }
  17769. }
  17770. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  17771. const [n] = args;
  17772. const [body_block, pre_header] = n.blocks();
  17773. const temp_block = n.addBlock();
  17774. temp_block.cloneFrom(pre_header, (v) => v);
  17775. torch._C.InlineBlockBeforeNode(n, temp_block);
  17776. n.insertInput(1, temp_block.outputs()[0]);
  17777. n.eraseBlock(2);
  17778. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  17779. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  17780. n.eraseBlock(1);
  17781. } else {
  17782. throw new python.Error('Not implemented.');
  17783. }
  17784. });
  17785. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  17786. torch._C.inlineLoopCondition(graph.block());
  17787. });
  17788. this.registerType('torch._C.EraseLoadStores', class {
  17789. pushFrame(b) {
  17790. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  17791. }
  17792. popFrame() {
  17793. const old_frame = this.environment_stack;
  17794. this.environment_stack = this.environment_stack.next;
  17795. return old_frame;
  17796. }
  17797. eraseBlockLoadStores(block) {
  17798. this.pushFrame(block);
  17799. for (const n of block.nodes()) {
  17800. switch (n.kind()) {
  17801. case 'prim::Store': {
  17802. this.environment_stack.setVar(n.s('name'), n.input());
  17803. n.destroy();
  17804. break;
  17805. }
  17806. case 'prim::Load': {
  17807. const name = n.s('name');
  17808. const value = this.environment_stack.findInAnyFrame(name);
  17809. torch._C.TORCH_INTERNAL_ASSERT(value);
  17810. n.output().replaceAllUsesWith(value);
  17811. n.destroy();
  17812. break;
  17813. }
  17814. case 'prim::ComprehensionScope': {
  17815. const [body] = n.blocks();
  17816. this.eraseBlockLoadStores(body);
  17817. for (const body_node of body.nodes()) {
  17818. body_node.moveBefore(n);
  17819. }
  17820. n.destroy();
  17821. break;
  17822. }
  17823. default: {
  17824. for (const b of n.blocks()) {
  17825. this.eraseBlockLoadStores(b);
  17826. }
  17827. break;
  17828. }
  17829. }
  17830. }
  17831. this.popFrame();
  17832. }
  17833. run(graph) {
  17834. this.eraseBlockLoadStores(graph.block());
  17835. }
  17836. });
  17837. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  17838. });
  17839. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  17840. });
  17841. this.registerType('torch._C.ExitPair', class {
  17842. constructor(exit_v, exit_val_ref) {
  17843. const exit_vals = [];
  17844. for (const v of exit_val_ref) {
  17845. exit_vals.push(v);
  17846. }
  17847. if (exit_v.type() !== torch.BoolType.get()) {
  17848. throw new python.Error('Invalid exit value type.');
  17849. }
  17850. this.first = exit_v;
  17851. this.second = exit_vals;
  17852. }
  17853. hasExited() {
  17854. return this.first;
  17855. }
  17856. exitValues() {
  17857. return this.second;
  17858. }
  17859. });
  17860. this.registerType('torch._C.ExitTransformer', class {
  17861. constructor(graph) {
  17862. this._graph = graph;
  17863. this._target_block = null;
  17864. this._unit_values = new Map();
  17865. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  17866. this._true_val = this._graph.insertConstant(true);
  17867. this._false_val = this._graph.insertConstant(false);
  17868. this._throws_val = this.getUnitValue(torch.BoolType.get());
  17869. guard.dispose();
  17870. }
  17871. getUnitValue(type) {
  17872. const maybe_val = this._unit_values.get(type);
  17873. if (maybe_val) {
  17874. return maybe_val;
  17875. }
  17876. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  17877. this._unit_values.set(type, unit);
  17878. return unit;
  17879. }
  17880. transformReturnStmts() {
  17881. this._current_exit_kind = 'prim::ReturnStmt';
  17882. this.transformExits(this._graph.block());
  17883. }
  17884. transformLoopContinuations() {
  17885. this._current_exit_kind = 'prim::LoopContinuation';
  17886. this.transformExits(this._graph.block());
  17887. }
  17888. destroyNodeAfterExit(n) {
  17889. for (const output of n.outputs()) {
  17890. if (output.uses().length > 0) {
  17891. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  17892. }
  17893. }
  17894. n.destroy();
  17895. }
  17896. deleteAfterExitNodes(block, iter) {
  17897. const nodes = block.nodes();
  17898. if (iter === nodes.end()) {
  17899. return;
  17900. }
  17901. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  17902. for (const it of Array.from(nodes).reverse()) {
  17903. if (it === iter) {
  17904. break;
  17905. }
  17906. if (it !== block.return_node()) {
  17907. this.destroyNodeAfterExit(it);
  17908. }
  17909. }
  17910. this.destroyNodeAfterExit(iter);
  17911. insert.dispose();
  17912. }
  17913. updateTargetBlock(block) {
  17914. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  17915. this._target_block = block;
  17916. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  17917. this._target_block = block;
  17918. }
  17919. }
  17920. transformLoop(node) {
  17921. const loop = new torch._C.LoopView(node);
  17922. const body = loop.bodyBlock();
  17923. const exit_pair = this.transformExits(body);
  17924. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  17925. return this.constructWontExitPair();
  17926. }
  17927. const insert = new torch._C.WithInsertPoint(body);
  17928. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  17929. new_if.addInput(exit_pair.hasExited());
  17930. new_if.addBlock().registerOutput(this._false_val);
  17931. new_if.addBlock().registerOutput(loop.nextCond());
  17932. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  17933. loop.bodyBlock().eraseOutput(0);
  17934. loop.bodyBlock().insertOutput(0, new_condition);
  17935. node.addInput(this._false_val);
  17936. body.addInput().setType(torch.BoolType.get());
  17937. body.registerOutput(exit_pair.hasExited());
  17938. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  17939. for (const exit_value of exit_pair.exitValues()) {
  17940. const typ = exit_value.type();
  17941. node.addInput(this.getUnitValue(typ));
  17942. node.addOutput().setType(typ);
  17943. body.addInput().setType(typ);
  17944. body.registerOutput(exit_value);
  17945. }
  17946. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  17947. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  17948. insert.dispose();
  17949. return result;
  17950. }
  17951. calcIfExitStatus(then_status, else_status) {
  17952. if (then_status === 'THROWS') {
  17953. return else_status;
  17954. } else if (else_status === 'THROWS') {
  17955. return then_status;
  17956. }
  17957. if (then_status === 'WONT' && else_status === 'WONT') {
  17958. return 'WONT';
  17959. }
  17960. if (then_status === 'WILL' && else_status === 'WILL') {
  17961. return 'WILL';
  17962. }
  17963. return 'MIGHT';
  17964. }
  17965. transformIf(node) {
  17966. const [then_block, else_block] = node.blocks();
  17967. let then_pair = this.transformExits(then_block);
  17968. let else_pair = this.transformExits(else_block);
  17969. const then_status = this.getExitStatus(then_pair);
  17970. const else_status = this.getExitStatus(else_pair);
  17971. const if_status = this.calcIfExitStatus(then_status, else_status);
  17972. if (if_status === 'THROWS') {
  17973. return this.constructThrowsExitPair();
  17974. }
  17975. if (if_status === 'WONT') {
  17976. return this.constructWontExitPair();
  17977. }
  17978. if (then_status === 'WONT' || then_status === 'THROWS') {
  17979. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  17980. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  17981. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  17982. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  17983. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  17984. }
  17985. let has_exited = null;
  17986. if (if_status === 'WILL') {
  17987. has_exited = this._true_val;
  17988. } else {
  17989. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  17990. has_exited = node.outputs().at(node.outputs().length - 1);
  17991. }
  17992. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  17993. const num_exit_vals = then_pair.exitValues().size();
  17994. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  17995. return new torch._C.ExitPair(has_exited, exit_vals);
  17996. }
  17997. transformExits(block) {
  17998. const prev_target_block = this._target_block;
  17999. this.updateTargetBlock(block);
  18000. let exit_pair = this.constructWontExitPair();
  18001. for (const node of block.nodes()) {
  18002. const it = node.next;
  18003. switch (node.kind()) {
  18004. case 'prim::RaiseException': {
  18005. exit_pair = this.constructThrowsExitPair();
  18006. break;
  18007. }
  18008. case 'prim::ReturnStmt':
  18009. case 'prim::LoopContinuation': {
  18010. if (node.kind() === this._current_exit_kind) {
  18011. exit_pair = this.constructWillExitPair(node.inputs());
  18012. node.destroy();
  18013. }
  18014. break;
  18015. }
  18016. case 'prim::If': {
  18017. exit_pair = this.transformIf(node);
  18018. break;
  18019. }
  18020. case 'prim::With': {
  18021. exit_pair = this.transformWith(node);
  18022. break;
  18023. }
  18024. case 'prim::Closure': {
  18025. this.transformExits(node.blocks().at(0));
  18026. break;
  18027. }
  18028. case 'prim::Loop': {
  18029. exit_pair = this.transformLoop(node);
  18030. break;
  18031. }
  18032. default: {
  18033. break;
  18034. }
  18035. }
  18036. const status = this.getExitStatus(exit_pair);
  18037. if (status === 'WILL' || status === 'THROWS') {
  18038. this.deleteAfterExitNodes(block, it);
  18039. break;
  18040. }
  18041. if (status === 'MIGHT') {
  18042. throw new python.Error('Not implemented.');
  18043. // const nodes = block.nodes();
  18044. // if (node === nodes[nodes.length - 1]) {
  18045. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18046. // }
  18047. // break;
  18048. }
  18049. }
  18050. if (this._target_block === block) {
  18051. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18052. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18053. new_if.addBlock();
  18054. new_if.addBlock();
  18055. new_if.addInput(exit_pair.hasExited());
  18056. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18057. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18058. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18059. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18060. }
  18061. exit_pair = this.constructWontExitPair();
  18062. }
  18063. this._target_block = prev_target_block;
  18064. return exit_pair;
  18065. }
  18066. constructThrowsExitPair() {
  18067. return new torch._C.ExitPair(this._throws_val, []);
  18068. }
  18069. constructWontExitPair() {
  18070. return new torch._C.ExitPair(this._false_val, []);
  18071. }
  18072. constructWillExitPair(exit_val_ref) {
  18073. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18074. }
  18075. getExitStatus(exit_pair) {
  18076. const exit_v = exit_pair.hasExited();
  18077. if (exit_v === this._true_val) {
  18078. return 'WILL';
  18079. } else if (exit_v === this._false_val) {
  18080. return 'WONT';
  18081. } else if (exit_v === this._throws_val) {
  18082. return 'THROWS';
  18083. }
  18084. return 'MIGHT';
  18085. }
  18086. static owningNodeKind(block) {
  18087. if (block.owningNode()) {
  18088. return block.owningNode().kind();
  18089. }
  18090. return null;
  18091. }
  18092. static isGraphOrClosureBlock(block) {
  18093. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18094. }
  18095. static removeOutputs(b) {
  18096. while (b.outputs().length > 0) {
  18097. b.eraseOutput(0);
  18098. }
  18099. }
  18100. static registerBlockOutputs(b, outs) {
  18101. for (const out of outs) {
  18102. b.registerOutput(out);
  18103. }
  18104. }
  18105. static replaceBlockOutputs(b, outs) {
  18106. torch._C.ExitTransformer.removeOutputs(b);
  18107. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18108. }
  18109. });
  18110. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18111. });
  18112. this.registerFunction('torch._C.TransformExits', (graph) => {
  18113. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18114. const e_loop = new torch._C.ExitTransformer(graph);
  18115. e_loop.transformLoopContinuations();
  18116. const e_ret = new torch._C.ExitTransformer(graph);
  18117. e_ret.transformReturnStmts();
  18118. torch._C.inlineConsecutiveIfs(graph.block());
  18119. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18120. });
  18121. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18122. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18123. const args = iter.inputs();
  18124. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18125. newSub.replaceInput(0, args[1]);
  18126. newSub.replaceInput(1, args[0]);
  18127. iter.destroyCurrent();
  18128. return true;
  18129. }
  18130. return false;
  18131. });
  18132. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18133. });
  18134. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18135. const args = iter.inputs();
  18136. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18137. if (iter.kind() === 'aten::__is__') {
  18138. iter.replaceWithNewSymbol('aten::eq');
  18139. iter.destroyCurrent();
  18140. return true;
  18141. }
  18142. if (iter.kind() === 'aten::__isnot__') {
  18143. iter.replaceWithNewSymbol('aten::ne');
  18144. iter.destroyCurrent();
  18145. return true;
  18146. }
  18147. }
  18148. return false;
  18149. });
  18150. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18151. for (const it of block.nodes()) {
  18152. for (const sub of it.blocks()) {
  18153. torch._C.NormalizeOps(sub);
  18154. }
  18155. if (torch._C.normalizeRSub(it)) {
  18156. continue;
  18157. }
  18158. if (torch._C.normalizeOpAliases(it)) {
  18159. continue;
  18160. }
  18161. if (torch._C.normalizeIsBool(it)) {
  18162. continue;
  18163. }
  18164. }
  18165. });
  18166. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18167. return false;
  18168. });
  18169. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18170. /*
  18171. torch._C.liftClosures(to_clean);
  18172. torch._C.inlineForkedClosures(to_clean);
  18173. */
  18174. if (torch._C.getInlineEverythingMode()) {
  18175. torch._C.Inline(to_clean);
  18176. }
  18177. /*
  18178. torch._C.eraseListLiterals(to_clean);
  18179. */
  18180. torch._C.LowerSimpleTuples(to_clean);
  18181. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18182. torch._C.ConstantPooling(to_clean);
  18183. /*
  18184. torch._C.CanonicalizeOutputs(to_clean);
  18185. torch._C.AnnotateWarns(to_clean);
  18186. */
  18187. });
  18188. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18189. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18190. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18191. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18192. constructor(cpp_module) {
  18193. super();
  18194. this._initializing = true;
  18195. this._c = cpp_module;
  18196. }
  18197. static _construct(cpp_module, init_fn) {
  18198. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18199. init_fn(script_module);
  18200. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18201. return script_module;
  18202. }
  18203. static _finalize_scriptmodule(script_module) {
  18204. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18205. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18206. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18207. script_module._initializing = false;
  18208. }
  18209. get graph() {
  18210. // return this._c._get_method('forward').graph;
  18211. return this._c.graph;
  18212. }
  18213. get code_with_constants() {
  18214. // return this.forward.code_with_constants;
  18215. return this._c.code_with_constants;
  18216. }
  18217. __setattr__(name, value) {
  18218. if (this._initializing) {
  18219. super.__setattr__(name, value);
  18220. } else if (this._modules.has(name)) {
  18221. this._modules.set(name, value);
  18222. } else if (this._c.hasattr(name)) {
  18223. this._c.setattr(name, value);
  18224. } else {
  18225. //
  18226. }
  18227. }
  18228. __getattr__(name) {
  18229. if (this._initializing) {
  18230. return super.__getattr__(name);
  18231. }
  18232. if (this._modules.has(name)) {
  18233. return this._modules.get(name);
  18234. }
  18235. if (this._c.hasattr(name)) {
  18236. return this._c.getattr(name);
  18237. }
  18238. if (this._c._has_method(name)) {
  18239. //
  18240. }
  18241. return super.__getattr__(name);
  18242. }
  18243. });
  18244. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18245. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18246. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18247. torch.CompilationUnit = torch.jit.CompilationUnit;
  18248. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18249. torch._C.ScriptModule = torch.ScriptModule;
  18250. torch._C.ClassType = torch.ClassType;
  18251. this.registerType('torch._C.FlatBuffersLoader', class {
  18252. constructor(cu) {
  18253. this._cu = cu;
  18254. const torch = cu.execution.__import__('torch');
  18255. this._torch = torch;
  18256. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18257. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18258. this._ivalue_parsers = new Map();
  18259. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18260. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18261. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18262. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18263. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18264. }
  18265. parseModule(module) {
  18266. this._module = module;
  18267. this._all_functions = new Map();
  18268. this._all_ivalues = new Array(module.ivalues.length);
  18269. this._all_types = new Array(module.object_types.length);
  18270. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18271. for (let i = 0; i < mobile_ivalue_size; i++) {
  18272. this.parseAndPopulate(i, module.ivalues[i]);
  18273. }
  18274. const m = this._all_ivalues[module.state_obj];
  18275. for (const [name, value] of this._all_functions) {
  18276. const class_index = module.ivalues[name].val.class_type;
  18277. const class_type = this._all_types[class_index];
  18278. if (value) {
  18279. class_type.addMethod(value);
  18280. }
  18281. }
  18282. m._min_operator_version = module.operator_version;
  18283. m._bytecode_version = module.bytecode_version;
  18284. return m;
  18285. }
  18286. parseAndPopulate(i, ivalue) {
  18287. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18288. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18289. } else {
  18290. this._all_ivalues[i] = this.parseIValue(ivalue);
  18291. }
  18292. }
  18293. parseFunction(/* val */) {
  18294. return null;
  18295. }
  18296. parseIValue(ivalue) {
  18297. if (ivalue.val) {
  18298. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18299. return callback(ivalue);
  18300. }
  18301. return null;
  18302. }
  18303. parseTensor(ivalue) {
  18304. return this.parseTensorFromMetadata(ivalue.val);
  18305. }
  18306. parseTensorFromMetadata(metadata) {
  18307. if (metadata.quantized_schema) {
  18308. throw new torch.Error('Quantized schema not implemented.');
  18309. }
  18310. const index = metadata.storage_location_index;
  18311. const data = this._module.storage_data[index].data;
  18312. const dtype = this._dtypes.get(metadata.scalar_type);
  18313. const size = data.length / dtype.itemsize();
  18314. const storage = new torch.storage.TypedStorage(size, dtype);
  18315. storage._set_cdata(data);
  18316. const tensor = new torch.Tensor();
  18317. const shape = Array.from(metadata.sizes);
  18318. const stride = Array.from(metadata.strides);
  18319. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18320. return tensor;
  18321. }
  18322. parseObject(ivalue) {
  18323. const object = ivalue.val;
  18324. const obj_type = this._module.object_types[object.type_index];
  18325. const cls = this.getOrCreateClassTypeForObject(object);
  18326. switch (obj_type.type) {
  18327. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18328. const torch = this._torch;
  18329. const obj = torch.ScriptObject.create(cls);
  18330. for (let i = 0; i < object.attrs.length; i++) {
  18331. const attr_name = obj_type.attr_names[i];
  18332. const val = this._all_ivalues[object.attrs[i]];
  18333. obj.__setattr__(attr_name, val);
  18334. }
  18335. return obj;
  18336. }
  18337. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18338. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18339. default: {
  18340. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18341. }
  18342. }
  18343. }
  18344. getOrCreateClassTypeForObject(object) {
  18345. let cls = this._all_types[object.type_index];
  18346. const obj_type = this._module.object_types[object.type_index];
  18347. if (!cls) {
  18348. const name = obj_type.type_name;
  18349. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18350. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18351. if (!cls) {
  18352. const torch = this._torch;
  18353. cls = torch.ClassType.create(name, this._cu, true);
  18354. this._cu.register_type(cls);
  18355. }
  18356. } else {
  18357. // cls = c10::parseType(qn_str).cast<ClassType>();
  18358. }
  18359. this._all_types[object.type_index] = cls;
  18360. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18361. for (let i = 0; i < object.attrs.length; i++) {
  18362. // const val = this._all_ivalues[object.attrs[i]];
  18363. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18364. }
  18365. }
  18366. }
  18367. return cls;
  18368. }
  18369. });
  18370. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18371. constructor(export_module, flat_args_adapter) {
  18372. super();
  18373. const export_graph = copy.deepcopy(export_module.graph);
  18374. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18375. this.graph = torch.fx.Graph();
  18376. this.graph.owning_module = this;
  18377. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18378. this.flat_args_adapter = flat_args_adapter;
  18379. this.adapted = false;
  18380. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18381. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18382. }
  18383. });
  18384. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18385. constructor(input_specs, output_specs) {
  18386. this.input_specs = input_specs;
  18387. this.output_specs = output_specs;
  18388. }
  18389. get user_inputs() {
  18390. const user_inputs = [];
  18391. for (const s of this.input_specs) {
  18392. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18393. continue;
  18394. }
  18395. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18396. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18397. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18398. user_inputs.push(s.arg.name);
  18399. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18400. user_inputs.push(s.arg.value);
  18401. } else {
  18402. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18403. }
  18404. }
  18405. return user_inputs;
  18406. }
  18407. get user_outputs() {
  18408. const user_outputs = [];
  18409. for (const s of this.output_specs) {
  18410. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18411. continue;
  18412. }
  18413. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18414. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18415. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18416. user_outputs.push(s.arg.name);
  18417. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18418. user_outputs.push(s.arg.value);
  18419. } else {
  18420. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18421. }
  18422. }
  18423. return user_outputs;
  18424. }
  18425. get inputs_to_parameters() {
  18426. return new Map(this.input_specs
  18427. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18428. .map((s) => [s.arg.name, s.target]));
  18429. }
  18430. get inputs_to_buffers() {
  18431. return new Map(this.input_specs
  18432. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18433. .map((s) => [s.arg.name, s.target]));
  18434. }
  18435. get inputs_to_lifted_tensor_constants() {
  18436. return new Map(this.input_specs
  18437. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18438. .map((s) => [s.arg.name, s.target]));
  18439. }
  18440. });
  18441. torch.export.graph_signature.InputKind = {
  18442. USER_INPUT: 0,
  18443. PARAMETER: 1,
  18444. BUFFER: 2,
  18445. CONSTANT_TENSOR: 3,
  18446. CUSTOM_OBJ: 4,
  18447. TOKEN: 5
  18448. };
  18449. this.registerType('torch.export.graph_signature.InputSpec', class {
  18450. constructor(kind, arg, target, persistent) {
  18451. this.kind = kind;
  18452. this.arg = arg;
  18453. this.target = target;
  18454. this.persistent = persistent || null;
  18455. }
  18456. });
  18457. torch.export.graph_signature.OutputKind = {
  18458. USER_OUTPUT: 0,
  18459. LOSS_OUTPUT: 1,
  18460. BUFFER_MUTATION: 2,
  18461. GRADIENT_TO_PARAMETER: 3,
  18462. GRADIENT_TO_USER_INPUT: 4,
  18463. USER_INPUT_MUTATION: 5,
  18464. TOKEN: 6
  18465. };
  18466. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18467. constructor(kind, arg, target) {
  18468. this.kind = kind;
  18469. this.arg = arg;
  18470. this.target = target;
  18471. }
  18472. });
  18473. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18474. constructor(name, value) {
  18475. this.name = name;
  18476. this.value = value; // Union[int, float, bool, str, None]
  18477. }
  18478. });
  18479. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18480. constructor(name) {
  18481. this.name = name;
  18482. }
  18483. });
  18484. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18485. constructor(name) {
  18486. this.name = name;
  18487. }
  18488. });
  18489. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18490. constructor(name, class_fqn, fake_val) {
  18491. this.name = name;
  18492. this.class_fqn = class_fqn;
  18493. this.fake_val = fake_val;
  18494. }
  18495. });
  18496. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18497. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18498. // graph._codegen = torch.fx.graph.CodeGen()
  18499. this._graph_module = this._create_graph_module_for_export(root, graph);
  18500. if (root instanceof torch.fx.GraphModule) {
  18501. // this._graph_module.meta.update(root.meta);
  18502. }
  18503. this._graph_signature = graph_signature;
  18504. this._state_dict = state_dict;
  18505. this._range_constraints = range_constraints;
  18506. this._module_call_graph = module_call_graph;
  18507. this._example_inputs = example_inputs;
  18508. this._constants = tensor_constants || constants || {};
  18509. }
  18510. _create_graph_module_for_export(root, graph) {
  18511. let gm = null;
  18512. try {
  18513. gm = new torch.fx.GraphModule(root, graph);
  18514. } catch {
  18515. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18516. gm._graph = graph;
  18517. }
  18518. return gm;
  18519. }
  18520. get graph_module() {
  18521. return this._graph_module;
  18522. }
  18523. get graph() {
  18524. return this._graph_module.graph;
  18525. }
  18526. get graph_signature() {
  18527. return this._graph_signature;
  18528. }
  18529. get state_dict() {
  18530. return this._state_dict;
  18531. }
  18532. get constants() {
  18533. return this._constants;
  18534. }
  18535. });
  18536. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18537. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18538. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18539. return new torch.fx.graph_module.GraphModule(root, graph);
  18540. });
  18541. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18542. module = torch.export._remove_effect_tokens(module);
  18543. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18544. });
  18545. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18546. return new torch.fx.graph_module.GraphModule(root, graph);
  18547. });
  18548. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18549. constructor(exported_program, state_dict, constants, example_inputs) {
  18550. this.exported_program = exported_program;
  18551. this.state_dict = state_dict;
  18552. this.constants = constants;
  18553. this.example_inputs = example_inputs;
  18554. }
  18555. });
  18556. torch._export.serde.serialize._SYM_OPS = new Set([
  18557. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18558. operator.neg, operator.pos, operator.and_, operator.or_,
  18559. math.trunc, torch.sym_not,
  18560. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18561. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18562. operator.truediv, operator.and_
  18563. ]);
  18564. this.registerType('torch._export.serde.union._Union', class {
  18565. constructor(obj) {
  18566. if (obj.$type) {
  18567. this.type = obj.$type;
  18568. this[obj.$type] = obj.$value;
  18569. delete obj.$type;
  18570. delete obj.$value;
  18571. } else if (obj.type) {
  18572. this.type = obj.type;
  18573. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18574. this[obj.type] = Object.fromEntries(entries);
  18575. } else {
  18576. let entries = Object.entries(obj);
  18577. if (entries.length > 1) {
  18578. entries = entries.filter(([, value]) => value !== null);
  18579. }
  18580. if (entries.length !== 1) {
  18581. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18582. }
  18583. const [entry] = entries;
  18584. const [type, value] = entry;
  18585. this.type = type;
  18586. this[type] = value;
  18587. }
  18588. }
  18589. get value() {
  18590. return this[this.type];
  18591. }
  18592. });
  18593. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18594. constructor(obj) {
  18595. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18596. this.name = obj.name;
  18597. }
  18598. });
  18599. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18600. constructor(obj) {
  18601. super(obj);
  18602. switch (this.type) {
  18603. case 'as_int':
  18604. case 'as_ints':
  18605. case 'as_float':
  18606. case 'as_floats':
  18607. case 'as_bool':
  18608. case 'as_bools':
  18609. case 'as_string':
  18610. case 'as_strings':
  18611. case 'as_scalar_type':
  18612. case 'as_device':
  18613. case 'as_memory_format':
  18614. case 'as_layout':
  18615. break;
  18616. case 'as_none':
  18617. this.as_none = null;
  18618. break;
  18619. case 'as_tensor':
  18620. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18621. break;
  18622. case 'as_tensors':
  18623. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18624. break;
  18625. case 'as_graph':
  18626. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18627. break;
  18628. case 'as_sym_int':
  18629. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18630. break;
  18631. case 'as_sym_ints':
  18632. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18633. break;
  18634. case 'as_sym_bool':
  18635. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18636. break;
  18637. case 'as_sym_bools':
  18638. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18639. break;
  18640. case 'as_sym_float':
  18641. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18642. break;
  18643. case 'as_sym_floats':
  18644. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18645. break;
  18646. case 'as_optional_tensors':
  18647. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18648. break;
  18649. case 'as_custom_obj':
  18650. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18651. break;
  18652. // case 'as_graph': GraphArgument
  18653. default:
  18654. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18655. }
  18656. }
  18657. });
  18658. this.registerType('torch._export.serde.schema.Node', class {
  18659. constructor(obj) {
  18660. this.target = obj.target;
  18661. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18662. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18663. this.metadata = new Map(Object.entries(obj.metadata));
  18664. }
  18665. });
  18666. torch._export.serde.schema.ScalarType = {
  18667. UNKNOWN: 0,
  18668. BYTE: 1,
  18669. CHAR: 2,
  18670. SHORT: 3,
  18671. INT: 4,
  18672. LONG: 5,
  18673. HALF: 6,
  18674. FLOAT: 7,
  18675. DOUBLE: 8,
  18676. COMPLEXHALF: 9,
  18677. COMPLEXFLOAT: 10,
  18678. COMPLEXDOUBLE: 11,
  18679. BOOL: 12,
  18680. BFLOAT16: 13,
  18681. UINT16: 28,
  18682. FLOAT8E4M3FN: 29,
  18683. FLOAT8E5M2: 30,
  18684. FLOAT8E4M3FNUZ: 31,
  18685. FLOAT8E5M2FNUZ: 32,
  18686. };
  18687. torch._export.serde.schema.Layout = {
  18688. Unknown: 0,
  18689. SparseCoo: 1,
  18690. SparseCsr: 2,
  18691. SparseCsc: 3,
  18692. SparseBsr: 4,
  18693. SparseBsc: 5,
  18694. _mkldnn: 6,
  18695. Strided: 7
  18696. };
  18697. torch._export.serde.schema.MemoryFormat = {
  18698. Unknown: 0,
  18699. ContiguousFormat: 1,
  18700. ChannelsLast: 2,
  18701. ChannelsLast3d: 3,
  18702. PreserveFormat: 4,
  18703. };
  18704. this.registerType('torch._export.serde.schema.Device', class {
  18705. constructor(obj) {
  18706. Object.assign(this, { ...obj });
  18707. }
  18708. });
  18709. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18710. constructor(obj) {
  18711. obj = obj.meta || obj;
  18712. this.dtype = obj.dtype;
  18713. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18714. this.requires_grad = obj.requires_grad;
  18715. this.device = obj.device;
  18716. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18717. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18718. this.layout = obj.layout;
  18719. }
  18720. });
  18721. this.registerType('torch._export.serde.schema.Graph', class {
  18722. constructor(obj) {
  18723. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18724. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18725. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18726. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18727. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18728. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18729. this.is_single_tensor_return = obj.is_single_tensor_return;
  18730. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18731. if (obj.contants) {
  18732. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18733. // graph_signature -> input_specs -> tensor_constant
  18734. }
  18735. }
  18736. });
  18737. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18738. constructor(obj) {
  18739. Object.assign(this, { ...obj });
  18740. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18741. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18742. }
  18743. });
  18744. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18745. constructor(obj) {
  18746. Object.assign(this, { ...obj });
  18747. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18748. }
  18749. });
  18750. this.registerType('torch._export.serde.schema.GraphModule', class {
  18751. constructor(obj) {
  18752. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18753. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18754. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18755. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18756. }
  18757. });
  18758. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  18759. constructor(obj) {
  18760. Object.assign(this, { ...obj });
  18761. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  18762. }
  18763. });
  18764. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  18765. this.registerType('torch._export.serde.schema.SymExpr', class {
  18766. constructor(obj) {
  18767. this.expr_str = obj.expr_str;
  18768. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  18769. }
  18770. });
  18771. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  18772. constructor(obj) {
  18773. super(obj);
  18774. if (this.type === 'as_int') {
  18775. // continue
  18776. } else if (this.type === 'as_expr') {
  18777. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18778. } else {
  18779. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  18780. }
  18781. }
  18782. });
  18783. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  18784. constructor(obj) {
  18785. super(obj);
  18786. if (this.type === 'as_bool') {
  18787. // continue
  18788. } else if (this.type === 'as_expr') {
  18789. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18790. } else {
  18791. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  18792. }
  18793. }
  18794. });
  18795. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  18796. constructor(obj) {
  18797. super(obj);
  18798. Object.assign(this, { ...obj });
  18799. }
  18800. });
  18801. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  18802. constructor(obj) {
  18803. super(obj);
  18804. Object.assign(this, { ...obj });
  18805. }
  18806. });
  18807. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  18808. constructor(obj) {
  18809. super(obj);
  18810. Object.assign(this, { ...obj });
  18811. }
  18812. });
  18813. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  18814. constructor(obj) {
  18815. Object.assign(this, { ...obj });
  18816. }
  18817. });
  18818. this.registerType('torch._export.serde.schema.GraphSignature', class {
  18819. constructor(obj) {
  18820. this.input_specs = [];
  18821. if (Array.isArray(obj.input_specs)) {
  18822. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  18823. }
  18824. if (Array.isArray(obj.user_inputs)) {
  18825. for (const user_input of obj.user_inputs) {
  18826. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  18827. }
  18828. }
  18829. if (obj.inputs_to_parameters) {
  18830. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  18831. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  18832. }
  18833. }
  18834. this.output_specs = [];
  18835. if (Array.isArray(obj.output_specs)) {
  18836. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  18837. }
  18838. }
  18839. });
  18840. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  18841. constructor(obj) {
  18842. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18843. }
  18844. });
  18845. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  18846. constructor(obj) {
  18847. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18848. this.parameter_name = obj.parameter_name;
  18849. }
  18850. });
  18851. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  18852. constructor(obj) {
  18853. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18854. this.buffer_name = obj.buffer_name;
  18855. }
  18856. });
  18857. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  18858. constructor(obj) {
  18859. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18860. this.tensor_constant_name = obj.tensor_constant_name;
  18861. }
  18862. });
  18863. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  18864. constructor(obj) {
  18865. this.name = obj.name;
  18866. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  18867. }
  18868. });
  18869. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  18870. constructor(obj) {
  18871. super(obj);
  18872. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  18873. // continue
  18874. } else if (this.type === 'as_none') {
  18875. this.as_none = null;
  18876. } else {
  18877. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  18878. }
  18879. }
  18880. });
  18881. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  18882. constructor(obj) {
  18883. super(obj);
  18884. if (this.type === 'user_input') {
  18885. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  18886. } else if (this.type === 'parameter') {
  18887. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  18888. } else if (this.type === 'buffer') {
  18889. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  18890. } else if (this.type === 'tensor_constant') {
  18891. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  18892. } else if (this.type === 'constant_input') {
  18893. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  18894. } else {
  18895. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  18896. }
  18897. /*
  18898. custom_obj: InputToCustomObjSpec
  18899. token: InputTokenSpec
  18900. */
  18901. }
  18902. });
  18903. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  18904. constructor(obj) {
  18905. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18906. }
  18907. });
  18908. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  18909. constructor(obj) {
  18910. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  18911. this.buffer_name = obj.buffer_name;
  18912. }
  18913. });
  18914. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  18915. constructor(obj) {
  18916. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18917. this.parameter_name = obj.parameter_name;
  18918. }
  18919. });
  18920. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  18921. constructor(obj) {
  18922. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18923. this.user_input_name = obj.user_input_name;
  18924. }
  18925. });
  18926. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  18927. constructor(obj) {
  18928. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18929. this.user_input_name = obj.user_input_name;
  18930. }
  18931. });
  18932. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  18933. constructor(obj) {
  18934. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  18935. }
  18936. });
  18937. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  18938. constructor(obj) {
  18939. super(obj);
  18940. if (this.type === 'user_output') {
  18941. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  18942. } else if (this.type === 'loss_output') {
  18943. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  18944. } else if (this.type === 'buffer_mutation') {
  18945. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  18946. } else if (this.type === 'gradient_to_parameter') {
  18947. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  18948. } else if (this.type === 'gradient_to_user_input') {
  18949. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  18950. } else if (this.type === 'user_input_mutation') {
  18951. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  18952. } else if (this.type === 'token') {
  18953. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  18954. }
  18955. }
  18956. });
  18957. this.registerType('torch._export.serde.schema.TensorArgument', class {
  18958. constructor(obj) {
  18959. this.name = obj.name;
  18960. }
  18961. });
  18962. this.registerType('torch._export.serde.schema.TokenArgument', class {
  18963. constructor(obj) {
  18964. this.name = obj.name;
  18965. }
  18966. });
  18967. this.registerType('torch._export.serde.schema.GraphArgument', class {
  18968. constructor(obj) {
  18969. this.name = obj.name;
  18970. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18971. }
  18972. });
  18973. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  18974. constructor(obj) {
  18975. super(obj);
  18976. if (this.type === 'as_tensor') {
  18977. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  18978. } else if (this.type === 'as_none') {
  18979. this.as_none = null;
  18980. } else {
  18981. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  18982. }
  18983. }
  18984. });
  18985. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  18986. const legacy_file = `data/weights/${model_name}.pt`;
  18987. if (f.has(legacy_file)) {
  18988. return f.get(legacy_file);
  18989. }
  18990. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  18991. if (!f.has(weights_config_file)) {
  18992. return null;
  18993. }
  18994. const weights_config = f.get(weights_config_file);
  18995. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  18996. const state_dict = new builtins.dict();
  18997. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  18998. if (payload_meta.use_pickle) {
  18999. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19000. const weight_tensor = torch.load(weight_bytes);
  19001. state_dict.set(weight_fqn, weight_tensor);
  19002. } else {
  19003. const tensor_meta = payload_meta.tensor_meta;
  19004. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19005. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19006. const strides = tensor_meta.strides.map((s) => s.as_int);
  19007. const storage_offset = tensor_meta.storage_offset.as_int;
  19008. const weight_tensor = new torch.Tensor();
  19009. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19010. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19011. if (payload_meta.is_param) {
  19012. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19013. } else {
  19014. state_dict.set(weight_fqn, weight_tensor);
  19015. }
  19016. }
  19017. }
  19018. return state_dict;
  19019. });
  19020. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19021. const legacy_file = `data/constants/${model_name}.pt`;
  19022. if (f.has(legacy_file)) {
  19023. const entries = f.get(legacy_file);
  19024. return new builtins.dict(entries);
  19025. }
  19026. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19027. if (!f.has(constants_config_file)) {
  19028. return null;
  19029. }
  19030. const constants_config = f.get(constants_config_file);
  19031. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19032. const constants = new builtins.dict();
  19033. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19034. const path_name = payload_meta.path_name;
  19035. if (path_name.startsWith('tensor_')) {
  19036. if (payload_meta.use_pickle) {
  19037. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19038. const constant_tensor = torch.load(constant_bytes);
  19039. constants.set(constant_fqn, constant_tensor);
  19040. } else {
  19041. const tensor_meta = payload_meta.tensor_meta;
  19042. const tensor = constant_file_map.get(payload_meta.path_name);
  19043. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19044. const strides = tensor_meta.strides.map((s) => s.as_int);
  19045. const storage_offset = tensor_meta.storage_offset.as_int;
  19046. const constant_tensor = new torch.Tensor();
  19047. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19048. constants.set(constant_fqn, constant_tensor);
  19049. }
  19050. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19051. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19052. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19053. constants.set(constant_fqn, custom_obj);
  19054. }
  19055. }
  19056. return constants;
  19057. });
  19058. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19059. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19060. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19061. }
  19062. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19063. });
  19064. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19065. const file_map = new builtins.dict();
  19066. for (const payload_meta of Object.values(config.config)) {
  19067. if (payload_meta.use_pickle) {
  19068. continue;
  19069. }
  19070. if (file_map.has(payload_meta.path_name)) {
  19071. continue;
  19072. }
  19073. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19074. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19075. file_map.set(payload_meta.path_name, tensor);
  19076. }
  19077. return file_map;
  19078. });
  19079. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19080. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19081. const itemsize = dtype.itemsize();
  19082. const num_elements = tensor_bytes.length / itemsize;
  19083. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19084. storage._set_cdata(tensor_bytes);
  19085. const tensor = new torch.Tensor();
  19086. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19087. tensor.requires_grad = tensor_meta.requires_grad || false;
  19088. return tensor;
  19089. });
  19090. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19091. const exported_programs = new Map();
  19092. for (const name of f.keys()) {
  19093. const match = name.match(/^models\/([^/]+)\.json$/);
  19094. if (match) {
  19095. const [, model_name] = match;
  19096. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19097. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19098. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19099. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19100. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19101. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19102. exported_programs.set(model_name, exported_program);
  19103. }
  19104. }
  19105. return { exported_programs };
  19106. });
  19107. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19108. if (data === null) {
  19109. return data;
  19110. }
  19111. if (cls) {
  19112. return new cls(data);
  19113. }
  19114. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19115. });
  19116. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19117. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19118. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19119. });
  19120. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19121. constructor(expected_opset_version) {
  19122. this.expected_opset_version = expected_opset_version;
  19123. }
  19124. deserialize(exported_program, state_dict, constants, example_inputs) {
  19125. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19126. /*
  19127. symbol_name_to_range = {
  19128. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19129. for k, v in exported_program.range_constraints.items()
  19130. }
  19131. */
  19132. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19133. const res = deserializer.deserialize(
  19134. exported_program.graph_module,
  19135. state_dict,
  19136. constants,
  19137. example_inputs,
  19138. symbol_name_to_range);
  19139. const range_constraints = null;
  19140. /*
  19141. range_constraints = self.deserialize_range_constraints(
  19142. symbol_name_to_range, res.names_to_symbols,
  19143. )
  19144. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19145. self._validate_model_opset_version(model_opset_version)
  19146. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19147. */
  19148. return new torch.export.exported_program.ExportedProgram(
  19149. res.graph_module, res.graph_module.graph, res.signature,
  19150. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19151. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19152. res.constants);
  19153. // return upgrader.upgrade(exported_program)
  19154. }
  19155. });
  19156. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19157. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19158. return serialized;
  19159. }
  19160. if (serialized === null || serialized.length === 0) {
  19161. return new builtins.dict();
  19162. }
  19163. const artifact = torch.load(serialized);
  19164. return artifact;
  19165. });
  19166. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19167. constructor() {
  19168. this.serialized_name_to_node = new builtins.dict();
  19169. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19170. this.graph = new torch.fx.Graph();
  19171. this.module = new torch.nn.Module();
  19172. }
  19173. save_graph_module() {
  19174. const Context = class {
  19175. constructor(self) {
  19176. this.self = self;
  19177. }
  19178. __enter__() {
  19179. this.saved = [
  19180. this.self.graph,
  19181. this.self.module,
  19182. this.self.serialized_name_to_node,
  19183. this.self.serialized_name_to_meta,
  19184. this.self.unbacked_symbols,
  19185. ];
  19186. this.self.graph = new torch.fx.graph.Graph();
  19187. this.self.module = new torch.nn.modules.module.Module();
  19188. this.self.serialized_name_to_node = new builtins.dict();
  19189. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19190. this.self.unbacked_symbols = new Set();
  19191. }
  19192. __exit__(/* exc_type, exc_value, traceback */) {
  19193. const self = this.self;
  19194. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19195. }
  19196. };
  19197. return new Context(this);
  19198. }
  19199. deserialize_graph_output(output) {
  19200. if (output.type === 'as_tensor') {
  19201. return this.serialized_name_to_node.get(output.as_tensor.name);
  19202. } else if (output.type === 'as_sym_int') {
  19203. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19204. } else if (output.type === 'as_sym_bool') {
  19205. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19206. } else if (output.type === 'as_int') {
  19207. return this.serialized_name_to_node.get(output.as_int.as_name);
  19208. } else if (output.type === 'as_none') {
  19209. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19210. }
  19211. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19212. }
  19213. deserialize_graph(serialized_graph) {
  19214. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19215. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19216. this.serialized_name_to_meta.set(name, meta_val);
  19217. }
  19218. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19219. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19220. }
  19221. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19222. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19223. }
  19224. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19225. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19226. }
  19227. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19228. const input = serialized_graph.inputs[i];
  19229. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19230. const node_name = input.value.name;
  19231. const placeholder_node = this.graph.placeholder(node_name);
  19232. placeholder_node.name = node_name;
  19233. this.sync_fx_node(node_name, placeholder_node);
  19234. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19235. const node_name = this.signature.input_specs[i].arg.name;
  19236. const placeholder_node = this.graph.placeholder(node_name);
  19237. placeholder_node.meta.set('val', this.deserialize_input(input));
  19238. } else {
  19239. throw new python.Error(`Invalid input ${input.type}.`);
  19240. }
  19241. }
  19242. for (const serialized_node of serialized_graph.nodes) {
  19243. const target = this.deserialize_operator(serialized_node.target);
  19244. this.deserialize_node(serialized_node, target);
  19245. }
  19246. let outputs = [];
  19247. for (const output of serialized_graph.outputs) {
  19248. outputs.push(this.deserialize_graph_output(output));
  19249. }
  19250. if (serialized_graph.is_single_tensor_return) {
  19251. [outputs] = outputs;
  19252. } else {
  19253. outputs = new builtins.tuple(outputs);
  19254. }
  19255. const output_node = this.graph.output(outputs);
  19256. if (serialized_graph.is_single_tensor_return) {
  19257. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19258. } else {
  19259. /* output_node.meta['val'] = tuple(
  19260. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19261. for arg in output_node.args[0]
  19262. ) */
  19263. }
  19264. return self.graph;
  19265. }
  19266. deserialize_operator(serialized_target) {
  19267. let module = null;
  19268. let serialized_target_names = null;
  19269. if (serialized_target.startsWith('_operator')) {
  19270. module = operator;
  19271. serialized_target_names = serialized_target.split('.').slice(1);
  19272. } else if (serialized_target.startsWith('torch')) {
  19273. module = torch;
  19274. serialized_target_names = serialized_target.split('.').slice(1);
  19275. } else if (serialized_target.startsWith('#')) {
  19276. return self.deserialize_extension_operator(serialized_target);
  19277. } else {
  19278. return serialized_target;
  19279. }
  19280. let target = module;
  19281. for (const name of serialized_target_names) {
  19282. target = builtins.getattr(target, name);
  19283. if (!target) {
  19284. return serialized_target;
  19285. }
  19286. }
  19287. return target;
  19288. }
  19289. deserialize_node(serialized_node, target) {
  19290. let fx_node = null;
  19291. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19292. const name = serialized_node.outputs[0].value.as_name;
  19293. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19294. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19295. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19296. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19297. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19298. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19299. for (const x of [...args, ...kwargs.values()]) {
  19300. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19301. x.meta.update(metadata);
  19302. }
  19303. }
  19304. const name = serialized_node.outputs.length === 1 &&
  19305. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19306. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19307. serialized_node.outputs[0].as_tensor.name : null;
  19308. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19309. this.deserialize_outputs(serialized_node, fx_node);
  19310. fx_node.meta.update(metadata);
  19311. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19312. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19313. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19314. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19315. this.deserialize_outputs(serialized_node, fx_node);
  19316. } else if (typeof target === 'string') {
  19317. // Handle unresolved operators
  19318. execution.emit('resolve', target);
  19319. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19320. throw new python.Error(`Unsupported node target type '${target}'.`);
  19321. }
  19322. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19323. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19324. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19325. this.deserialize_outputs(serialized_node, fx_node);
  19326. } else {
  19327. throw new python.Error(`Unsupported node target type '${target}'.`);
  19328. }
  19329. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19330. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19331. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19332. }
  19333. }
  19334. deserialize_input_spec(i) {
  19335. if (i.type === 'user_input') {
  19336. return new torch.export.graph_signature.InputSpec(
  19337. torch.export.graph_signature.InputKind.USER_INPUT,
  19338. this.deserialize_argument_spec(i.user_input.arg),
  19339. null);
  19340. } else if (i.type === 'parameter') {
  19341. return new torch.export.graph_signature.InputSpec(
  19342. torch.export.graph_signature.InputKind.PARAMETER,
  19343. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19344. i.parameter.parameter_name,
  19345. );
  19346. } else if (i.type === 'buffer') {
  19347. return new torch.export.graph_signature.InputSpec(
  19348. torch.export.graph_signature.InputKind.BUFFER,
  19349. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19350. i.buffer.buffer_name,
  19351. i.buffer.persistent,
  19352. );
  19353. } else if (i.type === 'tensor_constant') {
  19354. return new torch.export.graph_signature.InputSpec(
  19355. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19356. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19357. i.tensor_constant.tensor_constant_name);
  19358. } else if (i.type === 'custom_obj') {
  19359. return new torch.export.graph_signature.InputSpec(
  19360. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19361. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19362. i.custom_obj.custom_obj_name);
  19363. } else if (i.type === 'token') {
  19364. return new torch.export.graph_signature.InputSpec(
  19365. torch.export.graph_signature.InputKind.TOKEN,
  19366. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19367. null);
  19368. } else if (i.type === 'constant_input') {
  19369. return new torch.export.graph_signature.InputSpec(
  19370. torch.export.graph_signature.InputKind.USER_INPUT,
  19371. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19372. null);
  19373. }
  19374. throw new python.Error(`Unknown input spec ${i}`);
  19375. }
  19376. deserialize_constant_input(inp) {
  19377. if (inp.type === 'as_int') {
  19378. return inp.as_int;
  19379. } else if (inp.type === 'as_float') {
  19380. return inp.as_float;
  19381. } else if (inp.type === 'as_string') {
  19382. return inp.as_string;
  19383. } else if (inp.type === 'as_bool') {
  19384. return inp.as_bool;
  19385. } else if (inp.type === 'as_none') {
  19386. return null;
  19387. }
  19388. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19389. }
  19390. deserialize_output_spec(o) {
  19391. if (o.type === 'user_output') {
  19392. return new torch.export.graph_signature.OutputSpec(
  19393. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19394. this.deserialize_argument_spec(o.user_output.arg),
  19395. null);
  19396. } else if (o.type === 'loss_output') {
  19397. return new torch.export.graph_signature.OutputSpec(
  19398. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19399. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19400. null);
  19401. } else if (o.type === 'buffer_mutation') {
  19402. return new torch.export.graph_signature.OutputSpec(
  19403. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19404. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19405. o.buffer_mutation.buffer_name);
  19406. } else if (o.type === 'gradient_to_parameter') {
  19407. return new torch.export.graph_signature.OutputSpec(
  19408. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19409. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19410. o.gradient_to_parameter.parameter_name);
  19411. } else if (o.type === 'gradient_to_user_input') {
  19412. return new torch.export.graph_signature.OutputSpec(
  19413. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19414. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19415. o.gradient_to_user_input.user_input_name);
  19416. } else if (o.type === 'user_input_mutation') {
  19417. return new torch.export.graph_signature.OutputSpec(
  19418. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19419. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19420. o.user_input_mutation.user_input_name);
  19421. } else if (o.type === 'token') {
  19422. return new torch.export.graph_signature.OutputSpec(
  19423. torch.export.graph_signature.OutputKind.TOKEN,
  19424. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19425. null);
  19426. }
  19427. throw new python.Error(`Unknown output spec ${o}.`);
  19428. }
  19429. deserialize_signature(sig) {
  19430. return new torch.export.graph_signature.ExportGraphSignature(
  19431. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19432. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19433. }
  19434. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19435. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19436. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19437. this.sympy_functions = new Map([
  19438. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19439. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19440. ['Where', torch.utils._sympy.functions.Where],
  19441. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19442. ['Mod', torch.utils._sympy.functions.Mod],
  19443. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19444. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19445. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19446. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19447. ['LShift', torch.utils._sympy.functions.LShift],
  19448. ['RShift', torch.utils._sympy.functions.RShift],
  19449. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19450. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19451. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19452. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19453. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19454. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19455. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19456. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19457. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19458. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19459. ['Identity', torch.utils._sympy.functions.Identity],
  19460. ]);
  19461. this.symbol_name_to_symbol = new Map();
  19462. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19463. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19464. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19465. /*
  19466. if symbol_name_to_range:
  19467. for k, vr in symbol_name_to_range.items():
  19468. lower = int(vr.lower)
  19469. if vr.upper >= 2: # max is >= 2, not sym bool range
  19470. lower = max(2, lower)
  19471. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19472. */
  19473. this.example_inputs = null;
  19474. if (example_inputs) {
  19475. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19476. }
  19477. this.deserialize_graph(serialized_graph_module.graph);
  19478. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19479. return {
  19480. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19481. signature: this.signature,
  19482. module_call_graph,
  19483. names_to_symbols: this.symbol_name_to_symbol,
  19484. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19485. constants: this.constants,
  19486. example_inputs: this.example_inputs,
  19487. };
  19488. }
  19489. sync_fx_node(name, fx_node) {
  19490. if (this.serialized_name_to_node.has(name)) {
  19491. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19492. }
  19493. this.serialized_name_to_node.set(name, fx_node);
  19494. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19495. }
  19496. deserialize_sym_op_inputs(inputs) {
  19497. return inputs.map((input) => this.deserialize_input(input.arg));
  19498. }
  19499. deserialize_inputs(target, serialized_node) {
  19500. const schema_args = this._get_schema_from_target(target).arguments;
  19501. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19502. const args = new builtins.list();
  19503. const kwargs = new builtins.dict();
  19504. for (const schema_arg of schema_args) {
  19505. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19506. if (is_positional) {
  19507. args.push(actual_args.get(schema_arg.name));
  19508. } else if (actual_args.has(schema_arg.name)) {
  19509. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19510. }
  19511. }
  19512. return [args, kwargs];
  19513. }
  19514. deserialize_hoo_inputs(inputs) {
  19515. const args = [];
  19516. const kwargs = new builtins.dict();
  19517. for (const input_ of inputs) {
  19518. if (input_.name === '') {
  19519. args.push(this.deserialize_input(input_.arg));
  19520. } else {
  19521. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19522. }
  19523. }
  19524. return [new builtins.tuple(args), kwargs];
  19525. }
  19526. deserialize_input(inp) {
  19527. const value = inp.value;
  19528. const typ_ = inp.type;
  19529. if (typ_ === 'as_none') {
  19530. return null;
  19531. } else if (typ_ === 'as_tensor') {
  19532. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19533. } else if (typ_ === 'as_scalar_type') {
  19534. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19535. } else if (typ_ === 'as_memory_format') {
  19536. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19537. } else if (typ_ === 'as_layout') {
  19538. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19539. } else if (typ_ === 'as_graph') {
  19540. const context = this.save_graph_module();
  19541. context.__enter__();
  19542. this.deserialize_graph(value.graph);
  19543. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19544. context.__exit__(null, null, null);
  19545. this.module.register_module(value.name, submodule);
  19546. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19547. } else if (typ_ === 'as_device') {
  19548. return this.deserialize_device(inp.as_device);
  19549. } else if (typ_ === 'as_int') {
  19550. return inp.as_int;
  19551. } else if (typ_ === 'as_float') {
  19552. return inp.as_float;
  19553. } else if (typ_ === 'as_bool') {
  19554. return inp.as_bool;
  19555. } else if (typ_ === 'as_string') {
  19556. return inp.as_string;
  19557. } else if (typ_ === 'as_sym_int') {
  19558. return this.deserialize_sym_argument(inp.as_sym_int);
  19559. } else if (typ_ === 'as_sym_float') {
  19560. return this.deserialize_sym_argument(inp.as_sym_float);
  19561. } else if (typ_ === 'as_sym_bool') {
  19562. return this.deserialize_sym_argument(inp.as_sym_bool);
  19563. } else if (Array.isArray(value)) {
  19564. if (value.length === 0) {
  19565. return [];
  19566. } else if (typ_ === 'as_tensors') {
  19567. const result = [];
  19568. for (const arg of value) {
  19569. result.push(this.serialized_name_to_node.get(arg.name));
  19570. }
  19571. return result;
  19572. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19573. return Array.from(value);
  19574. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19575. return value.map((arg) => this.deserialize_sym_argument(arg));
  19576. } else if (typ_ === 'as_optional_tensors') {
  19577. const deserialize_optional_tensor_args = (a) => {
  19578. if (a.type === 'as_none') {
  19579. return null;
  19580. } else if (a.type === 'as_tensor') {
  19581. return this.serialized_name_to_node.get(a.value.name);
  19582. }
  19583. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19584. };
  19585. return value.map((item) => deserialize_optional_tensor_args(item));
  19586. }
  19587. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19588. } else if (typ_ === 'as_custom_obj') {
  19589. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19590. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19591. }
  19592. return this.constants[inp.as_custom_obj.name];
  19593. } else if (typ_ === 'as_operator') {
  19594. return this.deserialize_operator(inp.as_operator);
  19595. }
  19596. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19597. }
  19598. deserialize_sym_argument(sym_arg) {
  19599. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19600. if (sym_arg.type === 'as_int') {
  19601. return sym_arg.as_int;
  19602. } else if (sym_arg.type === 'as_name') {
  19603. return this.serialized_name_to_node.get(sym_arg.as_name);
  19604. }
  19605. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19606. if (sym_arg.type === 'as_float') {
  19607. return sym_arg.as_float;
  19608. } else if (sym_arg.type === 'as_name') {
  19609. return this.serialized_name_to_node.get(sym_arg.as_name);
  19610. }
  19611. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19612. if (sym_arg.type === 'as_bool') {
  19613. return sym_arg.as_bool;
  19614. } else if (sym_arg.type === 'as_name') {
  19615. return this.serialized_name_to_node.get(sym_arg.as_name);
  19616. }
  19617. }
  19618. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19619. }
  19620. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19621. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19622. }
  19623. deserialize_outputs(serialized_node, fx_node) {
  19624. if (serialized_node.outputs.length === 0) {
  19625. return;
  19626. }
  19627. if (serialized_node.outputs.length === 1 &&
  19628. serialized_node.outputs[0].type === 'as_tensor') {
  19629. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19630. return;
  19631. } else if (serialized_node.outputs.length === 1 &&
  19632. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19633. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19634. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19635. return;
  19636. }
  19637. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19638. }
  19639. deserialize_multiple_outputs(serialized_node, fx_node) {
  19640. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19641. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19642. let name = '';
  19643. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19644. name = arg.name;
  19645. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19646. name = arg.as_name;
  19647. } else {
  19648. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19649. }
  19650. const individual_output = this.graph.create_node(
  19651. 'call_function',
  19652. operator.getitem,
  19653. new builtins.tuple([fx_node, idx]),
  19654. null,
  19655. name,
  19656. );
  19657. this.sync_fx_node(name, individual_output);
  19658. meta_val.push(this.serialized_name_to_meta.get(name));
  19659. individual_output.meta.update(deserialized_metadata);
  19660. };
  19661. const generate_getitems = (meta_val, fx_node, args) => {
  19662. for (let idx = 0; idx < args.length; idx++) {
  19663. let arg = args[idx];
  19664. if (arg instanceof torch._export.serde.schema.Argument) {
  19665. arg = arg.value;
  19666. }
  19667. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19668. generate_getitem(meta_val, fx_node, arg, idx);
  19669. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19670. const list_output = this.graph.create_node(
  19671. 'call_function',
  19672. operator.getitem,
  19673. (fx_node, idx),
  19674. );
  19675. meta_val.append([]);
  19676. generate_getitems(meta_val[-1], list_output, arg);
  19677. list_output.meta.update(deserialized_metadata);
  19678. list_output.meta.set('val', meta_val[-1]);
  19679. } else {
  19680. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19681. }
  19682. }
  19683. };
  19684. const meta_val = [];
  19685. if (serialized_node.outputs.length === 1) {
  19686. // assert isinstance(serialized_node.outputs[0].value, list)
  19687. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19688. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19689. } else {
  19690. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19691. }
  19692. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19693. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19694. }
  19695. deserialize_metadata(metadata) {
  19696. const ret = new builtins.dict();
  19697. const stack_trace = metadata.get('stack_trace');
  19698. if (stack_trace) {
  19699. ret.set('stack_trace', stack_trace);
  19700. }
  19701. const deserialize_meta_func = (serialized_target) => {
  19702. let module = null;
  19703. let serialized_target_names = [];
  19704. if (serialized_target.startsWith('torch.nn')) {
  19705. module = torch.nn;
  19706. serialized_target_names = serialized_target.split('.').slice(1);
  19707. } else if (serialized_target.startsWith('torch')) {
  19708. module = torch;
  19709. serialized_target_names = serialized_target.split('.').slice(1);
  19710. } else {
  19711. return this.deserialize_operator(serialized_target);
  19712. }
  19713. let target = module;
  19714. for (const name of serialized_target_names) {
  19715. if (!builtins.hasattr(target, name)) {
  19716. return serialized_target;
  19717. }
  19718. target = builtins.getattr(target, name);
  19719. }
  19720. return target;
  19721. };
  19722. const nn_module_stack_str = metadata.get('nn_module_stack');
  19723. if (nn_module_stack_str) {
  19724. const import_nn_module_stack = (key, path, ty) => {
  19725. return [key, [path, ty]];
  19726. };
  19727. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19728. ret.set('nn_module_stack', nn_module_stack);
  19729. }
  19730. const source_fn_st_str = metadata.get('source_fn_stack');
  19731. if (source_fn_st_str) {
  19732. const source_fn_st = [];
  19733. for (const source_fn_str of source_fn_st_str.split(';')) {
  19734. const [name, target_str] = source_fn_str.split(',');
  19735. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19736. }
  19737. ret.set('source_fn_stack', source_fn_st);
  19738. }
  19739. const torch_fn = metadata.get('torch_fn');
  19740. if (torch_fn) {
  19741. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19742. }
  19743. const custom_str = metadata.get('custom');
  19744. if (custom_str) {
  19745. ret.set('custom', JSON.parse(custom_str));
  19746. }
  19747. return ret;
  19748. }
  19749. deserialize_argument_spec(x) {
  19750. if (x.type === 'as_tensor') {
  19751. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19752. } else if (x.type === 'as_sym_int') {
  19753. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19754. } else if (x.type === 'as_custom_obj') {
  19755. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19756. }
  19757. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19758. }
  19759. deserialize_tensor_meta(tensor_meta) {
  19760. try {
  19761. this.fake_tensor_mode.__enter__();
  19762. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  19763. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  19764. const device = this.deserialize_device(tensor_meta.device);
  19765. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19766. return torch.empty_strided(sizes, strides, dtype, null, device);
  19767. } finally {
  19768. this.fake_tensor_mode.__exit__(null, null, null);
  19769. }
  19770. }
  19771. deserialize_script_obj_meta(script_obj_meta) {
  19772. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  19773. }
  19774. _parse_sym_expr(expr_str, hint) {
  19775. const _process_sym_expr = (sym, hint) => {
  19776. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  19777. return sym;
  19778. }
  19779. expr_str = sym.__str__();
  19780. for (const arg of sym.args) {
  19781. this._parse_sym_expr(arg);
  19782. }
  19783. if (this.symbol_name_to_symbol.has(expr_str)) {
  19784. sym = this.symbol_name_to_symbol.get(expr_str);
  19785. } else {
  19786. this.symbol_name_to_symbol.set(expr_str, sym);
  19787. if (builtins.isinstance(sym, sympy.core.symbol.Symbol) && torch.fx.experimental.symbolic_shapes.symbol_is_type(sym, [torch.utils._sympy.symbol.SymT.UNBACKED_INT, torch.utils._sympy.symbol.SymT.UNBACKED_FLOAT])) {
  19788. this.unbacked_symbols.add(sym);
  19789. }
  19790. }
  19791. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  19792. this.shape_env.add_var_to_val(sym, hint);
  19793. }
  19794. const vr = this.symbol_name_to_range.get(expr_str);
  19795. if (vr) {
  19796. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  19797. }
  19798. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  19799. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  19800. }
  19801. return sym;
  19802. };
  19803. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  19804. const expr = sympy.core.sympify.sympify(expr_str, locals);
  19805. return _process_sym_expr(expr, hint);
  19806. }
  19807. deserialize_sym_int(s) {
  19808. const val = s.value;
  19809. let hint = null;
  19810. if (s.type === 'as_expr') {
  19811. if (val.hint === null) {
  19812. hint = null;
  19813. } else {
  19814. // assert val.hint.type == "as_int"
  19815. hint = val.hint.value;
  19816. }
  19817. const sym = this._parse_sym_expr(val.expr_str, hint);
  19818. return this.shape_env.create_symintnode(sym, hint);
  19819. } else if (s.type === 'as_int') {
  19820. // assert type(val) is int
  19821. return val;
  19822. }
  19823. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  19824. }
  19825. deserialize_sym_bool(s) {
  19826. const val = s.value;
  19827. let hint = null;
  19828. if (s.type === 'as_expr') {
  19829. if (val.hint === null) {
  19830. hint = null;
  19831. } else {
  19832. // assert val.hint.type == "as_bool"
  19833. hint = val.hint.value;
  19834. }
  19835. const sym = this._parse_sym_expr(val.expr_str, hint);
  19836. return this.shape_env.create_symboolnode(sym, hint);
  19837. } else if (s.type === 'as_bool') {
  19838. // assert type(val) is bool
  19839. return val;
  19840. }
  19841. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  19842. }
  19843. deserialize_device(d) {
  19844. if (d.index === null) {
  19845. return new torch.device(d.type);
  19846. }
  19847. return new torch.device(d.type, d.index);
  19848. }
  19849. _get_schema_from_target(target) {
  19850. if (target instanceof torch._ops.OpOverload) {
  19851. return target._schema;
  19852. }
  19853. throw new python.Error(`Unsupported schema '${target.name}'.`);
  19854. }
  19855. _is_single_tensor_return(target) {
  19856. const schema = this._get_schema_from_target(target);
  19857. const returns = schema.returns;
  19858. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  19859. }
  19860. });
  19861. this.registerType('torch._export.verifier.Verifier', class {});
  19862. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  19863. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  19864. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  19865. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  19866. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  19867. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  19868. constructor(mod, dynamo_ctx) {
  19869. builtins.object.__setattr__(self, '_orig_mod', mod);
  19870. // this._super_module_initialized = false;
  19871. super();
  19872. // this._super_module_initialized = true;
  19873. this._orig_mod = mod;
  19874. this.dynamo_ctx = dynamo_ctx;
  19875. // this._initialize();
  19876. this.training = this._orig_mod.training;
  19877. }
  19878. });
  19879. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  19880. this.registerType('torch._dynamo.hooks.Hooks', class {});
  19881. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  19882. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  19883. this.registerType('torch._TorchCompileInductorWrapper', class {});
  19884. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  19885. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  19886. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  19887. const module = new types.ModuleType(name);
  19888. execution.register('sys').modules.set(name, module);
  19889. const context = new python.Execution.Context(module, null);
  19890. execution.exec(meta.get('module_src'), context);
  19891. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  19892. const state = meta.get('state');
  19893. if (state) {
  19894. if (obj.__setstate__) {
  19895. obj.__setstate__(state);
  19896. } else {
  19897. for (const [key, value] of state) {
  19898. obj[key] = value;
  19899. }
  19900. }
  19901. }
  19902. return obj;
  19903. });
  19904. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  19905. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  19906. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  19907. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  19908. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  19909. this.registerType('torch.device', class {
  19910. constructor(type, index) {
  19911. this.type = type;
  19912. this.index = index ? index : null;
  19913. }
  19914. __str__() {
  19915. return this.index === null ? this.type : `${this.type}:${this.index}`;
  19916. }
  19917. toString() {
  19918. const index = this.index === null ? '' : `, index=${this.index}`;
  19919. return `device(type='${this.type}'${index})`;
  19920. }
  19921. });
  19922. this.registerType('torch.memory_format', class {
  19923. constructor(name) {
  19924. this.name = name;
  19925. }
  19926. __str__() {
  19927. return `torch.${this.name}`;
  19928. }
  19929. toString() {
  19930. return this.__str__();
  19931. }
  19932. });
  19933. this.registerType('torch.dtype', class {
  19934. constructor(scalar_type, name, itemsize) {
  19935. this._scalar_type = scalar_type;
  19936. this._name = name;
  19937. this._itemsize = itemsize;
  19938. }
  19939. scalar_type() {
  19940. return this._scalar_type;
  19941. }
  19942. itemsize() {
  19943. return this._itemsize;
  19944. }
  19945. __reduce__() {
  19946. return this._name;
  19947. }
  19948. __str__() {
  19949. return `torch.${this._name}`;
  19950. }
  19951. toString() {
  19952. return this.__str__();
  19953. }
  19954. });
  19955. this.registerType('torch.layout', class {
  19956. constructor(name) {
  19957. this._name = name;
  19958. }
  19959. __str__() {
  19960. return `torch.${this._name}`;
  19961. }
  19962. toString() {
  19963. return this.__str__();
  19964. }
  19965. });
  19966. this.registerType('torch.qscheme', class {
  19967. constructor(name) {
  19968. this._name = name;
  19969. }
  19970. __str__() {
  19971. return this._name;
  19972. }
  19973. toString() {
  19974. return this.__str__();
  19975. }
  19976. });
  19977. this.registerType('torch.utils.hooks.RemovableHandle', class {
  19978. __setstate__(state) {
  19979. [this.hooks_dict_ref, this.id] = state;
  19980. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  19981. }
  19982. });
  19983. this.registerType('torch.storage._StorageBase', class {
  19984. constructor(size, dtype) {
  19985. this._size = size;
  19986. this._dtype = dtype;
  19987. this._device = null;
  19988. }
  19989. get device() {
  19990. return this._device;
  19991. }
  19992. get dtype() {
  19993. return this._dtype;
  19994. }
  19995. element_size() {
  19996. return this._dtype.element_size;
  19997. }
  19998. size() {
  19999. return this._size;
  20000. }
  20001. get data() {
  20002. return this._cdata;
  20003. }
  20004. _set_cdata(data) {
  20005. const length = this.size() * this.dtype.itemsize();
  20006. if (length !== data.length) {
  20007. throw new python.Error('Typed storage data size mismatch.');
  20008. }
  20009. this._cdata = data;
  20010. }
  20011. _set_from_file(unpickler) {
  20012. const buffer = unpickler.read(8);
  20013. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20014. if (size !== this.size()) {
  20015. throw new python.Error('Typed storage size mismatch.');
  20016. }
  20017. const itemsize = this.dtype.itemsize();
  20018. const data = unpickler.stream(itemsize * size);
  20019. this._set_cdata(data);
  20020. }
  20021. static _new_with_file(unpickler) {
  20022. const buffer = unpickler.read(8);
  20023. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20024. const storage = new this(size);
  20025. const itemsize = storage.dtype.itemsize();
  20026. const data = unpickler.stream(itemsize * size);
  20027. storage._set_cdata(data);
  20028. return storage;
  20029. }
  20030. });
  20031. this.registerType('torch.storage.UntypedStorage', class {
  20032. constructor(size) {
  20033. this._size = size;
  20034. }
  20035. _set_cdata(data) {
  20036. if (this._size !== data.length) {
  20037. throw new python.Error('Untyped storage data size mismatch.');
  20038. }
  20039. this._cdata = data;
  20040. }
  20041. });
  20042. this.registerType('torch.storage.TypedStorage', class {
  20043. constructor(...args) {
  20044. if (args.length === 0) {
  20045. this._size = 0;
  20046. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20047. [this._size] = args;
  20048. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20049. if (args[3] instanceof torch.device) {
  20050. [this._size, this.dtype, , this._device] = args;
  20051. } else {
  20052. [this._size, this.dtype] = args;
  20053. }
  20054. } else {
  20055. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20056. }
  20057. }
  20058. get device() {
  20059. return this._device;
  20060. }
  20061. get dtype() {
  20062. return this._dtype;
  20063. }
  20064. set dtype(value) {
  20065. this._dtype = value;
  20066. }
  20067. element_size() {
  20068. return this._dtype.element_size;
  20069. }
  20070. size() {
  20071. return this._size;
  20072. }
  20073. get data() {
  20074. return this._cdata;
  20075. }
  20076. _set_cdata(data) {
  20077. const length = this.size() * this.dtype.itemsize();
  20078. if (length !== data.length) {
  20079. throw new python.Error('Storage data size mismatch.');
  20080. }
  20081. this._cdata = data;
  20082. }
  20083. _set_from_file(unpickler) {
  20084. const buffer = unpickler.read(8);
  20085. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20086. if (size !== this.size()) {
  20087. throw new python.Error('Storage size mismatch.');
  20088. }
  20089. const itemsize = this.dtype.itemsize();
  20090. const data = unpickler.stream(itemsize * size);
  20091. this._set_cdata(data);
  20092. }
  20093. static _new_with_file(unpickler) {
  20094. const buffer = unpickler.read(8);
  20095. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20096. const storage = new this(size);
  20097. const itemsize = storage.dtype.itemsize();
  20098. const data = unpickler.stream(itemsize * size);
  20099. storage._set_cdata(data);
  20100. return storage;
  20101. }
  20102. });
  20103. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20104. });
  20105. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20106. constructor(...args) {
  20107. /* eslint-disable no-constructor-return */
  20108. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20109. /* eslint-enable no-constructor-return */
  20110. }
  20111. });
  20112. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20113. constructor(...args) {
  20114. /* eslint-disable no-constructor-return */
  20115. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20116. /* eslint-enable no-constructor-return */
  20117. }
  20118. });
  20119. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20120. constructor(...args) {
  20121. /* eslint-disable no-constructor-return */
  20122. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20123. /* eslint-enable no-constructor-return */
  20124. }
  20125. });
  20126. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20127. constructor(...args) {
  20128. /* eslint-disable no-constructor-return */
  20129. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20130. /* eslint-enable no-constructor-return */
  20131. }
  20132. });
  20133. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20134. constructor(...args) {
  20135. /* eslint-disable no-constructor-return */
  20136. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20137. /* eslint-enable no-constructor-return */
  20138. }
  20139. });
  20140. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20141. constructor(...args) {
  20142. /* eslint-disable no-constructor-return */
  20143. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20144. /* eslint-enable no-constructor-return */
  20145. }
  20146. });
  20147. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20148. constructor(...args) {
  20149. /* eslint-disable no-constructor-return */
  20150. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20151. /* eslint-enable no-constructor-return */
  20152. }
  20153. });
  20154. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20155. constructor(...args) {
  20156. /* eslint-disable no-constructor-return */
  20157. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20158. /* eslint-enable no-constructor-return */
  20159. }
  20160. });
  20161. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20162. constructor(...args) {
  20163. /* eslint-disable no-constructor-return */
  20164. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20165. /* eslint-enable no-constructor-return */
  20166. }
  20167. });
  20168. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20169. constructor(...args) {
  20170. /* eslint-disable no-constructor-return */
  20171. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20172. /* eslint-enable no-constructor-return */
  20173. }
  20174. });
  20175. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20176. constructor(...args) {
  20177. /* eslint-disable no-constructor-return */
  20178. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20179. /* eslint-enable no-constructor-return */
  20180. }
  20181. });
  20182. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20183. constructor(...args) {
  20184. /* eslint-disable no-constructor-return */
  20185. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20186. /* eslint-enable no-constructor-return */
  20187. }
  20188. });
  20189. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20190. constructor(...args) {
  20191. /* eslint-disable no-constructor-return */
  20192. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20193. /* eslint-enable no-constructor-return */
  20194. }
  20195. });
  20196. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20197. constructor(...args) {
  20198. /* eslint-disable no-constructor-return */
  20199. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20200. /* eslint-enable no-constructor-return */
  20201. }
  20202. });
  20203. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20204. constructor(...args) {
  20205. /* eslint-disable no-constructor-return */
  20206. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20207. /* eslint-enable no-constructor-return */
  20208. }
  20209. });
  20210. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20211. constructor(...args) {
  20212. /* eslint-disable no-constructor-return */
  20213. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20214. /* eslint-enable no-constructor-return */
  20215. }
  20216. });
  20217. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20218. constructor(...args) {
  20219. /* eslint-disable no-constructor-return */
  20220. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20221. /* eslint-enable no-constructor-return */
  20222. }
  20223. });
  20224. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20225. constructor(...args) {
  20226. /* eslint-disable no-constructor-return */
  20227. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20228. /* eslint-enable no-constructor-return */
  20229. }
  20230. });
  20231. this.registerType('torch.Size', class extends Array {
  20232. constructor(size) {
  20233. super(size.length);
  20234. for (let i = 0; i < size.length; i++) {
  20235. this[i] = size[i];
  20236. }
  20237. }
  20238. __len__() {
  20239. return this.length;
  20240. }
  20241. });
  20242. this.registerType('torch._C.TensorMeta', class {
  20243. });
  20244. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20245. });
  20246. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20247. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20248. super();
  20249. if (storage) {
  20250. this._storage = storage;
  20251. }
  20252. if (shape !== null && shape !== undefined) {
  20253. this._shape = shape;
  20254. }
  20255. if (dtype) {
  20256. this._dtype = dtype;
  20257. }
  20258. this._layout = layout || torch.strided;
  20259. if (device) {
  20260. this._device = device;
  20261. }
  20262. if (requires_grad !== undefined) {
  20263. this.requires_grad = requires_grad;
  20264. }
  20265. }
  20266. get device() {
  20267. if (this._device !== undefined) {
  20268. return this._device;
  20269. }
  20270. return this.storage().device;
  20271. }
  20272. get dtype() {
  20273. if (this._dtype !== undefined) {
  20274. return this._dtype;
  20275. }
  20276. if (this._layout === torch.sparse_coo) {
  20277. return this._values.dtype;
  20278. }
  20279. return this.storage().dtype;
  20280. }
  20281. get shape() {
  20282. return this._shape;
  20283. }
  20284. get layout() {
  20285. return this._layout;
  20286. }
  20287. get values() {
  20288. if (this._layout === torch.sparse_coo) {
  20289. return this._values;
  20290. }
  20291. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20292. }
  20293. get indices() {
  20294. if (this._layout === torch.sparse_coo) {
  20295. return this._indices;
  20296. }
  20297. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20298. }
  20299. get is_quantized() {
  20300. return this.__quantized__ === true;
  20301. }
  20302. get is_nested() {
  20303. return this.__nested__ === true;
  20304. }
  20305. get is_sparse() {
  20306. return this.layout !== torch.strided;
  20307. }
  20308. size() {
  20309. return this._shape;
  20310. }
  20311. storage() {
  20312. return this._storage;
  20313. }
  20314. storage_offset() {
  20315. return this._storage_offset;
  20316. }
  20317. stride() {
  20318. return this._stride;
  20319. }
  20320. resize_(shape) {
  20321. this._shape = shape;
  20322. }
  20323. __len__() {
  20324. return this._shape[0];
  20325. }
  20326. __setstate__(state) {
  20327. switch (state.length) {
  20328. case 3:
  20329. break;
  20330. case 4:
  20331. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20332. break;
  20333. case 5:
  20334. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20335. break;
  20336. default:
  20337. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20338. }
  20339. }
  20340. set_(source, storage_offset, size, stride) {
  20341. this._storage = source;
  20342. this._storage_offset = storage_offset;
  20343. this._shape = size;
  20344. this._stride = stride;
  20345. }
  20346. __bool__() {
  20347. return true;
  20348. }
  20349. __int__() {
  20350. const storage = this.storage();
  20351. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20352. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20353. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20354. return view.getBigInt64(0, true);
  20355. }
  20356. return NaN;
  20357. }
  20358. __float__() {
  20359. const storage = this.storage();
  20360. if (storage && storage.dtype.__reduce__() === 'float32') {
  20361. if (storage.size() !== undefined && storage.data.length === 4) {
  20362. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20363. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20364. return view.getFloat32(0, true);
  20365. }
  20366. }
  20367. return NaN;
  20368. }
  20369. __str__() {
  20370. return 'tensor(...)';
  20371. }
  20372. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20373. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20374. t.__setstate__([null, storage_offset, size, stride]);
  20375. return t;
  20376. }
  20377. });
  20378. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20379. constructor(data, requires_grad) {
  20380. super();
  20381. this.data = data || new torch.Tensor([]);
  20382. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20383. }
  20384. });
  20385. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20386. });
  20387. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20388. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20389. super();
  20390. this.allow_fallback_kernels = allow_fallback_kernels;
  20391. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20392. this.shape_env = shape_env;
  20393. this.enter_stack = [];
  20394. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20395. }
  20396. __enter__() {
  20397. const prev_only_lift_cpu_tensors = null;
  20398. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20399. if (this === maybe_prev_fake_mode) {
  20400. torch._C._set_dispatch_mode(this);
  20401. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20402. } else {
  20403. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20404. return super.__enter__();
  20405. }
  20406. return this;
  20407. }
  20408. __exit__(exc_type, exc_value, traceback) {
  20409. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20410. if (live) {
  20411. super.__exit__(exc_type, exc_value, traceback);
  20412. if (maybe_prev_fake_mode !== null) {
  20413. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20414. }
  20415. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20416. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20417. }
  20418. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20419. }
  20420. }
  20421. });
  20422. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20423. constructor(requires_grad /*, device, dtype */) {
  20424. super(undefined, requires_grad);
  20425. }
  20426. });
  20427. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20428. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20429. constructor(...args) {
  20430. /* eslint-disable no-constructor-return */
  20431. return new torch.Tensor(...args);
  20432. /* eslint-enable no-constructor-return */
  20433. }
  20434. });
  20435. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20436. constructor(...args) {
  20437. /* eslint-disable no-constructor-return */
  20438. return new torch.Tensor(...args);
  20439. /* eslint-enable no-constructor-return */
  20440. }
  20441. });
  20442. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20443. constructor(...args) {
  20444. /* eslint-disable no-constructor-return */
  20445. return new torch.Tensor(...args);
  20446. /* eslint-enable no-constructor-return */
  20447. }
  20448. });
  20449. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20450. constructor(...args) {
  20451. /* eslint-disable no-constructor-return */
  20452. return new torch.Tensor(...args);
  20453. /* eslint-enable no-constructor-return */
  20454. }
  20455. });
  20456. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20457. constructor(...args) {
  20458. /* eslint-disable no-constructor-return */
  20459. return new torch.Tensor(...args);
  20460. /* eslint-enable no-constructor-return */
  20461. }
  20462. });
  20463. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20464. constructor(...args) {
  20465. /* eslint-disable no-constructor-return */
  20466. return new torch.Tensor(...args);
  20467. /* eslint-enable no-constructor-return */
  20468. }
  20469. });
  20470. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20471. constructor(...args) {
  20472. /* eslint-disable no-constructor-return */
  20473. return new torch.Tensor(...args);
  20474. /* eslint-enable no-constructor-return */
  20475. }
  20476. });
  20477. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20478. constructor(...args) {
  20479. /* eslint-disable no-constructor-return */
  20480. return new torch.Tensor(...args);
  20481. /* eslint-enable no-constructor-return */
  20482. }
  20483. });
  20484. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20485. constructor(...args) {
  20486. /* eslint-disable no-constructor-return */
  20487. return new torch.Tensor(...args);
  20488. /* eslint-enable no-constructor-return */
  20489. }
  20490. });
  20491. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20492. constructor(...args) {
  20493. /* eslint-disable no-constructor-return */
  20494. return new torch.Tensor(...args);
  20495. /* eslint-enable no-constructor-return */
  20496. }
  20497. });
  20498. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20499. constructor(...args) {
  20500. /* eslint-disable no-constructor-return */
  20501. return new torch.Tensor(...args);
  20502. /* eslint-enable no-constructor-return */
  20503. }
  20504. });
  20505. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20506. constructor(...args) {
  20507. /* eslint-disable no-constructor-return */
  20508. return new torch.Tensor(...args);
  20509. /* eslint-enable no-constructor-return */
  20510. }
  20511. });
  20512. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20513. constructor(...args) {
  20514. /* eslint-disable no-constructor-return */
  20515. return new torch.Tensor(...args);
  20516. /* eslint-enable no-constructor-return */
  20517. }
  20518. });
  20519. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20520. constructor(...args) {
  20521. /* eslint-disable no-constructor-return */
  20522. return new torch.Tensor(...args);
  20523. /* eslint-enable no-constructor-return */
  20524. }
  20525. });
  20526. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20527. constructor(...args) {
  20528. /* eslint-disable no-constructor-return */
  20529. return new torch.Tensor(...args);
  20530. /* eslint-enable no-constructor-return */
  20531. }
  20532. });
  20533. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20534. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20535. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20536. constructor(...args) {
  20537. /* eslint-disable no-constructor-return */
  20538. return new torch.Tensor(...args);
  20539. /* eslint-enable no-constructor-return */
  20540. }
  20541. });
  20542. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20543. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20544. constructor(...args) {
  20545. /* eslint-disable no-constructor-return */
  20546. return new torch.Tensor(...args);
  20547. /* eslint-enable no-constructor-return */
  20548. }
  20549. });
  20550. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20551. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20552. constructor(...args) {
  20553. /* eslint-disable no-constructor-return */
  20554. return new torch.Tensor(...args);
  20555. /* eslint-enable no-constructor-return */
  20556. }
  20557. });
  20558. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20559. this.registerType('torchao.dtypes.utils.Layout', class {});
  20560. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20561. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20562. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20563. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20564. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20565. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20566. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20567. this.registerType('torch.SymBool', class {
  20568. constructor(node) {
  20569. this.node = node;
  20570. }
  20571. });
  20572. this.registerType('torch.SymInt', class {
  20573. constructor(node) {
  20574. this.node = node;
  20575. }
  20576. toString() {
  20577. return this.node.__str__();
  20578. }
  20579. });
  20580. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20581. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20582. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20583. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20584. /* eslint-disable no-multi-assign */
  20585. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20586. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20587. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20588. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20589. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20590. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20591. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20592. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20593. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20594. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20595. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20596. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20597. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20598. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20599. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20600. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20601. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20602. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20603. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20604. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20605. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20606. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20607. torch.bits8 = new torch.dtype(21, 'bits8');
  20608. torch.bits16 = new torch.dtype(22, 'bits16');
  20609. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20610. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20611. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20612. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20613. torch.uint16 = new torch.dtype(27, 'uint16', 2);
  20614. torch.uint32 = new torch.dtype(28, 'uint32', 4);
  20615. torch.uint64 = new torch.dtype(29, 'uint64', 8);
  20616. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20617. ['uint8', 'BYTE'],
  20618. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20619. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20620. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20621. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20622. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20623. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20624. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20625. torch.channels_last = new torch.memory_format('channels_last');
  20626. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20627. torch.preserve_format = new torch.memory_format('preserve_format');
  20628. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20629. ['contiguous_format', 'ContiguousFormat'],
  20630. ['channels_last', 'ChannelsLast'],
  20631. ['channels_last_3d', 'ChannelsLast3d'],
  20632. ['preserve_format', 'PreserveFormat']
  20633. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20634. /* eslint-enable no-multi-assign */
  20635. torch.strided = new torch.layout('strided');
  20636. torch.sparse_coo = new torch.layout('sparse_coo');
  20637. torch.sparse_csr = new torch.layout('sparse_csr');
  20638. torch.sparse_csc = new torch.layout('sparse_csc');
  20639. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20640. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20641. torch._mkldnn = new torch.layout('_mkldnn');
  20642. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20643. ['sparse_coo', 'SparseCoo'],
  20644. ['sparse_csr', 'SparseCsr'],
  20645. ['sparse_csc', 'SparseCsc'],
  20646. ['sparse_bsr', 'SparseBsr'],
  20647. ['sparse_bsc', 'SparseBsc'],
  20648. ['_mkldnn', '_mkldnn'],
  20649. ['strided', 'Strided'],
  20650. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20651. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20652. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20653. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20654. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20655. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20656. torch.inf = this.register('math').inf;
  20657. this.registerFunction('fastcore.basics._using_attr');
  20658. this.registerFunction('fastcore.imports.noop');
  20659. this.registerType('fastcore.basics.fastuple', class {});
  20660. this.registerType('fastcore.basics.GetAttr', class {});
  20661. this.registerType('fastcore.dispatch._TypeDict', class {});
  20662. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20663. this.registerType('fastcore.foundation.L', class {});
  20664. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20665. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20666. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20667. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20668. this.registerType('fastai.basic_train.Learner', class {});
  20669. this.registerType('fastai.basic_train.Recorder', class {});
  20670. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20671. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20672. return self.invoke(cls, [tensor]);
  20673. });
  20674. this.registerFunction('fastai.torch_core.trainable_params');
  20675. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20676. const tensor = self.invoke(type, [func(...args)]);
  20677. Object.assign(tensor, dict);
  20678. return tensor;
  20679. });
  20680. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20681. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20682. constructor(x) {
  20683. super();
  20684. Object.assign(this, x);
  20685. }
  20686. });
  20687. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20688. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20689. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20690. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20691. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20692. this.registerFunction('fastai.torch_core.uniform');
  20693. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20694. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20695. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20696. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20697. this.registerFunction('fastai.callback.hook._hook_inner');
  20698. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20699. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20700. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20701. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20702. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20703. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20704. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20705. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20706. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20707. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20708. this.registerType('fastai.data.core.Datasets', class {});
  20709. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20710. this.registerType('fastai.data.core.FilteredBase', class {});
  20711. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20712. this.registerType('fastai.data.core.TfmdLists', class {});
  20713. this.registerType('fastai.data.load._FakeLoader', class {});
  20714. this.registerFunction('fastai.data.load._wif');
  20715. this.registerType('fastai.data.transforms.Categorize', class {});
  20716. this.registerType('fastai.data.transforms.Category', class {});
  20717. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20718. this.registerType('fastai.data.transforms.ColReader', class {});
  20719. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20720. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20721. this.registerType('fastai.data.transforms.Normalize', class {});
  20722. this.registerType('fastai.data.transforms.parent_label', class {});
  20723. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20724. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20725. this.registerType('fastai.data.transforms.ToTensor', class {});
  20726. this.registerType('fastai.data_block.CategoryList', class {});
  20727. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20728. this.registerType('fastai.imports.noop', class {});
  20729. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20730. this.registerType('fastai.layers.ConvLayer', class {});
  20731. this.registerType('fastai.layers.Embedding', class {});
  20732. this.registerType('fastai.layers.Flatten', class {});
  20733. this.registerType('fastai.layers.FlattenedLoss', class {});
  20734. this.registerType('fastai.layers.LinBnDrop', class {});
  20735. this.registerType('fastai.layers.MergeLayer', class {});
  20736. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20737. this.registerType('fastai.layers.ResBlock', class {});
  20738. this.registerType('fastai.layers.SelfAttention', class {});
  20739. this.registerType('fastai.layers.SigmoidRange', class {});
  20740. this.registerType('fastai.layers.TimeDistributed', class {});
  20741. this.registerType('fastai.layers.ToTensorBase', class {});
  20742. this.registerType('fastai.learner._ConstantFunc', class {});
  20743. this.registerType('fastai.learner.Metric', class {});
  20744. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20745. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20746. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20747. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20748. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20749. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20750. this.registerType('fastai.learner.Recorder', class {});
  20751. this.registerType('fastai.losses.BaseLoss', class {});
  20752. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20753. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20754. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20755. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20756. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20757. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20758. this.registerType('fastai.metrics.Dice', class {});
  20759. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20760. this.registerFunction('fastai.metrics._rmse');
  20761. this.registerFunction('fastai.metrics.accuracy');
  20762. this.registerFunction('fastai.metrics.accuracy_multi');
  20763. this.registerFunction('fastai.metrics.foreground_acc');
  20764. this.registerFunction('fastai.metrics.mse');
  20765. this.registerFunction('fastai.metrics.error_rate');
  20766. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  20767. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  20768. this.registerFunction('fastai.optimizer.Adam');
  20769. this.registerFunction('fastai.optimizer.adam_step');
  20770. this.registerFunction('fastai.optimizer.average_grad');
  20771. this.registerFunction('fastai.optimizer.average_sqr_grad');
  20772. this.registerFunction('fastai.optimizer.RAdam');
  20773. this.registerFunction('fastai.optimizer.step_stat');
  20774. this.registerFunction('fastai.optimizer.weight_decay');
  20775. this.registerType('fastai.tabular.core.Categorify', class {});
  20776. this.registerType('fastai.tabular.core.FillMissing', class {});
  20777. this.registerType('fastai.tabular.core.FillStrategy', class {});
  20778. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  20779. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  20780. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  20781. this.registerType('fastai.tabular.core.Tabular', class {});
  20782. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  20783. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  20784. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  20785. this.registerType('fastai.tabular.model.TabularModel', class {});
  20786. this.registerFunction('fastai.vision.augment.aug_transforms');
  20787. this.registerFunction('fastai.vision.augment.dihedral_mat');
  20788. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  20789. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  20790. this.registerType('fastai.vision.augment._WarpCoord', class {});
  20791. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  20792. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  20793. this.registerType('fastai.vision.augment.Brightness', class {});
  20794. this.registerType('fastai.vision.augment.flip_mat', class {});
  20795. this.registerType('fastai.vision.augment.Flip', class {});
  20796. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  20797. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  20798. this.registerType('fastai.vision.augment.Resize', class {});
  20799. this.registerType('fastai.vision.augment.rotate_mat', class {});
  20800. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  20801. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  20802. this.registerType('fastai.vision.augment.zoom_mat', class {});
  20803. this.registerType('fastai.vision.core.PILImage', class {});
  20804. this.registerType('fastai.vision.core.PILMask', class {});
  20805. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  20806. this.registerType('fastai.vision.data.ImageList', class {});
  20807. this.registerType('fastai.vision.data.ImageItemList', class {});
  20808. this.registerType('fastai.vision.image.Image', class {});
  20809. this.registerType('fastai.vision.image.RandTransform', class {});
  20810. this.registerType('fastai.vision.image.TfmCrop', class {});
  20811. this.registerFunction('fastai.vision.learner._resnet_split');
  20812. this.registerFunction('fastai.vision.learner.default_split');
  20813. this.registerFunction('fastai.vision.learner.default_split');
  20814. this.registerType('fastai.vision.learner.TimmBody', class {});
  20815. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  20816. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  20817. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  20818. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  20819. this.registerFunction('fastai.vision.transform._crop_pad');
  20820. }
  20821. exec(code , context) {
  20822. const ast = this.ast;
  20823. const program = ast.parse(code, '', null, null);
  20824. if (!program) {
  20825. throw new python.Error("Module '?' parse error.");
  20826. }
  20827. this.block(program.body, context);
  20828. }
  20829. debug(/* file */) {
  20830. }
  20831. source(file) {
  20832. if (this._sources.has(file)) {
  20833. return this._sources.get(file);
  20834. }
  20835. return null;
  20836. }
  20837. read(file) {
  20838. const buffer = this.source(file);
  20839. if (buffer) {
  20840. const debug = this.debug(file);
  20841. return this.parse(file, buffer, debug);
  20842. }
  20843. return null;
  20844. }
  20845. parse(filename, buffer, debug) {
  20846. const ast = this.ast;
  20847. const source = this._utf8Decoder.decode(buffer);
  20848. const program = ast.parse(source, filename, null, debug);
  20849. if (!program) {
  20850. throw new python.Error(`Module '${filename}' parse error.`);
  20851. }
  20852. return program;
  20853. }
  20854. import(name, current, level) {
  20855. if (level) {
  20856. let bits = current.split('.');
  20857. if (bits.length < level) {
  20858. throw new python.Error('Invalid relative import beyond top-level package.');
  20859. }
  20860. bits = bits.slice(0, bits.length - level);
  20861. const base = bits.join('.');
  20862. name = name ? [base, name].join('.') : base;
  20863. }
  20864. const index = name.lastIndexOf('.');
  20865. let parent = null;
  20866. let child = null;
  20867. if (index > 0) {
  20868. parent = name.substring(0, index);
  20869. child = name.substring(index + 1);
  20870. this.import(parent);
  20871. }
  20872. if (!this._modules.has(name)) {
  20873. const module = this._registry.get(name) || new this.builtins.module(name);
  20874. module.__package__ = name;
  20875. this._modules.set(name, module);
  20876. const path = name.split('.').join('/');
  20877. module.__path__ = [path];
  20878. const file = `${path}.py`;
  20879. const program = this.read(file);
  20880. if (program) {
  20881. module.__file__ = file;
  20882. for (const [name, value] of Object.entries(this.builtins)) {
  20883. switch (name) {
  20884. case '__class__':
  20885. case '__package__':
  20886. case '__module__':
  20887. case '__name__':
  20888. case '__path__':
  20889. case '__file__':
  20890. break;
  20891. default:
  20892. module[name] = value;
  20893. break;
  20894. }
  20895. }
  20896. const context = new python.Execution.Context(module, null);
  20897. if (name !== 'builtins') {
  20898. context.set('__builtins__', this._modules.get('builtins'));
  20899. }
  20900. this.block(program.body, context);
  20901. }
  20902. if (parent) {
  20903. const parent_module = this._modules.get(parent);
  20904. parent_module[child] = module;
  20905. }
  20906. }
  20907. return this._modules.get(name);
  20908. }
  20909. __import__(name, globals, locals, fromlist, level) {
  20910. let module = null;
  20911. level = level || 0;
  20912. if (level === 0) {
  20913. module = this.import(name);
  20914. } else {
  20915. globals = globals || {};
  20916. let current = globals.__package__;
  20917. if (!current) {
  20918. const spec = globals.__spec__;
  20919. if (spec) {
  20920. current = spec.parent;
  20921. } else {
  20922. const name = globals.__name__;
  20923. const bits = name.split('.');
  20924. bits.pop();
  20925. current = bits.join('.');
  20926. }
  20927. }
  20928. module = this.import(name, current, level);
  20929. }
  20930. if (!fromlist) {
  20931. if (level === 0) {
  20932. return this.import(name.split('.')[0]);
  20933. } else if (name) {
  20934. throw new python.Error(`Unsupported relative import '${name}'.`);
  20935. // cut_off = len(name) - len(name.partition('.')[0])
  20936. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  20937. }
  20938. } else if (module.__path__) {
  20939. const handle_fromlist = (module, fromlist, recursive) => {
  20940. for (const name of fromlist) {
  20941. if (name === '*') {
  20942. if (!recursive && module.__all__) {
  20943. handle_fromlist(module, module.__all__, true);
  20944. }
  20945. } else if (!module[name]) {
  20946. this.import(`${module.__name__}.${name}`);
  20947. }
  20948. }
  20949. return module;
  20950. };
  20951. handle_fromlist(module, fromlist);
  20952. }
  20953. return module;
  20954. }
  20955. module(name) {
  20956. return this._modules.get(name);
  20957. }
  20958. resolve(name) {
  20959. const index = name.lastIndexOf('.');
  20960. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  20961. const moduleName = index === -1 ? '' : name.substring(0, index);
  20962. const module = this.import(moduleName);
  20963. let type = module ? module[memberName] : null;
  20964. if (!type) {
  20965. if (!this._unresolved.has(name)) {
  20966. const moduleName = name.split('.').shift();
  20967. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  20968. this.emit('resolve', name);
  20969. }
  20970. const type = this._createType(name, class {});
  20971. this._unresolved.set(name, type);
  20972. }
  20973. type = this._unresolved.get(name);
  20974. }
  20975. return type;
  20976. }
  20977. invoke(target, args) {
  20978. const builtins = this.builtins;
  20979. if (typeof target === 'string') {
  20980. target = this.resolve(target);
  20981. }
  20982. if (target) {
  20983. if (target.__class__ === builtins.type) {
  20984. if (target.prototype && target.prototype.__class__ === target) {
  20985. return Reflect.construct(target, args);
  20986. }
  20987. const obj = Object.create(target);
  20988. if (obj.__init__ && typeof obj.__init__ === 'function') {
  20989. obj.__init__(...args);
  20990. }
  20991. return obj;
  20992. } else if (target.__class__ === builtins.function) {
  20993. if (target.__call__) {
  20994. return target.__call__(args);
  20995. }
  20996. return target(...args);
  20997. }
  20998. }
  20999. throw new python.Error('Unsupported invoke target.');
  21000. }
  21001. call(target, name, args, keywords, context) {
  21002. const builtins = this.builtins;
  21003. const callTarget = this.target(target, context);
  21004. const callArguments = args.map((arg) => this.expression(arg, context));
  21005. if (!callTarget || (name !== null && !callTarget[name])) {
  21006. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21007. name = null;
  21008. callArguments.shift();
  21009. } else {
  21010. const targetName = `${this.identifier(target)}.${name}`;
  21011. throw new python.Error(`Unknown function '${targetName}'.`);
  21012. }
  21013. }
  21014. const func = name ? callTarget[name] : callTarget;
  21015. if (func.__class__ === builtins.type) {
  21016. if (func.prototype && func.prototype.__class__ === func) {
  21017. return Reflect.construct(func, callArguments);
  21018. }
  21019. const obj = Object.create(func);
  21020. obj.__class__ = func;
  21021. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21022. obj.__init__(...args);
  21023. }
  21024. return obj;
  21025. }
  21026. if (func.__class__ === builtins.function) {
  21027. if (func.__call__) {
  21028. return func.__call__(callArguments);
  21029. }
  21030. }
  21031. if (func.__class__ === builtins.method) {
  21032. if (func.__call__) {
  21033. return func.__call__([callTarget].concat(callArguments));
  21034. }
  21035. }
  21036. if (typeof func === 'function') {
  21037. return func.apply(callTarget, callArguments);
  21038. }
  21039. throw new python.Error('Unsupported call expression.');
  21040. }
  21041. apply(method, args, context) {
  21042. const locals = Array.prototype.slice.call(args);
  21043. context = new python.Execution.Context(context.globals, {});
  21044. args = method.args.posonlyargs.concat(method.args.args);
  21045. const default_pos = args.length - method.args.defaults.length;
  21046. for (let i = 0; i < method.args.args.length; i++) {
  21047. const arg = method.args.args[i];
  21048. let value = null;
  21049. if (locals.length > 0) {
  21050. value = locals.shift();
  21051. } else if (i >= default_pos) {
  21052. value = this.expression(method.args.defaults[i - default_pos], context);
  21053. } else {
  21054. throw new python.Error('Missing required positional argument.');
  21055. }
  21056. context.set(arg.arg, value);
  21057. }
  21058. return this.block(method.body, context);
  21059. }
  21060. block(statements, context) {
  21061. statements = Array.prototype.slice.call(statements);
  21062. while (statements.length > 0) {
  21063. const stmt = statements.shift();
  21064. const value = this.statement(stmt, context);
  21065. if (value !== undefined) {
  21066. return value;
  21067. }
  21068. }
  21069. return undefined;
  21070. }
  21071. statement(stmt, context) {
  21072. const ast = this.ast;
  21073. const builtins = this.builtins;
  21074. if (stmt instanceof ast.Pass) {
  21075. // pass
  21076. } else if (stmt instanceof ast.Constant) {
  21077. // pass
  21078. } else if (stmt instanceof ast.Return) {
  21079. return this.expression(stmt.value, context);
  21080. } else if (stmt instanceof ast.FunctionDef) {
  21081. const module = context.get('__name__');
  21082. /* eslint-disable consistent-this */
  21083. const self = this;
  21084. /* eslint-enable consistent-this */
  21085. const parent = context.get('__class__');
  21086. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21087. const func = {
  21088. __class__: type,
  21089. __globals__: context,
  21090. __module__: module,
  21091. __name__: stmt.name,
  21092. __code__: stmt,
  21093. __call__(args) {
  21094. return self.apply(this.__code__, args, this.__globals__);
  21095. }
  21096. };
  21097. context.set(stmt.name, func);
  21098. } else if (stmt instanceof ast.ClassDef) {
  21099. const bases = stmt.bases.map((base) => this.base(base, context));
  21100. if (bases.length > 1) {
  21101. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21102. }
  21103. const base = bases.length === 1 ? bases[0] : null;
  21104. const name = `${context.get('__name__')}.${stmt.name}`;
  21105. const value = this._createType(name, base ? class extends base {} : class {});
  21106. value.__bases__ = bases;
  21107. context.set(stmt.name, value);
  21108. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21109. } else if (stmt instanceof ast.AnnAssign) {
  21110. const target = this.identifier(stmt.target, context);
  21111. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21112. } else if (stmt instanceof ast.Assign) {
  21113. this.expression(stmt, context);
  21114. } else if (stmt instanceof ast.If) {
  21115. const test = this.expression(stmt.test, context);
  21116. if (test === true || test) {
  21117. const value = this.block(stmt.body, context);
  21118. if (value !== undefined) {
  21119. return value;
  21120. }
  21121. } else if (test === false) {
  21122. if (stmt.orelse) {
  21123. const value = this.block(stmt.orelse, context);
  21124. if (value !== undefined) {
  21125. return value;
  21126. }
  21127. }
  21128. } else {
  21129. throw new python.Error('Unsupported condition.');
  21130. }
  21131. } else if (stmt instanceof ast.For) {
  21132. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21133. const range = this.expression(stmt.iter, context);
  21134. const variable = stmt.target;
  21135. for (const current of range) {
  21136. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21137. const value = this.block(stmt.body.statements, context);
  21138. if (value !== undefined) {
  21139. return value;
  21140. }
  21141. }
  21142. } else {
  21143. throw new python.Error("Unsupported 'for' statement.");
  21144. }
  21145. } else if (stmt instanceof ast.While) {
  21146. const test = this.expression(stmt.test, context);
  21147. if (test) {
  21148. const value = this.block(stmt.body.statements, context);
  21149. if (value !== undefined) {
  21150. return value;
  21151. }
  21152. }
  21153. } else if (stmt instanceof ast.With) {
  21154. const items = [];
  21155. for (const item of stmt.items) {
  21156. items.push(this.expression(item.context_expr, context));
  21157. }
  21158. for (const item of items) {
  21159. if (item.__enter__ && item.__enter__.__call__) {
  21160. item.__enter__.__call__([item]);
  21161. }
  21162. }
  21163. const value = this.block(stmt.body, context);
  21164. for (const item of items) {
  21165. if (item.__exit__ && item.__exit__.__call__) {
  21166. item.__exit__.__call__([item]);
  21167. }
  21168. }
  21169. if (value !== undefined) {
  21170. return value;
  21171. }
  21172. } else if (stmt instanceof ast.Expr) {
  21173. this.expression(stmt.value, context);
  21174. } else if (stmt instanceof ast.Import) {
  21175. for (const alias of stmt.names) {
  21176. let module = this.__import__(alias.name, context);
  21177. if (alias.asname) {
  21178. const bits = alias.name.split('.').reverse();
  21179. bits.pop();
  21180. while (bits.length > 0) {
  21181. module = module[bits.pop()];
  21182. }
  21183. context.set(alias.asname, module);
  21184. } else {
  21185. context.set(alias.name.split('.')[0], module);
  21186. }
  21187. }
  21188. } else if (stmt instanceof ast.ImportFrom) {
  21189. const fromlist = stmt.names.map((name) => name.name);
  21190. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21191. for (const entry of stmt.names) {
  21192. const name = entry.name;
  21193. const asname = entry.asname ? entry.asname : null;
  21194. if (!module[name]) {
  21195. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21196. }
  21197. context.set(asname ? asname : name, module[name]);
  21198. }
  21199. } else {
  21200. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21201. }
  21202. return undefined;
  21203. }
  21204. expression(expr, context) {
  21205. const ast = this.ast;
  21206. const builtins = this.builtins;
  21207. const typing = this.typing;
  21208. const self = context.get('self');
  21209. switch (expr.__class__.__name__) {
  21210. case 'Assign': {
  21211. const [target] = expr.targets;
  21212. if (target instanceof ast.Name) {
  21213. const value = this.expression(expr.value, context);
  21214. context.set(target.id, value);
  21215. return undefined;
  21216. } else if (target instanceof ast.Subscript) {
  21217. if (target.value instanceof ast.Name &&
  21218. target.slice instanceof ast.List &&
  21219. target.slice.elts.length === 1) {
  21220. const index = this.expression(target.slice.elts[0], context);
  21221. const id = target.value.id;
  21222. if (id === '__annotations__') {
  21223. context.set(id, context.get(id) || {});
  21224. }
  21225. const obj = context.get(id);
  21226. const value = this.expression(expr.value, context);
  21227. if (obj instanceof Map) {
  21228. obj.set(index, value);
  21229. } else {
  21230. obj[index] = value;
  21231. }
  21232. return undefined;
  21233. }
  21234. } else if (target instanceof ast.Attribute) {
  21235. const obj = this.expression(target.value, context);
  21236. const value = this.expression(expr.value, context);
  21237. obj[target.attr] = value;
  21238. return undefined;
  21239. } else if (target instanceof ast.Tuple) {
  21240. context.target.push(target.elts);
  21241. const value = this.expression(expr.value, context);
  21242. context.target.pop();
  21243. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21244. if (target.elts.length < value.length) {
  21245. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21246. }
  21247. if (target.elts.length > value.length) {
  21248. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21249. }
  21250. for (let i = 0; i < value.length; i++) {
  21251. context.set(target.elts[i].id, value[i]);
  21252. }
  21253. return undefined;
  21254. }
  21255. }
  21256. break;
  21257. }
  21258. case 'List': {
  21259. return expr.elts.map((expr) => this.expression(expr, context));
  21260. }
  21261. case 'Constant': {
  21262. return expr.value;
  21263. }
  21264. case 'Subscript': {
  21265. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21266. const id = expr.value.id;
  21267. if (context.get(id)) {
  21268. const index = this.expression(expr.slice, context);
  21269. const target = context.get(id);
  21270. if (target instanceof Map) {
  21271. return target.get(index);
  21272. }
  21273. return target[index < 0 ? target.length + index : index];
  21274. }
  21275. }
  21276. const value = this.expression(expr.value, context);
  21277. if (value && expr.slice instanceof ast.List &&
  21278. (value.__class__ === typing._TupleType ||
  21279. value.__class__ === typing._SpecialGenericAlias ||
  21280. value.__class__ === typing._SpecialForm)) {
  21281. const type = { ...value };
  21282. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21283. return type;
  21284. }
  21285. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21286. const index = this.expression(expr.slice.elts[0], context);
  21287. if (value instanceof Map) {
  21288. return value.get(index);
  21289. }
  21290. return value[index < 0 ? value.length + index : index];
  21291. }
  21292. break;
  21293. }
  21294. case 'Attribute': {
  21295. const value = this.target(expr.value, context);
  21296. return value[expr.attr];
  21297. }
  21298. case 'Call': {
  21299. const func = expr.func;
  21300. if (func instanceof ast.Attribute) {
  21301. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21302. }
  21303. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21304. }
  21305. case 'Name': {
  21306. const id = expr.id;
  21307. if (id === 'self') {
  21308. return self;
  21309. }
  21310. const type = (value) => {
  21311. return value &&
  21312. (value.__class__ === builtins.type ||
  21313. value.__class__ === typing._TupleType ||
  21314. value.__class__ === typing._SpecialGenericAlias ||
  21315. value.__class__ === typing._SpecialForm);
  21316. };
  21317. const builtin = builtins[id];
  21318. if (type(builtin)) {
  21319. return builtin;
  21320. }
  21321. const value = context.get(id);
  21322. if (value === undefined) {
  21323. const value = typing[id];
  21324. if (type(value)) {
  21325. return value;
  21326. }
  21327. }
  21328. return value;
  21329. }
  21330. case 'Tuple': {
  21331. return expr.elts.map((expr) => this.expression(expr, context));
  21332. }
  21333. case 'Dict': {
  21334. const dict = {};
  21335. for (let i = 0; i < expr.keys.length; i++) {
  21336. const key = this.expression(expr.keys[i], context);
  21337. const value = this.expression(expr.values[i], context);
  21338. dict[key] = value;
  21339. }
  21340. return dict;
  21341. }
  21342. case 'UnaryOp': {
  21343. if (expr.op instanceof ast.USub) {
  21344. return -this.expression(expr.operand, context);
  21345. }
  21346. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21347. }
  21348. case 'binary': {
  21349. switch (expr.op) {
  21350. case '==': {
  21351. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21352. }
  21353. default: {
  21354. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21355. }
  21356. }
  21357. }
  21358. default: {
  21359. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21360. }
  21361. }
  21362. return undefined;
  21363. }
  21364. base(expr, context) {
  21365. return this.expression(expr, context);
  21366. }
  21367. identifier(expr) {
  21368. const ast = this.ast;
  21369. if (expr instanceof ast.Name) {
  21370. return expr.id;
  21371. }
  21372. if (expr instanceof ast.Attribute) {
  21373. return `${this.identifier(expr.value)}.${expr.attr}`;
  21374. }
  21375. return null;
  21376. }
  21377. target(expr, context) {
  21378. const ast = this.ast;
  21379. let current = expr;
  21380. let path = [];
  21381. for (;;) {
  21382. if (current instanceof ast.Attribute) {
  21383. path.push(current.attr);
  21384. current = current.value;
  21385. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21386. path.push(current.id);
  21387. break;
  21388. } else {
  21389. path = null;
  21390. break;
  21391. }
  21392. }
  21393. if (path) {
  21394. let target = null;
  21395. for (let i = path.length - 1; i >= 0; i--) {
  21396. const name = path[i];
  21397. if (target) {
  21398. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21399. } else {
  21400. target = context.get(name);
  21401. }
  21402. if (!target) {
  21403. break;
  21404. }
  21405. }
  21406. if (!target) {
  21407. path.reverse();
  21408. const name = path.join('.');
  21409. const file = `${path.join('/')}.py`;
  21410. if (this._sources.has(file)) {
  21411. target = this.import(name);
  21412. } else {
  21413. target = this.resolve(name);
  21414. }
  21415. }
  21416. return target;
  21417. }
  21418. return this.expression(expr, context);
  21419. }
  21420. add(name, source) {
  21421. this._sources.set(name, source);
  21422. }
  21423. on(event, listener) {
  21424. const value = this._events.get(event) || [];
  21425. value.push(listener);
  21426. this._events.set(event, value);
  21427. }
  21428. emit(event, ...args) {
  21429. if (this._events.has(event)) {
  21430. for (const callback of this._events.get(event)) {
  21431. callback(this, ...args);
  21432. }
  21433. }
  21434. }
  21435. register(name, value) {
  21436. if (!this._registry.has(name)) {
  21437. value = value || new (this._registry.get('builtins').module)(name);
  21438. this._registry.set(name, value);
  21439. let current = name;
  21440. for (;;) {
  21441. const index = current.lastIndexOf('.');
  21442. if (index === -1) {
  21443. break;
  21444. }
  21445. const child = current.substring(index + 1);
  21446. current = current.substring(0, index);
  21447. if (!value.__module__) {
  21448. value.__module__ = current;
  21449. }
  21450. const parent = this.register(current);
  21451. parent[child] = value;
  21452. value = parent;
  21453. }
  21454. }
  21455. return this._registry.get(name);
  21456. }
  21457. registerFunction(name, value) {
  21458. const builtins = this.builtins;
  21459. const index = name.lastIndexOf('.');
  21460. if (!value) {
  21461. value = () => {
  21462. throw new python.Error(`'${name}' is not implemented.`);
  21463. };
  21464. }
  21465. value.__class__ = builtins.function;
  21466. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21467. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21468. const module = this.register(value.__module__);
  21469. if (module[name]) {
  21470. throw new python.Error(`Function '${name}' is already registered.`);
  21471. }
  21472. module[value.__name__] = value;
  21473. return value;
  21474. }
  21475. registerOperator(name, value) {
  21476. this._operators.set(name, value);
  21477. }
  21478. _createType(name, value) {
  21479. const builtins = this.builtins;
  21480. const index = name.lastIndexOf('.');
  21481. value.__class__ = builtins.type;
  21482. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21483. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21484. value.prototype.__class__ = value;
  21485. return value;
  21486. }
  21487. registerType(name, value) {
  21488. value = this._createType(name, value);
  21489. const parts = name.split('.');
  21490. const memberName = parts.pop();
  21491. const moduleName = parts.join('.');
  21492. const module = this.register(moduleName);
  21493. if (module[memberName]) {
  21494. throw new python.Error(`Class '${memberName}' is already registered.`);
  21495. }
  21496. module[memberName] = value;
  21497. return value;
  21498. }
  21499. };
  21500. python.Execution.Context = class {
  21501. constructor(globals, locals) {
  21502. this.globals = globals;
  21503. this.locals = locals;
  21504. }
  21505. set(name, value) {
  21506. if (this.locals) {
  21507. this.locals[name] = value;
  21508. } else {
  21509. this.globals[name] = value;
  21510. }
  21511. }
  21512. get(name) {
  21513. if (this.locals && name in this.locals) {
  21514. return this.locals[name];
  21515. }
  21516. if (name in this.globals) {
  21517. return this.globals[name];
  21518. }
  21519. return undefined;
  21520. }
  21521. get target() {
  21522. this._target = this._target || [];
  21523. return this._target;
  21524. }
  21525. };
  21526. python.BinaryReader = class {
  21527. constructor(buffer) {
  21528. this._buffer = buffer;
  21529. this._length = buffer.length;
  21530. this._position = 0;
  21531. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21532. this._utf8Decoder = new TextDecoder('utf-8');
  21533. this._asciiDecoder = new TextDecoder('ascii');
  21534. }
  21535. get position() {
  21536. return this._position;
  21537. }
  21538. get length() {
  21539. return this._length;
  21540. }
  21541. seek(position) {
  21542. this._position = position >= 0 ? position : this._length + position;
  21543. if (this._position > this._buffer.length) {
  21544. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21545. }
  21546. }
  21547. skip(offset) {
  21548. this._position += offset;
  21549. if (this._position > this._buffer.length) {
  21550. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21551. }
  21552. }
  21553. stream(length) {
  21554. const buffer = this.read(length);
  21555. return new python.BinaryReader(buffer);
  21556. }
  21557. peek(length) {
  21558. const position = this._position;
  21559. length = length === undefined ? this._length - this._position : length;
  21560. this.skip(length);
  21561. const end = this._position;
  21562. this.skip(-length);
  21563. if (position === 0 && length === this._length) {
  21564. return this._buffer;
  21565. }
  21566. return this._buffer.subarray(position, end);
  21567. }
  21568. read(length) {
  21569. const position = this._position;
  21570. length = length === undefined ? this._length - this._position : length;
  21571. this.skip(length);
  21572. if (position === 0 && length === this._length) {
  21573. return this._buffer;
  21574. }
  21575. return this._buffer.subarray(position, this._position);
  21576. }
  21577. byte() {
  21578. const position = this._position;
  21579. this.skip(1);
  21580. return this._view.getUint8(position);
  21581. }
  21582. uint16() {
  21583. const position = this._position;
  21584. this.skip(2);
  21585. return this._view.getUint16(position, true);
  21586. }
  21587. int32() {
  21588. const position = this._position;
  21589. this.skip(4);
  21590. return this._view.getInt32(position, true);
  21591. }
  21592. uint32() {
  21593. const position = this._position;
  21594. this.skip(4);
  21595. return this._view.getUint32(position, true);
  21596. }
  21597. int64() {
  21598. const position = this._position;
  21599. this.skip(8);
  21600. return this._view.getBigInt64(position, true);
  21601. }
  21602. float64() {
  21603. const position = this._position;
  21604. this.skip(8);
  21605. return this._view.getFloat64(position, false);
  21606. }
  21607. string(size, encoding) {
  21608. const data = this.read(size);
  21609. return (encoding === 'utf-8') ?
  21610. this._utf8Decoder.decode(data) :
  21611. this._asciiDecoder.decode(data);
  21612. }
  21613. line() {
  21614. const index = this._buffer.indexOf(0x0A, this._position);
  21615. if (index === -1) {
  21616. throw new python.Error('Could not find end of line.');
  21617. }
  21618. const size = index - this._position;
  21619. const text = this.string(size, 'ascii');
  21620. this.skip(1);
  21621. return text;
  21622. }
  21623. };
  21624. python.StreamReader = class {
  21625. constructor(stream) {
  21626. this._stream = stream;
  21627. this._length = stream.length;
  21628. this._position = 0;
  21629. this._utf8Decoder = new TextDecoder('utf-8');
  21630. this._asciiDecoder = new TextDecoder('ascii');
  21631. }
  21632. get position() {
  21633. return this._position;
  21634. }
  21635. get length() {
  21636. return this._length;
  21637. }
  21638. seek(position) {
  21639. this._stream.seek(position);
  21640. this._position = this._stream.position;
  21641. }
  21642. skip(offset) {
  21643. this._position += offset;
  21644. if (this._position > this._length) {
  21645. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21646. }
  21647. }
  21648. stream(length) {
  21649. this._stream.seek(this._position);
  21650. this.skip(length);
  21651. return this._stream.stream(length);
  21652. }
  21653. peek(length) {
  21654. this._stream.seek(this._position);
  21655. return this._stream.peek(length);
  21656. }
  21657. read(length) {
  21658. this._stream.seek(this._position);
  21659. this.skip(length);
  21660. return this._stream.read(length);
  21661. }
  21662. byte() {
  21663. const position = this._fill(1);
  21664. return this._view.getUint8(position);
  21665. }
  21666. uint16() {
  21667. const position = this._fill(2);
  21668. return this._view.getUint16(position, true);
  21669. }
  21670. int32() {
  21671. const position = this._fill(4);
  21672. return this._view.getInt32(position, true);
  21673. }
  21674. uint32() {
  21675. const position = this._fill(4);
  21676. return this._view.getUint32(position, true);
  21677. }
  21678. int64() {
  21679. const position = this._fill(8);
  21680. return this._view.getBigInt64(position, true);
  21681. }
  21682. float64() {
  21683. const position = this._fill(8);
  21684. return this._view.getFloat64(position, false);
  21685. }
  21686. string(size, encoding) {
  21687. const data = this.read(size);
  21688. return (encoding === 'utf-8') ?
  21689. this._utf8Decoder.decode(data) :
  21690. this._asciiDecoder.decode(data);
  21691. }
  21692. line() {
  21693. let position = this._fill(0);
  21694. let index = this._buffer.indexOf(0x0A, position);
  21695. if (index === -1) {
  21696. const size = Math.min(0x20000000, this._stream.length - this._position);
  21697. this._fill(size);
  21698. this.skip(-size);
  21699. position = this._fill(0);
  21700. index = this._buffer.indexOf(0x0A, position);
  21701. if (index === -1) {
  21702. throw new python.Error('Could not find end of line.');
  21703. }
  21704. }
  21705. const size = index - position;
  21706. const text = this.string(size, 'ascii');
  21707. this.skip(1);
  21708. return text;
  21709. }
  21710. _fill(length) {
  21711. if (this._position + length > this._length) {
  21712. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21713. }
  21714. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21715. this._offset = this._position;
  21716. this._stream.seek(this._offset);
  21717. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21718. this._buffer = this._stream.read(size);
  21719. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21720. }
  21721. const position = this._position;
  21722. this._position += length;
  21723. return position - this._offset;
  21724. }
  21725. };
  21726. python.Error = class extends Error {
  21727. constructor(message) {
  21728. super(message);
  21729. this.name = 'Python Error';
  21730. }
  21731. };
  21732. export const Execution = python.Execution;