python.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960
  1. // Experimental Python Execution
  2. const python = {};
  3. python.Execution = class {
  4. constructor(sources) {
  5. /* eslint-disable consistent-this */
  6. const self = this;
  7. /* eslint-enable consistent-this */
  8. const execution = self;
  9. this._sources = sources || new Map();
  10. this._events = new Map();
  11. this._utf8Decoder = new TextDecoder('utf-8');
  12. this._unresolved = new Map();
  13. this._operators = new Map();
  14. const dict = class extends Map {
  15. constructor(items) {
  16. super();
  17. if (items) {
  18. if (items instanceof Map) {
  19. items = Array.from(items);
  20. } else if (!Array.isArray(items)) {
  21. items = Object.entries(items);
  22. }
  23. for (const [name, value] of items) {
  24. this.__setitem__(name, value);
  25. }
  26. }
  27. }
  28. __contains__(key) {
  29. return this.has(key);
  30. }
  31. __setitem__(key, value) {
  32. this.set(key, value);
  33. }
  34. __getitem__(key) {
  35. return this.get(key);
  36. }
  37. __delitem__(key) {
  38. this.delete(key);
  39. }
  40. get(key, defaultValue) {
  41. return super.has(key) ? super.get(key) : defaultValue;
  42. }
  43. setdefault(key, defaultValue) {
  44. if (this.has(key)) {
  45. return this.get(key);
  46. }
  47. const value = defaultValue || null;
  48. this.set(key, value);
  49. return value;
  50. }
  51. pop(key) {
  52. if (this.__contains__(key)) {
  53. const v = this.__getitem__(key);
  54. this.__delitem__(key);
  55. return v;
  56. }
  57. return null;
  58. }
  59. items() {
  60. return Array.from(this);
  61. }
  62. update(other) {
  63. for (const [key, value] of other) {
  64. this.set(key, value);
  65. }
  66. }
  67. };
  68. this._modules = new dict();
  69. this._registry = new Map();
  70. const module = class {
  71. constructor(name) {
  72. this.__name__ = name;
  73. }
  74. };
  75. const builtins = this.register('builtins', new module('builtins'));
  76. this.builtins = builtins;
  77. this._registry.set('__builtin__', builtins);
  78. this.registerType('builtins.type', class {
  79. constructor(...args) {
  80. if (args.length === 1) {
  81. const [obj] = args;
  82. if (obj === null) {
  83. // eslint-disable-next-line no-constructor-return
  84. return builtins.NoneType;
  85. }
  86. if (obj && obj.__class__) {
  87. // eslint-disable-next-line no-constructor-return
  88. return obj.__class__;
  89. }
  90. throw new python.Error(`Unknown type '${obj}'`);
  91. }
  92. if (args.length === 3) {
  93. const [name, bases, body] = args;
  94. const cls = bases.length > 0 ? class extends bases[0] {} : class {};
  95. execution.registerType(name, cls);
  96. for (const [key, value] of body) {
  97. cls[key] = value;
  98. }
  99. // eslint-disable-next-line no-constructor-return
  100. return cls;
  101. }
  102. throw new python.Error(`Invalid 'builtins.dict' argument count.`);
  103. }
  104. }).__class__ = builtins.type;
  105. this.registerType('builtins.module', module);
  106. this.registerType('builtins.method', class {});
  107. this.registerType('builtins.function', class {
  108. constructor(code, globals, name) {
  109. this.__code__ = code;
  110. this.__globals__ = globals;
  111. this.__name__ = name;
  112. }
  113. });
  114. this.registerType('builtins.classmethod', class {});
  115. this.registerType('builtins.code', class {});
  116. this.import('builtins');
  117. this.registerType('builtins.builtin_function_or_method', class {});
  118. const typing = this.register('typing');
  119. this.typing = typing;
  120. const operator = this.register('operator');
  121. this.register('_codecs');
  122. this.register('argparse');
  123. this.enum = this.register('enum');
  124. const collections = this.register('collections');
  125. const copy = this.register('copy');
  126. this.register('copy_reg');
  127. const ast = this.register('ast');
  128. this.ast = ast;
  129. this.register('cuml');
  130. const cloudpickle = this.register('cloudpickle');
  131. const datetime = this.register('datetime');
  132. this.register('gensim');
  133. const io = this.register('io');
  134. const joblib = this.register('joblib');
  135. const jax = this.register('jax');
  136. this.register('jax.numpy');
  137. this.register('jax._src.array');
  138. this.register('jax._src.device_array');
  139. const functools = this.register('functools');
  140. const keras = this.register('keras');
  141. const catboost = this.register('catboost');
  142. this.register('lightgbm');
  143. this.register('nolearn');
  144. const fastcore = this.register('fastcore');
  145. const fastai = this.register('fastai');
  146. const math = this.register('math');
  147. math.inf = Infinity;
  148. const numpy = this.register('numpy');
  149. this.register('numpy.core.multiarray');
  150. this.register('numpy.core._multiarray_umath');
  151. this.register('numpy.matrixlib.defmatrix');
  152. const pandas = this.register('pandas');
  153. this.register('pandas.indexes.base');
  154. this.register('pandas.indexes.range');
  155. this.register('pandas._libs.tslib');
  156. this.register('pandas._libs.internals');
  157. const pickle = this.register('pickle');
  158. const shap = this.register('shap');
  159. this.register('shap.explainers.linear');
  160. const sklearn = this.register('sklearn');
  161. this.register('sklearn.externals.joblib.numpy_pickle');
  162. const torch = this.register('torch');
  163. this.torch = torch;
  164. const torchvision = this.register('torchvision');
  165. const torchao = this.register('torchao');
  166. const sympy = this.register('sympy');
  167. this.register('torch.storage');
  168. this.register('torch.nn.parameter');
  169. this.register('torch.ops');
  170. this.register('torch._ops');
  171. this.register('torch.ops.higher_order');
  172. this.register('torch.ops.torchvision');
  173. this.register('torch.ops.torchaudio');
  174. this.register('torch.ops._caffe2');
  175. this.register('torchvision');
  176. this.register('__torch__');
  177. const sys = this.register('sys');
  178. sys.modules = this._modules;
  179. this.register('xgboost');
  180. this.registerType('ast.AST', class {});
  181. this.registerType('ast.mod', class extends ast.AST {});
  182. this.registerType('ast.expr', class extends ast.AST {});
  183. this.registerType('ast.unaryop', class extends ast.AST {});
  184. this.registerType('ast.binop', class extends ast.AST {});
  185. this.registerType('ast.operator', class extends ast.AST {});
  186. this.registerType('ast.boolop', class extends ast.AST {});
  187. this.registerType('ast.cmpop', class extends ast.AST {});
  188. this.registerType('ast.stmt', class extends ast.AST {});
  189. this.registerType('ast.excepthandler', class extends ast.AST {});
  190. this.registerType('ast.keyword', class extends ast.AST {
  191. constructor(arg, value) {
  192. super();
  193. this.arg = arg;
  194. this.value = value;
  195. }
  196. });
  197. this.registerType('ast.alias', class extends ast.AST {
  198. constructor(name, asname) {
  199. super();
  200. this.name = name;
  201. this.asname = asname;
  202. }
  203. });
  204. this.registerType('ast.Name', class extends ast.expr {
  205. constructor(id, ctx) {
  206. super();
  207. this.id = id;
  208. if (ctx) {
  209. this.ctx = ctx;
  210. }
  211. }
  212. });
  213. this.registerType('ast.Constant', class extends ast.expr {
  214. constructor(value, type) {
  215. super();
  216. this.value = value;
  217. this.type = type || null;
  218. }
  219. });
  220. this.registerType('ast.Ellipsis', class extends ast.Constant {
  221. constructor() {
  222. super(builtins.ellipsis);
  223. }
  224. });
  225. this.registerType('ast.Starred', class extends ast.expr {
  226. constructor(value, ctx) {
  227. super();
  228. this.value = value;
  229. if (ctx) {
  230. this.ctx = ctx;
  231. }
  232. }
  233. });
  234. this.registerType('ast.List', class extends ast.expr {
  235. constructor(elts, ctx) {
  236. super();
  237. this.elts = elts;
  238. if (ctx) {
  239. this.ctx = ctx;
  240. }
  241. }
  242. });
  243. this.registerType('ast.Set', class extends ast.expr {
  244. constructor(elts) {
  245. super();
  246. this.elts = elts;
  247. }
  248. });
  249. this.registerType('ast.Tuple', class extends ast.expr {
  250. constructor(elts, ctx) {
  251. super();
  252. this.elts = elts;
  253. if (ctx) {
  254. this.ctx = ctx;
  255. }
  256. }
  257. });
  258. this.registerType('ast.Dict', class extends ast.expr {
  259. constructor(keys, values) {
  260. super();
  261. this.keys = keys;
  262. this.values = values;
  263. }
  264. });
  265. this.registerType('ast.ListComp', class extends ast.expr {
  266. constructor(elt, generators) {
  267. super();
  268. this.elt = elt;
  269. this.generators = generators;
  270. }
  271. });
  272. this.registerType('ast.SetComp', class extends ast.expr {
  273. constructor(elt, generators) {
  274. super();
  275. this.elt = elt;
  276. this.generators = generators;
  277. }
  278. });
  279. this.registerType('ast.GeneratorExp', class extends ast.expr {
  280. constructor(elt, generators) {
  281. super();
  282. this.elt = elt;
  283. this.generators = generators;
  284. }
  285. });
  286. this.registerType('ast.DictComp', class extends ast.expr {
  287. constructor(key, value, generators) {
  288. super();
  289. this.key = key;
  290. this.value = value;
  291. this.generators = generators;
  292. }
  293. });
  294. this.registerType('ast.comprehension', class extends ast.AST {
  295. constructor(target, iter, ifs, is_async) {
  296. super();
  297. this.target = target;
  298. this.iter = iter;
  299. this.ifs = ifs;
  300. this.is_async = is_async;
  301. }
  302. });
  303. this.registerType('ast.Subscript', class extends ast.expr {
  304. constructor(value, slice, ctx) {
  305. super();
  306. this.value = value;
  307. this.slice = slice;
  308. if (ctx) {
  309. this.ctx = ctx;
  310. }
  311. }
  312. });
  313. this.registerType('ast.Slice', class extends ast.expr {
  314. constructor(lower, upper, step) {
  315. super();
  316. this.lower = lower;
  317. this.upper = upper;
  318. this.step = step;
  319. }
  320. });
  321. this.registerType('ast.UnaryOp', class extends ast.expr {
  322. constructor(op, operand) {
  323. super();
  324. this.op = op;
  325. this.operand = operand;
  326. }
  327. });
  328. this.registerType('ast.UAdd', class extends ast.unaryop {});
  329. this.registerType('ast.USub', class extends ast.unaryop {});
  330. this.registerType('ast.Not', class extends ast.unaryop {});
  331. this.registerType('ast.Invert', class extends ast.unaryop {});
  332. this.registerType('ast.BinOp', class extends ast.expr {
  333. constructor(left, op, right) {
  334. super();
  335. this.left = left;
  336. this.op = op;
  337. this.right = right;
  338. }
  339. });
  340. this.registerType('ast.Add', class extends ast.operator {});
  341. this.registerType('ast.Sub', class extends ast.operator {});
  342. this.registerType('ast.Mult', class extends ast.operator {});
  343. this.registerType('ast.Div', class extends ast.operator {});
  344. this.registerType('ast.FloorDiv', class extends ast.operator {});
  345. this.registerType('ast.Mod', class extends ast.operator {});
  346. this.registerType('ast.Pow', class extends ast.operator {});
  347. this.registerType('ast.LShift', class extends ast.operator {});
  348. this.registerType('ast.RShift', class extends ast.operator {});
  349. this.registerType('ast.BitOr', class extends ast.operator {});
  350. this.registerType('ast.BitXor', class extends ast.operator {});
  351. this.registerType('ast.BitAnd', class extends ast.operator {});
  352. this.registerType('ast.MatMult', class extends ast.operator {});
  353. this.registerType('ast.BoolOp', class extends ast.expr {
  354. constructor(op, values) {
  355. super();
  356. this.op = op;
  357. this.values = values;
  358. }
  359. });
  360. this.registerType('ast.And', class extends ast.boolop {});
  361. this.registerType('ast.Or', class extends ast.boolop {});
  362. this.registerType('ast.Compare', class extends ast.expr {
  363. constructor(left, ops, comparators) {
  364. super();
  365. this.left = left;
  366. this.ops = ops;
  367. this.comparators = comparators;
  368. }
  369. });
  370. this.registerType('ast.Eq', class extends ast.cmpop {});
  371. this.registerType('ast.NotEq', class extends ast.cmpop {});
  372. this.registerType('ast.Lt', class extends ast.cmpop {});
  373. this.registerType('ast.LtE', class extends ast.cmpop {});
  374. this.registerType('ast.Gt', class extends ast.cmpop {});
  375. this.registerType('ast.GtE', class extends ast.cmpop {});
  376. this.registerType('ast.Is', class extends ast.cmpop {});
  377. this.registerType('ast.IsNot', class extends ast.cmpop {});
  378. this.registerType('ast.In', class extends ast.cmpop {});
  379. this.registerType('ast.NotIn', class extends ast.cmpop {});
  380. this.registerType('ast.Call', class extends ast.expr {
  381. constructor(func, args, keywords) {
  382. super();
  383. this.func = func;
  384. this.args = args;
  385. this.keywords = keywords || [];
  386. }
  387. });
  388. this.registerType('ast.Attribute', class extends ast.expr {
  389. constructor(value, attr, ctx) {
  390. super();
  391. this.value = value;
  392. this.attr = attr;
  393. if (ctx) {
  394. this.ctx = ctx;
  395. }
  396. }
  397. });
  398. this.registerType('ast.Lambda', class extends ast.expr {
  399. constructor(args, body) {
  400. super();
  401. this.args = args;
  402. this.body = body;
  403. }
  404. });
  405. this.registerType('ast.IfExp', class extends ast.expr {
  406. constructor(test, body, orelse) {
  407. super();
  408. this.test = test;
  409. this.body = body;
  410. this.orelse = orelse;
  411. }
  412. });
  413. this.registerType('ast.NamedExpr', class extends ast.expr {
  414. constructor(target, value) {
  415. super();
  416. this.target = target;
  417. this.value = value;
  418. }
  419. });
  420. this.registerType('ast.Yield', class extends ast.expr {
  421. constructor(value) {
  422. super();
  423. this.value = value;
  424. }
  425. });
  426. this.registerType('ast.YieldFrom', class extends ast.expr {
  427. constructor(value) {
  428. super();
  429. this.value = value;
  430. }
  431. });
  432. this.registerType('ast.Expr', class extends ast.stmt {
  433. constructor(value) {
  434. super();
  435. this.value = value;
  436. }
  437. });
  438. this.registerType('ast.Assign', class extends ast.stmt {
  439. constructor(targets, value, ctx) {
  440. super();
  441. this.targets = targets;
  442. this.value = value;
  443. if (ctx) {
  444. this.ctx = ctx;
  445. }
  446. }
  447. });
  448. this.registerType('ast.AnnAssign', class extends ast.stmt {
  449. constructor(target, annotation, value, simple) {
  450. super();
  451. this.target = target;
  452. this.annotation = annotation;
  453. this.value = value;
  454. this.simple = simple;
  455. }
  456. });
  457. this.registerType('ast.AugAssign', class extends ast.stmt {
  458. constructor(target, op, value) {
  459. super();
  460. this.target = target;
  461. this.op = op;
  462. this.value = value;
  463. }
  464. });
  465. this.registerType('ast.If', class extends ast.stmt {
  466. constructor(test, body, orelse) {
  467. super();
  468. this.test = test;
  469. this.body = body;
  470. this.orelse = orelse;
  471. }
  472. });
  473. this.registerType('ast.For', class extends ast.stmt {
  474. constructor(target, iter, body, orelse /*, type_comment */) {
  475. super();
  476. this.target = target;
  477. this.iter = iter;
  478. this.body = body;
  479. this.orelse = orelse;
  480. }
  481. });
  482. this.registerType('ast.While', class extends ast.stmt {
  483. constructor(test, body, orelse /*, type_comment */) {
  484. super();
  485. this.test = test;
  486. this.body = body;
  487. this.orelse = orelse;
  488. }
  489. });
  490. this.registerType('ast.Del', class extends ast.stmt {
  491. constructor(targets) {
  492. super();
  493. this.targets = targets;
  494. }
  495. });
  496. this.registerType('ast.Return', class extends ast.stmt {
  497. constructor(value) {
  498. super();
  499. this.value = value;
  500. }
  501. });
  502. this.registerType('ast.Try', class extends ast.stmt {
  503. constructor(body, handlers, orelse, finalbody) {
  504. super();
  505. this.body = body;
  506. this.handlers = handlers;
  507. this.orelse = orelse;
  508. this.finalbody = finalbody;
  509. }
  510. });
  511. this.registerType('ast.ExceptHandler', class extends ast.excepthandler {
  512. constructor(type, name, body) {
  513. super();
  514. this.type_ = type;
  515. this.name = name;
  516. this.body = body;
  517. }
  518. });
  519. this.registerType('ast.ClassDef', class extends ast.stmt {
  520. constructor(name, bases, keywords, body, decorator_list, type_params) {
  521. super();
  522. this.name = name;
  523. this.bases = bases;
  524. this.keywords = keywords;
  525. this.body = body;
  526. this.decorator_list = decorator_list;
  527. this.type_params = type_params;
  528. }
  529. });
  530. this.registerType('ast.FunctionDef', class extends ast.stmt {
  531. constructor(name, args, body, decorator_list, returns, type_comment, type_params) {
  532. super();
  533. this.name = name;
  534. this.args = args;
  535. this.body = body;
  536. this.decorator_list = decorator_list;
  537. this.returns = returns;
  538. this.type_comment = type_comment;
  539. this.type_params = type_params;
  540. }
  541. });
  542. this.registerType('ast.arguments', class extends ast.AST {
  543. constructor(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults) {
  544. super();
  545. this.posonlyargs = posonlyargs;
  546. this.args = args;
  547. this.vararg = vararg;
  548. this.kwonlyargs = kwonlyargs;
  549. this.kw_defaults = kw_defaults;
  550. this.kwarg = kwarg;
  551. this.defaults = defaults;
  552. }
  553. });
  554. this.registerType('ast.arg', class extends ast.AST {
  555. constructor(arg, annotation, type_comment) {
  556. super();
  557. this.arg = arg;
  558. this.annotation = annotation;
  559. this.type_comment = type_comment;
  560. }
  561. });
  562. this.registerType('ast.Import', class extends ast.stmt {
  563. constructor(names) {
  564. super();
  565. this.names = names;
  566. }
  567. });
  568. this.registerType('ast.ImportFrom', class extends ast.stmt {
  569. constructor(module, names, level) {
  570. super();
  571. this.module = module;
  572. this.names = names;
  573. this.level = level;
  574. }
  575. });
  576. this.registerType('ast.Assert', class extends ast.stmt {
  577. constructor(test, msg) {
  578. super();
  579. this.test = test;
  580. this.msg = msg;
  581. }
  582. });
  583. this.registerType('ast.Raise', class extends ast.stmt {
  584. constructor(exc, cause) {
  585. super();
  586. this.exc = exc;
  587. this.cause = cause;
  588. }
  589. });
  590. this.registerType('ast.With', class extends ast.stmt {
  591. constructor(items, body, type_comment) {
  592. super();
  593. this.items = items;
  594. this.body = body;
  595. this.type_comment = type_comment;
  596. }
  597. });
  598. this.registerType('ast.withitem', class extends ast.AST {
  599. constructor(context_expr, optional_vars) {
  600. super();
  601. this.context_expr = context_expr;
  602. this.optional_vars = optional_vars;
  603. }
  604. });
  605. this.registerType('ast.Global', class extends ast.stmt {
  606. constructor(names) {
  607. super();
  608. this.names = names;
  609. }
  610. });
  611. this.registerType('ast.Nonlocal', class extends ast.stmt {
  612. constructor(names) {
  613. super();
  614. this.names = names;
  615. }
  616. });
  617. this.registerType('ast.Continue', class extends ast.stmt {});
  618. this.registerType('ast.Break', class extends ast.stmt {});
  619. this.registerType('ast.Pass', class extends ast.stmt {});
  620. this.registerType('ast.Await', class extends ast.stmt {
  621. constructor(value) {
  622. super();
  623. this.value = value;
  624. }
  625. });
  626. this.registerType('ast.Module', class extends ast.mod {
  627. constructor(body, type_ignores) {
  628. super();
  629. this.body = body;
  630. this.type_ignores = type_ignores;
  631. }
  632. });
  633. this.registerFunction('ast.parse', (source, filename, mode, debug) => {
  634. const parser = new ast._Parser();
  635. const module = parser.parse(source, filename, debug, mode);
  636. return module;
  637. });
  638. this.registerFunction('ast._convert_literal', (node) => {
  639. if (node instanceof ast.Constant) {
  640. return node.value;
  641. }
  642. if (node instanceof ast.Dict && node.keys.length === node.values.length) {
  643. const keys = node.keys.map((k) => ast._convert_literal(k));
  644. const values = node.values.map((v) => ast._convert_literal(v));
  645. return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  646. }
  647. if (node instanceof ast.Tuple) {
  648. return new builtins.tuple(node.elts.map((e) => ast._convert_literal(e)));
  649. }
  650. if (node instanceof ast.List) {
  651. return new builtins.list(node.elts.map((e) => ast._convert_literal(e)));
  652. }
  653. throw new python.Error(`'${node.__class__.__name__}' not implemented.`);
  654. });
  655. this.registerFunction('ast.literal_eval', (node_or_string) => {
  656. if (typeof node_or_string === 'string') {
  657. node_or_string = ast.parse(node_or_string, '', 'eval').body;
  658. } else {
  659. throw new python.Error(`'ast.literal_eval' node eval not implemented.`);
  660. }
  661. return ast._convert_literal(node_or_string);
  662. });
  663. this.registerType('ast._Parser', class {
  664. constructor() {
  665. ast._Parser._precedence = ast._Parser._precedence || {
  666. 'or': 2, 'and': 3, 'not' : 4,
  667. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  668. '|': 6, '^' : 7, '&' : 8,
  669. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  670. // '+': 12, '-': 12,
  671. '~': 13, '**': 14
  672. };
  673. }
  674. parse(text, file, debug, mode) {
  675. this._tokenizer = new ast._Tokenizer(text, file);
  676. this._debug = debug;
  677. const position = this._position();
  678. let body = [];
  679. while (!this._tokenizer.match('eof')) {
  680. const statement = this._parseStatement();
  681. if (statement) {
  682. body.push(statement);
  683. continue;
  684. }
  685. if (this._tokenizer.accept('\n') || this._tokenizer.accept(';') || this._tokenizer.peek().type === 'eof') {
  686. continue;
  687. }
  688. if (this._tokenizer.accept('indent') && this._tokenizer.peek().type === 'eof') {
  689. continue;
  690. }
  691. throw new python.Error(`Unsupported statement ${this._location()}`);
  692. }
  693. if (mode === 'eval') {
  694. if (body.length !== 1 || body[0] instanceof ast.Expr === false) {
  695. throw new python.Error('Expected expression.');
  696. }
  697. body = body[0].value;
  698. }
  699. const module = new ast.Module(body);
  700. this._mark(module, position);
  701. return module;
  702. }
  703. _parseSuite() {
  704. const body = [];
  705. let statement = null;
  706. if (this._tokenizer.accept('\n')) {
  707. if (this._tokenizer.accept('indent')) {
  708. while (!this._tokenizer.accept('eof') && !this._tokenizer.accept('dedent')) {
  709. if (this._tokenizer.accept(';')) {
  710. continue;
  711. }
  712. statement = this._parseStatement();
  713. if (statement) {
  714. body.push(statement);
  715. continue;
  716. }
  717. if (this._tokenizer.accept('\n')) {
  718. continue;
  719. }
  720. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  721. continue;
  722. }
  723. throw new python.Error(`Empty statement ${this._location()}`);
  724. }
  725. }
  726. } else if (!this._tokenizer.accept('eof')) {
  727. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  728. if (this._tokenizer.accept(';')) {
  729. continue;
  730. }
  731. statement = this._parseStatement();
  732. if (statement) {
  733. body.push(statement);
  734. continue;
  735. }
  736. throw new python.Error(`Empty statement ${this._location()}`);
  737. }
  738. this._tokenizer.accept('\n');
  739. }
  740. return body;
  741. }
  742. _parseStatement() {
  743. let node = null;
  744. let position = this._position();
  745. if (this._eat('id', 'break')) {
  746. const node = new ast.Break();
  747. return this._mark(node, position);
  748. }
  749. if (this._eat('id', 'continue')) {
  750. const node = new ast.Continue();
  751. return this._mark(node, position);
  752. }
  753. if (this._eat('id', 'return')) {
  754. const value = this._parseExpression(-1, [], true);
  755. const node = new ast.Return(value);
  756. return this._mark(node, position);
  757. }
  758. if (this._eat('id', 'raise')) {
  759. let exc = this._parseExpression(-1, ['from']);
  760. let cause = null;
  761. if (this._tokenizer.accept('id', 'from')) {
  762. cause = this._parseExpression();
  763. } else if (this._tokenizer.accept(',')) {
  764. exc = [exc];
  765. exc.push(this._parseExpression());
  766. if (this._tokenizer.accept(',')) {
  767. exc.push(this._parseExpression());
  768. }
  769. }
  770. node = new ast.Raise(exc, cause);
  771. return this._mark(node, position);
  772. }
  773. if (this._eat('id', 'assert')) {
  774. const test = this._parseExpression(-1, [',']);
  775. let msg = null;
  776. if (this._tokenizer.accept(',')) {
  777. msg = this._parseExpression();
  778. }
  779. node = new ast.Assert(test, msg);
  780. return this._mark(node, position);
  781. }
  782. if (this._eat('id', 'global')) {
  783. const names = [];
  784. do {
  785. const name = this._parseName(true);
  786. names.push(name.id);
  787. }
  788. while (this._tokenizer.accept(','));
  789. const node = new ast.Global(names);
  790. return this._mark(node, position);
  791. }
  792. if (this._eat('id', 'nonlocal')) {
  793. const names = [];
  794. do {
  795. const name = this._parseName(true);
  796. names.push(name.id);
  797. }
  798. while (this._tokenizer.accept(','));
  799. const node = new ast.Nonlocal(names);
  800. return this._mark(node, position);
  801. }
  802. if (this._eat('id', 'import')) {
  803. const names = [];
  804. do {
  805. const name = this._parseDottedName();
  806. let asname = null;
  807. if (this._tokenizer.accept('id', 'as')) {
  808. asname = this._parseName(true).id;
  809. }
  810. const node = new ast.alias(name, asname);
  811. names.push(node);
  812. }
  813. while (this._tokenizer.accept(','));
  814. const node = new ast.Import(names);
  815. return this._mark(node, position);
  816. }
  817. if (this._eat('id', 'from')) {
  818. let level = 0;
  819. const dots = this._tokenizer.peek();
  820. if (dots && Array.from(dots.type).every((c) => c === '.')) {
  821. this._eat(dots.type);
  822. level = Array.from(dots.type).length;
  823. }
  824. const module = this._parseDottedName();
  825. this._tokenizer.expect('id', 'import');
  826. const names = [];
  827. const close = this._tokenizer.accept('(');
  828. do {
  829. const name = this._parseName(true).id;
  830. let asname = null;
  831. if (this._tokenizer.accept('id', 'as')) {
  832. asname = this._parseName(true).id;
  833. }
  834. const node = new ast.alias(name, asname);
  835. names.push(node);
  836. }
  837. while (this._tokenizer.accept(','));
  838. if (close) {
  839. this._tokenizer.expect(')');
  840. }
  841. const node = new ast.ImportFrom(module, names, level);
  842. return this._mark(node, position);
  843. }
  844. const decorator_list = this._decorator();
  845. position = this._position();
  846. if (this._eat('id', 'class')) {
  847. const name = this._parseName(true);
  848. const bases = [];
  849. if (this._tokenizer.accept('(')) {
  850. while (!this._tokenizer.accept(')')) {
  851. if (this._tokenizer.accept('\n')) {
  852. continue;
  853. }
  854. const expression = this._parseExpression(-1, [], false);
  855. if (expression === null) {
  856. throw new python.Error(`Expected expression ${this._location()}`);
  857. }
  858. bases.push(expression);
  859. if (!this._tokenizer.accept(',')) {
  860. this._tokenizer.accept('\n');
  861. this._tokenizer.expect(')');
  862. break;
  863. }
  864. }
  865. }
  866. this._tokenizer.expect(':');
  867. const body = this._parseSuite();
  868. const node = new ast.ClassDef(name.id, bases, null, body, decorator_list, null);
  869. return this._mark(node, position);
  870. }
  871. const async = this._eat('id', 'async') !== null;
  872. if (async &&
  873. !this._tokenizer.match('id', 'def') &&
  874. !this._tokenizer.match('id', 'with') &&
  875. !this._tokenizer.match('id', 'for')) {
  876. throw new python.Error(`Expected 'def', 'with' or 'for' ${this._location()}`);
  877. }
  878. if (this._eat('id', 'def')) {
  879. const name = this._parseName(true);
  880. this._tokenizer.expect('(');
  881. const args = this._parseArguments(')');
  882. let returns = null;
  883. if (this._tokenizer.accept('->')) {
  884. returns = this._parseType();
  885. }
  886. this._tokenizer.expect(':');
  887. const body = this._parseSuite();
  888. const node = new ast.FunctionDef(name.id, args, body, decorator_list, returns, null, null);
  889. if (async) {
  890. node.async = async;
  891. }
  892. return this._mark(node, position);
  893. }
  894. if (decorator_list && decorator_list.length > 0) {
  895. throw new python.Error('Unexpected decorator.');
  896. }
  897. if (this._eat('id', 'del')) {
  898. const targets = this._parseExpression(-1, [], true);
  899. node = new ast.Del(targets);
  900. return this._mark(node, position);
  901. }
  902. if (this._eat('id', 'if')) {
  903. const test = this._parseExpression();
  904. this._tokenizer.expect(':');
  905. const body = this._parseSuite();
  906. const node = new ast.If(test, body);
  907. let current = node;
  908. this._tokenizer.accept('\n');
  909. while (this._tokenizer.accept('id', 'elif')) {
  910. const test = this._parseExpression();
  911. this._tokenizer.expect(':');
  912. const body = this._parseSuite();
  913. current.orelse = new ast.If(test, body);
  914. current = current.orelse;
  915. this._tokenizer.accept('\n');
  916. }
  917. if (this._tokenizer.accept('id', 'else')) {
  918. this._tokenizer.expect(':');
  919. current.orelse = this._parseSuite();
  920. }
  921. return this._mark(node, position);
  922. }
  923. if (this._eat('id', 'while')) {
  924. const test = this._parseExpression();
  925. this._tokenizer.expect(':');
  926. const body = this._parseSuite();
  927. let orelse = null;
  928. if (this._tokenizer.accept('id', 'else')) {
  929. this._tokenizer.expect(':');
  930. orelse = this._parseSuite();
  931. }
  932. const node = new ast.While(test, body, orelse);
  933. return this._mark(node, position);
  934. }
  935. if (this._eat('id', 'pass')) {
  936. const node = new ast.Pass();
  937. return this._mark(node, position);
  938. }
  939. if (this._eat('id', 'for')) {
  940. let target = this._parseExpression(-1, ['in']);
  941. while (this._tokenizer.accept(',')) {
  942. if (target instanceof ast.Tuple === false) {
  943. target = new ast.Tuple([target]);
  944. }
  945. if (this._tokenizer.match('id', 'in')) {
  946. target.elts.push({});
  947. break;
  948. }
  949. target.elts.push(this._parseExpression(-1, ['in']));
  950. }
  951. this._tokenizer.expect('id', 'in');
  952. let iter = this._parseExpression();
  953. while (this._tokenizer.accept(',')) {
  954. if (iter.type !== 'tuple') {
  955. iter = new ast.Tuple([iter]);
  956. }
  957. if (this._tokenizer.match(':')) {
  958. iter.elts.push({});
  959. break;
  960. }
  961. iter.elts.push(this._parseExpression(-1, ['in']));
  962. }
  963. this._tokenizer.expect(':');
  964. const body = this._parseSuite();
  965. let orelse = null;
  966. if (this._tokenizer.accept('id', 'else')) {
  967. this._tokenizer.expect(':');
  968. orelse = this._parseSuite();
  969. }
  970. const node = new ast.For(target, iter, body, orelse);
  971. return this._mark(node, position);
  972. }
  973. if (this._eat('id', 'with')) {
  974. const items = [];
  975. do {
  976. const context_expr = this._parseExpression();
  977. let optional_vars = null;
  978. if (this._tokenizer.accept('id', 'as')) {
  979. optional_vars = this._parseExpression();
  980. }
  981. const node = new ast.withitem(context_expr, optional_vars);
  982. items.push(node);
  983. }
  984. while (this._tokenizer.accept(','));
  985. this._tokenizer.expect(':');
  986. const body = this._parseSuite();
  987. const node = new ast.With(items, body, null);
  988. if (async) {
  989. node.async = async;
  990. }
  991. return this._mark(node, position);
  992. }
  993. if (this._eat('id', 'try')) {
  994. this._tokenizer.expect(':');
  995. const body = this._parseSuite();
  996. const handlers = [];
  997. let orelse = null;
  998. let finalbody = null;
  999. while (this._tokenizer.match('id', 'except')) {
  1000. this._tokenizer.expect('id', 'except');
  1001. const type = this._parseExpression();
  1002. const name = this._tokenizer.accept('id', 'as') ? this._parseExpression() : null;
  1003. this._tokenizer.expect(':');
  1004. const body = this._parseSuite();
  1005. const except = new ast.ExceptHandler(type, name, body);
  1006. handlers.push(except);
  1007. }
  1008. if (this._tokenizer.match('id', 'else')) {
  1009. this._tokenizer.expect('id', 'else');
  1010. this._tokenizer.expect(':');
  1011. orelse = this._parseSuite();
  1012. }
  1013. if (this._tokenizer.match('id', 'finally')) {
  1014. this._tokenizer.expect('id', 'finally');
  1015. this._tokenizer.expect(':');
  1016. finalbody = this._parseSuite();
  1017. }
  1018. const node = new ast.Try(body, handlers, orelse, finalbody);
  1019. return this._mark(node, position);
  1020. }
  1021. const expr = this._parseExpression(-1, [], true);
  1022. if (expr) {
  1023. if (expr instanceof ast.Name && this._tokenizer.accept(':')) {
  1024. const position = this._position();
  1025. const annotation = this._parseExpression(-1, ['=']);
  1026. let value = null;
  1027. if (this._tokenizer.accept('=')) {
  1028. value = this._parseExpression();
  1029. }
  1030. node = new ast.AnnAssign(expr, annotation, value, expr instanceof ast.Name);
  1031. return this._mark(node, position);
  1032. }
  1033. if (expr instanceof ast.stmt) {
  1034. return expr;
  1035. }
  1036. switch (expr.__class__.__name__) {
  1037. case 'AnnAssign':
  1038. case 'Assert':
  1039. case 'Assign':
  1040. case 'Attribute':
  1041. case 'AugAssign':
  1042. case 'Await':
  1043. case 'BinOp':
  1044. case 'Call':
  1045. case 'Compare':
  1046. case 'Constant':
  1047. case 'Dict':
  1048. case 'Ellipsis':
  1049. case 'For':
  1050. case 'If':
  1051. case 'Lambda':
  1052. case 'List':
  1053. case 'Name':
  1054. case 'NamedExpr':
  1055. case 'Raise':
  1056. case 'Subscript':
  1057. case 'Tuple':
  1058. case 'Yield':
  1059. // return expr;
  1060. return new ast.Expr(expr);
  1061. default:
  1062. throw new python.Error(`Unhandled expression ${this._location()}`);
  1063. }
  1064. }
  1065. return null;
  1066. }
  1067. _parseExpression(minPrecedence, terminal, tuple) {
  1068. minPrecedence = minPrecedence || -1;
  1069. const terminalSet = new Set(terminal);
  1070. const stack = [];
  1071. for (;;) {
  1072. let position = this._position();
  1073. let node = null;
  1074. const token = this._tokenizer.peek();
  1075. if (stack.length === 1 && terminalSet.has(token.value)) {
  1076. break;
  1077. }
  1078. const precedence = ast._Parser._precedence[token.value];
  1079. if (precedence) {
  1080. if (precedence >= minPrecedence) {
  1081. this._tokenizer.read();
  1082. if (token.value === 'not' && this._tokenizer.accept('id', 'in')) {
  1083. token.value = 'not in';
  1084. } else if (token.value === 'is' && this._tokenizer.accept('id', 'not')) {
  1085. token.value = 'is not';
  1086. }
  1087. if (stack.length > 0) {
  1088. let op = null;
  1089. switch (token.value) {
  1090. case '+': op = new ast.Add(); break;
  1091. case '-': op = new ast.Sub(); break;
  1092. case '*': op = new ast.Mult(); break;
  1093. case '/': op = new ast.Div(); break;
  1094. case '//': op = new ast.FloorDiv(); break;
  1095. case '**': op = new ast.Pow(); break;
  1096. case '@': op = new ast.MatMult(); break;
  1097. case '&': op = new ast.BitAnd(); break;
  1098. case '^': op = new ast.BitXor(); break;
  1099. case '|': op = new ast.BitOr(); break;
  1100. case '%': op = new ast.Mod(); break;
  1101. case '>>': op = new ast.RShift(); break;
  1102. case '<<': op = new ast.LShift(); break;
  1103. default: break;
  1104. }
  1105. if (op) {
  1106. const left = stack.pop();
  1107. const right = this._parseExpression(precedence, terminal, tuple === true);
  1108. node = new ast.BinOp(left, op, right);
  1109. } else {
  1110. switch (token.value) {
  1111. case '==': op = new ast.Eq(); break;
  1112. case '!=': op = new ast.NotEq(); break;
  1113. case '>=': op = new ast.GtE(); break;
  1114. case '<=': op = new ast.LtE(); break;
  1115. case '<': op = new ast.Lt(); break;
  1116. case '>': op = new ast.Gt(); break;
  1117. case 'is': op = new ast.Is(); break;
  1118. case 'is not': op = new ast.IsNot(); break;
  1119. case 'in': op = new ast.In(); break;
  1120. case 'not in': op = new ast.NotIn(); break;
  1121. default: break;
  1122. }
  1123. const left = stack.pop();
  1124. const comparator = this._parseExpression(precedence, ['for', 'if'], tuple === true);
  1125. node = new ast.Compare(left, [op], [comparator]);
  1126. }
  1127. } else if (token.value === '*') {
  1128. const value = this._parseExpression(precedence, terminal, tuple === true);
  1129. node = new ast.Starred(value);
  1130. } else if (token.value === '**') {
  1131. const value = this._parseExpression(precedence, terminal, tuple === true);
  1132. node = new ast.keyword(null, value);
  1133. } else {
  1134. let op = null;
  1135. switch (token.value) {
  1136. case '-': op = new ast.USub(); break;
  1137. case '+': op = new ast.UAdd(); break;
  1138. case '~': op = new ast.Invert(); break;
  1139. case 'not': op = new ast.Not(); break;
  1140. default: throw new python.Error(`Unsupported unary operator ${token.value} ${this._location()}`);
  1141. }
  1142. const operand = this._parseExpression(precedence, terminal, tuple === true);
  1143. node = new ast.UnaryOp(op, operand);
  1144. node = this._mark(node, position);
  1145. }
  1146. stack.push(node);
  1147. continue;
  1148. }
  1149. }
  1150. if (this._tokenizer.accept(':=')) {
  1151. const target = stack.pop();
  1152. const value = this._parseExpression(-1, terminal, tuple !== false);
  1153. const node = new ast.NamedExpr(target, value);
  1154. this._mark(node, position);
  1155. stack.push(node);
  1156. continue;
  1157. }
  1158. if (this._tokenizer.accept('=')) {
  1159. const position = this._position();
  1160. const targets = stack.pop();
  1161. const value = this._parseExpression(-1, terminal, tuple !== false);
  1162. const node = new ast.Assign([targets], value);
  1163. this._mark(node, position);
  1164. stack.push(node);
  1165. continue;
  1166. }
  1167. let op = null;
  1168. switch (token.type) {
  1169. case '+=': op = new ast.Add(); break;
  1170. case '-=': op = new ast.Sub(); break;
  1171. case '**=': op = new ast.Pow(); break;
  1172. case '*=': op = new ast.Mult(); break;
  1173. case '//=': op = new ast.FloorDiv(); break;
  1174. case '/=': op = new ast.Div(); break;
  1175. case '&=': op = new ast.BitAnd(); break;
  1176. case '%=': op = new ast.Mod(); break;
  1177. case '^=': op = new ast.BitXor(); break;
  1178. case '<<=': op = new ast.LShift(); break;
  1179. case '>>=': op = new ast.RShift(); break;
  1180. case '|=': op = new ast.BitOr(); break;
  1181. case '@=': op = new ast.MatMul(); break;
  1182. default: break;
  1183. }
  1184. if (op) {
  1185. this._tokenizer.expect(token.type);
  1186. const target = stack.pop();
  1187. const value = this._parseExpression(-1, terminal, true);
  1188. const node = new ast.AugAssign(target, op, value);
  1189. stack.push(node);
  1190. continue;
  1191. }
  1192. position = this._position();
  1193. if (this._eat('id', 'if')) {
  1194. const body = stack.pop();
  1195. const test = this._parseExpression();
  1196. this._tokenizer.expect('id', 'else');
  1197. const orelse = this._parseExpression();
  1198. const node = new ast.IfExp(test, body, orelse);
  1199. this._mark(node, position);
  1200. stack.push(node);
  1201. continue;
  1202. }
  1203. if (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1204. const position = this._position();
  1205. const elt = stack.pop();
  1206. const generators = this._parseGenerators();
  1207. let node = null;
  1208. if (elt instanceof ast.Dict) {
  1209. if (elt.keys.length !== 1 || elt.values.length !== 1) {
  1210. throw new python.Error(`Invalid dict comprehension ${this._location()}`);
  1211. }
  1212. node = new ast.DictComp(elt.keys[0], elt.values[0], generators);
  1213. } else if (elt instanceof ast.Set) {
  1214. if (elt.elts.length !== 1) {
  1215. throw new python.Error(`Invalid set comprehension ${this._location()}`);
  1216. }
  1217. node = new ast.SetComp(elt.elts[0], generators);
  1218. } else {
  1219. node = new ast.GeneratorExp(elt, generators);
  1220. }
  1221. this._mark(node, position);
  1222. stack.push(node);
  1223. continue;
  1224. }
  1225. if (this._eat('id', 'lambda')) {
  1226. const args = this._parseArguments(':');
  1227. const body = this._parseExpression(-1, terminal, false);
  1228. const node = new ast.Lambda(args, body);
  1229. this._mark(node, position);
  1230. stack.push(node);
  1231. continue;
  1232. }
  1233. if (this._eat('id', 'yield')) {
  1234. if (this._tokenizer.accept('id', 'from')) {
  1235. const value = this._parseExpression(-1, [], true);
  1236. node = new ast.YieldFrom(value);
  1237. stack.push(node);
  1238. } else {
  1239. const value = [];
  1240. do {
  1241. value.push(this._parseExpression(-1, [], false));
  1242. }
  1243. while (this._tokenizer.accept(','));
  1244. node = new ast.Yield(value);
  1245. stack.push(node);
  1246. }
  1247. continue;
  1248. }
  1249. if (this._eat('id', 'await')) {
  1250. const value = this._parseExpression(minPrecedence, terminal, tuple);
  1251. const node = new ast.Await(value);
  1252. this._mark(node, position);
  1253. stack.push(node);
  1254. continue;
  1255. }
  1256. if (this._eat('.')) {
  1257. const value = stack.pop();
  1258. const attr = this._parseName().id;
  1259. const node = new ast.Attribute(value, attr);
  1260. this._mark(node, position);
  1261. stack.push(node);
  1262. continue;
  1263. }
  1264. if (this._tokenizer.peek().type === '(') {
  1265. const position = this._position();
  1266. const args = [];
  1267. const keywords = [];
  1268. this._tokenizer.expect('(');
  1269. let tuple = false;
  1270. while (!this._tokenizer.accept(')')) {
  1271. if (this._tokenizer.accept('\n')) {
  1272. continue;
  1273. }
  1274. const position = this._position();
  1275. const expr = this._parseExpression(-1, [], false);
  1276. if (expr === null) {
  1277. throw new python.Error(`Expected expression ${this._location()}`);
  1278. }
  1279. if (expr instanceof ast.Assign && expr.targets.length === 1) {
  1280. const [target] = expr.targets;
  1281. if (target instanceof ast.Name === false) {
  1282. throw new python.Error(`Expected name ${this._location()}`);
  1283. }
  1284. const node = new ast.keyword(target.id, expr.value);
  1285. this._mark(node, position);
  1286. keywords.push(node);
  1287. } else {
  1288. args.push(expr);
  1289. }
  1290. if (this._tokenizer.accept(',')) {
  1291. tuple = true;
  1292. } else {
  1293. this._tokenizer.accept('\n');
  1294. this._tokenizer.expect(')');
  1295. break;
  1296. }
  1297. }
  1298. if (stack.length === 0 && keywords.length === 0) {
  1299. node = args.length === 1 && !tuple ? args[0] : new ast.Tuple(args);
  1300. this._mark(node, position);
  1301. } else {
  1302. const func = stack.pop();
  1303. node = new ast.Call(func, args, keywords);
  1304. let start = func;
  1305. while (start instanceof ast.Attribute) {
  1306. start = start.value;
  1307. }
  1308. position.lineno = start.lineno;
  1309. position.col_offset = start.col_offset;
  1310. this._mark(node, position);
  1311. }
  1312. stack.push(node);
  1313. continue;
  1314. }
  1315. if (this._tokenizer.peek().type === '[') {
  1316. if (stack.length === 0) {
  1317. stack.push(this._parseList());
  1318. } else {
  1319. const value = stack.pop();
  1320. const position = this._position();
  1321. const slice = this._parseSlice();
  1322. node = new ast.Subscript(value, slice);
  1323. this._mark(node, position);
  1324. stack.push(node);
  1325. }
  1326. continue;
  1327. }
  1328. if (this._tokenizer.peek().type === '{') {
  1329. const elts = [];
  1330. const keys = [];
  1331. const values = [];
  1332. this._tokenizer.expect('{');
  1333. let dict = true;
  1334. while (!this._tokenizer.accept('}')) {
  1335. const item = this._parseExpression(-1, [], false);
  1336. if (item === null) {
  1337. throw new python.Error(`Expected expression ${this._location()}`);
  1338. }
  1339. if (!this._tokenizer.accept(':')) {
  1340. dict = false;
  1341. }
  1342. if (dict) {
  1343. const value = this._parseExpression(-1, ['for'], false);
  1344. if (value === null) {
  1345. throw new python.Error(`Expected expression ${this._location()}`);
  1346. }
  1347. if (this._eat('id', 'for')) {
  1348. if (keys.length > 0 || values.length > 0 || elts.length > 0) {
  1349. throw new python.Error(`Invalid list expression ${this._location()}`);
  1350. }
  1351. const target = this._parseExpression(-1, ['in'], true);
  1352. this._tokenizer.expect('id', 'in');
  1353. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1354. const ifs = [];
  1355. while (this._tokenizer.accept('id', 'if')) {
  1356. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1357. }
  1358. const comprehension = new ast.comprehension(target, iter, ifs /*, async */);
  1359. const generators = [comprehension];
  1360. this._tokenizer.expect('}');
  1361. return new ast.DictComp(item, value, generators);
  1362. }
  1363. keys.push(item);
  1364. values.push(value);
  1365. } else {
  1366. elts.push(item);
  1367. }
  1368. this._tokenizer.accept(',');
  1369. this._tokenizer.accept('\n');
  1370. if (this._tokenizer.accept('}')) {
  1371. break;
  1372. }
  1373. }
  1374. if (keys.length !== values.length || (keys.length > 0 && elts.length > 0)) {
  1375. throw new python.Error(`Invalid set expression ${this._location()}`);
  1376. }
  1377. const node = elts.length > 0 ? new ast.Set(elts) : new ast.Dict(keys, values);
  1378. stack.push(node);
  1379. continue;
  1380. }
  1381. const literal = this._parseLiteral();
  1382. if (literal) {
  1383. if (stack.length === 1 && literal.type === 'str' && stack[0] instanceof ast.Constant && typeof stack[0].value === 'string') {
  1384. stack[0].value += literal.value.substring(1, literal.value.length - 1);
  1385. } else {
  1386. let value = literal.value;
  1387. switch (literal.type) {
  1388. case 'int':
  1389. case 'float':
  1390. value = value === 'inf' ? Infinity : Number(value);
  1391. break;
  1392. case 'complex':
  1393. value = new builtins.complex(0, Number(value.slice(0, -1)));
  1394. break;
  1395. case 'str':
  1396. value = value.substring(1, value.length - 1);
  1397. break;
  1398. default:
  1399. throw new python.Error(`Invalid literal type '${literal.type}' ${this._location()}`);
  1400. }
  1401. const node = new ast.Constant(value, literal.type);
  1402. this._mark(node, position);
  1403. stack.push(node);
  1404. }
  1405. continue;
  1406. }
  1407. if (this._eat('id', 'False')) {
  1408. const node = new ast.Constant(false, 'bool');
  1409. this._mark(node, position);
  1410. stack.push(node);
  1411. continue;
  1412. }
  1413. if (this._eat('id', 'True')) {
  1414. const node = new ast.Constant(true, 'bool');
  1415. this._mark(node, position);
  1416. stack.push(node);
  1417. continue;
  1418. }
  1419. if (this._eat('id', 'None')) {
  1420. const node = new ast.Constant(null);
  1421. this._mark(node, position);
  1422. stack.push(node);
  1423. continue;
  1424. }
  1425. if (this._tokenizer.peek().keyword) {
  1426. break;
  1427. }
  1428. if (this._eat('...')) {
  1429. const node = new ast.Ellipsis();
  1430. this._mark(node, position);
  1431. stack.push(node);
  1432. continue;
  1433. }
  1434. const name = this._parseName();
  1435. if (name) {
  1436. stack.push(name);
  1437. continue;
  1438. }
  1439. if (tuple === true && stack.length === 1 && this._tokenizer.accept(',')) {
  1440. if (stack[0] instanceof ast.Tuple) {
  1441. [node] = stack;
  1442. } else {
  1443. const position = this._position();
  1444. const elts = [stack.pop()];
  1445. node = new ast.Tuple(elts);
  1446. this._mark(node, position);
  1447. stack.push(node);
  1448. }
  1449. // for, bar, = <expr>
  1450. if (this._tokenizer.peek().type === '=') {
  1451. continue;
  1452. }
  1453. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  1454. const nextTerminal = terminal.slice(0).concat([',', '=']);
  1455. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  1456. if (expression) {
  1457. node.elts.push(expression);
  1458. continue;
  1459. }
  1460. }
  1461. break;
  1462. }
  1463. break;
  1464. }
  1465. if (stack.length === 1) {
  1466. return stack.pop();
  1467. }
  1468. if (stack.length !== 0) {
  1469. throw new python.Error(`Unexpected expression ${this._location()}`);
  1470. }
  1471. return null;
  1472. }
  1473. _decorator() {
  1474. const list = [];
  1475. while (this._tokenizer.accept('@')) {
  1476. const value = this._parseExpression();
  1477. if (!value || (value instanceof ast.Call === false && value instanceof ast.Name === false && value instanceof ast.Attribute === false)) {
  1478. throw new python.Error(`Invalid decorator ${this._location()}`);
  1479. }
  1480. this._tokenizer.accept('\n');
  1481. list.push(value);
  1482. }
  1483. return list;
  1484. }
  1485. _parseGenerators() {
  1486. const generators = [];
  1487. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  1488. const is_async = this._eat('id', 'async') ? 1 : 0;
  1489. this._tokenizer.expect('id', 'for');
  1490. const target = this._parseExpression(-1, ['in'], true);
  1491. this._tokenizer.expect('id', 'in');
  1492. const iter = this._parseExpression(-1, ['for', 'if'], true);
  1493. const ifs = [];
  1494. while (this._tokenizer.accept('id', 'if')) {
  1495. ifs.push(this._parseExpression(-1, ['for', 'if']));
  1496. }
  1497. const comprehension = new ast.comprehension(target, iter, ifs, is_async);
  1498. generators.push(comprehension);
  1499. }
  1500. return generators;
  1501. }
  1502. _parseList() {
  1503. const elts = [];
  1504. this._tokenizer.expect('[');
  1505. if (!this._tokenizer.match(']')) {
  1506. const position = this._position();
  1507. const expr = this._parseExpression(-1, ['for']);
  1508. if (this._tokenizer.match('id', 'for')) {
  1509. const generators = this._parseGenerators();
  1510. this._tokenizer.expect(']');
  1511. const node = new ast.ListComp(expr, generators);
  1512. this._mark(node, position);
  1513. return node;
  1514. }
  1515. if (expr === null) {
  1516. throw new python.Error(`Expected expression ${this._location()}`);
  1517. }
  1518. elts.push(expr);
  1519. while (this._tokenizer.accept(',')) {
  1520. if (this._tokenizer.match(']')) {
  1521. break;
  1522. }
  1523. const expr = this._parseExpression(-1, ['for']);
  1524. if (!expr) {
  1525. throw new python.Error(`Expected expression ${this._location()}`);
  1526. }
  1527. elts.push(expr);
  1528. }
  1529. }
  1530. this._tokenizer.expect(']');
  1531. return new ast.List(elts);
  1532. }
  1533. _parseSlice() {
  1534. const elts = [];
  1535. let slice = [null, null, null];
  1536. let index = 0;
  1537. let valid = false;
  1538. this._tokenizer.expect('[');
  1539. while (true) {
  1540. if (this._tokenizer.accept(':')) {
  1541. index++;
  1542. valid = true;
  1543. } else if (index > 2 || this._tokenizer.match(',') || this._tokenizer.match(']')) {
  1544. if (!valid || index > 2) {
  1545. throw new python.Error(`Invalid slice at ${this._location()}`);
  1546. }
  1547. elts.push(index === 0 ? slice[0] : new ast.Slice(slice[0], slice[1], slice[2]));
  1548. slice = [null, null, null];
  1549. index = 0;
  1550. if (this._tokenizer.accept(']')) {
  1551. break;
  1552. }
  1553. this._tokenizer.expect(',');
  1554. } else {
  1555. const expression = this._parseExpression();
  1556. if (expression === null) {
  1557. throw new python.Error(`Expected expression ${this._location()}`);
  1558. }
  1559. slice[index] = expression;
  1560. valid = true;
  1561. }
  1562. }
  1563. if (elts.length > 1) {
  1564. return new ast.Tuple(elts);
  1565. }
  1566. return elts[0];
  1567. }
  1568. _parseName(required) {
  1569. const token = this._tokenizer.peek();
  1570. if (token.type === 'id' && !token.keyword) {
  1571. const position = this._position();
  1572. this._tokenizer.read();
  1573. const node = new ast.Name(token.value);
  1574. return this._mark(node, position);
  1575. }
  1576. if (required) {
  1577. throw new python.Error(`Invalid syntax ${this._location()}`);
  1578. }
  1579. return null;
  1580. }
  1581. _parseDottedName() {
  1582. const list = [];
  1583. do {
  1584. const name = this._parseName(true);
  1585. list.push(name.id);
  1586. }
  1587. while (this._tokenizer.accept('.'));
  1588. return list.join('.');
  1589. }
  1590. _parseLiteral() {
  1591. const token = this._tokenizer.peek();
  1592. if (token.type === 'str' || token.type === 'bool' || token.type === 'int' || token.type === 'float' || token.type === 'complex') {
  1593. this._tokenizer.read();
  1594. return token;
  1595. }
  1596. return null;
  1597. }
  1598. _parseTypeArguments() {
  1599. const list = [];
  1600. this._tokenizer.expect('[');
  1601. while (!this._tokenizer.accept(']')) {
  1602. const type = this._parseType();
  1603. if (type === null) {
  1604. throw new python.Error(`Expected type ${this._location()}`);
  1605. }
  1606. list.push(type);
  1607. if (!this._tokenizer.accept(',')) {
  1608. this._tokenizer.expect(']');
  1609. break;
  1610. }
  1611. }
  1612. return list;
  1613. }
  1614. _parseType() {
  1615. const target = this._parseExpression(-1, ['[', '=']);
  1616. if (target) {
  1617. if (this._tokenizer.peek().value === '[') {
  1618. const list = this._parseList();
  1619. const slice = list.elts.length === 1 ? list.elts[0] : new ast.Tuple(list.elts);
  1620. return new ast.Subscript(target, slice);
  1621. }
  1622. return target;
  1623. }
  1624. return null;
  1625. }
  1626. _parseArguments(terminal) {
  1627. let posonlyargs = [];
  1628. let args = [];
  1629. let vararg = null;
  1630. const kwonlyargs = [];
  1631. const kw_defaults = [];
  1632. let kwarg = null;
  1633. const defaults = [];
  1634. let is_slash = false;
  1635. let is_vararg = false; // '*'
  1636. let is_kwarg = false; // '**'
  1637. const read = (required) => {
  1638. const name = this._parseName(required);
  1639. if (name) {
  1640. const annotation = terminal !== ':' && this._tokenizer.accept(':') ? this._parseType() : null;
  1641. return new ast.arg(name.id, annotation, null);
  1642. }
  1643. return null;
  1644. };
  1645. while (!this._tokenizer.accept(terminal)) {
  1646. this._tokenizer.accept('\n');
  1647. if (this._tokenizer.accept('/')) {
  1648. if (is_slash || is_vararg || is_kwarg) {
  1649. throw new python.Error(`Invalid '/' in arguments ${this._location()}`);
  1650. }
  1651. is_slash = true;
  1652. } else if (this._tokenizer.accept('*')) {
  1653. if (is_vararg) {
  1654. throw new python.Error(`Multiple '*' arguments ${this._location()}`);
  1655. }
  1656. is_vararg = true;
  1657. const arg = read(false);
  1658. vararg = arg ? arg : vararg;
  1659. } else if (this._tokenizer.accept('**')) {
  1660. if (is_kwarg) {
  1661. throw new python.Error(`Multiple '**' arguments ${this._location()}`);
  1662. }
  1663. is_kwarg = true;
  1664. kwarg = read(true);
  1665. } else {
  1666. const arg = read(false);
  1667. if (!arg) {
  1668. this._tokenizer.expect(terminal);
  1669. break;
  1670. }
  1671. const default_value = this._tokenizer.accept('=') ? this._parseExpression() : null;
  1672. if (!is_vararg && !is_kwarg) {
  1673. if (is_slash) {
  1674. args.push(arg);
  1675. } else {
  1676. posonlyargs.push(arg);
  1677. }
  1678. if (default_value !== null) {
  1679. defaults.push(default_value);
  1680. }
  1681. } else if (is_vararg && !is_kwarg) {
  1682. kwonlyargs.push(arg);
  1683. kw_defaults.push(default_value);
  1684. } else {
  1685. throw new python.Error(`Argument after '**' parameter ${this._location()}`);
  1686. }
  1687. }
  1688. this._tokenizer.accept('\n');
  1689. if (!this._tokenizer.accept(',')) {
  1690. this._tokenizer.expect(terminal);
  1691. break;
  1692. }
  1693. }
  1694. if (!is_slash) {
  1695. args = posonlyargs.concat(args);
  1696. posonlyargs = [];
  1697. }
  1698. return new ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults);
  1699. }
  1700. _eat(type, value) {
  1701. if (this._tokenizer.match(type, value)) {
  1702. const position = this._position();
  1703. this._tokenizer.expect(type, value);
  1704. return position;
  1705. }
  1706. return null;
  1707. }
  1708. _mark(node, position) {
  1709. node.filename = position.filename;
  1710. node.lineno = position.lineno;
  1711. node.col_offset = position.col_offset;
  1712. node.end_lineno = this._tokenizer.lineno;
  1713. node.end_col_offset = this._tokenizer.col_offset;
  1714. return node;
  1715. }
  1716. _position() {
  1717. return {
  1718. filename: this._tokenizer.filename,
  1719. lineno: this._tokenizer.lineno,
  1720. col_offset: this._tokenizer.col_offset
  1721. };
  1722. }
  1723. _location() {
  1724. return this._tokenizer.location();
  1725. }
  1726. });
  1727. this.registerType('ast._Tokenizer', class {
  1728. constructor(text, file) {
  1729. this._text = text;
  1730. this.filename = file;
  1731. this.linepos = 0;
  1732. this.lineno = 1;
  1733. this._position = 0;
  1734. this._token = { type: '', value: '' };
  1735. this._brackets = 0;
  1736. this._indentation = [];
  1737. this._outdent = 0;
  1738. if (!ast._Tokenizer._whitespace) {
  1739. ast._Tokenizer._whitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  1740. 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';
  1741. 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';
  1742. ast._Tokenizer._identifierStart = new RegExp(`[${identifierStartChars}]`);
  1743. /* eslint-disable no-misleading-character-class */
  1744. ast._Tokenizer._identifierChar = new RegExp(`[${identifierStartChars}${identifierChars}]`);
  1745. /* eslint-enable no-misleading-character-class */
  1746. }
  1747. }
  1748. peek() {
  1749. if (!this._cache) {
  1750. this._tokenize();
  1751. this._cache = true;
  1752. }
  1753. return this._token;
  1754. }
  1755. read() {
  1756. if (!this._cache) {
  1757. this._tokenize();
  1758. }
  1759. const next = this._position + this._token.value.length;
  1760. while (this._position < next) {
  1761. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1762. this._position = this._newLine(this._position);
  1763. this.linepos = this._position;
  1764. this.lineno++;
  1765. } else {
  1766. this._position++;
  1767. }
  1768. }
  1769. this._cache = false;
  1770. return this._token;
  1771. }
  1772. match(type, value) {
  1773. const token = this.peek();
  1774. if (token.type === type && (!value || token.value === value)) {
  1775. return true;
  1776. }
  1777. return false;
  1778. }
  1779. accept(type, value) {
  1780. const token = this.peek();
  1781. if (token.type === type && (!value || token.value === value)) {
  1782. this.read();
  1783. return true;
  1784. }
  1785. return false;
  1786. }
  1787. expect(type, value) {
  1788. const token = this.peek();
  1789. if (token.type !== type) {
  1790. throw new python.Error(`Unexpected '${token.value}' instead of '${type}' ${this.location()}`);
  1791. }
  1792. if (value && token.value !== value) {
  1793. throw new python.Error(`Unexpected '${token.value}' instead of '${value}' ${this.location()}`);
  1794. }
  1795. this.read();
  1796. }
  1797. location() {
  1798. return `at ${this.filename}:${this.lineno}:${this.col_offset}.`;
  1799. }
  1800. get col_offset() {
  1801. return this._position - this.linepos + 1;
  1802. }
  1803. static _isSpace(c) {
  1804. if (c === ' ' || c === '\t' || c === '\v' || c === '\f' || c === '\xA0') {
  1805. return true;
  1806. }
  1807. if (c.charCodeAt(0) >= 0x1680) {
  1808. return ast._Tokenizer._whitespace.test(c);
  1809. }
  1810. return false;
  1811. }
  1812. static _isNewline(c) {
  1813. switch (c) {
  1814. case '\n':
  1815. case '\r':
  1816. case '\u2028': // 8232
  1817. case '\u2029': // 8233
  1818. return true;
  1819. default:
  1820. return false;
  1821. }
  1822. }
  1823. static _isIdentifierStartChar(c) {
  1824. if (c < 'A') {
  1825. return c === '$';
  1826. }
  1827. if (c <= 'Z') {
  1828. return true;
  1829. }
  1830. if (c < 'a') {
  1831. return c === '_';
  1832. }
  1833. if (c <= 'z') {
  1834. return true;
  1835. }
  1836. const code = c.charCodeAt(0);
  1837. if (code >= 0xAA) {
  1838. return ast._Tokenizer._identifierStart.test(c);
  1839. }
  1840. return false;
  1841. }
  1842. static _isIdentifierChar(c) {
  1843. if (c < '0') {
  1844. return c === '$';
  1845. }
  1846. if (c <= '9') {
  1847. return true;
  1848. }
  1849. if (c < 'A') {
  1850. return false;
  1851. }
  1852. if (c <= 'Z') {
  1853. return true;
  1854. }
  1855. if (c < 'a') {
  1856. return c === '_';
  1857. }
  1858. if (c <= 'z') {
  1859. return true;
  1860. }
  1861. const code = c.charCodeAt(0);
  1862. if (code >= 0xAA) {
  1863. return ast._Tokenizer._identifierChar.test(c);
  1864. }
  1865. return false;
  1866. }
  1867. _get(position) {
  1868. return position >= this._text.length ? '\0' : this._text[position];
  1869. }
  1870. _skipLine() {
  1871. while (this._position < this._text.length) {
  1872. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1873. break;
  1874. }
  1875. this._position++;
  1876. }
  1877. }
  1878. _skipWhitespace() {
  1879. while (this._position < this._text.length) {
  1880. const c = this._text[this._position];
  1881. if (c === '#') {
  1882. this._skipLine();
  1883. } else if (ast._Tokenizer._isSpace(c)) {
  1884. this._position++;
  1885. } else if (c === '\\') {
  1886. // Explicit Line Continuation
  1887. this._position++;
  1888. if (ast._Tokenizer._isNewline(this._get(this._position))) {
  1889. this._position = this._newLine(this._position);
  1890. this.linepos = this._position;
  1891. this.lineno += 1;
  1892. } else {
  1893. throw new python.Error(`Unexpected '${this._text[this._position]}' after line continuation ${this.location()}`);
  1894. }
  1895. } else if (this._brackets > 0 && ast._Tokenizer._isNewline(c)) {
  1896. // Implicit Line Continuation
  1897. this._position = this._newLine(this._position);
  1898. this.linepos = this._position;
  1899. this.lineno += 1;
  1900. } else {
  1901. break;
  1902. }
  1903. }
  1904. }
  1905. _newLine(position) {
  1906. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') || (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1907. return position + 2;
  1908. }
  1909. return position + 1;
  1910. }
  1911. _tokenize() {
  1912. if (this._token.type !== '\n') {
  1913. this._skipWhitespace();
  1914. }
  1915. if (this._token.type === 'dedent') {
  1916. this._indentation.pop();
  1917. this._outdent--;
  1918. if (this._outdent > 0) {
  1919. this._token = { type: 'dedent', value: '' };
  1920. return;
  1921. }
  1922. }
  1923. if (this._token.type === '\n') {
  1924. let indent = '';
  1925. let i = this._position;
  1926. while (i < this._text.length) {
  1927. const c = this._text[i];
  1928. if (ast._Tokenizer._isSpace(c)) {
  1929. indent += c;
  1930. i++;
  1931. } else if (ast._Tokenizer._isNewline(c)) {
  1932. indent = '';
  1933. i = this._newLine(i);
  1934. this._position = i;
  1935. this.linepos = i;
  1936. this.lineno += 1;
  1937. } else if (c === '#') {
  1938. indent = '';
  1939. while (i < this._text.length && !ast._Tokenizer._isNewline(this._text[i])) {
  1940. i++;
  1941. }
  1942. continue;
  1943. } else {
  1944. break;
  1945. }
  1946. }
  1947. let type = null;
  1948. if (indent.length > 0) {
  1949. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1950. if (indent.length > current.length) {
  1951. type = 'indent';
  1952. this._indentation.push(indent);
  1953. } else if (indent.length > 0 && indent.length < current.length) {
  1954. type = 'dedent';
  1955. this._outdent = 0;
  1956. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1957. this._outdent++;
  1958. }
  1959. } else {
  1960. this._position += indent.length;
  1961. }
  1962. } else if (i >= this._text.length) {
  1963. this._token = { type: 'eof', value: '' };
  1964. return;
  1965. } else if (this._indentation.length > 0) {
  1966. type = 'dedent';
  1967. this._outdent = this._indentation.length;
  1968. }
  1969. if (type === 'indent' || type === 'dedent') {
  1970. this._token = { type, value: indent };
  1971. return;
  1972. }
  1973. }
  1974. if (this._position >= this._text.length) {
  1975. this._token = { type: 'eof', value: '' };
  1976. return;
  1977. }
  1978. const c = this._get(this._position);
  1979. const string = this._string();
  1980. if (string) {
  1981. this._token = string;
  1982. return;
  1983. }
  1984. switch (c) {
  1985. case '(':
  1986. case '[':
  1987. case '{':
  1988. this._brackets++;
  1989. this._token = { type: c, value: c };
  1990. return;
  1991. case ')':
  1992. case ']':
  1993. case '}':
  1994. if (this._brackets === 0) {
  1995. throw new python.Error(`Unexpected '${c}' ${this.location}`);
  1996. }
  1997. this._brackets--;
  1998. this._token = { type: c, value: c };
  1999. return;
  2000. case ',':
  2001. case ';':
  2002. case '?':
  2003. this._token = { type: c, value: c };
  2004. return;
  2005. default: {
  2006. const number = this._number();
  2007. if (number) {
  2008. this._token = number;
  2009. return;
  2010. }
  2011. if (c === '.') {
  2012. let end = this._position + 1;
  2013. while (this._get(end) === '.') {
  2014. end++;
  2015. }
  2016. const text = this._text.substring(this._position, end);
  2017. this._token = { type: text, value: text };
  2018. return;
  2019. }
  2020. const identifier = this._identifier();
  2021. if (identifier) {
  2022. this._token = identifier;
  2023. return;
  2024. }
  2025. const operator = this._operator();
  2026. if (operator) {
  2027. this._token = operator;
  2028. return;
  2029. }
  2030. break;
  2031. }
  2032. }
  2033. if (c === '.') {
  2034. this._token = { type: c, value: c };
  2035. return;
  2036. }
  2037. if (c === '\\') {
  2038. this._token = { type: '\\', value: c };
  2039. return;
  2040. }
  2041. if (ast._Tokenizer._isNewline(c)) {
  2042. this._token = { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  2043. return;
  2044. }
  2045. throw new python.Error(`Unexpected token '${c}' ${this.location()}`);
  2046. }
  2047. _number() {
  2048. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  2049. const binary = (c) => c === '0' || c === '1' || c === '_';
  2050. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  2051. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  2052. let c = this._get(this._position);
  2053. let i = this._position;
  2054. c = this._get(i);
  2055. if (c === '0') {
  2056. let radix = 0;
  2057. const n = this._get(i + 1);
  2058. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  2059. i += 2;
  2060. while (hex(this._get(i))) {
  2061. i += 1;
  2062. }
  2063. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2064. i += 1;
  2065. }
  2066. radix = 16;
  2067. } else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  2068. i += 2;
  2069. while (binary(this._get(i))) {
  2070. i++;
  2071. }
  2072. radix = 2;
  2073. } else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  2074. i += 2;
  2075. while (octal(this._get(i))) {
  2076. i++;
  2077. }
  2078. radix = 8;
  2079. } else if (n >= '0' && n <= '7') {
  2080. i++;
  2081. while (octal(this._get(i))) {
  2082. i += 1;
  2083. }
  2084. if (this._get(i) === 'l' || this._get(i) === 'L') {
  2085. i += 1;
  2086. }
  2087. radix = 8;
  2088. }
  2089. if (radix > 0 && this._get(i) !== '.') {
  2090. const radixText = this._text.substring(this._position, i);
  2091. const radixParseText = radixText.indexOf('_') === -1 ? radixText : radixText.split('_').join('');
  2092. if (!isNaN(parseInt(radixParseText, radix))) {
  2093. return { type: 'int', value: radixText };
  2094. }
  2095. }
  2096. }
  2097. i = this._position;
  2098. let isDecimal = false;
  2099. if (this._get(i) >= '1' && this._get(i) <= '9') {
  2100. while (decimal(this._get(i))) {
  2101. i++;
  2102. }
  2103. c = this._get(i).toLowerCase();
  2104. isDecimal = c !== '.' && c !== 'e';
  2105. }
  2106. if (this._get(i) === '0') {
  2107. i++;
  2108. c = this._get(i).toLowerCase();
  2109. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  2110. }
  2111. if (isDecimal) {
  2112. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2113. return { 'type': 'complex', value: this._text.substring(this._position, i + 1) };
  2114. }
  2115. // if (this._get(i) === 'l' || this._get(i) === 'L') {
  2116. // Python 2 long integer
  2117. // }
  2118. const intText = this._text.substring(this._position, i);
  2119. if (!isNaN(parseInt(intText, 10))) {
  2120. return { type: 'int', value: intText };
  2121. }
  2122. }
  2123. i = this._position;
  2124. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  2125. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  2126. while (decimal(this._get(i))) {
  2127. i++;
  2128. }
  2129. if (this._get(i) === '.') {
  2130. i++;
  2131. }
  2132. while (decimal(this._get(i))) {
  2133. i++;
  2134. }
  2135. if (i > this._position) {
  2136. if (this._get(i) === 'e' || this._get(i) === 'E') {
  2137. i++;
  2138. if (this._get(i) === '-' || this._get(i) === '+') {
  2139. i++;
  2140. }
  2141. if (decimal(this._get(i))) {
  2142. while (decimal(this._get(i))) {
  2143. i++;
  2144. }
  2145. } else {
  2146. i = this._position;
  2147. }
  2148. } else {
  2149. while (decimal(this._get(i))) {
  2150. i++;
  2151. }
  2152. }
  2153. }
  2154. if (i > this._position) {
  2155. if (this._get(i) === 'j' || this._get(i) === 'J') {
  2156. return { type: 'complex', value: this._text.substring(this._position, i + 1) };
  2157. }
  2158. const floatText = this._text.substring(this._position, i);
  2159. const floatParseText = floatText.indexOf('_') === -1 ? floatText : floatText.split('_').join('');
  2160. if (!isNaN(parseFloat(floatParseText))) {
  2161. return { type: 'float', value: floatText };
  2162. }
  2163. }
  2164. }
  2165. return null;
  2166. }
  2167. _identifier() {
  2168. let i = this._position;
  2169. if (ast._Tokenizer._isIdentifierStartChar(this._get(i))) {
  2170. i++;
  2171. while (ast._Tokenizer._isIdentifierChar(this._get(i))) {
  2172. i++;
  2173. }
  2174. }
  2175. if (i > this._position) {
  2176. const text = this._text.substring(this._position, i);
  2177. let keyword = false;
  2178. switch (text) {
  2179. case 'and':
  2180. case 'as':
  2181. case 'else':
  2182. case 'For':
  2183. case 'If':
  2184. case 'Import':
  2185. case 'in':
  2186. case 'is':
  2187. case 'not':
  2188. case 'or':
  2189. keyword = true;
  2190. break;
  2191. default:
  2192. break;
  2193. }
  2194. return { type: 'id', value: text, keyword };
  2195. }
  2196. return null;
  2197. }
  2198. _operator() {
  2199. let length = 0;
  2200. const c0 = this._get(this._position);
  2201. const c1 = this._get(this._position + 1);
  2202. const c2 = this._get(this._position + 2);
  2203. switch (c0) {
  2204. case '+': case '&': case '|': case '^': case '=': case '!': case '%': case '~':
  2205. length = c1 === '=' ? 2 : 1;
  2206. break;
  2207. case '-':
  2208. length = c1 === '=' || c1 === '>' ? 2 : 1;
  2209. break;
  2210. case '*':
  2211. switch (c1) {
  2212. case '*': length = c2 === '=' ? 3 : 2; break;
  2213. case '=': length = 2; break;
  2214. default: length = 1; break;
  2215. }
  2216. break;
  2217. case '/':
  2218. switch (c1) {
  2219. case '/': length = c2 === '=' ? 3 : 2; break;
  2220. case '=': length = 2; break;
  2221. default: length = 1; break;
  2222. }
  2223. break;
  2224. case '<':
  2225. switch (c1) {
  2226. case '>': length = 2; break;
  2227. case '<': length = c2 === '=' ? 3 : 2; break;
  2228. case '=': length = 2; break;
  2229. default: length = 1; break;
  2230. }
  2231. break;
  2232. case '>':
  2233. switch (c1) {
  2234. case '>': length = c2 === '=' ? 3 : 2; break;
  2235. case '=': length = 2; break;
  2236. default: length = 1; break;
  2237. }
  2238. break;
  2239. case '@':
  2240. length = c1 === '=' ? 2 : 1;
  2241. break;
  2242. case ':':
  2243. length = c1 === '=' ? 2 : 1;
  2244. break;
  2245. default:
  2246. return null;
  2247. }
  2248. const text = this._text.substring(this._position, this._position + length);
  2249. return { type: text, value: text };
  2250. }
  2251. _string() {
  2252. let i = this._position;
  2253. let prefix = -1;
  2254. if (this._get(i) === "'" || this._get(i) === '"') {
  2255. prefix = '';
  2256. } else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  2257. const c = this._get(i);
  2258. const cc = c.toLowerCase();
  2259. if (cc === 'b' || cc === 'f' || cc === 'r' || cc === 'u') {
  2260. prefix = c;
  2261. }
  2262. } else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  2263. const c = this._text.substring(this._position, this._position + 2);
  2264. const cc = c.toLowerCase();
  2265. if (cc === 'br' || cc === 'fr' || cc === 'rb' || cc === 'rf' || cc === 'ur') {
  2266. prefix = c;
  2267. }
  2268. }
  2269. if (prefix.length >= 0) {
  2270. i += prefix.length;
  2271. let quote = '';
  2272. let count = 0;
  2273. const q0 = this._get(i);
  2274. const q1 = this._get(i + 1);
  2275. const q2 = this._get(i + 2);
  2276. switch (q0) {
  2277. case "'":
  2278. quote = q0;
  2279. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  2280. break;
  2281. case '"':
  2282. quote = q0;
  2283. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  2284. break;
  2285. default:
  2286. throw new python.Error(`Unsupported string quote '${q0}'.`);
  2287. }
  2288. i += count;
  2289. if (count === 1) {
  2290. while (i < this._text.length) {
  2291. if (this._text[i] === quote) {
  2292. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2293. } else if (this._text[i] === '\\' &&
  2294. (this._get(i + 1) === quote || this._get(i + 1) === '\n' || this._get(i + 1) === '\\')) {
  2295. i += 2;
  2296. } else if (this._text[i] === '\r' || this._text[i] === '\n') {
  2297. break;
  2298. } else {
  2299. i++;
  2300. }
  2301. }
  2302. } else if (count === 3) {
  2303. while (i < this._text.length) {
  2304. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  2305. return { type: 'str', value: this._text.substring(this._position, i + 3) };
  2306. } else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  2307. i += 2;
  2308. continue;
  2309. }
  2310. i++;
  2311. }
  2312. }
  2313. }
  2314. i = this._position;
  2315. if (this._get(i) === '`') {
  2316. i++;
  2317. while (i < this._text.length) {
  2318. if (this._text[i] === '`') {
  2319. return { type: 'str', value: this._text.substring(this._position, i + 1) };
  2320. }
  2321. i++;
  2322. }
  2323. }
  2324. return null;
  2325. }
  2326. });
  2327. this.registerType('builtins.dict', dict);
  2328. this.registerType('builtins.ellipsis', class {});
  2329. this.registerType('builtins.cell', class {});
  2330. this.registerType('builtins.list', class extends Array {
  2331. constructor(iterable) {
  2332. super();
  2333. if (Array.isArray(iterable)) {
  2334. this.push(...iterable);
  2335. }
  2336. }
  2337. });
  2338. this.registerType('builtins.number', class {});
  2339. this.registerFunction('builtins.__import__', (name, globals, locals, fromlist, level) => {
  2340. return execution.__import__(name, globals, locals, fromlist, level);
  2341. });
  2342. this.registerType('builtins.bool', class extends Boolean {
  2343. constructor(value) {
  2344. if (value && value.__bool__) {
  2345. value = value.__bool__();
  2346. } else if (value && value.__len__) {
  2347. value = value.__len__() > 0;
  2348. } else {
  2349. value = value ? true : false;
  2350. }
  2351. super(value);
  2352. }
  2353. });
  2354. this.registerType('builtins.int', class extends Number {
  2355. constructor(value) {
  2356. if (value && value.__int__) {
  2357. value = value.__int__();
  2358. } else if (!Number.isInteger(value)) {
  2359. value = NaN;
  2360. }
  2361. super(value);
  2362. }
  2363. });
  2364. this.registerType('builtins.float', class extends Number {
  2365. constructor(value) {
  2366. if (value && value.__float__) {
  2367. value = value.__float__();
  2368. } else if (Number(value) !== value) {
  2369. value = NaN;
  2370. }
  2371. super(value);
  2372. }
  2373. });
  2374. this.registerType('builtins.long', class extends Number {
  2375. constructor(value) {
  2376. if (value && value.__int__) {
  2377. value = value.__int__();
  2378. } else if (!Number.isInteger(value)) {
  2379. value = NaN;
  2380. }
  2381. super(value);
  2382. }
  2383. });
  2384. this.registerType('builtins.str', class extends String {
  2385. constructor(value) {
  2386. if (value && value.__str__) {
  2387. value = value.__str__();
  2388. } else if (typeof value !== 'string') {
  2389. value = JSON.stringify(value);
  2390. }
  2391. super(value);
  2392. }
  2393. });
  2394. this.registerType('builtins.complex', class {
  2395. constructor(real, imaginary) {
  2396. this.real = real;
  2397. this.imag = imaginary;
  2398. }
  2399. toString() {
  2400. return `${this.real}${this.imag < 0 ? '' : '+'}${this.imag}j`;
  2401. }
  2402. });
  2403. this.registerType('builtins.NoneType', class {});
  2404. this.registerType('builtins.object', class {
  2405. static __new__(cls, ...args) {
  2406. return execution.invoke(cls, args);
  2407. }
  2408. static __setattr__(obj, name, value) {
  2409. builtins.setattr(obj, name, value);
  2410. }
  2411. });
  2412. this.registerType('builtins.tuple', class extends Array {
  2413. constructor(items) {
  2414. super(items ? items.length : 0);
  2415. if (items) {
  2416. for (let i = 0; i < items.length; i++) {
  2417. this[i] = items[i];
  2418. }
  2419. }
  2420. }
  2421. });
  2422. this.registerType('builtins.staticmethod', class {});
  2423. this.registerType('builtins.Warning', class {});
  2424. this.registerType('builtins.FutureWarning', class extends builtins.Warning {});
  2425. this.registerType('builtins.BaseException', class {});
  2426. this.registerType('builtins.Exception', class extends builtins.BaseException {});
  2427. this.registerType('builtins.AttributeError', class extends builtins.Exception {});
  2428. this.registerType('builtins.SyntaxError', class extends builtins.Exception {});
  2429. this.registerFunction('builtins.print', () => {});
  2430. this.registerFunction('builtins.unicode');
  2431. builtins.Ellipsis = new builtins.ellipsis();
  2432. this.registerType('typing._Final', class {});
  2433. this.registerType('typing._SpecialForm', class extends typing._Final {});
  2434. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  2435. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  2436. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  2437. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  2438. this.registerType('typing._CallableType', class {});
  2439. this.registerFunction('typing.cast');
  2440. typing.Any = Reflect.construct(typing._SpecialForm, []);
  2441. typing.Callable = Reflect.construct(typing._CallableType, []);
  2442. typing.Dict = Reflect.construct(typing._SpecialGenericAlias, []);
  2443. typing.List = Reflect.construct(typing._SpecialGenericAlias, []);
  2444. typing.Optional = Reflect.construct(typing._SpecialForm, []);
  2445. typing.OrderedDict = Reflect.construct(typing._SpecialGenericAlias, []);
  2446. typing.Sequence = Reflect.construct(typing._SpecialGenericAlias, []);
  2447. typing.Tuple = Reflect.construct(typing._TupleType, []);
  2448. typing.Union = Reflect.construct(typing._SpecialForm, []);
  2449. this.registerType('enum.Enum', class {
  2450. // __reduce_ex__(proto) {
  2451. // return self.__class__, (self._value_, )
  2452. // }
  2453. });
  2454. this.registerFunction('operator.add');
  2455. this.registerFunction('operator.and_');
  2456. this.registerFunction('operator.and_');
  2457. this.registerFunction('operator.eq');
  2458. this.registerFunction('operator.floordiv');
  2459. this.registerFunction('operator.ge');
  2460. this.registerFunction('operator.getitem');
  2461. this.registerFunction('operator.gt');
  2462. this.registerFunction('operator.le');
  2463. this.registerFunction('operator.lt');
  2464. this.registerFunction('operator.mod');
  2465. this.registerFunction('operator.mul');
  2466. this.registerFunction('operator.ne');
  2467. this.registerFunction('operator.neg');
  2468. this.registerFunction('operator.or_');
  2469. this.registerFunction('operator.pos');
  2470. this.registerFunction('operator.pow');
  2471. this.registerFunction('operator.sub');
  2472. this.registerFunction('operator.truediv');
  2473. this.registerFunction('sys.path.append', () => {});
  2474. this.registerFunction('sys.path.insert', () => {});
  2475. this.registerType('argparse.Namespace', class {
  2476. constructor(args) {
  2477. this.args = args;
  2478. }
  2479. });
  2480. this.registerType('catboost._catboost._CatBoost', class {
  2481. _deserialize_model(/* serialized_model_str */) {
  2482. }
  2483. });
  2484. this.registerType('catboost.core._CatBoostBase', class {
  2485. constructor() {
  2486. this._object = new catboost._catboost._CatBoost();
  2487. }
  2488. __setstate__(state) {
  2489. for (const [key, value] of state) {
  2490. if (key === '__model') {
  2491. this._load_from_string(value);
  2492. continue;
  2493. }
  2494. this[key] = value;
  2495. }
  2496. }
  2497. _load_from_string(dump_model_str) {
  2498. this._deserialize_model(dump_model_str);
  2499. }
  2500. _deserialize_model(dump_model_str) {
  2501. this._object._deserialize_model(dump_model_str);
  2502. }
  2503. });
  2504. this.registerType('catboost.core.CatBoost', class extends catboost.core._CatBoostBase {
  2505. load_model(/* blob */) {
  2506. throw new python.Error("'catboost.core.CatBoostClassifier.load_model' not implemented.");
  2507. // this._load_from_string(blob);
  2508. }
  2509. });
  2510. this.registerType('catboost.core.CatBoostClassifier', class extends catboost.core.CatBoost {});
  2511. this.registerType('catboost.core.CatBoostRegressor', class extends catboost.core.CatBoost {});
  2512. catboost.CatBoostClassifier = catboost.core.CatBoostClassifier;
  2513. catboost.CatBoostRegressor = catboost.core.CatBoostRegressor;
  2514. catboost.CatBoost = catboost.core.CatBoost;
  2515. this.registerType('collections.deque', class extends Array {
  2516. constructor(iterable) {
  2517. super();
  2518. if (Array.isArray(iterable)) {
  2519. for (const value of iterable) {
  2520. this.push(value);
  2521. }
  2522. }
  2523. }
  2524. });
  2525. this.registerType('collections.OrderedDict', class extends dict {});
  2526. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  2527. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  2528. this.registerType('cuml.internals.array.CumlArray', class {});
  2529. this.registerType('cuml.internals.mem_type.MemoryType', class {});
  2530. this.registerType('cuml.raft.common.handle.Handle', class {
  2531. __setstate__(state) {
  2532. this._handle = state;
  2533. }
  2534. });
  2535. this.registerType('cuml.svm.svr.SVR', class {});
  2536. this.registerType('datetime.date', class {});
  2537. this.registerType('datetime.datetime', class extends datetime.date {});
  2538. this.registerType('datetime.timedelta', class {});
  2539. this.registerType('datetime.tzinfo', class {});
  2540. this.registerType('datetime.timezone', class extends datetime.tzinfo {});
  2541. this.registerType('dnnlib.tflib.network.Network', class {});
  2542. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  2543. this.registerType('haiku._src.data_structures.FlatMapping', class {
  2544. constructor(dict) {
  2545. Object.assign(this, dict);
  2546. }
  2547. });
  2548. this.registerType('haiku._src.data_structures.frozendict', class {
  2549. constructor(obj) {
  2550. Object.assign(this, obj);
  2551. }
  2552. });
  2553. this.registerType('hmmlearn.hmm.GaussianHMM', class {});
  2554. this.registerType('hmmlearn.hmm.GMMHMM', class {});
  2555. this.registerType('hmmlearn.hmm.MultinomialHMM', class {});
  2556. this.registerType('hmmlearn.base.ConvergenceMonitor', class {});
  2557. this.registerType('io.BytesIO', class {
  2558. constructor(buf, mode) {
  2559. this.mode = mode || 'r';
  2560. this._buf = this.mode === 'w' ? null : buf;
  2561. this._point = 0;
  2562. }
  2563. seek(offset) {
  2564. if (this._buf.seek) {
  2565. this._buf.seek(offset);
  2566. }
  2567. this._point = offset;
  2568. }
  2569. read(size, stream) {
  2570. if (this._buf.stream && stream) {
  2571. return this._buf.stream(size);
  2572. }
  2573. if (this._buf.peek) {
  2574. return this._buf.read(size);
  2575. }
  2576. if (this._buf instanceof Uint8Array) {
  2577. const start = this._point;
  2578. this._point = size === undefined ? this._buf.length : start + size;
  2579. return this._buf.subarray(start, this._point);
  2580. }
  2581. throw new python.Error('Unsupported buffer type.');
  2582. }
  2583. write(data) {
  2584. const src = this._buf || new Uint8Array();
  2585. const end = this._point + data.length;
  2586. const size = Math.max(src.length, end);
  2587. this._buf = new Uint8Array(size);
  2588. this._buf.set(src, 0);
  2589. this._buf.set(data, this._point);
  2590. this._point = end;
  2591. }
  2592. getbuffer() {
  2593. return new builtins.memoryview(this._buf);
  2594. }
  2595. });
  2596. this.registerType('io.StringIO', class {
  2597. constructor() {
  2598. this._buf = [];
  2599. }
  2600. write(text) {
  2601. this._buf.push(text);
  2602. }
  2603. toString() {
  2604. return this._buf.join('');
  2605. }
  2606. });
  2607. this.registerType('numpy.dtype', class {
  2608. constructor(obj, align, copy) {
  2609. if (typeof obj !== 'string' && obj && Array.isArray(obj.names)) {
  2610. this.kind = 'V';
  2611. this.byteorder = '|';
  2612. this.itemsize = obj.itemsize;
  2613. this.names = obj.names;
  2614. this.fields = new Map();
  2615. for (let i = 0; i < obj.names.length; i++) {
  2616. this.fields.set(obj.names[i], new builtins.tuple([obj.formats[i], obj.offsets[i]]));
  2617. }
  2618. return;
  2619. }
  2620. if (typeof obj === 'string' && (obj.startsWith('<') || obj.startsWith('>') || obj.startsWith('|'))) {
  2621. this.byteorder = obj.substring(0, 1);
  2622. obj = obj.substring(1);
  2623. } else {
  2624. this.byteorder = '=';
  2625. }
  2626. switch (obj) {
  2627. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  2628. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  2629. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  2630. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  2631. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  2632. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  2633. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  2634. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  2635. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  2636. case 'f1': case 'float8_e5m2': this.itemsize = 1; this.kind = 'f'; break;
  2637. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  2638. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  2639. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  2640. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  2641. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  2642. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  2643. case 'm8': case 'm': this.itemsize = 8; this.kind = 'm'; break;
  2644. case 'V': case 'void': this.itemsize = 0; this.kind = 'V'; break;
  2645. default:
  2646. if (obj.startsWith('V')) {
  2647. this.itemsize = parseInt(obj.substring(1), 10);
  2648. this.kind = 'V';
  2649. } else if (obj.startsWith('O')) {
  2650. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  2651. this.kind = 'O';
  2652. } else if (obj.startsWith('S')) {
  2653. this.itemsize = parseInt(obj.substring(1), 10);
  2654. this.kind = 'S';
  2655. } else if (obj.startsWith('U')) { // Unicode string
  2656. this.kind = 'U';
  2657. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  2658. } else if (obj.startsWith('T')) {
  2659. this.kind = 'T';
  2660. this.itemsize = parseInt(obj.substring(1), 10);
  2661. } else {
  2662. throw new python.Error(`Unsupported dtype '${obj}'.`);
  2663. }
  2664. break;
  2665. }
  2666. if (align) {
  2667. this.align = align;
  2668. }
  2669. if (copy) {
  2670. this.copy = copy;
  2671. }
  2672. }
  2673. get str() {
  2674. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  2675. }
  2676. get name() {
  2677. switch (this.kind) {
  2678. case 'V': return `void${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2679. case 'S': return `bytes${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2680. case 'U': return `str${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2681. case 'T': return `StringDType${this.itemsize === 0 ? '' : (this.itemsize * 8)}`;
  2682. case 'M': return 'datetime64';
  2683. case 'm': return 'timedelta64';
  2684. case 'b': return 'bool';
  2685. default: return this.__name__;
  2686. }
  2687. }
  2688. __setstate__(state) {
  2689. switch (state.length) {
  2690. case 8:
  2691. [
  2692. this.version, this.byteorder, this.subarray, this.names,
  2693. this.fields, this.elsize, this.alignment, this.int_dtypeflags
  2694. ] = state;
  2695. break;
  2696. case 9:
  2697. [
  2698. this.version, this.byteorder, this.subarray, this.names,
  2699. this.fields, this.elsize, this.alignment, this.int_dtypeflags,
  2700. this.metadata
  2701. ] = state;
  2702. break;
  2703. default:
  2704. throw new python.Error(`Unsupported numpy.dtype setstate length '${state.length}'.`);
  2705. }
  2706. }
  2707. get __name__() {
  2708. switch (this.kind) {
  2709. case 'b':
  2710. switch (this.itemsize) {
  2711. case 1: return 'boolean';
  2712. default: throw new python.Error(`Unsupported boolean itemsize '${this.itemsize}'.`);
  2713. }
  2714. case 'i':
  2715. switch (this.itemsize) {
  2716. case 1: return 'int8';
  2717. case 2: return 'int16';
  2718. case 4: return 'int32';
  2719. case 8: return 'int64';
  2720. default: throw new python.Error(`Unsupported int itemsize '${this.itemsize}'.`);
  2721. }
  2722. case 'u':
  2723. switch (this.itemsize) {
  2724. case 1: return 'uint8';
  2725. case 2: return 'uint16';
  2726. case 4: return 'uint32';
  2727. case 8: return 'uint64';
  2728. default: throw new python.Error(`Unsupported uint itemsize '${this.itemsize}'.`);
  2729. }
  2730. case 'f':
  2731. switch (this.itemsize) {
  2732. case 1: return 'float8e5m2';
  2733. case 2: return 'float16';
  2734. case 4: return 'float32';
  2735. case 8: return 'float64';
  2736. default: throw new python.Error(`Unsupported float itemsize '${this.itemsize}'.`);
  2737. }
  2738. case 'c':
  2739. switch (this.itemsize) {
  2740. case 8: return 'complex<float32>';
  2741. case 16: return 'complex<float64>';
  2742. default: throw new python.Error(`Unsupported complex itemsize '${this.itemsize}'.`);
  2743. }
  2744. case 'S':
  2745. case 'T':
  2746. return 'string';
  2747. case 'U':
  2748. return 'string';
  2749. case 'M':
  2750. return 'datetime';
  2751. case 'm':
  2752. return 'timedelta';
  2753. case 'O':
  2754. return 'object';
  2755. case 'V':
  2756. return 'void';
  2757. default:
  2758. throw new python.Error(`Unsupported dtype kind '${this.kind}'.`);
  2759. }
  2760. }
  2761. });
  2762. this.registerType('numpy.generic', class {});
  2763. this.registerType('numpy.inexact', class {});
  2764. this.registerType('numpy.flexible', class extends numpy.generic {});
  2765. this.registerType('numpy.void', class extends numpy.flexible {});
  2766. this.registerType('numpy.bool_', class extends numpy.generic {});
  2767. this.registerType('numpy.number', class extends numpy.generic {});
  2768. this.registerType('numpy.integer', class extends numpy.number {});
  2769. this.registerType('numpy.floating', class extends numpy.inexact {});
  2770. this.registerType('numpy.float16', class extends numpy.floating {});
  2771. this.registerType('numpy.float32', class extends numpy.floating {});
  2772. this.registerType('numpy.float64', class extends numpy.floating {});
  2773. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  2774. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  2775. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  2776. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  2777. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  2778. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  2779. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  2780. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  2781. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  2782. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  2783. this.registerType('numpy.datetime64', class extends numpy.generic {
  2784. constructor(...args) {
  2785. super();
  2786. if (args.length === 1 && args[0] instanceof Uint8Array) {
  2787. [this.buffer] = args;
  2788. }
  2789. }
  2790. toString() {
  2791. const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, 8);
  2792. const value = view.getBigInt64(0, true);
  2793. if (value === -9223372036854775808n) {
  2794. return 'NaT';
  2795. }
  2796. const date = new Date(Number(value / 1000000n));
  2797. return date.toISOString().slice(0, -1);
  2798. }
  2799. });
  2800. this.registerType('numpy.dtypes.StringDType', class extends numpy.dtype {
  2801. constructor() {
  2802. super('|T16');
  2803. }
  2804. });
  2805. this.registerType('gensim.models.doc2vec.Doctag', class {});
  2806. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  2807. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  2808. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  2809. this.registerType('gensim.models.fasttext.FastText', class {});
  2810. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  2811. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  2812. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  2813. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  2814. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  2815. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  2816. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  2817. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  2818. this.registerType('gensim.models.ldamodel.LdaState', class {});
  2819. this.registerType('gensim.models.ldamulticore.LdaMulticore', class {});
  2820. this.registerFunction('gensim.models.phrases.original_scorer');
  2821. this.registerType('gensim.models.phrases.Phraser', class {});
  2822. this.registerType('gensim.models.phrases.Phrases', class {});
  2823. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  2824. this.registerType('gensim.models.word2vec.Vocab', class {});
  2825. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  2826. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  2827. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  2828. this.registerFunction('gensim.models.tfidfmodel.df2idf');
  2829. this.registerFunction('gensim.utils.call_on_class_only', () => {
  2830. throw new builtins.AttributeError('This method should be called on a class object.');
  2831. });
  2832. this.registerFunction('gensim.utils.identity');
  2833. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  2834. constructor(obj) {
  2835. Object.assign(this, obj);
  2836. }
  2837. });
  2838. this.registerType('joblib._store_backends.FileSystemStoreBackend', class {});
  2839. this.registerType('joblib.memory.NotMemorizedFunc', class {});
  2840. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  2841. __read__(unpickler) {
  2842. if (this.dtype.__name__ === 'object') {
  2843. return unpickler.load();
  2844. }
  2845. if (this.numpy_array_alignment_bytes) {
  2846. const [size] = unpickler.read(1);
  2847. unpickler.read(size);
  2848. }
  2849. if (this.order === 'F') {
  2850. throw new python.Error('Fortran order not implemented.');
  2851. }
  2852. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2853. this.data = unpickler.read(size);
  2854. return execution.invoke(this.subclass, [this.shape, this.dtype, this.data]);
  2855. }
  2856. });
  2857. this.registerType('joblib.numpy_pickle.NDArrayWrapper', class {
  2858. __setstate__(state) {
  2859. this.subclass = state.get('subclass');
  2860. this.filename = state.get('state');
  2861. this.allow_mmap = state.get('allow_mmap');
  2862. }
  2863. __read__(/* unpickler */) {
  2864. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2865. }
  2866. });
  2867. sklearn.externals.joblib.numpy_pickle.NDArrayWrapper = joblib.numpy_pickle.NDArrayWrapper;
  2868. sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper = joblib.numpy_pickle.NumpyArrayWrapper;
  2869. this.registerType('keras.engine.sequential.Sequential', class {});
  2870. this.registerType('keras.src.legacy.preprocessing.text.Tokenizer', class {});
  2871. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2872. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2873. this.registerType('lasagne.layers.input.InputLayer', class {});
  2874. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2875. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2876. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2877. this.registerType('lightgbm.basic.Booster', class {
  2878. constructor() {
  2879. this.average_output = false;
  2880. this.models = [];
  2881. this.loaded_parameter = '';
  2882. }
  2883. __setstate__(state) {
  2884. const model_str = state.get('_handle', state.get('handle', null));
  2885. if (model_str) {
  2886. this.LoadModelFromString(model_str);
  2887. return;
  2888. }
  2889. for (const [key, value] of state) {
  2890. this[key] = value;
  2891. }
  2892. }
  2893. LoadModelFromString(model_str) {
  2894. const lines = model_str.split('\n');
  2895. const signature = lines.shift() || '?';
  2896. if (signature.trim() !== 'tree') {
  2897. throw new python.Error(`Invalid signature '${signature.trim()}'.`);
  2898. }
  2899. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2900. const key_vals = new Map();
  2901. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2902. const cur_line = lines.shift().trim();
  2903. if (cur_line.length > 0) {
  2904. const strs = cur_line.split('=');
  2905. if (strs.length === 1) {
  2906. key_vals.set(strs[0], '');
  2907. } else if (strs.length === 2) {
  2908. key_vals.set(strs[0], strs[1]);
  2909. } else if (strs.length > 2) {
  2910. if (strs[0] === "feature_names") {
  2911. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2912. } else if (strs[0] === 'monotone_constraints') {
  2913. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2914. } else {
  2915. throw new python.Error(`Wrong line: ${cur_line.substring(0, Math.min(128, cur_line.length))}`);
  2916. }
  2917. }
  2918. }
  2919. }
  2920. const atoi = (key, value) => {
  2921. if (key_vals.has(key)) {
  2922. return parseInt(key_vals.get(key), 10);
  2923. }
  2924. if (value !== undefined) {
  2925. return value;
  2926. }
  2927. throw new python.Error(`Model file does not specify ${key}.`);
  2928. };
  2929. const list = (key, size) => {
  2930. if (key_vals.has(key)) {
  2931. const value = key_vals.get(key).split(' ');
  2932. if (value.length !== size) {
  2933. throw new python.Error(`Wrong size of ${key}.`);
  2934. }
  2935. return value;
  2936. }
  2937. throw new python.Error(`Model file does not contain ${key}.`);
  2938. };
  2939. this.version = key_vals.get('version') || '';
  2940. this.num_class = atoi('num_class');
  2941. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2942. this.label_index = atoi('label_index');
  2943. this.max_feature_idx = atoi('max_feature_idx');
  2944. if (key_vals.has('average_output')) {
  2945. this.average_output = true;
  2946. }
  2947. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2948. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2949. if (key_vals.has('monotone_constraints')) {
  2950. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2951. }
  2952. if (key_vals.has('objective')) {
  2953. this.objective = key_vals.get('objective');
  2954. }
  2955. let tree = null;
  2956. while (lines.length > 0) {
  2957. const text = lines.shift();
  2958. const line = text.trim();
  2959. if (line.length === 0) {
  2960. continue;
  2961. }
  2962. if (line.startsWith('Tree=')) {
  2963. tree = { index: parseInt(line.split('=').pop(), 10) };
  2964. this.models.push(tree);
  2965. continue;
  2966. }
  2967. if (line === 'end of trees') {
  2968. break;
  2969. }
  2970. const param = line.split('=');
  2971. if (param.length !== 2) {
  2972. throw new python.Error(`Invalid property '${line}'.`);
  2973. }
  2974. const name = param[0].trim();
  2975. const value = param[1].trim();
  2976. tree[name] = value;
  2977. }
  2978. const ss = [];
  2979. let is_inparameter = false;
  2980. while (lines.length > 0) {
  2981. const text = lines.shift();
  2982. const line = text.trim();
  2983. if (line === 'parameters:') {
  2984. is_inparameter = true;
  2985. continue;
  2986. } else if (line === 'end of parameters') {
  2987. break;
  2988. } else if (is_inparameter) {
  2989. ss.push(line);
  2990. }
  2991. }
  2992. if (ss.length > 0) {
  2993. this.loaded_parameter = ss.join('\n');
  2994. }
  2995. }
  2996. });
  2997. this.registerFunction('megengine.functional.elemwise.clip', () => {});
  2998. this.registerFunction('megengine.functional.elemwise.sqrt', () => {});
  2999. this.registerFunction('megengine.functional.nn.conv2d', () => {});
  3000. this.registerFunction('megengine.functional.nn.relu', () => {});
  3001. this.registerFunction('megengine.functional.nn.sigmoid', () => {});
  3002. this.registerFunction('megengine.functional.tensor.arange', () => {});
  3003. this.registerFunction('megengine.functional.tensor.broadcast_to', () => {});
  3004. this.registerFunction('megengine.functional.tensor.concat', () => {});
  3005. this.registerFunction('megengine.functional.tensor.expand_dims', () => {});
  3006. this.registerFunction('megengine.functional.tensor.flatten', () => {});
  3007. this.registerFunction('megengine.functional.tensor.full', () => {});
  3008. this.registerFunction('megengine.functional.tensor.reshape', () => {});
  3009. this.registerFunction('megengine.functional.tensor.split', () => {});
  3010. this.registerFunction('megengine.functional.tensor.stack', () => {});
  3011. this.registerFunction('megengine.functional.tensor.transpose', () => {});
  3012. this.registerFunction('megengine.functional.vision.interpolate', () => {});
  3013. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', () => {});
  3014. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  3015. this.registerType('megengine.core._imperative_rt.ops.ElemwiseMultiType', class {});
  3016. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  3017. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  3018. this.registerType('megengine.core._imperative_rt.ops.Resize', class {});
  3019. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  3020. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  3021. this.registerType('megengine.distributed.group.Group', class {});
  3022. this.registerType('megengine.module.activation.ReLU', class {});
  3023. this.registerType('megengine.module.activation.Softmax', class {});
  3024. this.registerType('megengine.module.adaptive_pooling.AdaptiveAvgPool2d', class {});
  3025. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  3026. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  3027. this.registerType('megengine.module.conv.Conv2d', class {});
  3028. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  3029. this.registerType('megengine.module.conv_bn.ConvBn2d', class {});
  3030. this.registerType('megengine.module.dropout.Dropout', class {});
  3031. this.registerType('megengine.module.identity.Identity', class {});
  3032. this.registerType('megengine.module.linear.Linear', class {});
  3033. this.registerType('megengine.module.module.Module', class {});
  3034. this.registerType('megengine.module.normalization.InstanceNorm', class {});
  3035. this.registerType('megengine.module.normalization.GroupNorm', class {});
  3036. this.registerType('megengine.module.normalization.LayerNorm', class {});
  3037. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  3038. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  3039. this.registerType('megengine.module.qat.concat.Concat', class {});
  3040. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  3041. this.registerType('megengine.module.sequential.Sequential', class {});
  3042. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  3043. this.registerType('megengine.quantization.fake_quant.LSQ', class {});
  3044. this.registerType('megengine.quantization.fake_quant.TQT', class {});
  3045. this.registerType('megengine.quantization.utils.QParams', class {});
  3046. this.registerType('megengine.quantization.utils.QuantMode', class {});
  3047. this.registerType('megengine.quantization.observer.ExponentialMovingAverageObserver', class {});
  3048. this.registerType('megengine.quantization.observer.HistogramObserver', class {});
  3049. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  3050. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  3051. this.registerType('megengine.quantization.observer.SyncExponentialMovingAverageObserver', class {});
  3052. this.registerType('megengine.quantization.observer.SyncMinMaxObserver', class {});
  3053. this.registerType('megengine.traced_module.expr.Apply', class {});
  3054. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  3055. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  3056. this.registerType('megengine.traced_module.expr.Constant', class {});
  3057. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  3058. this.registerType('megengine.traced_module.expr.Input', class {});
  3059. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  3060. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  3061. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  3062. this.registerType('megengine.traced_module.node.TensorNode', class {});
  3063. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  3064. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  3065. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  3066. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  3067. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  3068. this.registerType('megengine.tensor.Parameter', class {
  3069. constructor(data, dtype, device) {
  3070. this.data = data;
  3071. this.dtype = dtype;
  3072. this.device = device;
  3073. }
  3074. });
  3075. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  3076. toString() {
  3077. let content = '';
  3078. for (const child of this.children_defs) {
  3079. content += `${child},`;
  3080. }
  3081. if (typeof this.type === "string") {
  3082. return `${this.type.split(".").slice(-1)}(${content})`;
  3083. }
  3084. return `${this.type.__name__}(${content})`;
  3085. }
  3086. });
  3087. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  3088. toString() {
  3089. let content = '';
  3090. if (this.const_val === null) {
  3091. content += '[';
  3092. } else {
  3093. content += this.const_val;
  3094. }
  3095. for (const t of Object.values(this.type)) {
  3096. content += t.__name__;
  3097. }
  3098. content += ']';
  3099. return content;
  3100. }
  3101. });
  3102. this.registerType('megengine.tensor.Tensor', class {
  3103. constructor(data, dtype, device) {
  3104. this.data = data;
  3105. this.dtype = dtype;
  3106. this.device = device;
  3107. }
  3108. });
  3109. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  3110. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  3111. this.name = name;
  3112. this.cname = cname;
  3113. this.np_dtype = np_dtype;
  3114. this.qmin = qmin;
  3115. this.qmax = qmax;
  3116. this.is_signed = is_signed;
  3117. }
  3118. });
  3119. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  3120. this.registerType('nolearn.lasagne.base.Layers', class {});
  3121. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  3122. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  3123. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  3124. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  3125. this.registerType('numpy.ndarray', class {
  3126. constructor(shape, dtype, buffer, offset, strides, order) {
  3127. this.shape = shape;
  3128. this.dtype = dtype;
  3129. this.data = buffer === undefined ? null : buffer;
  3130. this.offset = offset === undefined ? 0 : offset;
  3131. this._strides = strides === undefined ? null : strides;
  3132. this.order = order === undefined ? null : order;
  3133. this.flags = {};
  3134. this._read();
  3135. }
  3136. static __new__(cls, shape, dtype, buffer, offset, strides, order) {
  3137. return new cls(shape, dtype, buffer, offset, strides, order);
  3138. }
  3139. __setstate__(state) {
  3140. [this.version, this.shape, this.dtype, this.flags.fn, this.data] = state;
  3141. this._read();
  3142. }
  3143. flatten() {
  3144. const size = this.shape.reduce((a, b) => a * b, 1);
  3145. const value = new numpy.ndarray([size], this.dtype, this.data, this.offset, this.strides, this.order);
  3146. value.flags = this.flags;
  3147. return value;
  3148. }
  3149. reshape(shape, order) {
  3150. return new numpy.ndarray(shape, this.dtype, this.data, this.offset, this.strides, order);
  3151. }
  3152. tobytes() {
  3153. return this.data;
  3154. }
  3155. tolist() {
  3156. if (this.shape.length < 0 || this.shape.length > 1) {
  3157. throw new python.Error(`Unsupported shape '${JSON.stringify(this.shape)}'.`);
  3158. }
  3159. const size = this.shape.reduce((a, b) => a * b, 1);
  3160. const list = new Array(size);
  3161. switch (this.dtype.kind) {
  3162. case 'U': {
  3163. const data = new Uint32Array(new Uint8Array(this.data).buffer);
  3164. const itemsize = this.dtype.itemsize >> 2;
  3165. let offset = 0;
  3166. for (let i = 0; i < size; i++) {
  3167. const buffer = data.subarray(offset, offset + itemsize);
  3168. const index = buffer.indexOf(0);
  3169. list[i] = Array.from(index >= 0 ? buffer.subarray(0, index) : buffer).map((c) => String.fromCodePoint(c)).join('');
  3170. offset += itemsize;
  3171. }
  3172. return list;
  3173. }
  3174. case 'S': {
  3175. const data = this.data;
  3176. const itemsize = this.dtype.itemsize;
  3177. const decoder = new TextDecoder('utf-8');
  3178. let offset = 0;
  3179. for (let i = 0; i < size; i++) {
  3180. const buffer = data.subarray(offset, offset + itemsize);
  3181. const index = buffer.indexOf(0);
  3182. list[i] = decoder.decode(index >= 0 ? buffer.subarray(0, index) : buffer);
  3183. offset += itemsize;
  3184. }
  3185. return list;
  3186. }
  3187. case 'V': {
  3188. const itemsize = this.dtype.itemsize;
  3189. let offset = 0;
  3190. for (let i = 0; i < size; i++) {
  3191. list[i] = this.data.slice(offset, offset + itemsize);
  3192. offset += itemsize;
  3193. }
  3194. return list;
  3195. }
  3196. case 'M': {
  3197. const itemsize = this.dtype.itemsize;
  3198. let offset = 0;
  3199. for (let i = 0; i < size; i++) {
  3200. const buffer = this.data.slice(offset, offset + itemsize);
  3201. list[i] = new numpy.datetime64(buffer);
  3202. offset += itemsize;
  3203. }
  3204. return list;
  3205. }
  3206. case 'T': {
  3207. return this.data;
  3208. }
  3209. case 'O': {
  3210. return this.data;
  3211. }
  3212. default: {
  3213. throw new python.Error(`Type kind '${this.dtype.kind}' not implemented.`);
  3214. }
  3215. }
  3216. }
  3217. get itemsize() {
  3218. return this.dtype.itemsize;
  3219. }
  3220. get size() {
  3221. return (this.shape || []).reduce((a, b) => a * b, 1);
  3222. }
  3223. get strides() {
  3224. if (!this._strides) {
  3225. const shape = this.shape;
  3226. const strides = new Array(shape.length);
  3227. let stride = this.itemsize;
  3228. for (let i = shape.length - 1; i >= 0; i--) {
  3229. strides[i] = stride;
  3230. stride *= shape[i];
  3231. }
  3232. return strides;
  3233. }
  3234. return this._strides;
  3235. }
  3236. _read() {
  3237. if (this.data) {
  3238. const length = this.dtype.itemsize * this.size;
  3239. if (typeof this.data === 'string') {
  3240. this.data = this._unescape(this.data, length);
  3241. if (this.data.length !== length) {
  3242. throw new python.Error('Invalid string array data size.');
  3243. }
  3244. } else if (this.data.length !== length) {
  3245. // throw new python.Error('Invalid array data size.');
  3246. }
  3247. }
  3248. }
  3249. _unescape(token, size) {
  3250. const length = token.length;
  3251. const a = new Uint8Array(length);
  3252. if (size && size === length) {
  3253. for (let p = 0; p < size; p++) {
  3254. a[p] = token.charCodeAt(p);
  3255. }
  3256. return a;
  3257. }
  3258. let i = 0;
  3259. let o = 0;
  3260. while (i < length) {
  3261. let c = token.charCodeAt(i++);
  3262. if (c !== 0x5C || i >= length) {
  3263. a[o++] = c;
  3264. } else {
  3265. c = token.charCodeAt(i++);
  3266. switch (c) {
  3267. case 0x27: a[o++] = 0x27; break; // '
  3268. case 0x5C: a[o++] = 0x5C; break; // \\
  3269. case 0x22: a[o++] = 0x22; break; // "
  3270. case 0x72: a[o++] = 0x0D; break; // \r
  3271. case 0x6E: a[o++] = 0x0A; break; // \n
  3272. case 0x74: a[o++] = 0x09; break; // \t
  3273. case 0x62: a[o++] = 0x08; break; // \b
  3274. case 0x58: // x
  3275. case 0x78: { // X
  3276. const xsi = i - 1;
  3277. const xso = o;
  3278. for (let xi = 0; xi < 2; xi++) {
  3279. if (i >= length) {
  3280. i = xsi;
  3281. o = xso;
  3282. a[o] = 0x5c;
  3283. break;
  3284. }
  3285. let c = token.charCodeAt(i++);
  3286. if (c >= 65 && c <= 70) {
  3287. c -= 55;
  3288. } else if (c >= 97 && c <= 102) {
  3289. c -= 87;
  3290. } else if (c >= 48 && c <= 57) {
  3291. c -= 48;
  3292. } else {
  3293. c = -1;
  3294. }
  3295. if (c === -1) {
  3296. i = xsi;
  3297. o = xso;
  3298. a[o] = 0x5c;
  3299. break;
  3300. }
  3301. a[o] = a[o] << 4 | c;
  3302. }
  3303. o++;
  3304. break;
  3305. }
  3306. default:
  3307. if (c < 48 || c > 57) { // 0-9
  3308. a[o++] = 0x5c;
  3309. a[o++] = c;
  3310. } else {
  3311. i--;
  3312. const osi = i;
  3313. const oso = o;
  3314. for (let oi = 0; oi < 3; oi++) {
  3315. if (i >= length) {
  3316. i = osi;
  3317. o = oso;
  3318. a[o] = 0x5c;
  3319. break;
  3320. }
  3321. const od = token.charCodeAt(i++);
  3322. if (od < 48 || od > 57) {
  3323. i = osi;
  3324. o = oso;
  3325. a[o] = 0x5c;
  3326. break;
  3327. }
  3328. a[o] = a[o] << 3 | od - 48;
  3329. }
  3330. o++;
  3331. }
  3332. break;
  3333. }
  3334. }
  3335. }
  3336. return a.slice(0, o);
  3337. }
  3338. });
  3339. this.registerType('numpy.matrix', class extends numpy.ndarray {
  3340. static __new__(/* subtype, data, dtype, copy */) {
  3341. throw new python.Error("'numpy.matrix.__new__' not implemented.");
  3342. }
  3343. });
  3344. numpy.matrixlib.defmatrix.matrix = numpy.matrix;
  3345. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  3346. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  3347. super(data.shape, data.dtype, data.data);
  3348. }
  3349. });
  3350. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {});
  3351. this.registerType('pandas.core.arrays.categorical.Categorical', class {});
  3352. this.registerType('pandas.core.arrays.base.ExtensionArray', class {});
  3353. this.registerType('pandas.core.arrays.masked.BaseMaskedArray', class extends pandas.core.arrays.base.ExtensionArray {});
  3354. this.registerType('pandas.core.arrays.numeric.NumericArray', class extends pandas.core.arrays.masked.BaseMaskedArray {});
  3355. this.registerType('pandas.core.arrays.datetimes.DatetimeArray', class {
  3356. __setstate__(state) {
  3357. [this._dtype, this._ndarray] = state;
  3358. Object.assign(this, Object.fromEntries(state[2]));
  3359. }
  3360. });
  3361. this.registerType('pandas.core.arrays.timedeltas.TimedeltaArray', class {
  3362. __setstate__(state) {
  3363. [this._dtype, this._ndarray] = state;
  3364. Object.assign(this, Object.fromEntries(state[2]));
  3365. }
  3366. });
  3367. this.registerType('pandas.core.arrays.period.PeriodArray', class {
  3368. __setstate__(state) {
  3369. [this._dtype, this._ndarray] = state;
  3370. Object.assign(this, Object.fromEntries(state[2]));
  3371. }
  3372. });
  3373. this.registerType('pandas.core.arrays.interval.IntervalArray', class {});
  3374. this.registerType('pandas.core.arrays.integer.IntegerArray', class extends pandas.core.arrays.numeric.NumericArray {});
  3375. this.registerType('pandas.core.arrays.integer.Int64Dtype', class {});
  3376. this.registerType('pandas._libs.tslibs.dtypes.PeriodDtypeBase', class {});
  3377. this.registerType('pandas.core.dtypes.dtypes.PeriodDtype', class extends pandas._libs.tslibs.dtypes.PeriodDtypeBase {});
  3378. this.registerType('pandas.core.dtypes.dtypes.IntervalDtype', class {});
  3379. this.registerType('pandas.core.generic.Flags', class {});
  3380. this.registerType('pandas.core.generic.NDFrame', class {
  3381. constructor(data) {
  3382. this._internal_names = ["_mgr", "_item_cache", "_cache", "_name", "_metadata", "_flags"];
  3383. this._metadata = [];
  3384. builtins.object.__setattr__(self, "_mgr", data);
  3385. builtins.object.__setattr__(self, "_attrs", {});
  3386. builtins.object.__setattr__(self, "_flags", new pandas.core.generic.Flags(this, true));
  3387. }
  3388. __setstate__(state) {
  3389. if (state instanceof pandas.core.internals.managers.BlockManager) {
  3390. this._mgr = state;
  3391. } else if (state instanceof builtins.dict) {
  3392. if (state.__contains__('_data') && !state.__contains__('_mgr')) {
  3393. state.__setitem__('_mgr', state.pop('_data'));
  3394. }
  3395. const typ = state.get('_typ');
  3396. if (typ) {
  3397. let attrs = state.get('_attrs', new builtins.dict());
  3398. if (!attrs) {
  3399. attrs = new builtins.dict();
  3400. }
  3401. builtins.object.__setattr__(this, '_attrs', attrs);
  3402. const flags = state.get('_flags', new builtins.dict({ 'allows_duplicate_labels': true }));
  3403. builtins.object.__setattr__(this, '_flags', new pandas.core.generic.Flags(this, flags));
  3404. const meta = new builtins.set(this._internal_names.concat(this._metadata));
  3405. for (const k of meta) {
  3406. if (state.__contains__(k) && k !== '_flags') {
  3407. const v = state.__getitem__(k);
  3408. builtins.object.__setattr__(this, k, v);
  3409. }
  3410. }
  3411. for (const [k, v] of state) {
  3412. if (!meta.has(k)) {
  3413. builtins.object.__setattr__(this, k, v);
  3414. }
  3415. }
  3416. } else {
  3417. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3418. }
  3419. } else if (state.size === 2) {
  3420. throw new python.Error('Pre-0.12 pickles are no longer supported.');
  3421. }
  3422. }
  3423. });
  3424. this.registerType('pandas.core.frame.DataFrame', class extends pandas.core.generic.NDFrame {
  3425. });
  3426. this.registerFunction('pandas.core.indexes.base._new_Index', (cls, d) => {
  3427. return new cls(d);
  3428. });
  3429. this.registerType('pandas.core.indexes.datetimes._new_DatetimeIndex', class {});
  3430. this.registerType('pandas.core.indexes.datetimes.DatetimeIndex', class {});
  3431. this.registerType('pandas.core.indexes.base.Index', class {});
  3432. this.registerType('pandas.core.indexes.range.RangeIndex', class {});
  3433. this.registerType('pandas.core.indexes.multi.MultiIndex', class {});
  3434. this.registerType('pandas.core.indexes.numeric.Int64Index', class {});
  3435. this.registerType('pandas.core.index.Int64Index', class {});
  3436. this.registerFunction('pandas.core.internals.blocks.Block', class {
  3437. });
  3438. this.registerFunction('pandas.core.internals.blocks.NumpyBlock', class extends pandas.core.internals.blocks.Block {
  3439. });
  3440. this.registerFunction('pandas.core.internals.blocks.get_block_type', (/* dtype */) => {
  3441. return pandas.core.internals.blocks.NumpyBlock;
  3442. });
  3443. this.registerFunction('pandas.core.internals.blocks.maybe_coerce_values', (values) => {
  3444. return values;
  3445. });
  3446. this.registerFunction('pandas.core.internals.blocks.new_block', (values, placement, ndim, refs) => {
  3447. const klass = execution.invoke('pandas.core.internals.blocks.get_block_type', [values.dtype]);
  3448. return new klass(values, ndim, placement, refs);
  3449. });
  3450. this.registerType('pandas.core.internals.managers.SingleBlockManager', class {});
  3451. this.registerType('pandas.core.internals.managers.BlockManager', class {});
  3452. this.registerType('pandas.core.series.Series', class {});
  3453. this.registerFunction('pandas._libs.arrays.__pyx_unpickle_NDArrayBacked', (cls, checksum, state) => {
  3454. const obj = new cls();
  3455. if (state && obj.__setstate__) {
  3456. obj.__setstate__(state);
  3457. }
  3458. return obj;
  3459. });
  3460. this.registerFunction('pandas._libs.interval.__pyx_unpickle_IntervalMixin', (cls, checksum, state) => {
  3461. const obj = new cls();
  3462. if (state && obj.__setstate__) {
  3463. obj.__setstate__(state);
  3464. }
  3465. return obj;
  3466. });
  3467. this.registerFunction('pandas._libs.internals._unpickle_block', (values, placement, ndim) => {
  3468. values = pandas.core.internals.blocks.maybe_coerce_values(values);
  3469. // if not isinstance(placement, BlockPlacement):
  3470. // placement = BlockPlacement(placement)
  3471. return pandas.core.internals.blocks.new_block(values, placement, ndim);
  3472. });
  3473. this.registerType('pandas._libs.tslibs.base.ABCTimestamp', class extends datetime.datetime {});
  3474. this.registerType('pandas._libs.tslibs.offsets.BaseOffset', class {});
  3475. this.registerType('pandas._libs.tslibs.offsets.SingleConstructorOffset', class extends pandas._libs.tslibs.offsets.BaseOffset {});
  3476. this.registerType('pandas._libs.tslibs.offsets.Tick', class extends pandas._libs.tslibs.offsets.SingleConstructorOffset {});
  3477. this.registerType('pandas._libs.tslibs.offsets.Day', class extends pandas._libs.tslibs.offsets.Tick {});
  3478. this.registerType('pandas._libs.tslibs.offsets.Minute', class extends datetime.datetime {});
  3479. this.registerFunction('pandas._libs.tslibs.timestamps._unpickle_timestamp');
  3480. this.registerType('pandas._libs.tslibs.timestamps._Timestamp', class extends pandas._libs.tslibs.base.ABCTimestamp {});
  3481. this.registerType('pandas._libs.tslibs.timestamps.Timestamp', class extends pandas._libs.tslibs.timestamps._Timestamp {});
  3482. pandas.indexes.base._new_Index = pandas.core.indexes.base._new_Index;
  3483. pandas.indexes.base.Index = pandas.core.indexes.base.Index;
  3484. pandas.indexes.range.RangeIndex = pandas.core.indexes.range.RangeIndex;
  3485. pandas.core.index.Index = pandas.core.indexes.base.Index;
  3486. pandas.core.index._new_Index = pandas.core.indexes.base._new_Index;
  3487. pandas.core.internals.BlockManager = pandas.core.internals.managers.BlockManager;
  3488. pandas._libs.tslib.Timestamp = pandas._libs.tslibs.timestamps.Timestamp;
  3489. this.registerType('pathlib.Path', class {});
  3490. this.registerType('pathlib._local.PosixPath', class {});
  3491. this.registerType('pathlib._local.WindowsPath', class {});
  3492. const pathlib = this.register('pathlib');
  3493. pathlib.PosixPath = pathlib._local.PosixPath;
  3494. pathlib.WindowsPath = pathlib._local.WindowsPath;
  3495. this.registerType('shap._serializable.Serializable', class {});
  3496. this.registerType('shap.explainers._explainer.Explainer', class extends shap._serializable.Serializable {});
  3497. this.registerType('shap.explainers._linear.LinearExplainer', class extends shap.explainers._explainer.Explainer {});
  3498. shap.explainers.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3499. shap.explainers.linear.LinearExplainer = shap.explainers._linear.LinearExplainer;
  3500. this.registerType('sklearn._loss.link.BaseLink', class {});
  3501. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfBinomialLoss', class {});
  3502. this.registerType('sklearn._loss._loss.__pyx_unpickle_CyHalfMultinomialLoss', class {});
  3503. this.registerType('sklearn._loss._loss.CyLossFunction', class {});
  3504. this.registerType('sklearn._loss._loss.CyHalfBinomialLoss', class {});
  3505. this.registerType('sklearn._loss._loss.CyHalfMultinomialLoss', class {});
  3506. this.registerType('sklearn._loss._loss.CyHalfSquaredError', class extends sklearn._loss._loss.CyLossFunction {});
  3507. this.registerType('sklearn._loss.link.IdentityLink', class extends sklearn._loss.link.BaseLink {});
  3508. this.registerType('sklearn._loss.link.Interval', class {});
  3509. this.registerType('sklearn._loss.link.LogitLink', class {});
  3510. this.registerType('sklearn._loss.link.MultinomialLogit', class extends sklearn._loss.link.BaseLink {});
  3511. this.registerFunction('sklearn._loss._loss.__pyx_unpickle_CyHalfSquaredError');
  3512. this.registerType('sklearn._loss.loss.BaseLoss', class {});
  3513. this.registerType('sklearn._loss.loss.HalfBinomialLoss', class {});
  3514. this.registerType('sklearn._loss.loss.HalfMultinomialLoss', class extends sklearn._loss.loss.BaseLoss {});
  3515. this.registerType('sklearn._loss.loss.HalfSquaredError', class extends sklearn._loss.loss.BaseLoss {});
  3516. this.registerType('sklearn.base.BaseEstimator', class {});
  3517. this.registerType('sklearn.base.TransformerMixin', class {});
  3518. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  3519. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  3520. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  3521. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  3522. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  3523. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  3524. this.registerType('sklearn.cluster._kmeans.MiniBatchKMeans', class {});
  3525. this.registerType('sklearn.cluster.k_means_.MiniBatchKMeans', class {});
  3526. this.registerType('sklearn.compose._column_transformer._RemainderColsList', class {});
  3527. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  3528. this.registerType('sklearn.compose._column_transformer.make_column_selector', class {});
  3529. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  3530. this.registerType('sklearn.cross_decomposition._pls.PLSRegression', class {});
  3531. this.registerType('sklearn.cross_decomposition._pls.CCA', class {});
  3532. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  3533. this.registerType('sklearn.decomposition._incremental_pca.IncrementalPCA', class {});
  3534. this.registerType('sklearn.decomposition._pca.PCA', class {});
  3535. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  3536. this.registerType('sklearn.decomposition.pca.PCA', class {});
  3537. this.registerType('sklearn.decomposition.PCA', class {});
  3538. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  3539. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  3540. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  3541. this.registerType('sklearn.dummy.DummyClassifier', class {});
  3542. this.registerType('sklearn.dummy.DummyRegressor', class {});
  3543. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  3544. this.registerType('sklearn.ensemble._bagging.BaggingRegressor', class {});
  3545. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  3546. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  3547. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  3548. this.registerType('sklearn.ensemble._forest.ExtraTreesRegressor', class {});
  3549. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  3550. this.registerType('sklearn.ensemble._gb_losses.ExponentialLoss', class {});
  3551. this.registerType('sklearn.ensemble._gb_losses.LeastAbsoluteError', class {});
  3552. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  3553. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  3554. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  3555. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  3556. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  3557. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  3558. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingClassifier', class {});
  3559. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  3560. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  3561. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  3562. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  3563. this.registerType('sklearn.ensemble._stacking.StackingRegressor', class {});
  3564. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  3565. this.registerType('sklearn.ensemble._voting.VotingRegressor', class {});
  3566. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  3567. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostRegressor', class {});
  3568. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  3569. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  3570. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  3571. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  3572. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  3573. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  3574. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  3575. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  3576. this.registerType('sklearn.ensemble.voting_classifier.VotingClassifier', class {});
  3577. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  3578. this.registerType('sklearn.feature_extraction._dict_vectorizer.DictVectorizer', class {});
  3579. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  3580. this.registerType('sklearn.feature_extraction._hash.FeatureHasher', class {});
  3581. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  3582. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  3583. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  3584. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  3585. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  3586. this.registerFunction('sklearn.feature_selection._mutual_info.mutual_info_classif');
  3587. this.registerFunction('sklearn.feature_selection._univariate_selection.chi2');
  3588. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  3589. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  3590. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  3591. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  3592. this.registerType('sklearn.feature_selection._rfe.RFE', class {});
  3593. this.registerType('sklearn.feature_selection._rfe.RFECV', class extends sklearn.feature_selection._rfe.RFE {});
  3594. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  3595. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  3596. this.registerType('sklearn.gaussian_process._gpc.GaussianProcessClassifier', class {});
  3597. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  3598. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  3599. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  3600. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  3601. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  3602. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  3603. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  3604. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  3605. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  3606. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  3607. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  3608. this.registerType('sklearn.impute._iterative.IterativeImputer', class {});
  3609. this.registerType('sklearn.impute._iterative._ImputerTriplet', class {});
  3610. this.registerType('sklearn.impute.SimpleImputer', class {});
  3611. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  3612. this.registerType('sklearn.kernel_ridge.KernelRidge', class {});
  3613. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  3614. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  3615. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  3616. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  3617. this.registerType('sklearn.linear_model._coordinate_descent.Lasso', class {});
  3618. this.registerType('sklearn.linear_model._least_angle.LassoLarsCV', class {});
  3619. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  3620. this.registerType('sklearn.linear_model._logistic.LogisticRegressionCV', class {});
  3621. this.registerType('sklearn.linear_model._perceptron.Perceptron', class {});
  3622. this.registerType('sklearn.linear_model._quantile.QuantileRegressor', class {});
  3623. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  3624. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  3625. this.registerType('sklearn.linear_model._ridge.RidgeClassifierCV', class {});
  3626. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  3627. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  3628. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  3629. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  3630. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  3631. this.registerType('sklearn.linear_model._stochastic_gradient.SGDRegressor', class {});
  3632. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  3633. this.registerType('sklearn.linear_model.coordinate_descent.ElasticNet', class {});
  3634. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  3635. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  3636. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  3637. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  3638. this.registerType('sklearn.linear_model.LassoLars​', class {});
  3639. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  3640. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  3641. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  3642. this.registerType('sklearn.manifold._t_sne.TSNE', class {});
  3643. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric', class extends builtins.object {});
  3644. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric32', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3645. this.registerType('sklearn.metrics._dist_metrics.DistanceMetric64', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3646. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3647. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance32', class extends sklearn.metrics._dist_metrics.DistanceMetric32 {});
  3648. this.registerType('sklearn.metrics._dist_metrics.EuclideanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3649. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance', class extends sklearn.metrics._dist_metrics.DistanceMetric {});
  3650. this.registerType('sklearn.metrics._dist_metrics.ManhattanDistance64', class extends sklearn.metrics._dist_metrics.DistanceMetric64 {});
  3651. this.registerType('sklearn.metrics._scorer._PassthroughScorer', class {});
  3652. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  3653. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  3654. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  3655. this.registerType('sklearn.metrics._scorer._Scorer', class {});
  3656. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  3657. this.registerType('sklearn.mixture._gaussian_mixture.GaussianMixture', class {});
  3658. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  3659. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  3660. this.registerType('sklearn.model_selection._split.KFold', class {});
  3661. this.registerType('sklearn.model_selection._split.RepeatedKFold', class {});
  3662. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  3663. this.registerType('sklearn.model_selection._split.StratifiedShuffleSplit', class {});
  3664. this.registerType('sklearn.model_selection._split.TimeSeriesSplit', class {});
  3665. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  3666. this.registerType('sklearn.multioutput.ClassifierChain', class {});
  3667. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  3668. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  3669. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  3670. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  3671. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  3672. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  3673. this.registerType('sklearn.neighbors.ball_tree.BallTree', class {});
  3674. this.registerFunction('sklearn.neighbors.ball_tree.newObj', (obj) => {
  3675. return obj.__new__(obj);
  3676. });
  3677. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  3678. this.registerFunction('sklearn.neighbors._dist_metrics.newObj');
  3679. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  3680. this.registerType('sklearn.neighbors._kd_tree.BinaryTree64', class extends builtins.object {});
  3681. this.registerType('sklearn.neighbors._kd_tree.KDTree64', class extends sklearn.neighbors._kd_tree.BinaryTree64 {});
  3682. this.registerType('sklearn.neighbors._kd_tree.KDTree', class extends sklearn.neighbors._kd_tree.KDTree64 {});
  3683. this.registerFunction('sklearn.neighbors._kd_tree.newObj', (obj) => {
  3684. return obj.__new__(obj);
  3685. });
  3686. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  3687. this.registerType('sklearn.neighbors._unsupervised.NearestNeighbors', class {});
  3688. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  3689. this.registerFunction('sklearn.neighbors.dist_metrics.newObj', (obj) => {
  3690. return obj.__new__(obj);
  3691. });
  3692. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  3693. this.registerFunction('sklearn.neighbors.kd_tree.newObj', (obj) => {
  3694. return obj.__new__(obj);
  3695. });
  3696. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  3697. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  3698. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  3699. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  3700. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  3701. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  3702. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  3703. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  3704. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  3705. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  3706. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  3707. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  3708. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  3709. this.registerType('sklearn.pipeline.Pipeline', class {});
  3710. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  3711. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  3712. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  3713. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  3714. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  3715. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  3716. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  3717. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  3718. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  3719. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  3720. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  3721. this.registerType('sklearn.preprocessing._encoders.OrdinalEncoder', class {});
  3722. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  3723. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  3724. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  3725. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  3726. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  3727. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  3728. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  3729. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  3730. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  3731. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  3732. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  3733. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  3734. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  3735. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  3736. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  3737. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  3738. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  3739. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  3740. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  3741. this.registerType('sklearn.random_projection.GaussianRandomProjection', class {});
  3742. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  3743. this.registerType('sklearn.svm._classes.NuSVC', class {});
  3744. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  3745. this.registerType('sklearn.svm._classes.SVC', class {});
  3746. this.registerType('sklearn.svm._classes.SVR', class {});
  3747. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  3748. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  3749. this.registerType('sklearn.svm.classes.SVC', class {});
  3750. this.registerType('sklearn.svm.classes.SVR', class {});
  3751. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  3752. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  3753. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  3754. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  3755. this.registerType('sklearn.tree._tree.Tree', class {
  3756. constructor(n_features, n_classes, n_outputs) {
  3757. this.n_features = n_features;
  3758. this.n_classes = n_classes;
  3759. this.n_outputs = n_outputs;
  3760. }
  3761. __setstate__(state) {
  3762. this.max_depth = state.get('max_depth');
  3763. this.node_count = state.get('node_count');
  3764. this.nodes = state.get('nodes');
  3765. this.values = state.get('values');
  3766. }
  3767. });
  3768. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  3769. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  3770. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  3771. this.registerType('sklearn.utils._bunch.Bunch', class {});
  3772. this.registerType('sklearn.utils._metadata_requests.MetadataRequest', class {});
  3773. this.registerType('sklearn.utils._metadata_requests.MethodMetadataRequest', class {});
  3774. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  3775. this.registerType('pickle.Unpickler', class {
  3776. constructor(data) {
  3777. this._reader = data instanceof Uint8Array ? new python.BinaryReader(data) : new python.StreamReader(data);
  3778. this.persistent_load = () => {
  3779. throw new python.Error('Unsupported persistent id.');
  3780. };
  3781. }
  3782. load() {
  3783. const reader = this._reader;
  3784. const marker = [];
  3785. let stack = [];
  3786. const memo = {};
  3787. let size = 0;
  3788. while (reader.position < reader.length) {
  3789. const opcode = reader.byte();
  3790. // console.log(`${(reader.position - 1).toString()} ${opcode}`);
  3791. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3792. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3793. switch (opcode) {
  3794. case 128: { // PROTO
  3795. const version = reader.byte();
  3796. if (version > 5) {
  3797. throw new python.Error(`Unsupported protocol version '${version}'.`);
  3798. }
  3799. break;
  3800. }
  3801. case 99: { // GLOBAL 'c'
  3802. const module = reader.line();
  3803. const name = reader.line();
  3804. stack.push(this.find_class(module, name));
  3805. break;
  3806. }
  3807. case 147: { // STACK_GLOBAL '\x93' (Protocol 4)
  3808. const name = stack.pop();
  3809. const module = stack.pop();
  3810. stack.push(this.find_class(module, name));
  3811. break;
  3812. }
  3813. case 111: { // OBJ 'o'
  3814. const args = stack;
  3815. const cls = args.pop();
  3816. stack = marker.pop();
  3817. const obj = this._instantiate(cls, args);
  3818. stack.push(obj);
  3819. break;
  3820. }
  3821. case 112 : { // PUT 'p'
  3822. const index = parseInt(reader.line(), 10);
  3823. if (stack.length === 0) {
  3824. throw new python.Error(`Empty stack during 'PUT' operation.`);
  3825. }
  3826. memo[index] = stack[stack.length - 1];
  3827. size++;
  3828. break;
  3829. }
  3830. case 103: { // GET 'g'
  3831. const index = parseInt(reader.line(), 10);
  3832. if (index in memo === false) {
  3833. throw new python.Error(`Memo value not found at index '${index}'.`);
  3834. }
  3835. stack.push(memo[index]);
  3836. break;
  3837. }
  3838. case 48: // POP '0'
  3839. stack.pop();
  3840. break;
  3841. case 49: // POP_MARK '1'
  3842. stack = marker.pop();
  3843. break;
  3844. case 50: // DUP '2'
  3845. if (stack.length === 0) {
  3846. throw new python.Error(`Empty stack during 'DUP' operation.`);
  3847. }
  3848. stack.push(stack[stack.length - 1]);
  3849. break;
  3850. case 80: // PERSID 'P'
  3851. stack.push(this.persistent_load(reader.line()));
  3852. break;
  3853. case 81: // BINPERSID 'Q'
  3854. stack.push(this.persistent_load(stack.pop()));
  3855. break;
  3856. case 82: { // REDUCE 'R'
  3857. const args = stack.pop();
  3858. const func = stack.pop();
  3859. stack.push(this._reduce(func, args));
  3860. break;
  3861. }
  3862. case 129: { // NEWOBJ
  3863. const args = stack.pop();
  3864. const cls = stack.pop();
  3865. const obj = this._newobj(cls, args);
  3866. stack.push(obj);
  3867. break;
  3868. }
  3869. case 146: { // NEWOBJ_EX '\x92' (Protocol 4)
  3870. const kwargs = stack.pop();
  3871. const args = stack.pop();
  3872. const cls = stack.pop();
  3873. if (Object.entries(kwargs).length > 0) {
  3874. throw new python.Error("Unpickle 'NEWOBJ_EX' not implemented.");
  3875. }
  3876. const obj = this._newobj(cls, args);
  3877. stack.push(obj);
  3878. break;
  3879. }
  3880. case 104: { // BINGET 'h'
  3881. const index = reader.byte();
  3882. if (index in memo === false) {
  3883. throw new python.Error(`Memo value not found at index '${index}'.`);
  3884. }
  3885. stack.push(memo[index]);
  3886. break;
  3887. }
  3888. case 105: { // INST 'i'
  3889. const module = reader.line();
  3890. const name = reader.line();
  3891. const args = stack;
  3892. const cls = `${module}.${name}`;
  3893. stack = marker.pop();
  3894. // cls = this.find_class(module, name)
  3895. const obj = this._instantiate(cls, args);
  3896. stack.push(obj);
  3897. break;
  3898. }
  3899. case 106: { // LONG_BINGET 'j'
  3900. const index = reader.uint32();
  3901. if (index in memo === false) {
  3902. throw new python.Error(`Memo value not found at index '${index}'.`);
  3903. }
  3904. stack.push(memo[index]);
  3905. break;
  3906. }
  3907. case 113: // BINPUT 'q'
  3908. if (stack.length === 0) {
  3909. throw new python.Error(`Empty stack during 'BINPUT' operation.`);
  3910. }
  3911. memo[reader.byte()] = stack[stack.length - 1];
  3912. size++;
  3913. break;
  3914. case 114: // LONG_BINPUT 'r'
  3915. if (stack.length === 0) {
  3916. throw new python.Error(`Empty stack during 'LONG_BINPUT' operation.`);
  3917. }
  3918. memo[reader.uint32()] = stack[stack.length - 1];
  3919. size++;
  3920. break;
  3921. case 74: // BININT 'J'
  3922. stack.push(reader.int32());
  3923. break;
  3924. case 75: // BININT1 'K'
  3925. stack.push(reader.byte());
  3926. break;
  3927. case 76: // LONG 'L'
  3928. stack.push(parseInt(reader.line(), 10));
  3929. break;
  3930. case 77: // BININT2 'M'
  3931. stack.push(reader.uint16());
  3932. break;
  3933. case 66: // BINBYTES 'B' (Protocol 3)
  3934. stack.push(reader.read(reader.int32()));
  3935. break;
  3936. case 67: // SHORT_BINBYTES 'C' (Protocol 3)
  3937. stack.push(reader.read(reader.byte()));
  3938. break;
  3939. case 142: // BINBYTES8 '\x8e' (Protocol 4)
  3940. stack.push(reader.read(reader.int64().toNumber()));
  3941. break;
  3942. case 70: // FLOAT 'F'
  3943. stack.push(parseFloat(reader.line()));
  3944. break;
  3945. case 71: // BINFLOAT 'G'
  3946. stack.push(reader.float64());
  3947. break;
  3948. case 73: { // INT 'I'
  3949. const value = reader.line();
  3950. if (value === '01') {
  3951. stack.push(true);
  3952. } else if (value === '00') {
  3953. stack.push(false);
  3954. } else {
  3955. stack.push(parseInt(value, 10));
  3956. }
  3957. break;
  3958. }
  3959. case 93: // EMPTY_LIST ']'
  3960. stack.push(new builtins.list());
  3961. break;
  3962. case 41: // EMPTY_TUPLE ')'
  3963. stack.push([]);
  3964. break;
  3965. case 143: // EMPTY_SET '\x8f' (Protocol 4)
  3966. stack.push([]);
  3967. break;
  3968. case 144: { // ADDITEMS '\x90' (Protocol 4)
  3969. const items = stack;
  3970. stack = marker.pop();
  3971. const obj = stack[stack.length - 1];
  3972. for (let i = 0; i < items.length; i++) {
  3973. obj.push(items[i]);
  3974. }
  3975. break;
  3976. }
  3977. case 145: { // FROZENSET '\x91' (Protocol 4)
  3978. const items = stack;
  3979. stack = marker.pop();
  3980. stack.push(items);
  3981. break;
  3982. }
  3983. case 100: { // DICT 'd'
  3984. const items = stack;
  3985. stack = marker.pop();
  3986. const dict = new builtins.dict();
  3987. for (let i = 0; i < items.length; i += 2) {
  3988. dict.__setitem__(items[i], items[i + 1]);
  3989. }
  3990. stack.push(dict);
  3991. break;
  3992. }
  3993. case 108: { // LIST 'l'
  3994. const items = stack;
  3995. stack = marker.pop();
  3996. stack.push(items);
  3997. break;
  3998. }
  3999. case 116: { // TUPLE 't'
  4000. const items = stack;
  4001. stack = marker.pop();
  4002. stack.push(items);
  4003. break;
  4004. }
  4005. case 133: { // TUPLE1 // '\x85'
  4006. stack.push([stack.pop()]);
  4007. break;
  4008. }
  4009. case 134: { // TUPLE2 '\x86'
  4010. const b = stack.pop();
  4011. const a = stack.pop();
  4012. stack.push([a, b]);
  4013. break;
  4014. }
  4015. case 135: { // TUPLE3 '\x87'
  4016. const c = stack.pop();
  4017. const b = stack.pop();
  4018. const a = stack.pop();
  4019. stack.push([a, b, c]);
  4020. break;
  4021. }
  4022. case 115: { // SETITEM 's'
  4023. const value = stack.pop();
  4024. const key = stack.pop();
  4025. const obj = stack[stack.length - 1];
  4026. if (obj.__setitem__) {
  4027. obj.__setitem__(key, value);
  4028. } else {
  4029. obj[key] = value;
  4030. }
  4031. break;
  4032. }
  4033. case 117: { // SETITEMS 'u'
  4034. const items = stack;
  4035. stack = marker.pop();
  4036. const obj = stack[stack.length - 1];
  4037. if (obj.__setitem__) {
  4038. for (let i = 0; i < items.length; i += 2) {
  4039. obj.__setitem__(items[i], items[i + 1]);
  4040. }
  4041. } else {
  4042. for (let i = 0; i < items.length; i += 2) {
  4043. obj[items[i]] = items[i + 1];
  4044. }
  4045. }
  4046. break;
  4047. }
  4048. case 125: // EMPTY_DICT '}'
  4049. stack.push(new builtins.dict());
  4050. break;
  4051. case 97: { // APPEND 'a'
  4052. const append = stack.pop();
  4053. stack[stack.length - 1].push(append);
  4054. break;
  4055. }
  4056. case 101: { // APPENDS 'e'
  4057. const appends = stack;
  4058. stack = marker.pop();
  4059. const list = stack[stack.length - 1];
  4060. list.push(...appends);
  4061. break;
  4062. }
  4063. case 83: { // STRING 'S'
  4064. const str = reader.line();
  4065. stack.push(str.substring(1, str.length - 1));
  4066. break;
  4067. }
  4068. case 84: // BINSTRING 'T'
  4069. stack.push(reader.string(reader.uint32()));
  4070. break;
  4071. case 85 : // SHORT_BINSTRING 'U'
  4072. stack.push(reader.string(reader.byte()));
  4073. break;
  4074. case 86: // UNICODE 'V'
  4075. stack.push(reader.line());
  4076. break;
  4077. case 88: // BINUNICODE 'X
  4078. stack.push(reader.string(reader.uint32(), 'utf-8'));
  4079. break;
  4080. case 140: // SHORT_BINUNICODE '\x8c' (Protocol 4)
  4081. stack.push(reader.string(reader.byte(), 'utf-8'));
  4082. break;
  4083. case 98: { // BUILD 'b'
  4084. const state = stack.pop();
  4085. let obj = stack.pop();
  4086. if (obj.__setstate__) {
  4087. if (obj.__setstate__.__call__) {
  4088. obj.__setstate__.__call__([obj, state]);
  4089. } else {
  4090. obj.__setstate__(state);
  4091. }
  4092. } else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  4093. obj.__state__ = state;
  4094. } else if (obj instanceof Map && state instanceof Map) {
  4095. for (const [key, value] of state) {
  4096. obj.set(key, value);
  4097. }
  4098. } else if (obj instanceof Map) {
  4099. /* eslint-disable guard-for-in */
  4100. for (const key in state) {
  4101. obj.set(key, state[key]);
  4102. }
  4103. /* eslint-enable guard-for-in */
  4104. } else if (state instanceof Map) {
  4105. for (const [key, value] of state) {
  4106. obj[key] = value;
  4107. }
  4108. } else {
  4109. Object.assign(obj, state);
  4110. }
  4111. if (obj.__read__) {
  4112. obj = obj.__read__(this);
  4113. }
  4114. stack.push(obj);
  4115. break;
  4116. }
  4117. case 40: // MARK '('
  4118. marker.push(stack);
  4119. stack = [];
  4120. break;
  4121. case 136: // NEWTRUE '\x88'
  4122. stack.push(true);
  4123. break;
  4124. case 137: // NEWFALSE '\x89'
  4125. stack.push(false);
  4126. break;
  4127. case 138: { // LONG1 '\x8a'
  4128. const data = reader.read(reader.byte());
  4129. let number = 0;
  4130. switch (data.length) {
  4131. case 0: number = 0; break;
  4132. case 1: [number] = data; break;
  4133. case 2: number = data[1] << 8 | data[0]; break;
  4134. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  4135. case 4: number = (data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0; break;
  4136. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  4137. default: number = Array.prototype.slice.call(data, 0); break;
  4138. }
  4139. stack.push(number);
  4140. break;
  4141. }
  4142. case 139: // LONG4 '\x8b'
  4143. // decode LONG4
  4144. stack.push(reader.read(reader.uint32()));
  4145. break;
  4146. case 148: // MEMOIZE '\x94' (Protocol 4)
  4147. memo[size++] = stack[stack.length - 1];
  4148. break;
  4149. case 149: // FRAME '\x95' (Protocol 4)
  4150. reader.read(8);
  4151. break;
  4152. case 150: { // BYTEARRAY8 '\x96' (Protocol 5)
  4153. stack.push(reader.read(reader.int64().toNumber()));
  4154. break;
  4155. }
  4156. case 78: // NONE 'N'
  4157. stack.push(null);
  4158. break;
  4159. case 46: // STOP '.'
  4160. return stack.pop();
  4161. case 141: // BINUNICODE8 '\x8d' (Protocol 4)
  4162. case 151: // NEXT_BUFFER '\x97' (Protocol 5)
  4163. case 152: // READONLY_BUFFER '\x98' (Protocol 5)
  4164. default:
  4165. throw new python.Error(`Unknown opcode ${opcode} at position ${(reader.position - 1)}.`);
  4166. }
  4167. }
  4168. throw new python.Error('Unexpected end of file.');
  4169. }
  4170. find_class(module, name) {
  4171. execution.__import__(module);
  4172. return execution.resolve(`${module}.${name}`);
  4173. }
  4174. _instantiate(cls, args) {
  4175. return execution.invoke(cls, args);
  4176. }
  4177. _newobj(cls, args) {
  4178. // cls.__new__(cls, args)
  4179. return execution.invoke(cls, args);
  4180. }
  4181. _reduce(func, args) {
  4182. return execution.invoke(func, args);
  4183. }
  4184. read(size) {
  4185. return this._reader.read(size);
  4186. }
  4187. stream(size) {
  4188. return this._reader.stream(size);
  4189. }
  4190. });
  4191. this.registerType('random.Random', class {});
  4192. this.registerType('re.Pattern', class {
  4193. constructor(pattern, flags) {
  4194. this.pattern = pattern;
  4195. this.flags = flags;
  4196. }
  4197. });
  4198. this.registerType('spacy._ml.PrecomputableAffine', class {
  4199. __setstate__(state) {
  4200. Object.assign(this, new pickle.Unpickler(state).load());
  4201. }
  4202. });
  4203. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  4204. __setstate__(state) {
  4205. Object.assign(this, new pickle.Unpickler(state).load());
  4206. }
  4207. });
  4208. this.registerType('theano.compile.function_module._constructor_Function', class {});
  4209. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  4210. this.registerType('theano.compile.function_module.Function', class {});
  4211. this.registerType('theano.compile.function_module.Supervisor', class {});
  4212. this.registerType('theano.compile.io.In', class {});
  4213. this.registerType('theano.compile.io.SymbolicOutput', class {});
  4214. this.registerType('theano.compile.mode.Mode', class {});
  4215. this.registerType('theano.compile.ops.OutputGuard', class {});
  4216. this.registerType('theano.compile.ops.Shape', class {});
  4217. this.registerType('theano.compile.ops.Shape_i', class {});
  4218. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  4219. this.registerType('theano.gof.fg.FunctionGraph', class {});
  4220. this.registerType('theano.gof.graph.Apply', class {});
  4221. this.registerType('theano.gof.link.Container', class {});
  4222. this.registerType('theano.gof.opt._metadict', class {});
  4223. this.registerType('theano.gof.opt.ChangeTracker', class {});
  4224. this.registerType('theano.gof.opt.MergeFeature', class {});
  4225. this.registerType('theano.gof.optdb.Query', class {});
  4226. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  4227. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  4228. this.registerType('theano.gof.utils.scratchpad', class {});
  4229. this.registerType('theano.misc.ordered_set.Link', class {});
  4230. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  4231. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  4232. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  4233. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  4234. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  4235. this.registerType('theano.scalar.basic.Abs', class {});
  4236. this.registerType('theano.scalar.basic.Add', class {});
  4237. this.registerType('theano.scalar.basic.Cast', class {});
  4238. this.registerType('theano.scalar.basic.Composite', class {});
  4239. this.registerType('theano.scalar.basic.EQ', class {});
  4240. this.registerType('theano.scalar.basic.GE', class {});
  4241. this.registerType('theano.scalar.basic.Identity', class {});
  4242. this.registerType('theano.scalar.basic.IntDiv', class {});
  4243. this.registerType('theano.scalar.basic.Inv', class {});
  4244. this.registerType('theano.scalar.basic.LE', class {});
  4245. this.registerType('theano.scalar.basic.LT', class {});
  4246. this.registerType('theano.scalar.basic.Mul', class {});
  4247. this.registerType('theano.scalar.basic.Neg', class {});
  4248. this.registerType('theano.scalar.basic.Pow', class {});
  4249. this.registerType('theano.scalar.basic.Scalar', class {});
  4250. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  4251. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  4252. this.registerType('theano.scalar.basic.Second', class {});
  4253. this.registerType('theano.scalar.basic.Sgn', class {});
  4254. this.registerType('theano.scalar.basic.specific_out', class {});
  4255. this.registerType('theano.scalar.basic.Sub', class {});
  4256. this.registerType('theano.scalar.basic.Switch', class {});
  4257. this.registerType('theano.scalar.basic.Tanh', class {});
  4258. this.registerType('theano.scalar.basic.transfer_type', class {});
  4259. this.registerType('theano.scalar.basic.TrueDiv', class {});
  4260. this.registerType('theano.tensor.basic.Alloc', class {});
  4261. this.registerType('theano.tensor.basic.Dot', class {});
  4262. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  4263. this.registerType('theano.tensor.basic.Reshape', class {});
  4264. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  4265. this.registerType('theano.tensor.blas.Dot22', class {});
  4266. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  4267. this.registerType('theano.tensor.blas.Gemm', class {});
  4268. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  4269. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  4270. this.registerType('theano.tensor.elemwise.Sum', class {});
  4271. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  4272. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  4273. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  4274. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  4275. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  4276. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  4277. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  4278. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  4279. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  4280. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  4281. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  4282. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  4283. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  4284. this.registerType('theano.tensor.opt.MakeVector', class {});
  4285. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  4286. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  4287. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  4288. this.registerType('theano.tensor.signal.pool.Pool', class {});
  4289. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  4290. this.registerType('theano.tensor.type.TensorType', class {});
  4291. this.registerType('theano.tensor.var.TensorConstant', class {});
  4292. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  4293. this.registerType('theano.tensor.var.TensorVariable', class {});
  4294. this.registerType('thinc.describe.Biases', class {});
  4295. this.registerType('thinc.describe.Dimension', class {});
  4296. this.registerType('thinc.describe.Gradient', class {});
  4297. this.registerType('thinc.describe.Weights', class {});
  4298. this.registerType('thinc.describe.Synapses', class {});
  4299. this.registerType('thinc.neural._classes.affine.Affine', class {
  4300. __setstate__(state) {
  4301. Object.assign(this, new pickle.Unpickler(state).load());
  4302. }
  4303. });
  4304. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  4305. __setstate__(state) {
  4306. Object.assign(this, new pickle.Unpickler(state).load());
  4307. }
  4308. });
  4309. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  4310. __setstate__(state) {
  4311. Object.assign(this, new pickle.Unpickler(state).load());
  4312. }
  4313. });
  4314. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  4315. __setstate__(state) {
  4316. Object.assign(this, new pickle.Unpickler(state).load());
  4317. }
  4318. });
  4319. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  4320. __setstate__(state) {
  4321. Object.assign(this, new pickle.Unpickler(state).load());
  4322. }
  4323. });
  4324. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  4325. __setstate__(state) {
  4326. Object.assign(this, new pickle.Unpickler(state).load());
  4327. }
  4328. });
  4329. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  4330. __setstate__(state) {
  4331. Object.assign(this, new pickle.Unpickler(state).load());
  4332. }
  4333. });
  4334. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  4335. __setstate__(state) {
  4336. Object.assign(this, new pickle.Unpickler(state).load());
  4337. }
  4338. });
  4339. this.registerType('thinc.neural._classes.resnet.Residual', class {
  4340. __setstate__(state) {
  4341. Object.assign(this, new pickle.Unpickler(state).load());
  4342. }
  4343. });
  4344. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  4345. __setstate__(state) {
  4346. Object.assign(this, new pickle.Unpickler(state).load());
  4347. }
  4348. });
  4349. this.registerType('thinc.neural.mem.Memory', class {
  4350. });
  4351. this.registerType('thinc.neural.ops.NumpyOps', class {
  4352. });
  4353. this.registerType('__main__.BYOLState', class {
  4354. constructor(dict) {
  4355. Object.assign(this, dict);
  4356. }
  4357. });
  4358. const types = this.register('types');
  4359. this.registerType('types.GenericAlias', class {});
  4360. this.registerType('types.SimpleNamespace', class {});
  4361. this.registerType('types.BuiltinFunctionType', class {});
  4362. this.registerType('types.BuiltinMethodType', class {});
  4363. this.registerFunction('types.resolve_bases', (bases) => {
  4364. return bases;
  4365. });
  4366. this.registerFunction('types.prepare_class', (name, bases, kwds) => {
  4367. if (kwds) {
  4368. kwds = new builtins.dict(kwds);
  4369. } else {
  4370. kwds = new builtins.dict();
  4371. }
  4372. let meta = null;
  4373. if (kwds.__contains__('metaclass')) {
  4374. meta = kwds.pop('metaclass');
  4375. } else if (bases && bases.length > 0) {
  4376. meta = builtins.type(bases[0]);
  4377. } else {
  4378. meta = builtins.type;
  4379. }
  4380. if (meta instanceof builtins.type) {
  4381. meta = types._calculate_meta(meta, bases);
  4382. }
  4383. let ns = null;
  4384. if (builtins.hasattr(meta, '__prepare__')) {
  4385. // ns = meta.__prepare__(name, bases, **kwds)
  4386. } else {
  4387. ns = new builtins.dict();
  4388. }
  4389. return [meta, ns, kwds];
  4390. });
  4391. this.registerFunction('types._calculate_meta', (meta /*, bases*/) => {
  4392. const winner = meta;
  4393. return winner;
  4394. });
  4395. this.registerFunction('types.new_class', (name, bases, kwds, exec_body) => {
  4396. const resolved_bases = types.resolve_bases(bases);
  4397. const [meta, ns] = types.prepare_class(name, bases, kwds);
  4398. if (exec_body) {
  4399. exec_body(ns);
  4400. }
  4401. return new meta(name, resolved_bases, ns);
  4402. });
  4403. types.ObjectType = builtins.object;
  4404. types.ModuleType = builtins.module;
  4405. types.MethodType = builtins.method;
  4406. types.FunctionType = builtins.function;
  4407. types.TypeType = builtins.type;
  4408. types.CodeType = builtins.code;
  4409. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  4410. this.registerType('xgboost.core.Booster', class {
  4411. load_model(fname) {
  4412. if (fname instanceof Uint8Array) {
  4413. // XGBoosterLoadModel()
  4414. } else {
  4415. // XGBoosterUnserializeFromBuffer(handle) {
  4416. }
  4417. }
  4418. __setstate__(state) {
  4419. const handle = state.get('handle');
  4420. if (handle) {
  4421. this.handle = handle;
  4422. // XGBoosterLoadModelFromBuffer()
  4423. }
  4424. }
  4425. });
  4426. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  4427. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  4428. this.registerType('xgboost.sklearn.XGBRFClassifier', class {});
  4429. this.registerFunction('_codecs.encode', (obj, encoding) => {
  4430. return new builtins.bytearray(obj, encoding);
  4431. });
  4432. this.registerType('builtins.bytearray', class extends Uint8Array {
  4433. constructor(source, encoding /*, errors */) {
  4434. source = builtins.bytes.__encode__(source, encoding);
  4435. super(Number.isInteger(source) ? source : source.length);
  4436. if (Array.isArray(source)) {
  4437. for (let i = 0; i < source.length; i++) {
  4438. this[i] = source;
  4439. }
  4440. } else if (source instanceof Uint8Array) {
  4441. this.set(source, 0);
  4442. } else if (typeof source === 'string') {
  4443. for (let i = 0; i < source.length; i++) {
  4444. this[i] = source.charCodeAt(i);
  4445. }
  4446. }
  4447. }
  4448. static __encode__(source, encoding) {
  4449. if (source === undefined) {
  4450. return 0;
  4451. }
  4452. if (Number.isInteger(source)) {
  4453. return source;
  4454. }
  4455. if (Array.isArray(source) || source instanceof Uint8Array) {
  4456. return source;
  4457. }
  4458. if (typeof source === 'string') {
  4459. switch (encoding) {
  4460. case 'latin1':
  4461. case 'latin-1':
  4462. return source;
  4463. case 'utf8':
  4464. case 'utf-8':
  4465. return new TextEncoder('utf-8').encode(source);
  4466. case undefined:
  4467. throw new python.Error('Unsupported string argument without an encoding.');
  4468. default:
  4469. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4470. }
  4471. }
  4472. throw new python.Error('Unsupported source.');
  4473. }
  4474. });
  4475. this.registerType('builtins.bytes', class extends Uint8Array {
  4476. constructor(source, encoding /*, errors */) {
  4477. source = builtins.bytes.__encode__(source, encoding);
  4478. super(Number.isInteger(source) ? source : source.length);
  4479. if (Array.isArray(source)) {
  4480. for (let i = 0; i < source.length; i++) {
  4481. this[i] = source;
  4482. }
  4483. } else if (source instanceof Uint8Array) {
  4484. this.set(source, 0);
  4485. } else if (typeof source === 'string') {
  4486. for (let i = 0; i < source.length; i++) {
  4487. this[i] = source.charCodeAt(i);
  4488. }
  4489. }
  4490. }
  4491. static __encode__(source, encoding) {
  4492. if (source === undefined) {
  4493. return 0;
  4494. }
  4495. if (Number.isInteger(source)) {
  4496. return source;
  4497. }
  4498. if (Array.isArray(source) || source instanceof Uint8Array) {
  4499. return source;
  4500. }
  4501. if (typeof source === 'string') {
  4502. switch (encoding) {
  4503. case 'latin1':
  4504. case 'latin-1':
  4505. return source;
  4506. case 'utf8':
  4507. case 'utf-8':
  4508. return new TextEncoder('utf-8').encode(source);
  4509. case undefined:
  4510. throw new python.Error('Unsupported string argument without an encoding.');
  4511. default:
  4512. throw new python.Error(`Unsupported encoding '${encoding}'.`);
  4513. }
  4514. }
  4515. throw new python.Error('Unsupported source.');
  4516. }
  4517. });
  4518. this.registerType('builtins.memoryview', class {
  4519. constructor(buf) {
  4520. this._buf = buf;
  4521. }
  4522. get nbytes() {
  4523. return this._buf.length;
  4524. }
  4525. });
  4526. this.registerType('builtins.frozenset', class extends Set {
  4527. constructor(iterable) {
  4528. super();
  4529. if (iterable) {
  4530. for (const item of iterable) {
  4531. this.add(item);
  4532. }
  4533. }
  4534. }
  4535. });
  4536. this.registerFunction('builtins.exec');
  4537. this.registerFunction('builtins.issubclass', (obj, type) => {
  4538. const name = `${type.__module__}.${type.__name__}`;
  4539. if (obj.__module__ && obj.__name__) {
  4540. if (name === `${obj.__module__}.${obj.__name__}`) {
  4541. return true;
  4542. }
  4543. }
  4544. if (obj.__bases__) {
  4545. for (const base of obj.__bases__) {
  4546. if (builtins.issubclass(base, type)) {
  4547. return true;
  4548. }
  4549. }
  4550. }
  4551. return false;
  4552. });
  4553. this.registerFunction('builtins.isinstance', (obj, type) => {
  4554. if (obj && type && obj instanceof type) {
  4555. return true;
  4556. }
  4557. if (obj && obj.__class__) {
  4558. return builtins.issubclass(obj.__class__, type);
  4559. }
  4560. return false;
  4561. });
  4562. this.registerFunction('builtins.hasattr', (obj, name) => {
  4563. if (obj instanceof Map && obj.__contains__) {
  4564. return obj.__contains__(name);
  4565. }
  4566. return Object.prototype.hasOwnProperty.call(obj, name);
  4567. });
  4568. this.registerFunction('builtins.getattr', (obj, name, defaultValue) => {
  4569. if (obj && obj.__getattr__) {
  4570. return obj.__getattr__(name);
  4571. }
  4572. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  4573. return obj[name];
  4574. }
  4575. return defaultValue;
  4576. });
  4577. this.registerFunction('builtins.len', (obj) => {
  4578. return obj.length;
  4579. });
  4580. this.registerFunction('builtins.setattr', (obj, name, value) => {
  4581. if (obj && obj.__setattr__) {
  4582. obj.__setattr__(name, value);
  4583. } else {
  4584. obj[name] = value;
  4585. }
  4586. });
  4587. this.registerType('builtins.set', class extends Set {
  4588. __contains__(item) {
  4589. return this.has(item);
  4590. }
  4591. update(iterable) {
  4592. for (const item of iterable) {
  4593. this.add(item);
  4594. }
  4595. }
  4596. });
  4597. this.registerType('builtins.slice', class {
  4598. constructor(start, stop, step) {
  4599. this.start = start;
  4600. this.stop = stop;
  4601. this.step = step;
  4602. }
  4603. });
  4604. this.registerFunction('builtins.hash');
  4605. this.registerType('functools.partial', class {});
  4606. this.registerFunction('functools.reduce', (func, iterable, ...args) => {
  4607. const iter = Array.from(iterable);
  4608. let acc = args.length > 0 ? args[0] : iter.shift();
  4609. for (const item of iter) {
  4610. acc = func(acc, item);
  4611. }
  4612. return acc;
  4613. });
  4614. builtins.reduce = functools.reduce;
  4615. this.registerFunction('cloudpickle.cloudpickle._builtin_type', (name) => {
  4616. return name;
  4617. });
  4618. this.registerFunction('cloudpickle.cloudpickle._fill_function');
  4619. this.registerType('cloudpickle.cloudpickle._empty_cell_value', class {});
  4620. this.registerFunction('cloudpickle.cloudpickle._make_cell', (value) => {
  4621. value = value || cloudpickle.cloudpickle._empty_cell_value;
  4622. const cell = cloudpickle.cloudpickle._make_empty_cell();
  4623. if (value !== cloudpickle.cloudpickle._empty_cell_value) {
  4624. cell.cell_contents = value;
  4625. }
  4626. return cell;
  4627. });
  4628. this.registerFunction('cloudpickle.cloudpickle._make_function', (code, globals, name, argdefs, closure) => {
  4629. // globals["__builtins__"] = __builtins__
  4630. return new types.FunctionType(code, globals, name, argdefs, closure);
  4631. });
  4632. this.registerFunction('cloudpickle.cloudpickle._make_skel_func');
  4633. cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID = new builtins.dict();
  4634. this.registerFunction('cloudpickle.cloudpickle._lookup_class_or_track', (class_tracker_id, class_def) => {
  4635. if (class_tracker_id) {
  4636. class_def = cloudpickle.cloudpickle._DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(class_tracker_id, class_def);
  4637. }
  4638. return class_def;
  4639. });
  4640. this.registerFunction('cloudpickle.cloudpickle._make_skeleton_class', (type_constructor, name, bases, type_kwargs, class_tracker_id /*, extra */) => {
  4641. // https://github.com/ray-project/ray/blob/5cd8967f1c0c16d3ae5fedb8449d0d25dd4f9f3e/python/ray/cloudpickle/cloudpickle.py#L523
  4642. const kwds = { 'metaclass': type_constructor };
  4643. const skeleton_class = types.new_class(name, bases, kwds, (ns) => ns.update(type_kwargs));
  4644. return cloudpickle.cloudpickle._lookup_class_or_track(class_tracker_id, skeleton_class);
  4645. });
  4646. this.registerFunction('cloudpickle.cloudpickle._make_empty_cell', () => {
  4647. return new builtins.cell();
  4648. });
  4649. this.registerFunction('cloudpickle.cloudpickle._class_setstate', (obj, state) => {
  4650. [state] = state;
  4651. let registry = null;
  4652. for (const [attrname, attr] of state.items()) {
  4653. if (attrname === '_abc_impl') {
  4654. registry = attr;
  4655. } else {
  4656. builtins.setattr(obj, attrname, attr);
  4657. }
  4658. }
  4659. if (sys.version_info >= (3, 13) && state.__contains__('__firstlineno__')) {
  4660. obj.__firstlineno__ = state.get('__firstlineno__');
  4661. }
  4662. if (registry) {
  4663. for (const subclass of registry) {
  4664. obj.register(subclass);
  4665. }
  4666. }
  4667. return obj;
  4668. });
  4669. this.registerFunction('cloudpickle.cloudpickle._function_setstate', (obj, state) => {
  4670. const [, slotstate] = state;
  4671. [state] = state;
  4672. // obj.__dict__.update(state)
  4673. /* const obj_globals = */ slotstate.pop('__globals__');
  4674. const obj_closure = slotstate.pop('__closure__');
  4675. slotstate.pop('_cloudpickle_submodules');
  4676. if (obj.__globals__) {
  4677. // obj.__globals__.update(obj_globals);
  4678. // obj.__globals__.__builtins__ = __builtins__;
  4679. }
  4680. if (obj_closure) {
  4681. // let value = null;
  4682. for (let i = 0; i < obj_closure.length; i++) {
  4683. // const cell = obj_closure[i];
  4684. try {
  4685. // value = cell.cell_contents;
  4686. } catch {
  4687. // cell is empty
  4688. }
  4689. // obj.__closure__[i].cell_contents = value;
  4690. }
  4691. }
  4692. for (const [k, v] of slotstate.items()) {
  4693. builtins.setattr(obj, k, v);
  4694. }
  4695. });
  4696. this.registerFunction('cloudpickle.cloudpickle.subimport', (name) => {
  4697. execution.__import__(name);
  4698. return sys.modules.get(name);
  4699. });
  4700. this.registerFunction('cloudpickle.cloudpickle_fast._class_setstate');
  4701. this.registerFunction('cloudpickle.cloudpickle_fast._function_setstate');
  4702. const ray = this.register('ray');
  4703. this.register('ray.cloudpickle.cloudpickle');
  4704. this.register('ray.cloudpickle.cloudpickle_fast');
  4705. ray.cloudpickle.cloudpickle._builtin_type = cloudpickle.cloudpickle._builtin_type;
  4706. ray.cloudpickle.cloudpickle._fill_function = cloudpickle.cloudpickle._fill_function;
  4707. ray.cloudpickle.cloudpickle._make_cell = cloudpickle.cloudpickle._make_cell;
  4708. ray.cloudpickle.cloudpickle._make_function = cloudpickle.cloudpickle._make_function;
  4709. ray.cloudpickle.cloudpickle._make_skel_func = cloudpickle.cloudpickle._make_skel_func;
  4710. ray.cloudpickle.cloudpickle._make_skeleton_class = cloudpickle.cloudpickle._make_skeleton_class;
  4711. ray.cloudpickle.cloudpickle._make_empty_cell = cloudpickle.cloudpickle._make_empty_cell;
  4712. ray.cloudpickle.cloudpickle._empty_cell_value = cloudpickle.cloudpickle._empty_cell_value;
  4713. ray.cloudpickle.cloudpickle._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4714. ray.cloudpickle.cloudpickle._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4715. ray.cloudpickle.cloudpickle._lookup_class_or_track = cloudpickle.cloudpickle._lookup_class_or_track;
  4716. ray.cloudpickle.cloudpickle_fast._class_setstate = cloudpickle.cloudpickle._class_setstate;
  4717. ray.cloudpickle.cloudpickle_fast._function_setstate = cloudpickle.cloudpickle._function_setstate;
  4718. this.registerType('ray.rllib.algorithms.ppo.ppo.PPO', class {});
  4719. this.registerType('ray.rllib.algorithms.ppo.ppo.PPOConfig', class {});
  4720. this.registerType('ray.rllib.algorithms.algorithm_config.AlgorithmConfig', class {});
  4721. this.registerFunction('ray.rllib.algorithms.algorithm_config.AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN');
  4722. this.registerType('ray.rllib.algorithms.algorithm_config.TorchCompileWhatToCompile', class {});
  4723. this.registerType('ray.rllib.evaluation.collectors.simple_list_collector.SimpleListCollector', class {});
  4724. this.registerType('ray.rllib.callbacks.callbacks.RLlibCallback', class {});
  4725. this.registerType('ray.rllib.core.learner.learner.TorchCompileWhatToCompile', class {});
  4726. this.registerType('ray.rllib.policy.policy.PolicySpec', class {});
  4727. this.registerType('ray.rllib.policy.sample_batch.SampleBatch', class {});
  4728. this.registerType('ray.rllib.utils.metrics.stats.mean.MeanStats', class {});
  4729. this.registerType('ray.rllib.utils.metrics.stats.ema.EmaStats', class {});
  4730. this.registerType('ray.rllib.utils.metrics.stats.min.MinStats', class {});
  4731. this.registerType('ray.rllib.utils.metrics.stats.max.MaxStats', class {});
  4732. this.registerType('ray.rllib.utils.metrics.stats.sum.SumStats', class {});
  4733. this.registerType('ray.rllib.utils.metrics.stats.lifetime_sum.LifetimeSumStats', class {});
  4734. this.registerType('ray.rllib.utils.metrics.stats.percentiles.PercentilesStats', class {});
  4735. this.registerType('ray.rllib.utils.metrics.stats.item.ItemStats', class {});
  4736. this.registerType('ray.rllib.utils.metrics.stats.item_series.ItemSeriesStats', class {});
  4737. this.registerType('collections.Counter', class {});
  4738. this.registerFunction('collections.defaultdict', (/* default_factory */) => {
  4739. return {};
  4740. });
  4741. this.registerFunction('copy.deepcopy');
  4742. this.registerFunction('copy_reg._reconstructor', (cls, base, state) => {
  4743. // copyreg._reconstructor in Python 3
  4744. if (base === '__builtin__.object' || base === builtins.object) {
  4745. return self.invoke(cls, []);
  4746. } else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  4747. const obj = self.invoke(cls, []);
  4748. for (let i = 0; i < state.length; i++) {
  4749. obj[i] = state[i];
  4750. }
  4751. return obj;
  4752. }
  4753. throw new python.Error(`Unsupported copy_reg._reconstructor base type '${base}'.`);
  4754. });
  4755. this.registerFunction('copy.deepcopy', (/* x */) => {
  4756. throw new python.Error('Unsupported copy.deepcopy().');
  4757. });
  4758. this.registerFunction('dill._dill._create_array', (f, args, state, npdict) => {
  4759. const array = f(...args);
  4760. if (array.__setstate__) {
  4761. array.__setstate__(state);
  4762. }
  4763. if (npdict) {
  4764. throw new python.Error("'dill._dill._create_array::npdict' not implemented.");
  4765. }
  4766. return array;
  4767. });
  4768. this.registerFunction('dill._dill._create_cell', (/* args */) => {
  4769. return function() {
  4770. };
  4771. });
  4772. this.registerFunction('dill._dill._create_code', (args) => {
  4773. return self.invoke('types.CodeType', [args]);
  4774. });
  4775. this.registerFunction('dill._dill._create_function', (/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) => {
  4776. return function() {
  4777. };
  4778. });
  4779. this.registerFunction('dill._dill._create_namedtuple', (name, fieldnames, modulename /*, defaults */) => {
  4780. const obj = execution.invoke('dill._dill._import_module', [`${modulename}.${name}`]);
  4781. if (obj) {
  4782. return obj;
  4783. }
  4784. return undefined;
  4785. });
  4786. this.registerFunction('dill._dill._create_type', (typeobj, ...args) => {
  4787. const [name, bases, dict] = args;
  4788. const type = class extends bases[0] {};
  4789. const identifier = dict.__contains__('__module__') ? `${dict.__getitem__('__module__')}.${name}` : name;
  4790. return self.registerType(identifier, Object.assign(type, dict));
  4791. });
  4792. this.registerFunction('dill._dill._eval_repr');
  4793. this.registerFunction('dill._dill._get_attr', (self, name) => {
  4794. if (Object.prototype.hasOwnProperty.call(self, name)) {
  4795. return self[name];
  4796. }
  4797. return undefined;
  4798. });
  4799. this.registerFunction('dill._dill._import_module', (import_name, safe) => {
  4800. try {
  4801. if (import_name.startsWith('__runtime__.')) {
  4802. return execution.module(import_name);
  4803. } else if (import_name.indexOf('.') === -1) {
  4804. return execution.__import__(import_name);
  4805. }
  4806. return execution.resolve(import_name);
  4807. } catch (error) {
  4808. if (safe) {
  4809. return null;
  4810. }
  4811. throw error;
  4812. }
  4813. });
  4814. this.registerFunction('dill._dill._load_type', (name) => {
  4815. const _dill = self.register('dill._dill');
  4816. if (!_dill._reverse_typemap) {
  4817. _dill._reverse_typemap = new Map();
  4818. for (const name of ['__builtin__', 'types']) {
  4819. const module = self.register(name);
  4820. for (const [name, obj] of Object.entries(module)) {
  4821. if (obj.__module__ === 'builtins' && obj.__class__ === builtins.type) {
  4822. _dill._reverse_typemap.set(name, obj);
  4823. }
  4824. }
  4825. }
  4826. _dill._reverse_typemap.set('PartialType', functools.partial);
  4827. _dill._reverse_typemap.set('CellType', builtins.cell);
  4828. }
  4829. if (!_dill._reverse_typemap.has(name)) {
  4830. throw new python.Error(`Unknown type name '${name}' in 'dill._dill._load_type'.`);
  4831. }
  4832. return _dill._reverse_typemap.get(name);
  4833. });
  4834. this.registerFunction('dill._dill.loads');
  4835. this.registerFunction('jax._src.array._reconstruct_array', (fun, args, arr_state, aval_state) => {
  4836. const np_value = fun(...args);
  4837. np_value.__setstate__(arr_state);
  4838. const jnp_value = jax.device_put(np_value);
  4839. jnp_value.aval = jnp_value.aval.update(aval_state);
  4840. return jnp_value;
  4841. });
  4842. jax._src.device_array.reconstruct_device_array = jax._src.array._reconstruct_array;
  4843. this.registerFunction('jax.device_put', (x) => {
  4844. const aval = new jax._src.core.ShapedArray(x.shape, x.dtype);
  4845. return new jax.Array(aval, x.data);
  4846. });
  4847. this.registerType('jax._src.core.AbstractValue', class {});
  4848. this.registerType('jax._src.core.UnshapedArray', class extends jax._src.core.AbstractValue {});
  4849. this.registerType('jax._src.core.ShapedArray', class extends jax._src.core.UnshapedArray {
  4850. constructor(shape, dtype, weak_type) {
  4851. super();
  4852. this.shape = shape;
  4853. this.dtype = dtype;
  4854. this.weak_type = weak_type || false;
  4855. }
  4856. update(dict) {
  4857. const shape = dict.get('shape') || this.shape;
  4858. const dtype = dict.get('dtype') || this.dtype;
  4859. const weak_type = dict.get('weak_type') || this.weak_type;
  4860. return new jax._src.core.ShapedArray(shape, dtype, weak_type);
  4861. }
  4862. });
  4863. this.registerType('jax.Array', class {
  4864. constructor(aval, data) {
  4865. this.aval = aval;
  4866. this.data = data;
  4867. }
  4868. get dtype() {
  4869. return this.aval.dtype;
  4870. }
  4871. get shape() {
  4872. return this.aval.shape;
  4873. }
  4874. tobytes() {
  4875. return this.data;
  4876. }
  4877. });
  4878. jax.numpy.ndarray = jax.Array;
  4879. this.registerFunction('keras.saving.pickle_utils.deserialize_model_from_bytecode', (/* serialized_model */) => {
  4880. return null; // throw new python.Error("'keras.saving.pickle_utils.deserialize_model_from_bytecode' not implemented.");
  4881. });
  4882. this.registerFunction('keras.src.saving.pickle_utils.deserialize_model_from_bytecode', keras.saving.pickle_utils.deserialize_model_from_bytecode);
  4883. this.registerFunction('lasagne.nonlinearities.rectify');
  4884. this.registerFunction('lasagne.nonlinearities.softmax');
  4885. this.registerFunction('lasagne.objectives.categorical_crossentropy');
  4886. this.registerFunction('lasagne.updates.nesterov_momentum');
  4887. this.registerFunction('msgpack.unpackb', (packed, ext_hook) => {
  4888. const BinaryReader = class {
  4889. constructor(buffer, ext_hook) {
  4890. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  4891. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  4892. this._buffer = buffer;
  4893. this._position = 0;
  4894. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  4895. this._ext_hook = ext_hook;
  4896. }
  4897. value() {
  4898. const c = this._view.getUint8(this.skip(1));
  4899. if (c >= 0xe0) {
  4900. return c - 0x100;
  4901. }
  4902. if (c < 0xC0) {
  4903. if (c < 0x80) {
  4904. return c;
  4905. }
  4906. if (c < 0x90) {
  4907. return this.map(c - 0x80);
  4908. }
  4909. if (c < 0xa0) {
  4910. return this.array(c - 0x90);
  4911. }
  4912. return this.string(c - 0xa0);
  4913. }
  4914. switch (c) {
  4915. case 0xC0: return null;
  4916. case 0xC2: return false;
  4917. case 0xC3: return true;
  4918. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  4919. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  4920. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  4921. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  4922. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  4923. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  4924. case 0xCA: return this._view.getFloat32(this.skip(4));
  4925. case 0xCB: return this._view.getFloat64(this.skip(8));
  4926. case 0xCC: return this._view.getUint8(this.skip(1));
  4927. case 0xCD: return this._view.getUint16(this.skip(2));
  4928. case 0xCE: return this._view.getUint32(this.skip(4));
  4929. case 0xCF: return this._view.getBitUint64(this.skip(8));
  4930. case 0xD0: return this._view.getInt8(this.skip(1));
  4931. case 0xD1: return this._view.getInt16(this.skip(2));
  4932. case 0xD2: return this._view.getInt32(this.skip(4));
  4933. case 0xD3: return this._view.getBigInt64(this.skip(8));
  4934. case 0xD4: return this.extension(1);
  4935. case 0xD5: return this.extension(2);
  4936. case 0xD6: return this.extension(4);
  4937. case 0xD7: return this.extension(8);
  4938. case 0xD8: return this.extension(16);
  4939. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  4940. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  4941. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  4942. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  4943. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  4944. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  4945. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  4946. default: throw new python.Error(`Invalid code '${c}'.`);
  4947. }
  4948. }
  4949. map(size) {
  4950. const map = {};
  4951. for (let i = 0; i < size; i++) {
  4952. const key = this.value();
  4953. const value = this.value();
  4954. map[key] = value;
  4955. }
  4956. return map;
  4957. }
  4958. array(size) {
  4959. const array = new Array(size);
  4960. for (let i = 0; i < size; i++) {
  4961. array[i] = this.value();
  4962. }
  4963. return array;
  4964. }
  4965. extension(size) {
  4966. const code = this._view.getUint8(this.skip(1));
  4967. const data = this.read(size);
  4968. return this._ext_hook(code, data);
  4969. }
  4970. skip(offset) {
  4971. const position = this._position;
  4972. this._position += offset;
  4973. if (this._position > this._buffer.length) {
  4974. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  4975. }
  4976. return position;
  4977. }
  4978. read(size) {
  4979. const data = this._buffer.subarray(this._position, this._position + size);
  4980. this._position += size;
  4981. return data;
  4982. }
  4983. string(size) {
  4984. const buffer = this.read(size);
  4985. this._decoder = this._decoder || new TextDecoder('utf8');
  4986. return this._decoder.decode(buffer);
  4987. }
  4988. };
  4989. return new BinaryReader(packed, ext_hook).value();
  4990. });
  4991. this.registerFunction('nolearn.lasagne.base.objective');
  4992. this.registerFunction('numpy.core._DType_reconstruct');
  4993. this.registerFunction('numpy.core._ufunc_reconstruct');
  4994. this.registerFunction('numpy.core.multiarray._reconstruct', (subtype, shape, dtype) => {
  4995. return numpy.ndarray.__new__(subtype, shape, dtype);
  4996. });
  4997. this.registerFunction('numpy.core.multiarray.frombuffer', (buf, dtype) => {
  4998. const shape = [buf.length / dtype.itemsize];
  4999. return new numpy.ndarray(shape, dtype, buf);
  5000. });
  5001. this.registerFunction('numpy._core.numeric._frombuffer', (buf, dtype, shape, order) => {
  5002. return numpy._core.multiarray.frombuffer(buf, dtype).reshape(shape, order);
  5003. });
  5004. this.registerFunction('numpy._core._internal._convert_to_stringdtype_kwargs', () => {
  5005. return new numpy.dtypes.StringDType();
  5006. });
  5007. this.registerFunction('numpy.core.multiarray.scalar', (dtype, rawData) => {
  5008. let data = rawData;
  5009. if (typeof rawData === 'string' || rawData instanceof String) {
  5010. data = new Uint8Array(rawData.length);
  5011. for (let i = 0; i < rawData.length; i++) {
  5012. data[i] = rawData.charCodeAt(i);
  5013. }
  5014. }
  5015. switch (dtype.kind) {
  5016. case 'b': {
  5017. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5018. switch (dtype.itemsize) {
  5019. case 1: return view.getInt8(0) ? true : false;
  5020. default: throw new python.Error(`Unsupported scalar dtype boolean itemsize '${dtype.itemsize}'.`);
  5021. }
  5022. }
  5023. case 'f': {
  5024. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5025. switch (dtype.itemsize) {
  5026. case 2: return view.getFloat16(0, dtype.byteorder === '<');
  5027. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  5028. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  5029. default: throw new python.Error(`Unsupported scalar dtype float itemsize '${dtype.itemsize}'.`);
  5030. }
  5031. }
  5032. case 'i': {
  5033. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5034. switch (dtype.itemsize) {
  5035. case 1: return view.getInt8(0);
  5036. case 2: return view.getInt16(0, dtype.byteorder === '<');
  5037. case 4: return view.getInt32(0, dtype.byteorder === '<');
  5038. case 8: return view.getBigInt64(0, dtype.byteorder === '<');
  5039. default: throw new python.Error(`Unsupported scalar dtype int itemsize '${dtype.itemsize}'.`);
  5040. }
  5041. }
  5042. case 'u': {
  5043. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5044. switch (dtype.itemsize) {
  5045. case 1: return view.getUint8(0);
  5046. case 2: return view.getUint16(0, dtype.byteorder === '<');
  5047. case 4: return view.getUint32(0, dtype.byteorder === '<');
  5048. case 8: return view.getBigUint64(0, dtype.byteorder === '<');
  5049. default: throw new python.Error(`Unsupported scalar dtype uint itemsize '${dtype.itemsize}'.`);
  5050. }
  5051. }
  5052. case 'U': {
  5053. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5054. const list = [];
  5055. for (let i = 0; i < dtype.itemsize; i += 4) {
  5056. list.push(String.fromCodePoint(view.getUint32(i, true)));
  5057. }
  5058. return list.join('');
  5059. }
  5060. default: {
  5061. throw new python.Error(`Unsupported scalar dtype kind '${dtype.kind}'.`);
  5062. }
  5063. }
  5064. });
  5065. this.registerFunction('numpy.core._multiarray_umath.cbrt');
  5066. this.registerFunction('numpy.core._multiarray_umath.fmin');
  5067. this.registerFunction('numpy.core._multiarray_umath.fmax');
  5068. this.registerFunction('numpy.core._multiarray_umath.greater');
  5069. this.registerFunction('numpy.core._multiarray_umath.less');
  5070. this.registerFunction('numpy.core._multiarray_umath.log');
  5071. this.registerFunction('numpy.core._multiarray_umath.scalar', (dtype, rawData) => {
  5072. let data = rawData;
  5073. if (typeof rawData === 'string') {
  5074. data = new Uint8Array(rawData.length);
  5075. for (let i = 0; i < rawData.length; i++) {
  5076. data[i] = rawData.charCodeAt(i);
  5077. }
  5078. }
  5079. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  5080. switch (dtype.__name__) {
  5081. case 'uint8':
  5082. return dataView.getUint8(0);
  5083. case 'float32':
  5084. return dataView.getFloat32(0, true);
  5085. case 'float64':
  5086. return dataView.getFloat64(0, true);
  5087. case 'int8':
  5088. return dataView.getInt8(0, true);
  5089. case 'int16':
  5090. return dataView.getInt16(0, true);
  5091. case 'int32':
  5092. return dataView.getInt32(0, true);
  5093. case 'int64':
  5094. return dataView.getBigInt64(0, true);
  5095. default:
  5096. throw new python.Error(`Unsupported scalar type '${dtype.__name__}'.`);
  5097. }
  5098. });
  5099. this.registerFunction('numpy.core._multiarray_umath.sin');
  5100. this.registerFunction('numpy.core._multiarray_umath.sqrt');
  5101. this.register('numpy._core.multiarray', numpy.core.multiarray);
  5102. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5103. this.register('numpy._core._multiarray_umath', numpy.core._multiarray_umath);
  5104. this.register('numpy.core.numeric', numpy._core.numeric);
  5105. numpy._core._multiarray_umath._reconstruct = numpy.core.multiarray._reconstruct;
  5106. this.registerFunction('numpy.load', (file) => {
  5107. // https://github.com/numpy/numpy/blob/main/numpy/lib/_format_impl.py
  5108. const signature = [0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59];
  5109. if (!file.read(6).every((v, i) => v === signature[i])) {
  5110. throw new python.Error('Invalid signature.');
  5111. }
  5112. const version = file.read(2);
  5113. const [major, minor] = version;
  5114. if (major > 3) {
  5115. throw new python.Error(`Invalid version '${[major, minor].join('.')}'.`);
  5116. }
  5117. const [shape, fortran_order, dtype] = numpy.lib._format_impl._read_array_header(file, version);
  5118. let data = null;
  5119. switch (dtype.byteorder) {
  5120. case '|': {
  5121. data = file.read();
  5122. if (dtype.kind === 'O') {
  5123. const unpickler = new pickle.Unpickler(data);
  5124. return unpickler.load();
  5125. }
  5126. break;
  5127. }
  5128. case '>':
  5129. case '<': {
  5130. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  5131. const stream = file.getbuffer().nbytes > 0x1000000;
  5132. data = file.read(dtype.itemsize * count, stream);
  5133. break;
  5134. }
  5135. default: {
  5136. throw new python.Error(`Unsupported data type '${dtype.str}'.`);
  5137. }
  5138. }
  5139. if (fortran_order) {
  5140. data = null;
  5141. }
  5142. return self.invoke('numpy.ndarray', [shape, dtype, data]);
  5143. });
  5144. this.registerFunction('numpy.save', (file, arr) => {
  5145. const descr = arr.dtype.str;
  5146. if (descr[0] !== '<' && descr[0] !== '>') {
  5147. throw new python.Error(`Unsupported byte order '${descr}'.`);
  5148. }
  5149. if ((descr.length !== 3 && descr.substring(1) !== 'c16') || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  5150. throw new python.Error(`Unsupported data type '${descr}'.`);
  5151. }
  5152. let shape = '';
  5153. switch (arr.shape.length) {
  5154. case 0: shape = '()'; break;
  5155. case 1: shape = `(${arr.shape[0]},)`; break;
  5156. default: shape = `(${arr.shape.map((dimension) => dimension.toString()).join(', ')})`; break;
  5157. }
  5158. const properties = [
  5159. `'descr': '${descr}'`,
  5160. "'fortran_order': False",
  5161. `'shape': ${shape}`
  5162. ];
  5163. let header = `{ ${properties.join(', ')} }`;
  5164. header += `${' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f))}\n`;
  5165. const encoder = new TextEncoder('ascii');
  5166. file.write([0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00]); // '\\x93NUMPY' + version
  5167. file.write([header.length & 0xff, (header.length >> 8) & 0xff]);
  5168. file.write(encoder.encode(header));
  5169. file.write(arr.tobytes());
  5170. });
  5171. this.registerFunction('numpy.lib._format_impl._read_array_header', (file, version) => {
  5172. const buffer = new Uint8Array([0, 0, 0, 0]);
  5173. const [major] = version;
  5174. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  5175. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  5176. let header = file.read(header_length);
  5177. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  5178. header = decoder.decode(header).trim();
  5179. try {
  5180. header = ast.literal_eval(header);
  5181. } catch {
  5182. if (major <= 2) {
  5183. header = numpy.lib._format_impl._filter_header(header);
  5184. header = ast.literal_eval(header);
  5185. }
  5186. }
  5187. if (header.descr === undefined) {
  5188. throw new python.Error("Invalid 'descr'.");
  5189. }
  5190. if (!Array.isArray(header.shape)) {
  5191. throw new python.Error("Invalid 'shape'.");
  5192. }
  5193. const dtype = numpy.lib._format_impl.descr_to_dtype(header.descr);
  5194. return [header.shape, header.fortran_order, dtype];
  5195. });
  5196. this.registerFunction('numpy.lib._format_impl.descr_to_dtype', (descr) => {
  5197. if (typeof descr === 'string') {
  5198. return new numpy.dtype(descr);
  5199. } else if (descr instanceof builtins.tuple) {
  5200. const dt = numpy.lib._format_impl.descr_to_dtype(descr[0]);
  5201. return new numpy.dtype([dt, descr[1]]);
  5202. }
  5203. const titles = [];
  5204. const names = [];
  5205. const formats = [];
  5206. const offsets = [];
  5207. let offset = 0;
  5208. for (const field of descr) {
  5209. let name = null;
  5210. let dt = null;
  5211. let descr_str = null;
  5212. let shape = null;
  5213. let title = null;
  5214. if (field.length === 2) {
  5215. [name, descr_str] = field;
  5216. dt = numpy.lib._format_impl.descr_to_dtype(descr_str);
  5217. } else {
  5218. [name, descr_str, shape] = field;
  5219. dt = new numpy.dtype([numpy.lib._format_impl.descr_to_dtype(descr_str), shape]);
  5220. }
  5221. const is_pad = name === '' && dt.type === numpy.void && dt.names === null;
  5222. if (!is_pad) {
  5223. [title, name] = name instanceof builtins.tuple ? name : [null, name];
  5224. titles.push(title);
  5225. names.push(name);
  5226. formats.push(dt);
  5227. offsets.push(offset);
  5228. }
  5229. offset += dt.itemsize;
  5230. }
  5231. return new numpy.dtype({ names, formats, titles, offsets, itemsize: offset });
  5232. });
  5233. this.registerFunction('numpy.lib._format_impl._filter_header', (s) => {
  5234. const tokens = [];
  5235. const tokenizer = new ast._Tokenizer(s, '');
  5236. while (!tokenizer.match('eof')) {
  5237. const token = tokenizer.read();
  5238. if (token.type === 'int') {
  5239. const next = tokenizer.peek();
  5240. if (next.type === 'id' && next.value === 'L') {
  5241. tokenizer.read();
  5242. }
  5243. }
  5244. tokens.push(token.value);
  5245. }
  5246. return tokens.join('');
  5247. });
  5248. this.registerFunction('numpy.amin');
  5249. this.registerFunction('numpy.amax');
  5250. this.registerFunction('numpy.std');
  5251. this.registerFunction('numpy.asarray', (a, dtype) => {
  5252. const encode = (context, data, dim) => {
  5253. const size = context.shape[dim];
  5254. const littleendian = context.littleendian;
  5255. if (dim === context.shape.length - 1) {
  5256. for (let i = 0; i < size; i++) {
  5257. switch (context.dtype) {
  5258. case 'f2':
  5259. context.view.setFloat16(context.position, data[i], littleendian);
  5260. break;
  5261. case 'f4':
  5262. context.view.setFloat32(context.position, data[i], littleendian);
  5263. break;
  5264. case 'f8':
  5265. context.view.setFloat64(context.position, data[i], littleendian);
  5266. break;
  5267. case 'i1':
  5268. context.view.setInt8(context.position, data[i], littleendian);
  5269. break;
  5270. case 'i2':
  5271. context.view.setInt16(context.position, data[i], littleendian);
  5272. break;
  5273. case 'i4':
  5274. context.view.setInt32(context.position, data[i], littleendian);
  5275. break;
  5276. case 'i8':
  5277. context.view.setBigInt64(context.position, typeof data[i] === 'number' ? BigInt(data[i]) : data[i], littleendian);
  5278. break;
  5279. case 'u1':
  5280. context.view.setUint8(context.position, data[i], littleendian);
  5281. break;
  5282. case 'u2':
  5283. context.view.setUint16(context.position, data[i], littleendian);
  5284. break;
  5285. case 'u4':
  5286. context.view.setUint32(context.position, data[i], littleendian);
  5287. break;
  5288. case 'u8':
  5289. context.view.setComplexFloat16(context.position, data[i], littleendian);
  5290. break;
  5291. case 'c8':
  5292. context.view.setComplexFloat32(context.position, data[i], littleendian);
  5293. break;
  5294. case 'c16':
  5295. context.view.setComplexFloat64(context.position, data[i], littleendian);
  5296. break;
  5297. case 'b1':
  5298. context.view.setInt8(context.position, data[i] ? 1 : 0);
  5299. break;
  5300. default:
  5301. throw new python.Error(`Unsupported tensor data type '${context.dtype}'.`);
  5302. }
  5303. context.position += context.itemsize;
  5304. }
  5305. } else {
  5306. for (let j = 0; j < size; j++) {
  5307. encode(context, data[j], dim + 1);
  5308. }
  5309. }
  5310. };
  5311. const array_size = (value) => {
  5312. if (value.every((item) => Array.isArray(item))) {
  5313. const dims = value.map((item) => array_size(item));
  5314. const [dim] = dims;
  5315. for (let i = 1; i < dims.length; i++) {
  5316. if (dim.length === dims[i].length) {
  5317. if (!dims[i].every((value, i) => value === dim[i])) {
  5318. throw new python.Error('Invalid array shape.');
  5319. }
  5320. }
  5321. }
  5322. return [value.length].concat(dim);
  5323. }
  5324. return [value.length];
  5325. };
  5326. const shape = Array.isArray(a) ? array_size(a) : [];
  5327. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  5328. const context = {
  5329. position: 0,
  5330. itemsize: dtype.itemsize,
  5331. dtype: dtype.str.substring(1),
  5332. littleendian: dtype.str[0],
  5333. shape,
  5334. data: new Uint8Array(size)
  5335. };
  5336. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  5337. encode(context, a, 0);
  5338. return self.invoke('numpy.ndarray', [shape, dtype, context.data]);
  5339. });
  5340. this.registerFunction('numpy.max');
  5341. this.registerFunction('numpy.mean');
  5342. this.registerFunction('numpy.min');
  5343. this.registerFunction('numpy.ma.core._mareconstruct', (subtype, baseclass, baseshape, basetype) => {
  5344. const data = self.invoke(baseclass, [baseshape, basetype]);
  5345. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5346. const mask = self.invoke('numpy.ndarray', [baseshape, '']);
  5347. return self.invoke(subtype, [data, mask, basetype]);
  5348. });
  5349. this.registerFunction('numpy.random.__RandomState_ctor', () => {
  5350. return {};
  5351. });
  5352. this.registerFunction('numpy.random._pickle.__randomstate_ctor', () => {
  5353. return {};
  5354. });
  5355. this.registerType('numpy.random.bit_generator.BitGenerator', class {
  5356. __setstate__(state) {
  5357. if (state instanceof Map || !Array.isArray(state)) {
  5358. this.state = state;
  5359. } else {
  5360. [this.state, this._seed_seq] = state;
  5361. }
  5362. }
  5363. });
  5364. this.registerType('numpy.random.bit_generator.SeedSequence', class extends builtins.object {
  5365. __setstate__(state) {
  5366. [this.entropy, this.n_children_spawned, this.pool, this.pool_size, this.spawn_key] = state;
  5367. }
  5368. });
  5369. this.registerFunction('numpy.random.bit_generator.__pyx_unpickle_SeedSequence', (cls, checksum, state) => {
  5370. const obj = new cls();
  5371. if (state) {
  5372. obj.__setstate__(state);
  5373. }
  5374. return obj;
  5375. });
  5376. this.registerType('numpy.random._mt19937.MT19937', class extends numpy.random.bit_generator.BitGenerator {});
  5377. this.registerType('numpy.random._pcg64.PCG64', class extends numpy.random.bit_generator.BitGenerator {});
  5378. this.registerType('numpy.random._pcg64.PCG64DXSM', class extends numpy.random.bit_generator.BitGenerator {});
  5379. this.registerType('numpy.random._philox.Philox', class extends numpy.random.bit_generator.BitGenerator {});
  5380. this.registerType('numpy.random._sfc64.SFC64', class extends numpy.random.bit_generator.BitGenerator {});
  5381. numpy.random._pickle.BitGenerators = {
  5382. 'MT19937': numpy.random._mt19937.MT19937,
  5383. 'PCG64': numpy.random._pcg64.PCG64,
  5384. 'PCG64DXSM': numpy.random._pcg64.PCG64DXSM,
  5385. 'Philox': numpy.random._philox.Philox,
  5386. 'SFC64': numpy.random._sfc64.SFC64,
  5387. };
  5388. this.registerType('numpy.random._generator.Generator', class {
  5389. constructor(bit_generator) {
  5390. this.bit_generator = bit_generator;
  5391. }
  5392. });
  5393. this.registerFunction('numpy.random._pickle.__bit_generator_ctor', (bit_generator) => {
  5394. bit_generator = bit_generator || 'MT19937';
  5395. let bit_gen_class = null;
  5396. if (builtins.isinstance(bit_generator, builtins.type)) {
  5397. bit_gen_class = bit_generator;
  5398. } else {
  5399. bit_gen_class = numpy.random._pickle.BitGenerators[bit_generator];
  5400. }
  5401. if (bit_gen_class) {
  5402. return new bit_gen_class();
  5403. }
  5404. throw new python.Error(`Unknown bit generator '${bit_generator}'.`);
  5405. });
  5406. this.registerFunction('numpy.random._pickle.__generator_ctor', (bit_generator_name, bit_generator_ctor) => {
  5407. if (bit_generator_name instanceof numpy.random.bit_generator.BitGenerator) {
  5408. return new numpy.random._generator.Generator(bit_generator_name);
  5409. }
  5410. bit_generator_ctor = bit_generator_ctor || numpy.random._pickle.__bit_generator_ctor;
  5411. return new numpy.random._generator.Generator(bit_generator_ctor(bit_generator_name));
  5412. });
  5413. this.registerFunction('numpy.reshape');
  5414. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif');
  5415. this.registerFunction('sklearn.feature_selection._univariate_selection.f_regression');
  5416. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer');
  5417. this.registerFunction('sklearn.metrics._classification.accuracy_score');
  5418. this.registerFunction('sklearn.metrics._classification.balanced_accuracy_score');
  5419. this.registerFunction('sklearn.metrics._classification.cohen_kappa_score');
  5420. this.registerFunction('sklearn.metrics._classification.f1_score');
  5421. this.registerFunction('sklearn.metrics._classification.log_loss');
  5422. this.registerFunction('sklearn.metrics._classification.precision_score');
  5423. this.registerFunction('sklearn.metrics._classification.recall_score');
  5424. this.registerFunction('sklearn.metrics._dist_metrics.newObj', (obj) => {
  5425. return obj.__new__(obj);
  5426. });
  5427. this.registerFunction('sklearn.metrics._ranking.roc_auc_score');
  5428. this.registerFunction('sklearn.metrics._regression.mean_absolute_error');
  5429. this.registerFunction('sklearn.metrics._regression.mean_absolute_percentage_error');
  5430. this.registerFunction('sklearn.metrics._regression.mean_squared_error');
  5431. this.registerFunction('sklearn.metrics._regression.r2_score');
  5432. sklearn.metrics.regression = sklearn.metrics._regression;
  5433. sklearn.metrics.r2_score = sklearn.metrics._regression.r2_score;
  5434. this.registerFunction('sklearn.metrics._regression.root_mean_squared_error');
  5435. this.registerFunction('sklearn.metrics._scorer._passthrough_scorer');
  5436. this.registerFunction('re._compile', (pattern, flags) => {
  5437. return self.invoke('re.Pattern', [pattern, flags]);
  5438. });
  5439. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', (...args) => {
  5440. return function() {
  5441. return self.invoke(`types.${args[0]}`, args);
  5442. };
  5443. });
  5444. this.registerType('sympy.printing.defaults.Printable', class {});
  5445. this.registerType('sympy.core.basic.Basic', class extends sympy.printing.defaults.Printable {
  5446. constructor(...args) {
  5447. super();
  5448. this._args = args;
  5449. }
  5450. get args() {
  5451. return this._args;
  5452. }
  5453. });
  5454. this.registerType('sympy.core.function.Function', class extends sympy.core.basic.Basic {
  5455. });
  5456. this.registerType('sympy.core.expr.Expr', class extends sympy.core.basic.Basic {
  5457. });
  5458. this.registerType('sympy.core.operations.AssocOp', class extends sympy.core.expr.Expr /* sympy.core.basic.Basic */ {});
  5459. this.registerType('sympy.core.power.Pow', class extends sympy.core.expr.Expr {
  5460. __str__() {
  5461. return this._args.map((a) => a.__str__()).join('**');
  5462. }
  5463. });
  5464. this.registerType('sympy.core.add.Add', class extends sympy.core.operations.AssocOp {
  5465. __str__() {
  5466. return this._args.map((a) => a.__str__()).join(' + ');
  5467. }
  5468. });
  5469. this.registerType('sympy.core.mul.Mul', class extends sympy.core.operations.AssocOp {
  5470. __str__() {
  5471. return this._args.map((a) => a.__str__()).join('*');
  5472. }
  5473. });
  5474. this.registerType('sympy.core.numbers.Number', class extends sympy.core.expr.Expr {});
  5475. this.registerType('sympy.core.numbers.Rational', class extends sympy.core.numbers.Number {});
  5476. this.registerType('sympy.core.numbers.Integer', class extends sympy.core.numbers.Rational {
  5477. constructor(value) {
  5478. super();
  5479. this.value = value;
  5480. this.is_Integer = true;
  5481. }
  5482. __int__() {
  5483. return this.value;
  5484. }
  5485. __str__() {
  5486. return this.value.toString();
  5487. }
  5488. });
  5489. this.registerType('sympy.core.symbol.Symbol', class extends sympy.core.expr.Expr {
  5490. constructor(name) {
  5491. super();
  5492. this.name = name;
  5493. }
  5494. __int__() {
  5495. throw new python.Error('Cannot convert symbols to int.');
  5496. }
  5497. __str__() {
  5498. return this.name;
  5499. }
  5500. });
  5501. this.registerType('sympy.core.relational.Relational', class extends sympy.core.expr.Expr {
  5502. constructor(lhs, rhs, op) {
  5503. super();
  5504. this._args = [lhs, rhs];
  5505. this._op = op;
  5506. }
  5507. __str__() {
  5508. return `${this._args[0].__str__()} ${this._op} ${this._args[1].__str__()}`;
  5509. }
  5510. });
  5511. this.registerType('sympy.core.relational._Inequality', class extends sympy.core.relational.Relational {
  5512. });
  5513. this.registerType('sympy.core.relational._Greater', class extends sympy.core.relational._Inequality {
  5514. });
  5515. this.registerType('sympy.core.relational.GreaterThan', class extends sympy.core.relational._Greater {
  5516. constructor(lhs, rhs) {
  5517. super(lhs, rhs, '>=');
  5518. }
  5519. });
  5520. this.registerType('sympy.core.relational._Less', class extends sympy.core.relational._Inequality {
  5521. });
  5522. this.registerType('sympy.core.relational.LessThan', class extends sympy.core.relational.Relational {
  5523. constructor(lhs, rhs) {
  5524. super(lhs, rhs, '<=');
  5525. }
  5526. });
  5527. this.registerType('sympy.core.relational.StrictLessThan', class extends sympy.core.relational.Relational {
  5528. constructor(lhs, rhs) {
  5529. super(lhs, rhs, '<');
  5530. }
  5531. });
  5532. this.registerType('sympy.core.relational.StrictGreaterThan', class extends sympy.core.relational.Relational {
  5533. constructor(lhs, rhs) {
  5534. super(lhs, rhs, '>');
  5535. }
  5536. });
  5537. this.registerType('sympy.core.relational.Equality', class extends sympy.core.relational.Relational {
  5538. constructor(lhs, rhs) {
  5539. super(lhs, rhs, '==');
  5540. }
  5541. });
  5542. this.registerType('sympy.functions.elementary.miscellaneous.MinMaxBase', class extends sympy.core.expr.Expr {
  5543. });
  5544. this.registerType('sympy.functions.elementary.miscellaneous.Max', class extends sympy.functions.elementary.miscellaneous.MinMaxBase {
  5545. __str__() {
  5546. return `Max(${this._args.map((a) => a.__str__()).join(', ')})`;
  5547. }
  5548. });
  5549. this.registerFunction('sympy.core.sympify.sympify', (a /*, locals */) => {
  5550. if (a instanceof sympy.core.expr.Expr) {
  5551. return a;
  5552. }
  5553. const p = ast.parse(a);
  5554. const sympify = (node) => {
  5555. if (node instanceof ast.Call) {
  5556. switch (node.func.id) {
  5557. case 'Symbol': return new sympy.core.symbol.Symbol(node.args[0].value);
  5558. case 'Mul': return new sympy.core.mul.Mul(...node.args.map((arg) => sympify(arg)));
  5559. case 'Add': return new sympy.core.add.Add(...node.args.map((arg) => sympify(arg)));
  5560. case 'Pow': return new sympy.core.power.Pow(...node.args.map((arg) => sympify(arg)));
  5561. case 'Max': return new sympy.functions.elementary.miscellaneous.Max(...node.args.map((arg) => sympify(arg)));
  5562. case 'Integer': return new sympy.core.numbers.Integer(node.args[0].value);
  5563. case 'GreaterThan': return new sympy.core.relational.GreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5564. case 'StrictGreaterThan': return new sympy.core.relational.StrictGreaterThan(sympify(node.args[0]), sympify(node.args[1]));
  5565. case 'LessThan': return new sympy.core.relational.LessThan(sympify(node.args[0]), sympify(node.args[1]));
  5566. case 'StrictLessThan': return new sympy.core.relational.StrictLessThan(sympify(node.args[0]), sympify(node.args[1]));
  5567. case 'Equality': return new sympy.core.relational.Equality(sympify(node.args[0]), sympify(node.args[1]));
  5568. case 'FloorDiv': return new torch.utils._sympy.functions.FloorDiv(sympify(node.args[0]), sympify(node.args[1]));
  5569. default: throw new python.Error(`Unsupported SymPy function '${node.func.id}'.`);
  5570. }
  5571. }
  5572. if (node instanceof ast.Name) {
  5573. return new sympy.core.symbol.Symbol(node.id);
  5574. }
  5575. if (node instanceof ast.Constant) {
  5576. if (node.type === 'int') {
  5577. return new sympy.core.numbers.Integer(node.value);
  5578. }
  5579. }
  5580. if (node instanceof ast.BinOp) {
  5581. if (node.op instanceof ast.Mult) {
  5582. return new sympy.core.mul.Mul(sympify(node.left), sympify(node.right));
  5583. }
  5584. if (node.op instanceof ast.Pow) {
  5585. return new sympy.core.power.Pow(sympify(node.left), sympify(node.right));
  5586. }
  5587. throw new python.Error(`Unsupported SymPy BinOp op '${node.op.__class__.__name__}'.`);
  5588. }
  5589. if (node instanceof ast.Compare) {
  5590. const left = sympify(node.left);
  5591. const right = sympify(node.comparators[0]);
  5592. const [op] = node.ops;
  5593. if (op instanceof ast.Gt) {
  5594. return new sympy.core.relational.StrictGreaterThan(left, right);
  5595. }
  5596. if (op instanceof ast.GtE) {
  5597. return new sympy.core.relational.GreaterThan(left, right);
  5598. }
  5599. if (op instanceof ast.Lt) {
  5600. return new sympy.core.relational.StrictLessThan(left, right);
  5601. }
  5602. if (op instanceof ast.LtE) {
  5603. return new sympy.core.relational.LessThan(left, right);
  5604. }
  5605. if (op instanceof ast.Eq) {
  5606. return new sympy.core.relational.Equality(left, right);
  5607. }
  5608. throw new python.Error(`Unsupported comparison operator '${op.__class__.__name__}'.`);
  5609. }
  5610. throw new python.Error(`Unsupported SymPy expression '${node.__class__.__name__}'.`);
  5611. };
  5612. return sympify(p.body[0].value);
  5613. });
  5614. this.registerFunction('theano.scalar.basic.same_out');
  5615. this.registerFunction('theano.scalar.basic.same_out_nocomplex');
  5616. this.registerFunction('theano.scalar.basic.upcast_out');
  5617. this.registerFunction('theano.scalar.basic.upgrade_to_float');
  5618. this.registerFunction('theano.tensor.nnet.conv2d');
  5619. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan');
  5620. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan');
  5621. this.registerType('torch.nn.modules.module.Module', class {
  5622. constructor() {
  5623. this._modules = new collections.OrderedDict();
  5624. this._parameters = new collections.OrderedDict();
  5625. this._buffers = new collections.OrderedDict();
  5626. }
  5627. __setattr__(name, value) {
  5628. if (value instanceof torch.nn.modules.module.Module) {
  5629. this._modules.set(name, value);
  5630. } else {
  5631. this[name] = value;
  5632. }
  5633. }
  5634. __getattr__(name) {
  5635. if (this._modules.has(name)) {
  5636. return this._modules.get(name);
  5637. }
  5638. return this[name];
  5639. }
  5640. __delattr__(name) {
  5641. if (this._modules.has(name)) {
  5642. this._modules.delete(name);
  5643. }
  5644. }
  5645. children() {
  5646. return this._modules.values();
  5647. }
  5648. named_modules(memo, prefix, remove_duplicate) {
  5649. memo = memo || new Set();
  5650. prefix = prefix || '';
  5651. const modules = new builtins.dict();
  5652. if (!memo.has(this)) {
  5653. if (remove_duplicate) {
  5654. memo.add(this);
  5655. }
  5656. modules.set(prefix, this);
  5657. for (const [name, module] of this._modules.items()) {
  5658. if (module && module.named_modules) {
  5659. const submodule_prefix = `${prefix}${(prefix ? '.' : '')}${name}`;
  5660. for (const [k, v] of module.named_modules(memo, submodule_prefix, remove_duplicate)) {
  5661. modules.set(k, v);
  5662. }
  5663. }
  5664. }
  5665. }
  5666. return modules;
  5667. }
  5668. named_children() {
  5669. return this._modules;
  5670. }
  5671. parameters() {
  5672. return this._parameters.values();
  5673. }
  5674. named_parameters(recurse) {
  5675. if (recurse) {
  5676. throw new python.Error('Named parameters with recurse not implemented.');
  5677. }
  5678. return this._parameters;
  5679. }
  5680. buffers() {
  5681. return this._buffers.values();
  5682. }
  5683. named_buffers(recurse) {
  5684. if (recurse) {
  5685. throw new python.Error('Named parameters with recurse not implemented.');
  5686. }
  5687. return this._buffers;
  5688. }
  5689. _get_name() {
  5690. return this.__class__.__name__;
  5691. }
  5692. add_module(name, module) {
  5693. this._modules.set(name, module);
  5694. }
  5695. register_module(name, module) {
  5696. this.add_module(name, module);
  5697. }
  5698. });
  5699. torch.nn.Module = torch.nn.modules.module.Module;
  5700. torch.nn.modules.Module = torch.nn.modules.module.Module;
  5701. this.registerType('torch._C._TensorBase', class extends builtins.object {});
  5702. this.registerType('torch._C._TensorMeta', class extends builtins.type {});
  5703. this.registerType('torch._C._VariableFunctionsClass', class extends builtins.object {});
  5704. this.registerType('torch._C.SchemaParser', class {
  5705. constructor(str, allow_typevars) {
  5706. this.L = new torch._C.Lexer(str);
  5707. this.type_parser = new torch._C.SchemaTypeParser(this.L, false, allow_typevars);
  5708. }
  5709. parseName() {
  5710. const L = this.L;
  5711. let name = L.expect('id').text();
  5712. if (L.nextIf(':')) {
  5713. L.expect(':');
  5714. name = `${name}::${L.expect('ident').text()}`;
  5715. }
  5716. let overload_name = '';
  5717. if (L.nextIf('.')) {
  5718. overload_name = L.expect('ident').text();
  5719. }
  5720. // const is_a_valid_overload_name = !((overload_name === "default") || (overload_name.rfind("__", 0) == 0));
  5721. // TORCH_CHECK(is_a_valid_overload_name, overload_name, " is not a legal overload name for aten operators");
  5722. return new torch._C.OperatorName(name, overload_name);
  5723. }
  5724. parseDeclaration() {
  5725. const L = this.L;
  5726. const name = this.parseName();
  5727. if (L.cur().kind !== '(') {
  5728. return name;
  5729. }
  5730. throw new python.Error('Not implemented.');
  5731. }
  5732. parseExactlyOneDeclaration() {
  5733. // const L = this.L;
  5734. const result = this.parseDeclaration();
  5735. // L.nextIf(TK_NEWLINE);
  5736. // L.expect(TK_EOF);
  5737. return result;
  5738. }
  5739. parseArgument(idx, is_return, kwarg_only) {
  5740. const L = this.L;
  5741. const type_parser = this.type_parser;
  5742. let [fake_type, real_type, alias_info] = type_parser.parseFakeAndRealType();
  5743. let N = null;
  5744. if (L.nextIf('[')) {
  5745. fake_type = torch.ListType.create(fake_type);
  5746. real_type = torch.ListType.create(real_type);
  5747. if (L.cur().kind === '#') {
  5748. N = Number(L.cur().text());
  5749. L.next();
  5750. }
  5751. L.expect(']');
  5752. let container = type_parser.parseAliasAnnotation();
  5753. if (alias_info) {
  5754. if (!container) {
  5755. container = new torch._C.AliasInfo();
  5756. container.is_write = alias_info.is_write;
  5757. }
  5758. container.addContainedType(alias_info);
  5759. }
  5760. alias_info = container;
  5761. if (L.nextIf('?')) {
  5762. fake_type = torch.OptionalType.create(fake_type);
  5763. real_type = torch.OptionalType.create(real_type);
  5764. }
  5765. }
  5766. let name = null;
  5767. /* eslint-disable no-undef-init */
  5768. let default_value = undefined;
  5769. /* eslint-enable no-undef-init */
  5770. if (is_return) {
  5771. kwarg_only = false;
  5772. if (L.cur().kind === 'id') {
  5773. name = L.next().text();
  5774. } else {
  5775. name = '';
  5776. }
  5777. } else {
  5778. name = L.expect('id').text();
  5779. if (L.nextIf('=')) {
  5780. default_value = this.parseDefaultValue(fake_type, fake_type.kind(), real_type, N);
  5781. }
  5782. }
  5783. return new torch.Argument(name, fake_type, real_type, N, default_value, kwarg_only, alias_info);
  5784. }
  5785. parseDefaultValue(arg_type, kind, real_type, arg_N) {
  5786. // auto range = L.cur().range;
  5787. const L = this.L;
  5788. const range = null;
  5789. switch (kind) {
  5790. case torch._C.TypeKind.StringType:
  5791. case torch._C.TypeKind.OptionalType:
  5792. case torch._C.TypeKind.NumberType:
  5793. case torch._C.TypeKind.IntType:
  5794. case torch._C.TypeKind.BoolType:
  5795. case torch._C.TypeKind.FloatType:
  5796. case torch._C.TypeKind.ComplexType:
  5797. return this.parseSingleConstant(arg_type, kind, real_type);
  5798. case torch._C.TypeKind.ListType: {
  5799. const elem_type = arg_type.containedType(0);
  5800. const real_elem_type = real_type.containedType(0);
  5801. if (L.cur().kind === 'id') {
  5802. return this.parseTensorDefault(range);
  5803. } else if (arg_N && L.cur().kind !== '[') {
  5804. const v = this.parseSingleConstant(elem_type, elem_type.kind(), real_elem_type);
  5805. const repeated = Array(arg_N).fill(v);
  5806. // std::vector<IValue> repeated(arg_N, v);
  5807. return this.convertToList(elem_type, elem_type.kind(), range, repeated);
  5808. }
  5809. return this.parseConstantList(elem_type, elem_type.kind(), real_elem_type);
  5810. }
  5811. case torch._C.TypeKind.DynamicType:
  5812. return this.parseDefaultValue(arg_type, arg_type.dynamicKind(), real_type, arg_N);
  5813. default:
  5814. throw new python.Error(`Unsupported default value kind '${kind}'.`);
  5815. }
  5816. }
  5817. parseSingleConstant(type, kind, real_type) {
  5818. const L = this.L;
  5819. if (kind === torch._C.TypeKind.DynamicType) {
  5820. return this.parseSingleConstant(type, type.dynamicKind(), real_type);
  5821. }
  5822. // const auto& str2dtype = c10::getStringToDtypeMap();
  5823. if (L.cur().kind === 'id') {
  5824. if (L.cur().text() === 'True') {
  5825. L.next();
  5826. return new torch._C.IValue(true);
  5827. }
  5828. if (L.cur().text() === 'False') {
  5829. L.next();
  5830. return new torch._C.IValue(false);
  5831. }
  5832. if (L.cur().text() === 'None') {
  5833. L.next();
  5834. return new torch._C.IValue();
  5835. }
  5836. } else if (L.cur().kind === 'string') {
  5837. const token = L.next();
  5838. return new torch._C.IValue(torch._C.parseStringLiteral(null, token.text()));
  5839. } else if (L.cur().kind === '#') {
  5840. let n = '';
  5841. if (L.nextIf('-')) {
  5842. n = `-${L.expect('#').text()}`; // # .text();
  5843. } else {
  5844. n = L.expect('#').text(); // # .text();
  5845. }
  5846. if (kind === torch._C.TypeKind.ComplexType || n.indexOf('j') !== -1) {
  5847. throw new Error("Complex type not implemented.");
  5848. /*
  5849. const imag = std::stod(n.substr(0, n.size() - 1));
  5850. return c10::complex<double>(0, imag);
  5851. */
  5852. } else if (kind === torch._C.TypeKind.FloatType || n.indexOf('.') !== -1 || n.indexOf('e') !== -1) {
  5853. const v = parseFloat(n);
  5854. return new torch._C.IValue(v, 'Double');
  5855. } else {
  5856. const v = parseInt(n, 10);
  5857. return new torch._C.IValue(v, 'Int');
  5858. }
  5859. }
  5860. throw new python.Error('Not implemented.');
  5861. /*
  5862. switch (L.cur().kind) {
  5863. case TK_TRUE:
  5864. L.next();
  5865. return true;
  5866. case TK_FALSE:
  5867. L.next();
  5868. return false;
  5869. case TK_NONE:
  5870. L.next();
  5871. return IValue();
  5872. case TK_STRINGLITERAL: {
  5873. const token = L.next();
  5874. return parseStringLiteral(token.range, token.text());
  5875. }
  5876. case TK_IDENT: {
  5877. const tok = L.next();
  5878. const text_view = tok.text_view();
  5879. // NB: float/complex/long are here for BC purposes. Other dtypes
  5880. // are handled via str2dtype.
  5881. // Please don't add more cases to this if-else block.
  5882. if ("float" == text_view) {
  5883. return static_cast<int64_t>("at::kFloat");
  5884. } else if ("complex" == text_view) {
  5885. return static_cast<int64_t>("at::kComplexFloat");
  5886. } else if ("long" == text_view) {
  5887. return static_cast<int64_t>("at::kLong");
  5888. } else if ("strided" == text_view) {
  5889. return static_cast<int64_t>("at::kStrided");
  5890. } else if ("Mean" == text_view) {
  5891. return static_cast<int64_t>("at::Reduction::Mean");
  5892. } else if ("contiguous_format" == text_view) {
  5893. return static_cast<int64_t>("c10::MemoryFormat::Contiguous");
  5894. } else {
  5895. const text = tok.text();
  5896. if (isPossiblyOptionalScalarType(real_type) &&
  5897. str2dtype.count(text) > 0) {
  5898. return static_cast<int64_t>(str2dtype.at(text));
  5899. } else {
  5900. throw(ErrorReport(L.cur().range) << "invalid numeric default value");
  5901. }
  5902. }
  5903. }
  5904. default: {
  5905. let n;
  5906. if (L.nextIf('-')) {
  5907. n = "-" + L.expect(TK_NUMBER).text();
  5908. }
  5909. else {
  5910. n = L.expect(TK_NUMBER).text();
  5911. }
  5912. if (kind == torch._C.TypeKind.ComplexType || n.find('j') != "std::string::npos") {
  5913. throw new python.Error('Complex type not implemented.');
  5914. const imag = std::stod(n.substr(0, n.size() - 1));
  5915. return c10::complex<double>(0, imag);
  5916. } else if (kind == torch._C.TypeKind.FloatType || n.find('.') != "std::string::npos" || n.find('e') != "std::string::npos") {
  5917. throw new python.Error('Float type not implemented.');
  5918. return std::stod(n);
  5919. } else {
  5920. throw new python.Error("'torch._C.SchemaParser.parseSingleConstant' not implemented.");
  5921. int64_t v = std::stoll(n);
  5922. return v;
  5923. }
  5924. }
  5925. }
  5926. */
  5927. }
  5928. parseConstantList(type, kind, real_type) {
  5929. const L = this.L;
  5930. const tok = L.expect('[');
  5931. const vs = [];
  5932. if (L.cur().kind !== ']') {
  5933. do {
  5934. vs.push(this.parseSingleConstant(type, kind, real_type));
  5935. } while (L.nextIf(','));
  5936. }
  5937. L.expect(']');
  5938. return this.convertToList(type, kind, tok.range, vs);
  5939. }
  5940. convertToList(type, kind, range, vs) {
  5941. switch (kind) {
  5942. case torch._C.TypeKind.ComplexType:
  5943. return new torch._C.IValue(new torch._C.List(torch.ComplexType.get(), vs.map((v) => v)));
  5944. case torch._C.TypeKind.FloatType:
  5945. return new torch._C.IValue(new torch._C.List(torch.FloatType.get(), vs.map((v) => v)));
  5946. case torch._C.TypeKind.IntType:
  5947. return new torch._C.IValue(new torch._C.List(torch.IntType.get(), vs.map((v) => v)));
  5948. case torch._C.TypeKind.BoolType:
  5949. return new torch._C.IValue(new torch._C.List(torch.BoolType.get(), vs.map((v) => v)));
  5950. case torch._C.TypeKindDynamicType:
  5951. return this.convertToList(type.dynamicKind(), range, vs);
  5952. default:
  5953. // throw(ErrorReport(range) << "lists are only supported for float, int and complex types");
  5954. throw new python.Error('lists are only supported for float, int and complex types');
  5955. }
  5956. }
  5957. });
  5958. this.registerType('torch.FunctionSchema', class {
  5959. constructor(name, overload_name, args, returns, is_vararg, is_varret) {
  5960. const index = name.indexOf('(');
  5961. if (index === -1) {
  5962. this._name = name;
  5963. this._overload_name = overload_name || '';
  5964. this._arguments = args || [];
  5965. this._returns = returns || [];
  5966. this._is_vararg = is_vararg || false;
  5967. this._is_varret = is_varret || false;
  5968. } else {
  5969. const value = name.substring(0, index).trim();
  5970. const dot = value.indexOf('.');
  5971. if (dot === -1) {
  5972. this._name = value;
  5973. this._overload_name = '';
  5974. } else {
  5975. this._name = value.substring(0, dot);
  5976. this._overload_name = value.substring(dot + 1, value.length);
  5977. }
  5978. this._buffer = name.substring(index, name.length);
  5979. }
  5980. }
  5981. static parse(schema) {
  5982. return new torch.FunctionSchema(schema);
  5983. }
  5984. get name() {
  5985. return this._name;
  5986. }
  5987. get overload_name() {
  5988. return this._overload_name;
  5989. }
  5990. get arguments() {
  5991. this._parse();
  5992. return this._arguments;
  5993. }
  5994. get returns() {
  5995. this._parse();
  5996. return this._returns;
  5997. }
  5998. get is_vararg() {
  5999. this._parse();
  6000. return this._is_vararg;
  6001. }
  6002. get is_varret() {
  6003. this._parse();
  6004. return this._is_varret;
  6005. }
  6006. argumentIndexWithName(name) {
  6007. const index = this.arguments.findIndex((arg) => arg.name === name);
  6008. return index === -1 ? null : index;
  6009. }
  6010. _parse() {
  6011. if (this._buffer) {
  6012. const parser = new torch._C.SchemaParser(this._buffer, true /* parseSchemaOrName */);
  6013. const L = parser.L;
  6014. this._arguments = [];
  6015. this._is_vararg = false;
  6016. this._kwarg_only = false;
  6017. let idx = 0;
  6018. L.expect('(');
  6019. if (!L.nextIf(')')) {
  6020. while (true) {
  6021. if (this._is_vararg) {
  6022. throw new python.Error("Unexpected 'torch.FunctionSchema._is_vararg'.");
  6023. }
  6024. if (L.nextIf('*')) {
  6025. this._kwarg_only = true;
  6026. } else if (L.nextIf('...')) {
  6027. this._is_vararg = true;
  6028. } else {
  6029. const argument = parser.parseArgument(idx++, false, this._kwarg_only);
  6030. this._arguments.push(argument);
  6031. }
  6032. if (!L.nextIf(',')) {
  6033. break;
  6034. }
  6035. }
  6036. L.expect(')');
  6037. }
  6038. L.expect('->');
  6039. this._returns = [];
  6040. this._is_varret = false;
  6041. if (L.nextIf('...')) {
  6042. this._is_varret = true;
  6043. } else if (L.nextIf('(')) {
  6044. if (!L.nextIf(')')) {
  6045. while (true) {
  6046. if (this._is_varret) {
  6047. throw new python.Error("Unexpected 'torch.FunctionSchema._is_varret'.");
  6048. }
  6049. if (L.nextIf('...')) {
  6050. this._is_varret = true;
  6051. } else {
  6052. const argument = parser.parseArgument(idx++, true, false);
  6053. this._returns.push(argument);
  6054. }
  6055. if (!L.nextIf(',')) {
  6056. break;
  6057. }
  6058. }
  6059. L.expect(')');
  6060. }
  6061. } else {
  6062. this._returns.push(parser.parseArgument(0, true, false));
  6063. }
  6064. delete this._buffer;
  6065. }
  6066. }
  6067. __str__() {
  6068. const list = [this.name];
  6069. const overload_name = this.overload_name;
  6070. if (overload_name !== '' && overload_name !== 'default') {
  6071. list.push(`.${this.overload_name}`);
  6072. }
  6073. list.push('(');
  6074. let first = true;
  6075. let kwarg_only = false;
  6076. for (const argument of this.arguments) {
  6077. if (!first) {
  6078. list.push(', ');
  6079. }
  6080. if (argument.kwarg_only && !kwarg_only) {
  6081. list.push('*, ');
  6082. kwarg_only = true;
  6083. }
  6084. first = false;
  6085. list.push(argument.str());
  6086. }
  6087. if (this.is_vararg) {
  6088. if (!first) {
  6089. list.push(', ');
  6090. }
  6091. first = true;
  6092. list.push('...');
  6093. }
  6094. list.push(') -> ');
  6095. const returns = this.returns;
  6096. const braces = !this.is_varret &&
  6097. (returns.length !== 1 ||
  6098. returns[0].name ||
  6099. returns[0].real_type instanceof torch.TupleType ||
  6100. returns[0].real_type instanceof torch.ListType && returns[0].real_type.getElementType() instanceof torch.TupleType);
  6101. if (braces) {
  6102. list.push('(');
  6103. }
  6104. first = true;
  6105. for (const argument of this.returns) {
  6106. if (!first) {
  6107. list.push(', ');
  6108. }
  6109. first = false;
  6110. list.push(argument.str());
  6111. }
  6112. if (this.is_varret) {
  6113. if (!first) {
  6114. list.push(', ');
  6115. }
  6116. first = true;
  6117. list.push('...');
  6118. }
  6119. if (braces) {
  6120. list.push(')');
  6121. }
  6122. return list.join('');
  6123. }
  6124. aliasAnalysis() {
  6125. return this._alias_kind || 'CONSERVATIVE';
  6126. }
  6127. setAliasAnalysis(v) {
  6128. this._alias_kind = v;
  6129. }
  6130. hasAnyAliasInfo() {
  6131. for (const arg of this.arguments) {
  6132. if (arg.alias_info !== null) {
  6133. return true;
  6134. }
  6135. }
  6136. for (const ret of this.returns) {
  6137. if (ret.alias_info !== null) {
  6138. return true;
  6139. }
  6140. }
  6141. return false;
  6142. }
  6143. is_mutable() {
  6144. return this.arguments.some((arg) => {
  6145. const aliasInfo = arg.alias_info;
  6146. return aliasInfo && aliasInfo.is_write;
  6147. });
  6148. }
  6149. });
  6150. this.registerType('torch._C.SchemaInfo', class {
  6151. constructor(schema) {
  6152. this._schema = schema;
  6153. this._alias_maps_current = false;
  6154. this._has_init = false;
  6155. }
  6156. is_nondeterministic() {
  6157. if (this._schema.name === 'aten::dropout' && this._schema.overload === '') {
  6158. //
  6159. }
  6160. torch._C.nondeterministic_op_strings = torch._C.nondeterministic_op_strings || new Set([
  6161. 'aten::dropout(Tensor input, float p, bool train) -> Tensor',
  6162. 'aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)',
  6163. 'aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor',
  6164. 'aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor',
  6165. 'aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor',
  6166. 'aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor',
  6167. 'aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)',
  6168. 'aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor',
  6169. 'aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor',
  6170. 'aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor',
  6171. 'aten::poisson(Tensor self, Generator? generator) -> Tensor',
  6172. 'aten::binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor',
  6173. 'aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6174. 'aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor',
  6175. 'aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6176. 'aten::rand_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6177. 'aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6178. 'aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6179. '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',
  6180. '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',
  6181. 'aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor',
  6182. 'aten::randn_like(Tensor self, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor',
  6183. 'aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor'
  6184. ]);
  6185. if (torch._C.nondeterministic_op_strings.has(this._schema.__str__())) {
  6186. return true;
  6187. }
  6188. /*
  6189. const auto& op = c10::Dispatcher::singleton().findOp(
  6190. c10::OperatorName(schema_.name(), schema_.overload_name()));
  6191. return op && op->hasTag(at::Tag::nondeterministic_seeded);
  6192. */
  6193. return false;
  6194. }
  6195. });
  6196. this.registerType('torch._C.OperatorRegistry', class {
  6197. constructor() {
  6198. this.to_register = [];
  6199. this.operators = new Map();
  6200. }
  6201. registerPendingOperators() {
  6202. for (const op of this.to_register) {
  6203. const sym = op.schema().name;
  6204. if (!this.operators.has(sym)) {
  6205. this.operators.set(sym, []);
  6206. }
  6207. this.operators.get(sym).push(op);
  6208. }
  6209. this.to_register = [];
  6210. }
  6211. registerOperator(op) {
  6212. this.to_register.push(op);
  6213. }
  6214. getOperators(name) {
  6215. this.registerPendingOperators();
  6216. if (this.operators.has(name)) {
  6217. return this.operators.get(name);
  6218. }
  6219. return [];
  6220. }
  6221. });
  6222. this.registerFunction('torch._C.getAllOperatorsFor', (name) => {
  6223. return torch._C.getRegistry().getOperators(name);
  6224. });
  6225. this.registerType('torch._C.Operator', class {
  6226. constructor(schema) {
  6227. this._schema = schema;
  6228. }
  6229. schema() {
  6230. return this._schema;
  6231. }
  6232. getOperation(/* node */) {
  6233. return null;
  6234. }
  6235. aliasAnalysisKind() {
  6236. const schemaRef = this.schema();
  6237. const alias_analysis = schemaRef.aliasAnalysis();
  6238. torch._C.TORCH_CHECK(alias_analysis === 'FROM_SCHEMA' || !schemaRef.hasAnyAliasInfo());
  6239. return alias_analysis;
  6240. }
  6241. });
  6242. this.registerFunction('torch._C.getRegistry', () => {
  6243. torch._C.r = torch._C.r || new torch._C.OperatorRegistry();
  6244. return torch._C.r;
  6245. });
  6246. this.registerFunction('torch._C._get_schema', (op_name, overload_name) => {
  6247. const operations = torch._C.getAllOperatorsFor(op_name);
  6248. for (const op of operations) {
  6249. if (op.schema().overload_name === overload_name) {
  6250. return op.schema();
  6251. }
  6252. }
  6253. throw new python.Error(`Schema '${op_name}.${overload_name}' not found.`);
  6254. });
  6255. this.registerFunction('torch._C._jit_get_schemas_for_operator', (op_name) => {
  6256. return torch._C.getAllOperatorsFor(op_name).map((op) => op.schema());
  6257. });
  6258. this.registerFunction('torch._C._jit_get_operation', (op_name) => {
  6259. const sortedOps = torch._C.getAllOperatorsFor(op_name);
  6260. if (sortedOps.length === 0) {
  6261. return [null, null];
  6262. }
  6263. const overload_names = sortedOps.map((op) => op.schema().overload_name);
  6264. return [{}, overload_names];
  6265. });
  6266. this.registerFunction('torch._C._get_operation_overload', (op_name, overload_name) => {
  6267. const operations = torch._C.getAllOperatorsFor(op_name);
  6268. for (const op of operations) {
  6269. if (op.schema().overload_name === overload_name) {
  6270. return [{}, {}, null];
  6271. }
  6272. }
  6273. return null;
  6274. });
  6275. this.registerFunction('torch._C._unset_dispatch_mode', () => {
  6276. return null;
  6277. });
  6278. this.registerFunction('torch._C._set_dispatch_mode', () => {
  6279. });
  6280. this.registerType('torch._C.MatchedSchema', class {
  6281. constructor(inputs, return_types, return_field_names, schema_name) {
  6282. this.inputs = inputs;
  6283. this.return_types = return_types;
  6284. this.register_field_names = return_field_names;
  6285. this.schema_name = schema_name;
  6286. }
  6287. });
  6288. this.registerType('torch._C.Self', class {
  6289. });
  6290. this.registerFunction('torch._C.toValues', (g, nvs) => {
  6291. return nvs.map((v) => v.value(g));
  6292. });
  6293. this.registerType('torch._C.SimpleSelf', class extends torch._C.Self {
  6294. constructor(classType) {
  6295. super();
  6296. this._classType = classType;
  6297. }
  6298. makeSugared(v) {
  6299. v.setType(this._classType);
  6300. return new torch._C.SimpleValue(v);
  6301. }
  6302. getClassType() {
  6303. return this._classType;
  6304. }
  6305. });
  6306. this.registerType('torch._C.Function', class {
  6307. isGraphFunction() {
  6308. return false;
  6309. }
  6310. name() {
  6311. return this.qualname().name();
  6312. }
  6313. });
  6314. this.registerType('torch._C.BuiltinOpFunction', class extends torch._C.Function {
  6315. constructor(qualname, schema) {
  6316. super();
  6317. this._name = qualname;
  6318. this._schema = schema;
  6319. }
  6320. qualname() {
  6321. return this._name;
  6322. }
  6323. getSchema() {
  6324. return this._schema;
  6325. }
  6326. ensure_defined() {
  6327. }
  6328. });
  6329. this.registerType('torch._C.DeadCodeEliminator', class {
  6330. constructor(...args) {
  6331. this._aliasDb = null;
  6332. this._useAliasDb = false;
  6333. this._memo = new Map();
  6334. this._marked = new Set();
  6335. this._liveValues = new Set();
  6336. this._deleteCallback = () => {};
  6337. if (args.length > 0 && args[0] instanceof torch.Graph) {
  6338. [this._graph, this._sideEffectPolicy] = args;
  6339. this._useAliasDb = true;
  6340. } else {
  6341. [this._sideEffectPolicy] = args;
  6342. }
  6343. }
  6344. run(block, recurse) {
  6345. this.eliminateDeadForkInputs(block, recurse);
  6346. this.mark(block.return_node());
  6347. this.mark(block);
  6348. this._deleteCallback(this._liveValues);
  6349. this.sweep(block, recurse);
  6350. }
  6351. setDeleteCallback(deleteCallback) {
  6352. this._deleteCallback = deleteCallback;
  6353. }
  6354. eliminateDeadForkInputs(block, recurse) {
  6355. for (const node of block.nodes()) {
  6356. if (recurse) {
  6357. for (const sb of node.blocks()) {
  6358. this.eliminateDeadForkInputs(sb, recurse);
  6359. }
  6360. }
  6361. if (node.kind() !== 'prim::fork') {
  6362. continue;
  6363. }
  6364. const g = node.g("Subgraph");
  6365. for (let i = 0; i < g.inputs().length; i++) {
  6366. if (!g.inputs()[i].hasUses()) {
  6367. g.eraseInput(i);
  6368. node.removeInput(i);
  6369. }
  6370. }
  6371. }
  6372. }
  6373. markReturnNode(node) {
  6374. if (this._marked.has(node)) {
  6375. return false;
  6376. }
  6377. torch._C.AT_ASSERT(node.owningBlock().return_node() === node);
  6378. const outerNode = node.owningBlock().owningNode();
  6379. if (outerNode === null || outerNode.kind() === 'prim::Reverse') {
  6380. return this.mark(node);
  6381. }
  6382. if (outerNode.kind() === 'prim::Loop' || outerNode.kind() === 'c10::onnx::Loop') {
  6383. const loop = new torch._C.LoopView(outerNode);
  6384. for (let i = 0; i < loop.carriedOutputs().length; i++) {
  6385. if (outerNode.kind() === 'onnx::Loop') {
  6386. this._liveValues.add(loop.bodyCarriedOutputs()[i]);
  6387. continue;
  6388. }
  6389. const innerInput = loop.bodyCarriedInputs()[i];
  6390. const innerOutput = loop.bodyCarriedOutputs()[i];
  6391. const outerOutput = loop.carriedOutputs()[i];
  6392. if (this._liveValues.has(outerOutput) || innerInput.hasUses()) {
  6393. this._liveValues.add(innerOutput);
  6394. }
  6395. }
  6396. this._liveValues.add(loop.nextCond());
  6397. } else {
  6398. torch._C.AT_ASSERT(outerNode.outputs().length === node.inputs().length);
  6399. for (let i = 0; i < outerNode.outputs().length; i++) {
  6400. const innerOutput = node.inputs()[i];
  6401. const outerOutput = outerNode.outputs()[i];
  6402. if (!this._liveValues.has(outerOutput)) {
  6403. this._liveValues.add(innerOutput);
  6404. }
  6405. }
  6406. }
  6407. this._marked.add(node);
  6408. return true;
  6409. }
  6410. markLoop(node) {
  6411. torch._C.TORCH_INTERNAL_ASSERT(node.kind() === 'prim::Loop');
  6412. let marked = false;
  6413. let anyMarked = false;
  6414. do {
  6415. marked = this.mark(node.blocks().at(0));
  6416. anyMarked = anyMarked || marked;
  6417. } while (marked);
  6418. return anyMarked;
  6419. }
  6420. mark(...args) {
  6421. if (args.length === 1 && args[0] instanceof torch.Block) {
  6422. const [block] = args;
  6423. let anyMarked = false;
  6424. for (const node of block.nodes()) {
  6425. if (this._sideEffectPolicy === 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS' && this.hasSideEffects(node)) {
  6426. const marked = this.mark(node);
  6427. anyMarked = anyMarked || marked;
  6428. }
  6429. }
  6430. const marked = this.markReturnNode(block.return_node());
  6431. anyMarked = anyMarked || marked;
  6432. for (const node of block.nodes()) {
  6433. if (node.kind() === 'prim::Loop') {
  6434. const marked = this.markLoop(node);
  6435. anyMarked = anyMarked || marked;
  6436. } else {
  6437. for (const subBlock of node.blocks()) {
  6438. const marked = this.mark(subBlock);
  6439. anyMarked = anyMarked || marked;
  6440. }
  6441. }
  6442. const marked = this.markIfLive(node);
  6443. anyMarked = anyMarked || marked;
  6444. }
  6445. return anyMarked;
  6446. }
  6447. if (args.length === 1 && args[0] instanceof torch.Node) {
  6448. const [node] = args;
  6449. if (this._marked.has(node)) {
  6450. return false;
  6451. }
  6452. this._marked.add(node);
  6453. let curNode = node;
  6454. while (curNode && curNode.owningBlock()) {
  6455. this.mark(curNode);
  6456. curNode = curNode.owningBlock().owningNode();
  6457. }
  6458. for (const input of node.inputs()) {
  6459. if (!this._liveValues.has(input)) {
  6460. this._liveValues.add(input);
  6461. }
  6462. }
  6463. return true;
  6464. }
  6465. throw new python.Error('Not implemented.');
  6466. }
  6467. markIfLive(node) {
  6468. for (const output of node.outputs()) {
  6469. if (this._liveValues.has(output)) {
  6470. return this.mark(node);
  6471. }
  6472. }
  6473. if (this._useAliasDb) {
  6474. if (this.getOrCreateAliasDb().writesToAlias(node, this._liveValues)) {
  6475. return this.mark(node);
  6476. }
  6477. }
  6478. return false;
  6479. }
  6480. sweep(block, recurse) {
  6481. const nodes = Array.from(block.nodes()).reverse();
  6482. for (const node of nodes) {
  6483. this.removeDeadBlockOutputs(node);
  6484. this.removeDeadLoopOutputs(node);
  6485. if (recurse) {
  6486. for (const block of node.blocks()) {
  6487. this.sweep(block, true);
  6488. }
  6489. }
  6490. if (!this._marked.has(node) && !node.hasUses()) {
  6491. node.destroy();
  6492. }
  6493. }
  6494. }
  6495. hasUntrackedMutation(node) {
  6496. if (!this._useAliasDb) {
  6497. if (node.kind() === 'prim::SetAttr') {
  6498. return true;
  6499. }
  6500. const schema = node.maybeSchema();
  6501. return schema && schema.is_mutable();
  6502. }
  6503. return this.getOrCreateAliasDb().writesToWildcard(node);
  6504. }
  6505. hasSideEffects(node) {
  6506. const it = this._memo.get(node);
  6507. if (it) {
  6508. return it;
  6509. }
  6510. const has_side_effects = node.hasSideEffects() ||
  6511. node.blocks().some((b) => Array.from(b.nodes()).some((n) => this.hasSideEffects(n))) ||
  6512. this.hasUntrackedMutation(node);
  6513. this._memo.set(node, has_side_effects);
  6514. return has_side_effects;
  6515. }
  6516. removeDeadBlockOutputs(node) {
  6517. if (node.kind() !== 'prim::If' && node.kind() !== 'prim::GradOf') {
  6518. return;
  6519. }
  6520. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6521. const i = i_1 - 1;
  6522. if (!node.outputs()[i].hasUses()) {
  6523. node.eraseOutput(i);
  6524. for (const b of node.blocks()) {
  6525. b.eraseOutput(i);
  6526. }
  6527. }
  6528. }
  6529. }
  6530. removeDeadLoopOutputs() {
  6531. }
  6532. getOrCreateAliasDb() {
  6533. if (!this._aliasDb) {
  6534. this._aliasDb = new torch._C.AliasDb(this._graph);
  6535. }
  6536. return this._aliasDb;
  6537. }
  6538. });
  6539. this.registerFunction('torch._C.EliminateDeadCode', (...args) => {
  6540. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6541. const [graph] = args;
  6542. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6543. const worker = new torch._C.DeadCodeEliminator(graph, sideEffectPolicy);
  6544. worker.run(graph.block(), /*recurse=*/true);
  6545. } else if (args.length > 0 && args[0] instanceof torch.Block) {
  6546. const [block] = args;
  6547. const recurse = false;
  6548. const sideEffectPolicy = 'DONT_DELETE_NODES_WITH_SIDE_EFFECTS';
  6549. const worker = new torch._C.DeadCodeEliminator(sideEffectPolicy);
  6550. worker.run(block, recurse);
  6551. } else {
  6552. throw new python.Error('Not implemented.');
  6553. }
  6554. });
  6555. this.registerFunction('torch._C.removeTupleNodes', () => {
  6556. });
  6557. this.registerFunction('torch._C.LowerSimpleTuples', (...args) => {
  6558. if (args.length === 1 && args[0] instanceof torch.Graph) {
  6559. const [graph] = args;
  6560. torch._C.LowerSimpleTuples(graph.block());
  6561. torch._C.EliminateDeadCode(graph);
  6562. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  6563. const [block] = args;
  6564. for (const n of block.nodes()) {
  6565. torch._C.removeTupleNodes(n, false);
  6566. for (const b of n.blocks()) {
  6567. torch._C.LowerSimpleTuples(b);
  6568. }
  6569. }
  6570. } else {
  6571. throw new python.Error('Not implemented.');
  6572. }
  6573. });
  6574. this.registerFunction('torch._C.attributesEqualCSE', (lhs, rhs) => {
  6575. torch._C.AT_ASSERT(lhs !== null);
  6576. torch._C.AT_ASSERT(rhs !== null);
  6577. if (lhs.hasAttributes() !== rhs.hasAttributes()) {
  6578. return false;
  6579. }
  6580. if (!lhs.hasAttributes() && !rhs.hasAttributes()) {
  6581. return true;
  6582. }
  6583. const lnames = lhs.attributeNames();
  6584. const rnames = rhs.attributeNames();
  6585. lnames.sort();
  6586. rnames.sort();
  6587. if (lnames.length !== rnames.length && !lnames.every((v, i) => v !== rnames[i])) {
  6588. return false;
  6589. }
  6590. for (const name of lnames) {
  6591. if (lhs.kindOf(name) !== rhs.kindOf(name)) {
  6592. return false;
  6593. }
  6594. const kind = lhs.kindOf(name);
  6595. switch (kind) {
  6596. case 'i':
  6597. case 'f':
  6598. case 's':
  6599. case 't': {
  6600. if (lhs[kind](name) !== rhs[kind](name)) {
  6601. return false;
  6602. }
  6603. break;
  6604. }
  6605. case 'c': {
  6606. const lc = lhs.c(name);
  6607. const rc = rhs.c(name);
  6608. if (lc.real !== rc.real || lc.imag !== rc.imag) {
  6609. return false;
  6610. }
  6611. break;
  6612. }
  6613. case 'ival': {
  6614. if (lhs[kind](name) !== rhs[kind](name)) {
  6615. return false;
  6616. }
  6617. break;
  6618. }
  6619. default: {
  6620. throw new python.Error('Not implemented.');
  6621. }
  6622. }
  6623. }
  6624. return true;
  6625. });
  6626. this.registerFunction('torch._C.get_hash', (...args) => {
  6627. let hash = 0;
  6628. for (const value of args) {
  6629. if (typeof value === 'number') {
  6630. hash += (value | 0);
  6631. } else if (typeof value === 'string') {
  6632. hash += (value.length | 0);
  6633. } else if (Array.isArray(value)) {
  6634. for (const item of value) {
  6635. hash += torch._C.get_hash(item);
  6636. }
  6637. } else if (value instanceof builtins.complex) {
  6638. hash += (value.real | 0) + (value.imag | 0);
  6639. }
  6640. }
  6641. return hash;
  6642. });
  6643. this.registerFunction('torch._C.HashNode', (k) => {
  6644. torch._C.AT_ASSERT(k !== null);
  6645. let constant_hash = 0;
  6646. if (k.kind() === 'prim::Constant') {
  6647. const type = k.output().type();
  6648. if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'i') {
  6649. constant_hash = k.i('value');
  6650. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'f') {
  6651. constant_hash = k.f('value');
  6652. } else if (type.isSubtypeOf(torch.NumberType.get()) && k.kindOf('value') === 'c') {
  6653. constant_hash = k.c('value');
  6654. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  6655. constant_hash = k.i('value');
  6656. }
  6657. }
  6658. return torch._C.get_hash(k.kind(), k.outputs().map((v) => v.type().kind()), k.inputs().map((v) => v.unique()), constant_hash);
  6659. });
  6660. this.registerFunction('torch._C.EqualNode', (lhs, rhs) => {
  6661. if (lhs === null && rhs === null) {
  6662. return true;
  6663. }
  6664. if (lhs === null || rhs === null) {
  6665. return false;
  6666. }
  6667. if (lhs.kind() !== rhs.kind()) {
  6668. return false;
  6669. }
  6670. const lhs_outputs = lhs.outputs();
  6671. const rhs_outputs = rhs.outputs();
  6672. if (lhs_outputs.length !== rhs_outputs.length) {
  6673. return false;
  6674. }
  6675. for (let i = 0; i < lhs_outputs.length; i++) {
  6676. const lt = lhs_outputs[i].type();
  6677. const rt = rhs_outputs[i].type();
  6678. if (!lt.equals(rt)) {
  6679. return false;
  6680. }
  6681. }
  6682. const lhs_inputs = lhs.inputs();
  6683. const rhs_inputs = rhs.inputs();
  6684. if (lhs_inputs.length !== rhs_inputs.length) {
  6685. return false;
  6686. }
  6687. if (!lhs_inputs.every((v, i) => v === rhs_inputs[i])) {
  6688. return false;
  6689. }
  6690. if (!torch._C.attributesEqualCSE(lhs, rhs)) {
  6691. return false;
  6692. }
  6693. if (lhs.blocks().length !== rhs.blocks().length) {
  6694. return false;
  6695. }
  6696. for (let i = 0; i < lhs.blocks().length; i++) {
  6697. if (lhs.blocks().at(i) !== rhs.blocks().at(i)) {
  6698. return false;
  6699. }
  6700. }
  6701. return true;
  6702. });
  6703. this.registerType('torch._C.NodeSet', class {
  6704. constructor() {
  6705. this._nodes = new Map();
  6706. }
  6707. insert(n) {
  6708. const key = torch._C.HashNode(n);
  6709. if (this._nodes.has(key)) {
  6710. this._nodes.get(key).push(n);
  6711. } else {
  6712. this._nodes.set(key, [n]);
  6713. }
  6714. }
  6715. get(n) {
  6716. const key = torch._C.HashNode(n);
  6717. if (this._nodes.has(key)) {
  6718. const nodes = this._nodes.get(key);
  6719. for (const node of nodes) {
  6720. if (torch._C.EqualNode(node, n)) {
  6721. return node;
  6722. }
  6723. }
  6724. }
  6725. return null;
  6726. }
  6727. has(n) {
  6728. return this.get(n) !== null;
  6729. }
  6730. });
  6731. this.registerFunction('torch._C.isinstance', (stack, types) => {
  6732. const ty = stack.pop().type();
  6733. for (const candidate of types) {
  6734. if (ty.isSubtypeOf(candidate)) {
  6735. stack.push(new torch._C.IValue(true, 'Bool'));
  6736. stack.push(true);
  6737. return;
  6738. }
  6739. }
  6740. stack.push(new torch._C.IValue(false, 'Bool'));
  6741. });
  6742. this.registerType('torch._C.Tuple', class {
  6743. constructor(elements) {
  6744. this._elements = elements;
  6745. }
  6746. static create(elements) {
  6747. return new torch._C.Tuple(elements);
  6748. }
  6749. elements() {
  6750. return this._elements;
  6751. }
  6752. });
  6753. this.registerFunction('torch._C.tupleConstruct', (stack, num_inputs) => {
  6754. torch._C.TORCH_CHECK(num_inputs <= stack.length);
  6755. const elems = stack.splice(stack.length - num_inputs, num_inputs);
  6756. const tuple = torch._C.Tuple.create(elems.reverse());
  6757. stack.push(new torch._C.IValue(tuple));
  6758. });
  6759. this.registerFunction('torch._C.runNodeIfInputsAreConstant', (n, ignore_custom_classes, db) => {
  6760. let stack = [];
  6761. for (const input of n.inputs()) {
  6762. const ival = torch._C.toIValue(input);
  6763. if (ival) {
  6764. stack.push(ival);
  6765. } else {
  6766. return null;
  6767. }
  6768. }
  6769. switch (n.kind()) {
  6770. case 'prim::ListUnpack': {
  6771. if (stack.back().toList().size() !== n.outputs().length) {
  6772. return null;
  6773. }
  6774. torch._C.listUnpack(stack, n.outputs().length);
  6775. break;
  6776. }
  6777. case 'prim::TupleConstruct': {
  6778. const tt = n.output().type().expect(torch.TupleType);
  6779. if (tt.name()) {
  6780. torch._C.namedTupleConstruct(stack, tt, n.inputs().length);
  6781. } else {
  6782. torch._C.tupleConstruct(stack, n.inputs().length);
  6783. }
  6784. break;
  6785. }
  6786. case 'prim::ListConstruct': {
  6787. torch._C.listConstruct(stack, n.output().type().expect(torch.ListType), n.inputs().length);
  6788. break;
  6789. }
  6790. case 'prim::DictConstruct': {
  6791. torch._C.dictConstruct(stack, n.output().type().expect(torch.DictType), n.inputs().length);
  6792. break;
  6793. }
  6794. case 'prim::CreateObject': {
  6795. torch._C.createObject(stack, n.output().type().expect(torch.ClassType), /*use_weak_ref*/ true);
  6796. break;
  6797. }
  6798. case 'prim::GetAttr': {
  6799. const attr = torch._C.pop(stack).toObject().getAttr(n.s('name'));
  6800. torch._C.push(stack, attr);
  6801. break;
  6802. }
  6803. case 'prim::isinstance': {
  6804. torch._C.isinstance(stack, n.tys('types'));
  6805. break;
  6806. }
  6807. default: {
  6808. const maybe_schema = n.maybeSchema();
  6809. if (maybe_schema && maybe_schema.is_vararg) {
  6810. return null;
  6811. }
  6812. // try
  6813. // {
  6814. // const op = n.getOperation();
  6815. // op(stack);
  6816. const [module, name] = n.kind().split('::');
  6817. const obj = torch.ops[module];
  6818. if (!obj) {
  6819. throw new python.Error(`Unknown constant module 'torch.ops.${module}'.`);
  6820. }
  6821. const fn = torch.ops[module].__getattr__(name);
  6822. if (!fn || !fn.__call__) {
  6823. throw new python.Error(`Unknown constant function 'torch.ops.${module}.${name}'.`);
  6824. }
  6825. const args = stack.map((v) => v.value);
  6826. const result = fn.__call__(...args);
  6827. if (result === undefined) {
  6828. stack = [];
  6829. } else if (result instanceof torch._C.IValue) {
  6830. stack = [result];
  6831. } else if (Array.isArray(result) && result.every((v) => v instanceof torch._C.IValue)) {
  6832. stack = result;
  6833. } else {
  6834. stack = [new torch._C.IValue(result)];
  6835. }
  6836. // } catch {
  6837. // stack = [];
  6838. // return null;
  6839. // }
  6840. break;
  6841. }
  6842. }
  6843. for (const v of stack) {
  6844. if (v.isTensor()) {
  6845. const t = v.toTensor();
  6846. if (t.defined() && t.requires_grad()) {
  6847. return null;
  6848. }
  6849. }
  6850. if (ignore_custom_classes) {
  6851. if (v.isCustomClass()) {
  6852. return null;
  6853. }
  6854. }
  6855. if (v.isCustomClass()) {
  6856. if (v.toObject().is_weak_compilation_ref()) {
  6857. continue;
  6858. }
  6859. if (!db) {
  6860. continue;
  6861. }
  6862. const n_non_const = n;
  6863. if (db.mayContainAlias(n_non_const.inputs(), [n_non_const.outputs()])) {
  6864. continue;
  6865. }
  6866. const obj = v.toObject();
  6867. obj.unsafe_make_weak_compilation_ref();
  6868. }
  6869. if (v.isObject()) {
  6870. if (!v.toObject().is_weak_compilation_ref()) {
  6871. return null;
  6872. }
  6873. }
  6874. }
  6875. return stack;
  6876. });
  6877. this.registerType('torch._C.ConstantPropagator', class {
  6878. constructor(graph, aliasing_types, ignore_custom_classes) {
  6879. this._made_change = false;
  6880. this._graph = graph;
  6881. this._aliasing_types = aliasing_types;
  6882. this._ignore_custom_classes = ignore_custom_classes;
  6883. }
  6884. static NoAliasDb(graph) {
  6885. return new torch._C.ConstantPropagator(graph, false, false);
  6886. }
  6887. run() {
  6888. this.ConstantPropagation(this._graph.block());
  6889. return this._made_change;
  6890. }
  6891. propagateNode(n) {
  6892. let outputs = [];
  6893. const outputs_opt = torch._C.runNodeIfInputsAreConstant(n, this._ignore_custom_classes);
  6894. if (outputs_opt) {
  6895. outputs = outputs_opt;
  6896. const graph = n.owningGraph();
  6897. const guard = new torch._C.WithInsertPoint(n);
  6898. for (let i = 0; i < outputs.length; i++) {
  6899. const new_output = torch._C.tryInsertConstant(graph, outputs[i]);
  6900. if (new_output) {
  6901. this._made_change = true;
  6902. if (outputs[i].isNone()) {
  6903. new_output.setType(n.outputs()[i].type());
  6904. }
  6905. n.outputs()[i].replaceAllUsesWith(new_output);
  6906. }
  6907. }
  6908. guard.dispose();
  6909. }
  6910. }
  6911. removeLoopNode(n) {
  6912. const loop_input_offset = 2;
  6913. for (let i = 0; i < n.outputs().length; i++) {
  6914. n.outputs()[i].replaceAllUsesWith(n.inputs()[i + loop_input_offset]);
  6915. }
  6916. this._made_change = true;
  6917. n.destroy();
  6918. }
  6919. loopWillNotRun(node) {
  6920. const [trip_count, start_cond] = node.inputs();
  6921. const iter_len = torch._C.constant_as(trip_count, 'toInt', 1);
  6922. const cond_val = torch._C.constant_as(start_cond, 'toBool', true);
  6923. const loop_might_run = cond_val && iter_len > 0;
  6924. return !loop_might_run;
  6925. }
  6926. inlineIfBody(body) {
  6927. const n = body.owningNode();
  6928. for (const body_node of body.nodes()) {
  6929. body_node.moveBefore(n);
  6930. }
  6931. for (let i = 0; i < n.outputs().length; i++) {
  6932. n.outputs()[i].replaceAllUsesWith(body.outputs()[i]);
  6933. }
  6934. n.destroy();
  6935. }
  6936. inlineIf(n) {
  6937. const input_bool = torch._C.constant_as(n.input(), 'toBool');
  6938. torch._C.AT_ASSERT(input_bool !== null);
  6939. const block_index = input_bool ? 0 : 1;
  6940. this.ConstantPropagation(n.blocks().at(block_index));
  6941. this.inlineIfBody(n.blocks().at(block_index));
  6942. this._made_change = true;
  6943. }
  6944. replaceAndRemoveIfOutput(n, i, replacement) {
  6945. n.outputs()[i].replaceAllUsesWith(replacement);
  6946. n.eraseOutput(i);
  6947. n.blocks().at(0).eraseOutput(i);
  6948. n.blocks().at(1).eraseOutput(i);
  6949. }
  6950. removeExtraIfOutputs(n) {
  6951. torch._C.TORCH_CHECK(n.kind() === 'prim::If');
  6952. const [true_block, false_block] = n.blocks();
  6953. const graph = n.owningGraph();
  6954. const initial_outputs = true_block.outputs().length;
  6955. const guard = new torch._C.WithInsertPoint(n);
  6956. for (let i = 0; i < true_block.outputs().length;) {
  6957. const t_out = true_block.outputs()[i];
  6958. const f_out = false_block.outputs()[i];
  6959. if (true_block.outputs()[i] === false_block.outputs()[i]) {
  6960. this.replaceAndRemoveIfOutput(n, i, true_block.outputs()[i]);
  6961. continue;
  6962. }
  6963. const maybe_const = torch._C.toIValue(t_out);
  6964. if (maybe_const && torch._C.EqualNode(t_out.node(), f_out.node())) {
  6965. const new_const = graph.insertConstant(maybe_const);
  6966. this.replaceAndRemoveIfOutput(n, i, new_const);
  6967. continue;
  6968. }
  6969. i++;
  6970. }
  6971. this._made_change = this._made_change || (initial_outputs !== true_block.outputs().length);
  6972. guard.dispose();
  6973. }
  6974. removeExtraLoopOutputs(node) {
  6975. const initial_outputs = node.outputs().length;
  6976. const [loop_body] = node.blocks();
  6977. const loop_input_offset = 2;
  6978. const loop_body_offset = 1;
  6979. for (let i_1 = node.outputs().length; i_1 > 0; i_1--) {
  6980. const i = i_1 - 1;
  6981. if (loop_body.inputs()[loop_body_offset + i] === loop_body.outputs()[loop_body_offset + i]) {
  6982. const node_input = node.inputs()[loop_input_offset + i];
  6983. node.outputs().at(i).replaceAllUsesWith(node_input);
  6984. loop_body.inputs()[loop_body_offset + i].replaceAllUsesWith(node_input);
  6985. node.eraseOutput(i);
  6986. node.removeInput(loop_input_offset + i);
  6987. loop_body.eraseInput(loop_body_offset + i);
  6988. loop_body.eraseOutput(loop_body_offset + i);
  6989. }
  6990. }
  6991. this._made_change = this._made_change || (initial_outputs !== node.outputs().length);
  6992. }
  6993. noMutableValues(values) {
  6994. return values.every((v) => !torch._C.AliasDb.isMutableType(v));
  6995. }
  6996. getOrCreateAliasDb() {
  6997. if (!this._aliasDb) {
  6998. this._aliasDb = new torch._C.AliasDb(this._graph);
  6999. }
  7000. return this._aliasDb;
  7001. }
  7002. supportedNode(n) {
  7003. torch._C.skip_list = torch._C.skip_list || new Set([
  7004. 'prim::If',
  7005. 'prim::Loop',
  7006. 'prim::Closure',
  7007. 'prim::Constant',
  7008. 'prim::AutogradZero',
  7009. 'prim::Uninitialized',
  7010. 'prim::Guard',
  7011. 'prim::profile',
  7012. 'prim::profile_ivalue',
  7013. 'prim::unchecked_unwrap_optional',
  7014. 'prim::awaitable',
  7015. 'aten::dequantize'
  7016. ]);
  7017. let no_mutation = false;
  7018. if (this._aliasing_types) {
  7019. no_mutation = !this.getOrCreateAliasDb().hasWriters(n);
  7020. } else {
  7021. no_mutation = this.noMutableValues(n.inputs()) && this.noMutableValues(n.outputs());
  7022. }
  7023. return no_mutation && !n.kind().startsWith('onnx::') && !torch._C.skip_list.has(n.kind()) && !n.isNondeterministic() && !n.hasSideEffects() && n.blocks().length === 0;
  7024. }
  7025. ConstantPropagation(...args) {
  7026. if (args[0] instanceof torch.Graph) {
  7027. throw new python.Error('Not implemented.');
  7028. } else if (args[0] instanceof torch.Block) {
  7029. const [block] = args;
  7030. for (const n of block.nodes()) {
  7031. this.ConstantPropagation(n);
  7032. }
  7033. } else if (args[0] instanceof torch.Node) {
  7034. const [n] = args;
  7035. const constant_inputs = n.inputs().every((v) => v.node().kind() === 'prim::Constant');
  7036. if (n.kind() === 'prim::If') {
  7037. if (constant_inputs) {
  7038. this.inlineIf(n);
  7039. } else {
  7040. this.ConstantPropagation(n.blocks());
  7041. this.removeExtraIfOutputs(n);
  7042. }
  7043. } else if (n.kind() === 'prim::Loop') {
  7044. if (this.loopWillNotRun(n)) {
  7045. this.removeLoopNode(n);
  7046. } else {
  7047. this.ConstantPropagation(n.blocks());
  7048. this.removeExtraLoopOutputs(n);
  7049. }
  7050. } else if (constant_inputs && this.supportedNode(n)) {
  7051. this.propagateNode(n);
  7052. } else {
  7053. this.ConstantPropagation(n.blocks()); // not implemented
  7054. }
  7055. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((b) => b instanceof torch.Block)) {
  7056. const [blocks] = args;
  7057. for (const block of blocks) {
  7058. this.ConstantPropagation(block);
  7059. }
  7060. } else {
  7061. throw new python.Error('Not implemented.');
  7062. }
  7063. }
  7064. });
  7065. this.registerFunction('torch._C.ConstantPropagationImmutableTypes', (graph) => {
  7066. const cp = torch._C.ConstantPropagator.NoAliasDb(graph);
  7067. const made_change = cp.run();
  7068. if (made_change) {
  7069. torch._C.EliminateDeadCode(graph);
  7070. }
  7071. return made_change;
  7072. });
  7073. this.registerType('torch._C.MutableTypePtrHelper', class {
  7074. constructor(mutable_type_cache) {
  7075. this._mutable_type_cache = mutable_type_cache;
  7076. }
  7077. mapTypeToAliasTypeSet(type) {
  7078. if (this._mutable_type_cache) {
  7079. const result = this.mapTypeToBorrowedAliasTypeSet(type);
  7080. if (result) {
  7081. return result;
  7082. }
  7083. }
  7084. return this.mapTypeToAliasTypeSetImpl(type);
  7085. }
  7086. mapTypeToAliasTypeSetImpl(type) {
  7087. if (type instanceof torch.ListType ||
  7088. type instanceof torch.DictType ||
  7089. type instanceof torch.ClassType ||
  7090. type instanceof torch.TensorType) {
  7091. return [torch._C.unshapedType(type)];
  7092. }
  7093. if (type instanceof torch.UnionType) {
  7094. const mutable_types = [];
  7095. for (const inner of type.expect(torch.UnionType).containedTypes()) {
  7096. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7097. if (maybe_inner_types) {
  7098. mutable_types.push(...maybe_inner_types);
  7099. }
  7100. }
  7101. if (mutable_types.length === 0) {
  7102. return null;
  7103. }
  7104. return mutable_types;
  7105. }
  7106. if (type instanceof torch.OptionalType) {
  7107. const inner = type.getElementType();
  7108. return this.mapTypeToAliasTypeSet(inner);
  7109. }
  7110. if (type instanceof torch.AnyType) {
  7111. return [torch._C.AliasTypeSet([type])];
  7112. }
  7113. if (type instanceof torch.FutureType) {
  7114. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7115. if (maybe_mut_types) {
  7116. return [torch._C.AliasTypeSet([torch.FutureType.create(torch._C.toSingleType(maybe_mut_types))])];
  7117. }
  7118. return null;
  7119. }
  7120. if (type instanceof torch.AwaitType) {
  7121. const maybe_mut_types = this.mapTypeToAliasTypeSet(type.getElementType());
  7122. if (maybe_mut_types) {
  7123. return [torch._C.AliasTypeSet([torch.AwaitType.create(torch._C.toSingleType(maybe_mut_types))])];
  7124. }
  7125. return null;
  7126. }
  7127. if (type instanceof torch.TupleType) {
  7128. const mutable_types = [];
  7129. for (const inner of type.elements()) {
  7130. const maybe_inner_types = this.mapTypeToAliasTypeSet(inner);
  7131. if (maybe_inner_types) {
  7132. mutable_types.push(...maybe_inner_types);
  7133. }
  7134. }
  7135. if (mutable_types.length === 0) {
  7136. return null;
  7137. }
  7138. return [[torch.TupleType.create(mutable_types)]];
  7139. }
  7140. return null;
  7141. }
  7142. });
  7143. this.registerFunction('torch._C.isMutableTypeImpl', (type, mutable_type_cache) => {
  7144. if (type instanceof torch.TensorType || type instanceof torch.ListType ||
  7145. type instanceof torch.ClassType || type instanceof torch.DictType) {
  7146. return true;
  7147. }
  7148. const helper = new torch._C.MutableTypePtrHelper(mutable_type_cache);
  7149. if (mutable_type_cache) {
  7150. return helper.mapTypeToBorrowedAliasTypeSet(type) !== null;
  7151. }
  7152. return helper.mapTypeToAliasTypeSet(type) !== null;
  7153. });
  7154. this.registerType('torch._C.AliasDb', class {
  7155. constructor() {
  7156. this._writeIndex = new Map();
  7157. }
  7158. static isMutableType(...args) {
  7159. if (args[0] instanceof torch.Type) {
  7160. const [type] = args;
  7161. return torch._C.isMutableTypeImpl(type, null);
  7162. }
  7163. if (args[0] instanceof torch.Value) {
  7164. const [value] = args;
  7165. return torch._C.AliasDb.isMutableType(value.type());
  7166. }
  7167. throw new python.Error('Not implemented.');
  7168. }
  7169. writesToAlias(/* n, vs */) {
  7170. /*
  7171. const writtenTo = this.getWrites(n);
  7172. if (writtenTo.length === 0) {
  7173. return false;
  7174. }
  7175. MemoryLocations locs;
  7176. for (const v of vs) {
  7177. const it = elementMap_.find(v);
  7178. if (it != elementMap_.end()) {
  7179. const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
  7180. if (writtenTo.intersects(vlocs)) {
  7181. return true;
  7182. }
  7183. }
  7184. }
  7185. */
  7186. return false;
  7187. }
  7188. writesToWildcard(n) {
  7189. if (!this._writeIndex.has(n)) {
  7190. return false;
  7191. }
  7192. const writes = this._writeIndex.get(n);
  7193. for (const pr of this._wildcardIndex) {
  7194. const [, wildcardElement] = pr;
  7195. if (writes.test(wildcardElement.index)) {
  7196. return true;
  7197. }
  7198. }
  7199. return false;
  7200. }
  7201. safeToChangeAliasingRelationship(a, b) {
  7202. if (torch._C.hasWriters(a) || torch._C.hasWriters(b)) {
  7203. return false;
  7204. }
  7205. return !(torch._C.escapesScope(a) && torch._C.escapesScope(b));
  7206. }
  7207. });
  7208. this.registerFunction('torch._C.hasWriters', () => {
  7209. });
  7210. this.registerFunction('torch._C.escapesScope', () => {
  7211. });
  7212. this.registerType('torch._C.DepthFirstGraphNodeIterator', class {
  7213. constructor(graph) {
  7214. this._current = graph.block().nodes().front();
  7215. }
  7216. next() {
  7217. return null;
  7218. }
  7219. });
  7220. this.registerType('torch._C.ConcatCombiner', class {
  7221. constructor(graph) {
  7222. this._graph = graph;
  7223. this._aliasDb = new torch._C.AliasDb(graph);
  7224. this._combinable_concats = [];
  7225. }
  7226. collectOptimizableConcats() {
  7227. const graph_it = new torch._C.DepthFirstGraphNodeIterator(this._graph);
  7228. for (let node = graph_it.next(); node !== null; node = graph_it.next()) {
  7229. if (node.kind() === 'aten::cat') {
  7230. this.handleConcat(node);
  7231. }
  7232. }
  7233. }
  7234. combineConcats() {
  7235. if (this._combinable_concats.length === 0) {
  7236. return false;
  7237. }
  7238. const list_construct_inputs = this.getListConstructInputs();
  7239. for (const node_and_new_list of list_construct_inputs) {
  7240. const [node, inputs] = node_and_new_list;
  7241. const new_list_construct = this.createListConstruct(inputs);
  7242. const old_list_construct = node.input(0).node();
  7243. new_list_construct.output().setType(old_list_construct.output().type());
  7244. new_list_construct.insertBefore(node);
  7245. old_list_construct.replaceAllUsesWith(new_list_construct);
  7246. }
  7247. return true;
  7248. }
  7249. run() {
  7250. this.collectOptimizableConcats();
  7251. const changed = this.combineConcats();
  7252. if (changed) {
  7253. torch._C.EliminateDeadCode(this._graph);
  7254. }
  7255. return changed;
  7256. }
  7257. });
  7258. this.registerFunction('torch._C.CombineConcats', (graph) => {
  7259. const changed = new torch._C.ConcatCombiner(graph).run();
  7260. return changed;
  7261. });
  7262. this.registerType('torch._C.PeepholeOptimizeImpl', class {
  7263. constructor(graph, disable_shape_peepholes) {
  7264. this._graph = graph;
  7265. this._shape_peepholes = !disable_shape_peepholes;
  7266. }
  7267. run() {
  7268. let changed = this.optimizeBlock(this._graph.block());
  7269. /* changed |= torch._C.PeepholeOptimizeListIdioms(this._graph);
  7270. changed |= torch._C.PeepholeOptimizeDictIdioms(this._graph);
  7271. changed |= torch._C.PeepholeOptimizeAliasSensitive(this._graph, this._shape_peepholes);
  7272. changed |= torch._C.PeepholeOptimizeNonTensor(this._graph); */
  7273. changed = changed || torch._C.CombineConcats(this._graph);
  7274. return changed;
  7275. }
  7276. optimizeBlock(block) {
  7277. let changed = false;
  7278. for (const node of block.nodes()) {
  7279. for (const sub_block of node.blocks()) {
  7280. changed = changed || this.optimizeBlock(sub_block);
  7281. }
  7282. if (node.kind() !== 'prim::Constant') {
  7283. const guard = new torch._C.WithInsertPoint(node);
  7284. for (const output of node.outputs()) {
  7285. if (output.type() instanceof torch.NoneType) {
  7286. output.replaceAllUsesWith(this._graph.insertConstant(new torch._C.IValue()));
  7287. changed = true;
  7288. }
  7289. }
  7290. guard.dispose();
  7291. }
  7292. if (node.kind() === 'prim::If') {
  7293. // throw new python.Error('Not implemented.');
  7294. /*
  7295. const n = new torch._C.IfView(node);
  7296. // this handles redundant short circuits like "x and True" or "x or
  7297. // False"
  7298. for (const auto i : c10::irange(n.outputs().length)) {
  7299. if (n.outputs().at(i).type() != torch.BoolType.get()) {
  7300. continue;
  7301. }
  7302. const true_val = constant_as<bool>(n.thenOutputs().at(i)).value_or(false);
  7303. const false_val = constant_as<bool>(n.elseOutputs().at(i)).value_or(true);
  7304. if (true_val && !false_val) {
  7305. n.outputs().at(i).replaceAllUsesWith(n.cond());
  7306. changed = true;
  7307. }
  7308. }
  7309. for (let i = 0; i < n.outputs().length; ++i) {
  7310. const inputs_non_optional = !n.thenOutputs().at(i).type().cast<OptionalType>() && !n.elseOutputs().at(i).type().cast<OptionalType>();
  7311. const output_optional = n.outputs()[i].type();
  7312. if (inputs_non_optional && output_optional instanceof torch.OptionalType) {
  7313. const unif = torch._c.unifyTypes(n.thenOutputs().at(i).type(), n.elseOutputs().at(i).type())
  7314. if (unif) {
  7315. n.outputs()[i].setType(unif);
  7316. changed = true;
  7317. }
  7318. }
  7319. }
  7320. */
  7321. } else if (node.kind() === 'aten::__is__' || node.kind() === 'aten::__isnot__') {
  7322. torch._C.AT_ASSERT(node.inputs().length === 2);
  7323. for (const check_none_index of [0, 1]) {
  7324. const input_must_be_none = node.inputs()[check_none_index].mustBeNone();
  7325. const other_must_not_be_none = node.inputs().at(1 - check_none_index).mustNotBeNone();
  7326. if (input_must_be_none && other_must_not_be_none) {
  7327. const guard = new torch._C.WithInsertPoint(node);
  7328. const output = node.owningGraph().insertConstant(node.kind() === 'aten::__isnot__');
  7329. node.output().replaceAllUsesWith(output);
  7330. changed = true;
  7331. guard.dispose();
  7332. }
  7333. }
  7334. } else if (node.kind() === 'prim::unchecked_unwrap_optional' || node.kind() === 'aten::_unwrap_optional') {
  7335. throw new python.Error('Not implemented.');
  7336. /*
  7337. // we are unwrapping an input that can't be None, remove the unwrap
  7338. const input = node.input();
  7339. if (input.mustNotBeNone()) {
  7340. node.output().replaceAllUsesWith(node.input());
  7341. changed = true;
  7342. }
  7343. */
  7344. } else if (node.kind() === 'prim::unchecked_cast') {
  7345. const input_type = torch._C.unshapedType(node.input().type());
  7346. const output_type = torch._C.unshapedType(node.output().type());
  7347. if (input_type.isSubtypeOf(output_type)) {
  7348. node.output().replaceAllUsesWith(node.input());
  7349. changed = true;
  7350. }
  7351. } else if ((node.kind() === 'aten::Int' || node.kind() === 'aten::ceil') && node.inputs().length === 1 && node.input().type() instanceof torch.IntType) {
  7352. node.output().replaceAllUsesWith(node.input());
  7353. changed = true;
  7354. } else if (node.kind() === 'aten::ne' || node.kind() === 'aten::eq') {
  7355. if (node.inputs().length !== 2 || node.inputs()[0] !== node.inputs()[1]) {
  7356. continue;
  7357. }
  7358. const inp_type = node.inputs()[0].type();
  7359. const immut_type = (type) => {
  7360. const kind = type.kind();
  7361. const handled_immutable_types = new Set('BoolType', 'IntType', 'FloatType', 'NoneType');
  7362. return handled_immutable_types.has(kind);
  7363. };
  7364. let non_throwing_type = false;
  7365. if (inp_type instanceof torch.ListType) {
  7366. non_throwing_type = immut_type(inp_type.getElementType());
  7367. } else if (inp_type instanceof torch.DictType) {
  7368. non_throwing_type = immut_type(inp_type.getKeyType()) && immut_type(inp_type.getValueType());
  7369. } else {
  7370. non_throwing_type = immut_type(inp_type);
  7371. }
  7372. if (non_throwing_type) {
  7373. const guard = new torch._C.WithInsertPoint(node);
  7374. node.output().replaceAllUsesWith(this._graph.insertConstant(node.kind() === 'aten::eq'));
  7375. changed = true;
  7376. guard.dispose();
  7377. }
  7378. } else if (node.kind() === 'aten::mul' || node.kind() === 'aten::floordiv' || node.kind() === 'aten::div') {
  7379. // changed = changed || torch._C.trySimplifyMulOrDiv(node);
  7380. } else if (node.kind() === 'aten::add' || node.kind() === 'aten::sub') {
  7381. // changed = changed || torch._C.trySimplifyAddOrSub(node);
  7382. }
  7383. }
  7384. return changed;
  7385. }
  7386. });
  7387. this.registerFunction('torch._C.PeepholeOptimize', (graph, addmm_fusion_enabled) => {
  7388. const peephole = new torch._C.PeepholeOptimizeImpl(graph, addmm_fusion_enabled);
  7389. const changed = peephole.run();
  7390. if (changed) {
  7391. torch._C.EliminateDeadCode(graph.block());
  7392. }
  7393. return changed;
  7394. });
  7395. this.registerFunction('torch._C.TORCH_INTERNAL_ASSERT', (cond) => {
  7396. if (!cond) {
  7397. throw new python.Error('Assertion failed.');
  7398. }
  7399. });
  7400. this.registerFunction('torch._C.TORCH_CHECK', (cond) => {
  7401. if (!cond) {
  7402. throw new python.Error('Assertion failed.');
  7403. }
  7404. });
  7405. this.registerFunction('torch._C.AT_ASSERT', (cond) => {
  7406. if (!cond) {
  7407. throw new python.Error('Assertion failed.');
  7408. }
  7409. });
  7410. this.registerFunction('torch._C.eraseListLiterals', (graph) => {
  7411. const it = new torch._C.DepthFirstGraphNodeIterator(graph);
  7412. for (let next_node = it.next(); next_node !== null;) {
  7413. const node = next_node;
  7414. next_node = it.next();
  7415. if (node.kind() === 'prim::EmptyListLiteral') {
  7416. if (node.hasUses()) {
  7417. torch._C.TORCH_INTERNAL_ASSERT(node.output().type().isSubtypeOf(torch.ListType.ofTensors()));
  7418. }
  7419. const li = graph.createList(torch.TensorType.get(), []);
  7420. li.insertBefore(node);
  7421. node.replaceAllUsesWith(li);
  7422. }
  7423. node.destroy();
  7424. }
  7425. });
  7426. this.registerFunction('torch._C.ConstantPooling', (...args) => {
  7427. if (args.length === 1 && args[0] instanceof torch.Graph) {
  7428. const [graph] = args;
  7429. const aliasDb = new torch._C.AliasDb(graph);
  7430. const constants = new torch._C.NodeSet();
  7431. torch._C.ConstantPooling(graph.block(), constants, aliasDb);
  7432. } else if (args.length === 3 && args[0] instanceof torch.Block) {
  7433. const [block, constants, aliasDb] = args;
  7434. for (const node of block.nodes()) {
  7435. if (node.blocks().length > 0) {
  7436. for (const block of node.blocks()) {
  7437. torch._C.ConstantPooling(block, constants, aliasDb);
  7438. }
  7439. continue;
  7440. }
  7441. if (node.kind() !== 'prim::Constant') {
  7442. continue;
  7443. }
  7444. if (constants.has(node)) {
  7445. const existing = constants.get(node);
  7446. const old_ivalue = torch._C.toIValue(existing.output());
  7447. const new_ivalue = torch._C.toIValue(node.output());
  7448. const same_identity = (old_ivalue && new_ivalue && (old_ivalue.is(new_ivalue)));
  7449. if (!same_identity && !aliasDb.safeToChangeAliasingRelationship(node.outputs(), existing.outputs())) {
  7450. continue;
  7451. }
  7452. node.replaceAllUsesWith(existing);
  7453. node.destroy();
  7454. continue;
  7455. } else {
  7456. constants.insert(node);
  7457. }
  7458. const [first_node] = node.owningGraph().block().nodes();
  7459. if (node !== first_node) {
  7460. node.moveBefore(first_node);
  7461. }
  7462. }
  7463. } else {
  7464. throw new python.Error('Not implemented.');
  7465. }
  7466. });
  7467. this.registerFunction('torch._C.handleBlock', (/* block, initial_state */) =>{
  7468. /*
  7469. const autocast_stack = [];
  7470. let incompatible_amp = null;
  7471. const current_state = () => autocast_stack.length === 0 ? initial_state : autocast_stack.top().context;
  7472. for (const node of block.nodes()) {
  7473. switch (node.kind()) {
  7474. case 'prim::CallFunction':
  7475. if (current_state() === initial_state) {
  7476. if (current_state()) {
  7477. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7478. }
  7479. break;
  7480. }
  7481. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value(), "Calls are not expected with AMP & JIT");
  7482. incompatible_amp = true;
  7483. break;
  7484. case 'prim::CallMethod':
  7485. if (current_state() === initial_state) {
  7486. if (current_state()) {
  7487. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7488. }
  7489. break;
  7490. }
  7491. if (node.input(0).type() instanceof torch.ClassType) {
  7492. const class_type = node.input(0).type();
  7493. const name = node.s('name');
  7494. const fn = class_type.getMethod(name);
  7495. if (!fn.isGraphFunction()) {
  7496. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7497. incompatible_amp = true;
  7498. }
  7499. } else {
  7500. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || incompatible_amp.value());
  7501. incompatible_amp = true;
  7502. }
  7503. break;
  7504. case 'prim::Enter': {
  7505. const autocast_scope = torch._C.parseAutocast(node.input(), current_state());
  7506. if (autocast_scope) {
  7507. if (node.hasUses()) {
  7508. torch._C.TORCH_CHECK(false, "`with autocast() as ...` is not supported");
  7509. }
  7510. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7511. incompatible_amp = false;
  7512. autocast_stack.push(autocast_scope);
  7513. }
  7514. break;
  7515. }
  7516. case 'prim::Exit': {
  7517. if (torch._C.isAutocastNode(node.input(0))) {
  7518. torch._C.TORCH_INTERNAL_ASSERT(!autocast_stack.empty());
  7519. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.top().instance === node.input());
  7520. torch._C.TORCH_INTERNAL_ASSERT(!incompatible_amp.has_value() || !incompatible_amp.value());
  7521. incompatible_amp = false;
  7522. autocast_stack.pop();
  7523. }
  7524. break;
  7525. }
  7526. case 'aten::is_autocast_enabled': {
  7527. torch._C.updateAutocastEnabledCheck(node, current_state().gpu_enabled);
  7528. break;
  7529. }
  7530. case 'aten::is_autocast_cpu_enabled': {
  7531. torch._C.updateAutocastEnabledCheck(node, current_state().cpu_enabled);
  7532. break;
  7533. }
  7534. case 'aten::_convolution':
  7535. case 'aten::conv1d':
  7536. case 'aten::conv2d':
  7537. case 'aten::conv3d':
  7538. case 'aten::conv_tbc':
  7539. case 'aten::conv_transpose1d':
  7540. case 'aten::convolution':
  7541. case 'aten::cudnn_convolution':
  7542. case 'aten::cudnn_convolution_transpose':
  7543. case 'aten::prelu':
  7544. case 'aten::addmm':
  7545. case 'aten::addmv':
  7546. case 'aten::addr':
  7547. case 'aten::matmul':
  7548. case 'aten::mm':
  7549. case 'aten::mv':
  7550. case 'aten::linear':
  7551. case 'aten::addbmm':
  7552. case 'aten::baddbmm':
  7553. case 'aten::bmm':
  7554. case 'aten::chain_matmul':
  7555. case 'aten::_thnn_fused_lstm_cell':
  7556. case 'aten::_thnn_fused_gru_cell':
  7557. case 'aten::lstm_cell':
  7558. case 'aten::gru_cell':
  7559. case 'aten::rnn_tanh_cell':
  7560. case 'aten::rnn_relu_cell': {
  7561. if (!node.schema().is_mutable()) {
  7562. torch._C.castTensorInputs(node, 'aten::_autocast_to_reduced_precision', current_state());
  7563. }
  7564. break;
  7565. }
  7566. case 'aten::native_layer_norm':
  7567. case 'aten::acos':
  7568. case 'aten::asin':
  7569. case 'aten::cosh':
  7570. case 'aten::erfinv':
  7571. case 'aten::exp':
  7572. case 'aten::expm1':
  7573. case 'aten::log':
  7574. case 'aten::log10':
  7575. case 'aten::log2':
  7576. case 'aten::log1p':
  7577. case 'aten::reciprocal':
  7578. case 'aten::rsqrt':
  7579. case 'aten::sinh':
  7580. case 'aten::tan':
  7581. case 'aten::pow':
  7582. case 'aten::softplus':
  7583. case 'aten::gelu':
  7584. case 'aten::layer_norm':
  7585. case 'aten::group_norm':
  7586. case 'aten::frobenius_norm':
  7587. case 'aten::nuclear_norm':
  7588. case 'aten::cosine_similarity':
  7589. case 'aten::cosine_embedding_loss':
  7590. case 'aten::nll_loss':
  7591. case 'aten::nll_loss2d':
  7592. case 'aten::hinge_embedding_loss':
  7593. case 'aten::kl_div':
  7594. case 'aten::l1_loss':
  7595. case 'aten::smooth_l1_loss':
  7596. case 'aten::mse_loss':
  7597. case 'aten::margin_ranking_loss':
  7598. case 'aten::multilabel_margin_loss':
  7599. case 'aten::soft_margin_loss':
  7600. case 'aten::triplet_margin_loss':
  7601. case 'aten::multi_margin_loss':
  7602. case 'aten::binary_cross_entropy_with_logits':
  7603. case 'aten::dist':
  7604. case 'aten::pdist':
  7605. case 'aten::cdist':
  7606. case 'aten::renorm':
  7607. case 'aten::logsumexp': {
  7608. if (!node.schema().is_mutable()) {
  7609. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7610. }
  7611. break;
  7612. }
  7613. case 'aten::prod':
  7614. case 'aten::log_softmax':
  7615. case 'aten::cumprod':
  7616. case 'aten::cumsum':
  7617. case 'aten::sum': {
  7618. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7619. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', current_state());
  7620. }
  7621. break;
  7622. }
  7623. case 'aten::softmax': {
  7624. if (!node.schema().is_mutable() && !torch._C.hasExplicitDtypeArgument(node)) {
  7625. const context = current_state();
  7626. context.cpu_enabled = false;
  7627. torch._C.castTensorInputs(node, 'aten::_autocast_to_full_precision', context);
  7628. }
  7629. break;
  7630. }
  7631. case 'aten::addcdiv':
  7632. case 'aten::addcmul':
  7633. case 'aten::atan2':
  7634. case 'aten::bilinear':
  7635. case 'aten::cat':
  7636. case 'aten::cross':
  7637. case 'aten::dot':
  7638. case 'aten::equal':
  7639. case 'aten::index_put':
  7640. case 'aten::stack':
  7641. case 'aten::tensordot':
  7642. case 'aten::add':
  7643. case 'aten::sub':
  7644. case 'aten::mul':
  7645. case 'aten::div': {
  7646. if (!node.schema().is_mutable()) {
  7647. torch._C.castInputsToWidestType(node, current_state());
  7648. }
  7649. break;
  7650. }
  7651. case 'aten::binary_cross_entropy': {
  7652. if (current_state()) {
  7653. torch._C.TORCH_CHECK(false, "Unsafe to autocast");
  7654. }
  7655. break;
  7656. }
  7657. default: {
  7658. break;
  7659. }
  7660. }
  7661. for (const sub_block of node.blocks()) {
  7662. torch._C.handleBlock(sub_block, current_state());
  7663. }
  7664. }
  7665. torch._C.TORCH_INTERNAL_ASSERT(autocast_stack.length === 0);
  7666. */
  7667. });
  7668. this.registerFunction('torch._C.autocastEnabled', () => {
  7669. return true;
  7670. });
  7671. this.registerFunction('torch._C.Autocast', (graph) => {
  7672. if (torch._C.autocastEnabled()) {
  7673. const init = null;
  7674. /* AutocastContext init = {
  7675. at::autocast::is_autocast_enabled(at::kCUDA),
  7676. at::autocast::is_autocast_enabled(at::kCPU),
  7677. at::autocast::get_autocast_dtype(at::kCUDA),
  7678. at::autocast::get_autocast_dtype(at::kCPU)}; */
  7679. torch._C.handleBlock(graph.block(), init);
  7680. }
  7681. });
  7682. this.registerFunction('torch._C.preoptimizeGraph', (graph, disable_autocast) => {
  7683. disable_autocast = disable_autocast || false;
  7684. torch._C.Inline(graph);
  7685. torch._C.PeepholeOptimize(graph, true);
  7686. torch._C.ConstantPropagationImmutableTypes(graph);
  7687. if (!disable_autocast) {
  7688. torch._C.Autocast(graph);
  7689. }
  7690. torch._C.ConstantPooling(graph);
  7691. });
  7692. this.registerType('torch._C.GraphFunction', class extends torch._C.Function {
  7693. constructor(name, graph, function_creator, executor_execution_mode) {
  7694. super();
  7695. this._name = name;
  7696. this._graph = graph;
  7697. this._executor_execution_mode = executor_execution_mode || null;
  7698. this._function_creator = function_creator;
  7699. this._force_no_amp = false;
  7700. }
  7701. isGraphFunction() {
  7702. return true;
  7703. }
  7704. qualname() {
  7705. return this._name;
  7706. }
  7707. graph() {
  7708. return this._graph;
  7709. }
  7710. optimized_graph() {
  7711. const graph_ref = this._graph.copy();
  7712. torch._C.preoptimizeGraph(graph_ref, this._force_no_amp);
  7713. return graph_ref;
  7714. }
  7715. ensure_defined() {
  7716. if (this._function_creator) {
  7717. const creator = this._function_creator;
  7718. this._function_creator = () => {
  7719. throw new python.Error('Recursive method call.');
  7720. };
  7721. creator(this);
  7722. this._function_creator = null;
  7723. }
  7724. this.check_single_output();
  7725. }
  7726. check_single_output() {
  7727. if (this.graph().outputs().length !== 1) {
  7728. throw new python.Error('Graph must have a single output.');
  7729. }
  7730. }
  7731. getSchema() {
  7732. this._schema = this._schema || this.defaultSchemaFor(this);
  7733. return this._schema;
  7734. }
  7735. setSchema(schema) {
  7736. this._schema = schema;
  7737. }
  7738. num_inputs() {
  7739. return this.graph().inputs().length;
  7740. }
  7741. unshapedType(type) {
  7742. if (type.isSubtypeOf(torch.TensorType.get())) {
  7743. return torch.TensorType.get();
  7744. }
  7745. const contained = type.containedTypes();
  7746. if (contained.length === 0) {
  7747. return type;
  7748. }
  7749. return type.withContained(type.containedTypes((type) => this.unshapedType(type)));
  7750. }
  7751. defaultSchemaFor(fn) {
  7752. const args = [];
  7753. const returns = [];
  7754. const g = fn.graph();
  7755. const num_inputs = fn.num_inputs();
  7756. for (let i = 0; i < num_inputs; i++) {
  7757. const v = g.inputs()[i];
  7758. const name = v.hasDebugName() ? v.debugNameBase() : `argument_${i}`;
  7759. const argument = new torch.Argument(name, this.unshapedType(g.inputs()[i].type()));
  7760. args.push(argument);
  7761. }
  7762. const num_outputs = g.outputs().length;
  7763. for (let i = 0; i < num_outputs; i++) {
  7764. const argument = new torch.Argument('', this.unshapedType(g.outputs()[i].type()));
  7765. returns.push(argument);
  7766. }
  7767. return new torch.FunctionSchema(fn.name(), '', args, returns);
  7768. }
  7769. });
  7770. this.registerType('torch.utils._contextlib._DecoratorContextManager', class {});
  7771. this.registerType('torch.utils._contextlib._NoParamDecoratorContextManager', class extends torch.utils._contextlib._DecoratorContextManager {});
  7772. this.registerType('torch.utils._sympy.symbol.SymT', class extends this.enum.Enum {});
  7773. this.registerType('torch.utils._sympy.functions.FloorDiv', class extends sympy.core.function.Function {
  7774. __str__() {
  7775. return this._args.map((a) => a.__str__()).join('//');
  7776. }
  7777. });
  7778. this.registerType('torch.utils._sympy.functions.ModularIndexing', class {});
  7779. this.registerType('torch.utils._sympy.functions.Where', class {});
  7780. this.registerType('torch.utils._sympy.functions.PythonMod', class {});
  7781. this.registerType('torch.utils._sympy.functions.Mod', class {});
  7782. this.registerType('torch.utils._sympy.functions.CleanDiv', class {});
  7783. this.registerType('torch.utils._sympy.functions.CeilToInt', class {});
  7784. this.registerType('torch.utils._sympy.functions.FloorToInt', class {});
  7785. this.registerType('torch.utils._sympy.functions.CeilDiv', class {});
  7786. this.registerType('torch.utils._sympy.functions.LShift', class {});
  7787. this.registerType('torch.utils._sympy.functions.RShift', class {});
  7788. this.registerType('torch.utils._sympy.functions.PowByNatural', class {});
  7789. this.registerType('torch.utils._sympy.functions.FloatPow', class {});
  7790. this.registerType('torch.utils._sympy.functions.FloatTrueDiv', class {});
  7791. this.registerType('torch.utils._sympy.functions.IntTrueDiv', class {});
  7792. this.registerType('torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator', class {});
  7793. this.registerType('torch.utils._sympy.functions.TruncToFloat', class {});
  7794. this.registerType('torch.utils._sympy.functions.TruncToInt', class {});
  7795. this.registerType('torch.utils._sympy.functions.RoundToInt', class {});
  7796. this.registerType('torch.utils._sympy.functions.RoundDecimal', class {});
  7797. this.registerType('torch.utils._sympy.functions.ToFloat', class {});
  7798. this.registerType('torch.utils._sympy.functions.Identity', class {});
  7799. this.registerType('torch.utils._traceback.CapturedTraceback', class {
  7800. static extract() {
  7801. }
  7802. });
  7803. this.registerFunction('torch.utils.checkpoint.checkpoint');
  7804. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  7805. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  7806. this.registerFunction('torch.utils.data._utils.collate.default_collate');
  7807. torch.utils.data.dataloader.default_collate = torch.utils.data._utils.collate.default_collate;
  7808. this.registerType('torch.utils.data.dataset.Subset', class {});
  7809. this.registerType('torch.utils.data.dataset.Dataset', class {});
  7810. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  7811. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  7812. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  7813. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  7814. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  7815. this.registerType('torch.utils.data.sampler.SubsetRandomSampler', class {});
  7816. this.registerType('torch.ao.quantization.fake_quantize.FakeQuantize', class {});
  7817. this.registerType('torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize', class {});
  7818. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  7819. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  7820. this.registerType('torch.ao.quantization.observer.MovingAverageMinMaxObserver', class {});
  7821. this.registerType('torch.ao.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  7822. this.registerType('torch.ao.quantization.observer.MinMaxObserver', class {});
  7823. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  7824. this.registerType('torch.ao.quantization.observer.PlaceholderObserver', class {});
  7825. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  7826. this.registerType('torch.ao.quantization.qconfig.QConfigDynamic', class {});
  7827. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  7828. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  7829. this.registerType('torch.ao.quantization.stubs.QuantWrapper', class {});
  7830. this.registerFunction('torch.ao.quantization.qconfig._activation_is_memoryless');
  7831. this.registerFunction('torch.ao.quantization.qconfig._add_module_to_qconfig_obs_ctr');
  7832. this.registerFunction('torch.ao.quantization.fx.graph_module._save_packed_weight');
  7833. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._load_packed_weight');
  7834. this.registerFunction('torch.ao.quantization.fx._lower_to_native_backend._save_packed_weight');
  7835. this.registerFunction('torch.ao.quantization.observer._is_activation_post_process');
  7836. this.registerFunction('torch.ao.quantization.quantize._observer_forward_hook');
  7837. this.registerFunction('torch.ao.quantization.quantization_mappings._get_special_act_post_process');
  7838. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings');
  7839. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings');
  7840. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list');
  7841. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings');
  7842. this.registerFunction('torch.ao.quantization.quantization_mappings.get_default_static_quant_reference_module_mappings');
  7843. this.registerFunction('torch.ao.quantization.quantization_mappings.no_observer_set');
  7844. this.registerFunction('torch.ao.quantization.quantization_mappings._has_special_act_post_process');
  7845. this.registerFunction('torch.ao.quantization.utils.get_qparam_dict');
  7846. this.registerFunction('torch.ao.quantization.utils.has_no_children_ignoring_parametrizations');
  7847. this.registerFunction('torch.amp.grad_scaler._refresh_per_optimizer_state');
  7848. this.registerType('torch.amp.grad_scaler.GradScaler', class {});
  7849. this.registerType('torch._C._LegacyVariableBase', class {});
  7850. this.registerType('torch.autograd.grad_mode.no_grad', class extends torch.utils._contextlib._NoParamDecoratorContextManager {});
  7851. this.registerType('torch.autograd.variable.Variable', class extends torch._C._LegacyVariableBase {});
  7852. this.registerType('torch.autograd.function._SingleLevelFunction', class {});
  7853. this.registerType('torch.autograd.function.Function', class extends torch.autograd.function._SingleLevelFunction {});
  7854. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  7855. this.registerFunction('torch.distributed._shard.sharded_tensor.pre_load_state_dict_hook');
  7856. this.registerFunction('torch.distributed._shard.sharded_tensor.state_dict_hook');
  7857. this.registerFunction('torch.distributed._sharded_tensor.state_dict_hook');
  7858. this.registerFunction('torch.distributed._sharded_tensor.pre_load_state_dict_hook');
  7859. this.registerType('torch.distributed.algorithms.join._JoinConfig', class {});
  7860. this.registerType('torch.distributed.remote_device._remote_device', class {});
  7861. this.registerType('torch.distributed._shard.metadata.ShardMetadata', class {});
  7862. this.registerType('torch.distributed._shard.sharded_tensor.api.ShardedTensor', class {});
  7863. this.registerType('torch.distributed._shard.sharded_tensor.metadata.ShardedTensorMetadata', class {});
  7864. this.registerType('torch.distributed._shard.sharded_tensor.metadata.TensorProperties', class {});
  7865. this.registerType('torch.distributed._shard.sharded_tensor.shard.Shard', class {});
  7866. this.registerType('torch.distributed._tensor.api.DTensor', class extends torch._C._TensorMeta {});
  7867. this.registerType('torch.distributed._tensor.placement_types.DTensorSpec', class {});
  7868. this.registerType('torch.distributed._tensor.placement_types.Shard', class {});
  7869. this.registerType('torch.distributed._tensor.placement_types.TensorMeta', class {});
  7870. this.registerType('torch.distributed.device_mesh.DeviceMesh', class {});
  7871. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  7872. this.registerType('torch.distributions.beta.Beta', class {});
  7873. this.registerType('torch.distributions.binomial.Binomial', class {});
  7874. this.registerType('torch.distributions.categorical.Categorical', class {});
  7875. this.registerType('torch.distributions.constraints._GreaterThan', class {});
  7876. this.registerType('torch.distributions.constraints._Interval', class {});
  7877. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  7878. this.registerType('torch.distributions.constraints._Real', class {});
  7879. this.registerType('torch.distributions.dirichlet.Dirichlet', class {});
  7880. this.registerType('torch.distributions.mixture_same_family.MixtureSameFamily', class {});
  7881. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  7882. this.registerType('torch.distributions.normal.Normal', class {});
  7883. this.registerType('torch.distributions.transforms._InverseTransform', class {});
  7884. this.registerType('torch.distributions.transforms.AffineTransform', class {});
  7885. this.registerType('torch.distributions.transforms.ComposeTransform', class {});
  7886. this.registerType('torch.distributions.transforms.ExpTransform', class {});
  7887. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  7888. this.registerType('torch.distributions.uniform.Uniform', class {});
  7889. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  7890. this.registerType('torch.nn.intrinsic.modules.fused._FusedModule', class {});
  7891. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  7892. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  7893. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  7894. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBn2d', class {});
  7895. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  7896. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  7897. this.registerType('torch.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class {});
  7898. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class {});
  7899. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  7900. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  7901. this.registerType('torch.nn.modules.activation.CELU', class extends torch.nn.modules.module.Module {});
  7902. this.registerType('torch.nn.modules.activation.ELU', class extends torch.nn.modules.module.Module {});
  7903. this.registerType('torch.nn.modules.activation.GELU', class extends torch.nn.modules.module.Module {});
  7904. this.registerType('torch.nn.modules.activation.GLU', class extends torch.nn.modules.module.Module {});
  7905. this.registerType('torch.nn.modules.activation.Hardtanh', class extends torch.nn.modules.module.Module {});
  7906. this.registerType('torch.nn.modules.activation.Hardshrink', class extends torch.nn.modules.module.Module {});
  7907. this.registerType('torch.nn.modules.activation.Hardsigmoid', class extends torch.nn.modules.module.Module {});
  7908. this.registerType('torch.nn.modules.activation.Hardswish', class extends torch.nn.modules.module.Module {});
  7909. this.registerType('torch.nn.modules.activation.LeakyReLU', class extends torch.nn.modules.module.Module {});
  7910. this.registerType('torch.nn.modules.activation.LogSigmoid', class extends torch.nn.modules.module.Module {});
  7911. this.registerType('torch.nn.modules.activation.LogSoftmax', class extends torch.nn.modules.module.Module {});
  7912. this.registerType('torch.nn.modules.activation.Mish', class extends torch.nn.modules.module.Module {});
  7913. this.registerType('torch.nn.modules.activation.MultiheadAttention', class extends torch.nn.modules.module.Module {});
  7914. this.registerType('torch.nn.modules.activation.ReLU', class extends torch.nn.modules.module.Module {});
  7915. this.registerType('torch.nn.modules.activation.ReLU6', class extends torch.nn.modules.module.Module {});
  7916. this.registerType('torch.nn.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  7917. this.registerType('torch.nn.modules.activation.RReLU', class extends torch.nn.modules.module.Module {});
  7918. this.registerType('torch.nn.modules.activation.SELU', class extends torch.nn.modules.module.Module {});
  7919. this.registerType('torch.nn.modules.activation.Sigmoid', class extends torch.nn.modules.module.Module {});
  7920. this.registerType('torch.nn.modules.activation.SiLU', class extends torch.nn.modules.module.Module {});
  7921. this.registerType('torch.nn.modules.activation.Softmax', class extends torch.nn.modules.module.Module {});
  7922. this.registerType('torch.nn.modules.activation.Softmax2d', class extends torch.nn.modules.module.Module {});
  7923. this.registerType('torch.nn.modules.activation.Softmin', class extends torch.nn.modules.module.Module {});
  7924. this.registerType('torch.nn.modules.activation.Softplus', class extends torch.nn.modules.module.Module {});
  7925. this.registerType('torch.nn.modules.activation.Softshrink', class extends torch.nn.modules.module.Module {});
  7926. this.registerType('torch.nn.modules.activation.Softsign', class extends torch.nn.modules.module.Module {});
  7927. this.registerType('torch.nn.modules.activation.Tanh', class extends torch.nn.modules.module.Module {});
  7928. this.registerType('torch.nn.modules.activation.Tanhshrink', class extends torch.nn.modules.module.Module {});
  7929. this.registerType('torch.nn.modules.activation.Threshold', class extends torch.nn.modules.module.Module {});
  7930. this.registerType('torch.nn.modules.adaptive.AdaptiveLogSoftmaxWithLoss', class {});
  7931. this.registerType('torch.nn.modules.batchnorm._NormBase', class extends torch.nn.modules.module.Module {});
  7932. this.registerType('torch.nn.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._NormBase {});
  7933. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7934. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7935. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class extends torch.nn.modules.batchnorm._BatchNorm {});
  7936. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  7937. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm2d', class {});
  7938. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm3d', class {});
  7939. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  7940. this.registerType('torch.nn.modules.byted_batchnorm.BytedBatchNorm2d', class {});
  7941. this.registerType('torch.nn.modules.channelshuffle.ChannelShuffle', class {});
  7942. this.registerType('torch.nn.modules.container.ModuleDict', class extends torch.nn.modules.module.Module {});
  7943. this.registerType('torch.nn.modules.container.ModuleList', class extends torch.nn.modules.module.Module {});
  7944. this.registerType('torch.nn.modules.container.ParameterDict', class extends torch.nn.modules.module.Module {});
  7945. this.registerType('torch.nn.modules.container.ParameterList', class extends torch.nn.modules.module.Module {});
  7946. this.registerType('torch.nn.modules.container.Sequential', class extends torch.nn.modules.module.Module {});
  7947. this.registerType('torch.nn.modules.conv._ConvNd', class extends torch.nn.modules.module.Module {});
  7948. this.registerType('torch.nn.modules.conv.Conv1d', class extends torch.nn.modules.conv._ConvNd {});
  7949. this.registerType('torch.nn.modules.conv.Conv2d', class extends torch.nn.modules.conv._ConvNd {});
  7950. this.registerType('torch.nn.modules.conv.Conv3d', class extends torch.nn.modules.conv._ConvNd {});
  7951. this.registerType('torch.nn.modules.conv._ConvTransposeNd', class extends torch.nn.modules.module.Module {});
  7952. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7953. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7954. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class extends torch.nn.modules.conv._ConvTransposeNd {});
  7955. this.registerType('torch.nn.modules.conv.LazyConv1d', class {});
  7956. this.registerType('torch.nn.modules.conv.LazyConv2d', class {});
  7957. this.registerType('torch.nn.modules.conv.LazyConv3d', class {});
  7958. this.registerType('torch.nn.modules.conv.LazyConvTranspose2d', class {});
  7959. this.registerType('torch.nn.modules.conv.LazyConvTranspose3d', class {});
  7960. this.registerType('torch.nn.modules.distance.CosineSimilarity', class extends torch.nn.modules.module.Module {});
  7961. this.registerType('torch.nn.modules.distance.PairwiseDistance', class extends torch.nn.modules.module.Module {});
  7962. this.registerType('torch.nn.modules.dropout._DropoutNd', class extends torch.nn.modules.module.Module {});
  7963. this.registerType('torch.nn.modules.dropout.AlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7964. this.registerType('torch.nn.modules.dropout.Dropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7965. this.registerType('torch.nn.modules.dropout.Dropout1d', class extends torch.nn.modules.dropout._DropoutNd {});
  7966. this.registerType('torch.nn.modules.dropout.Dropout2d', class extends torch.nn.modules.dropout._DropoutNd {});
  7967. this.registerType('torch.nn.modules.dropout.Dropout3d', class extends torch.nn.modules.dropout._DropoutNd {});
  7968. this.registerType('torch.nn.modules.dropout.FeatureAlphaDropout', class extends torch.nn.modules.dropout._DropoutNd {});
  7969. this.registerType('torch.nn.modules.fold.Fold', class extends torch.nn.modules.module.Module {});
  7970. this.registerType('torch.nn.modules.fold.Unfold', class extends torch.nn.modules.module.Module {});
  7971. this.registerType('torch.nn.modules.flatten.Flatten', class extends torch.nn.modules.module.Module {});
  7972. this.registerType('torch.nn.modules.flatten.Unflatten', class extends torch.nn.modules.module.Module {});
  7973. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  7974. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  7975. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  7976. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm2d', class {});
  7977. this.registerType('torch.nn.modules.instancenorm.LazyInstanceNorm3d', class {});
  7978. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  7979. this.registerType('torch.nn.modules.linear.Bilinear', class extends torch.nn.modules.module.Module {});
  7980. this.registerType('torch.nn.modules.linear.Identity', class extends torch.nn.modules.module.Module {});
  7981. this.registerType('torch.nn.modules.linear.LazyLinear', class extends torch.nn.modules.module.Module {});
  7982. this.registerType('torch.nn.modules.linear.Linear', class extends torch.nn.modules.module.Module {});
  7983. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class extends torch.nn.modules.linear.Linear {});
  7984. this.registerType('torch.nn.modules.loss._Loss', class extends torch.nn.modules.module.Module {});
  7985. this.registerType('torch.nn.modules.loss._WeightedLoss', class extends torch.nn.modules.loss._Loss {});
  7986. this.registerType('torch.nn.modules.loss.BCELoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7987. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class extends torch.nn.modules.loss._Loss {});
  7988. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  7989. this.registerType('torch.nn.modules.loss.CosineEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7990. this.registerType('torch.nn.modules.loss.CTCLoss', class extends torch.nn.modules.loss._Loss {});
  7991. this.registerType('torch.nn.modules.loss.GaussianNLLLoss', class extends torch.nn.modules.loss._Loss {});
  7992. this.registerType('torch.nn.modules.loss.HuberLoss', class extends torch.nn.modules.loss._Loss {});
  7993. this.registerType('torch.nn.modules.loss.HingeEmbeddingLoss', class extends torch.nn.modules.loss._Loss {});
  7994. this.registerType('torch.nn.modules.loss.KLDivLoss', class extends torch.nn.modules.loss._Loss {});
  7995. this.registerType('torch.nn.modules.loss.L1Loss', class extends torch.nn.modules.loss._Loss {});
  7996. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class extends torch.nn.modules.loss._Loss {});
  7997. this.registerType('torch.nn.modules.loss.MultiLabelMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7998. this.registerType('torch.nn.modules.loss.MultiLabelSoftMarginLoss', class extends torch.nn.modules.loss._Loss {});
  7999. this.registerType('torch.nn.modules.loss.MultiMarginLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8000. this.registerType('torch.nn.modules.loss.MSELoss', class extends torch.nn.modules.loss._Loss {});
  8001. this.registerType('torch.nn.modules.loss.NLLLoss', class extends torch.nn.modules.loss._WeightedLoss {});
  8002. this.registerType('torch.nn.modules.loss.NLLLoss2d', class extends torch.nn.modules.loss.NLLLoss {});
  8003. this.registerType('torch.nn.modules.loss.PoissonNLLLoss', class {});
  8004. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  8005. this.registerType('torch.nn.modules.loss.SoftMarginLoss', class {});
  8006. this.registerType('torch.nn.modules.loss.TripletMarginLoss', class {});
  8007. this.registerType('torch.nn.modules.loss.TripletMarginWithDistanceLoss', class {});
  8008. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  8009. this.registerType('torch.nn.modules.module._WrappedHook', class {});
  8010. this.registerType('torch.nn.modules.module.PatchForward', class {});
  8011. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  8012. this.registerType('torch.nn.modules.normalization.GroupNorm', class extends torch.nn.modules.module.Module {});
  8013. this.registerType('torch.nn.modules.normalization.LayerNorm', class extends torch.nn.modules.module.Module {});
  8014. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  8015. this.registerType('torch.nn.modules.normalization.RMSNorm', class {});
  8016. this.registerType('torch.nn.modules.padding._ReflectionPadNd', class extends torch.nn.modules.module.Module {});
  8017. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8018. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8019. this.registerType('torch.nn.modules.padding.ReflectionPad3d', class extends torch.nn.modules.padding._ReflectionPadNd {});
  8020. this.registerType('torch.nn.modules.padding._ReplicationPadNd', class extends torch.nn.modules.module.Module {});
  8021. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8022. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8023. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class extends torch.nn.modules.padding._ReplicationPadNd {});
  8024. this.registerType('torch.nn.modules.padding.ZeroPad1d', class {});
  8025. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  8026. this.registerType('torch.nn.modules.padding.ZeroPad3d', class {});
  8027. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  8028. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  8029. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  8030. this.registerType('torch.nn.modules.padding.CircularPad3d', class {});
  8031. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  8032. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  8033. this.registerType('torch.nn.modules.pooling._AdaptiveAvgPoolNd', class extends torch.nn.modules.module.Module {});
  8034. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8035. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8036. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class extends torch.nn.modules.pooling._AdaptiveAvgPoolNd {});
  8037. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  8038. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  8039. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  8040. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  8041. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  8042. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  8043. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  8044. this.registerType('torch.nn.modules.pooling.FractionalMaxPool3d', class {});
  8045. this.registerType('torch.nn.modules.pooling.LPPool1d', class {});
  8046. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  8047. this.registerType('torch.nn.modules.pooling.LPPool3d', class {});
  8048. this.registerType('torch.nn.modules.pooling._MaxPoolNd', class extends torch.nn.modules.module.Module {});
  8049. this.registerType('torch.nn.modules.pooling.MaxPool1d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8050. this.registerType('torch.nn.modules.pooling.MaxPool2d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8051. this.registerType('torch.nn.modules.pooling.MaxPool3d', class extends torch.nn.modules.pooling._MaxPoolNd {});
  8052. this.registerType('torch.nn.modules.pooling._MaxUnpoolNd', class extends torch.nn.modules.module.Module {});
  8053. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8054. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8055. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class extends torch.nn.modules.pooling._MaxUnpoolNd {});
  8056. this.registerType('torch.nn.modules.rnn.GRU', class {});
  8057. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  8058. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  8059. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  8060. this.registerType('torch.nn.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8061. this.registerType('torch.nn.modules.rnn.RNN', class extends torch.nn.modules.rnn.RNNBase {});
  8062. this.registerType('torch.nn.modules.rnn.RNNCellBase', class extends torch.nn.modules.module.Module {});
  8063. this.registerType('torch.nn.modules.rnn.RNNCell', class extends torch.nn.modules.rnn.RNNCellBase {});
  8064. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  8065. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  8066. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  8067. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  8068. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  8069. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  8070. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  8071. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  8072. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  8073. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  8074. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  8075. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  8076. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  8077. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  8078. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  8079. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  8080. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  8081. this.registerType('torch.nn.quantized.modules.activation.Softmax', class {});
  8082. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  8083. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  8084. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  8085. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  8086. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  8087. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  8088. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  8089. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  8090. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  8091. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  8092. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  8093. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  8094. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  8095. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  8096. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  8097. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  8098. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  8099. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  8100. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  8101. this.registerType('torch.nn.quantized.modules.normalization.GroupNorm', class extends torch.nn.modules.normalization.GroupNorm {});
  8102. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8103. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  8104. this.registerType('torch.ao.nn.quantizable.modules.activation.MultiheadAttention', class extends torch.nn.modules.activation.MultiheadAttention {});
  8105. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMLayer', class {});
  8106. this.registerType('torch.ao.nn.quantizable.modules.rnn._LSTMSingleLayer', class {});
  8107. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTM', class {});
  8108. this.registerType('torch.ao.nn.quantizable.modules.rnn.LSTMCell', class {});
  8109. this.registerType('torch.ao.nn.quantized.modules.activation.ELU', class extends torch.nn.modules.activation.ELU {});
  8110. this.registerType('torch.ao.nn.quantized.modules.activation.Hardswish', class extends torch.nn.modules.activation.Hardswish {});
  8111. this.registerType('torch.ao.nn.quantized.modules.activation.MultiheadAttention', class extends torch.ao.nn.quantizable.modules.activation.MultiheadAttention {});
  8112. this.registerType('torch.ao.nn.quantized.modules.activation.PReLU', class extends torch.nn.modules.module.Module {});
  8113. this.registerType('torch.ao.nn.quantized.modules.activation.ReLU6', class extends torch.nn.modules.activation.ReLU {});
  8114. this.registerType('torch.ao.nn.quantized.modules.activation.LeakyReLU', class extends torch.nn.modules.activation.LeakyReLU {});
  8115. this.registerType('torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule', class extends torch.nn.modules.module.Module {});
  8116. this.registerType('torch.ao.nn.quantized.modules.batchnorm._BatchNorm', class extends torch.nn.modules.batchnorm._BatchNorm {});
  8117. this.registerType('torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d', class extends torch.ao.nn.quantized.modules.batchnorm._BatchNorm {});
  8118. this.registerType('torch.ao.nn.quantized.modules.conv.Conv1d', class extends torch.nn.modules.module.Module {});
  8119. this.registerType('torch.ao.nn.quantized.modules.conv.Conv2d', class extends torch.nn.modules.module.Module {});
  8120. this.registerType('torch.ao.nn.quantized.modules.conv._ConvNd', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8121. this.registerType('torch.ao.nn.quantized.modules.conv._ConvTransposeNd', class extends torch.ao.nn.quantized.modules.conv._ConvNd {});
  8122. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose1d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8123. this.registerType('torch.ao.nn.quantized.modules.conv.ConvTranspose2d', class extends torch.ao.nn.quantized.modules.conv._ConvTransposeNd {});
  8124. this.registerType('torch.ao.nn.quantized.modules.Quantize', class extends torch.nn.modules.module.Module {});
  8125. this.registerType('torch.ao.nn.quantized.modules.DeQuantize', class extends torch.nn.modules.module.Module {});
  8126. this.registerType('torch.ao.nn.quantized.modules.dropout.Dropout', class extends torch.nn.modules.dropout.Dropout {});
  8127. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.Embedding', class extends torch.nn.modules.module.Module {});
  8128. this.registerType('torch.ao.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class extends torch.nn.modules.module.Module {});
  8129. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FloatFunctional', class extends torch.nn.modules.module.Module {});
  8130. this.registerType('torch.ao.nn.quantized.modules.functional_modules.QFunctional', class extends torch.nn.modules.module.Module {});
  8131. this.registerType('torch.ao.nn.quantized.modules.functional_modules.FXFloatFunctional', class extends torch.nn.modules.module.Module {});
  8132. this.registerType('torch.ao.nn.quantized.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.utils.WeightedQuantizedModule {});
  8133. this.registerType('torch.ao.nn.quantized.modules.linear.LinearPackedParams', class extends torch.nn.modules.module.Module {});
  8134. this.registerType('torch.ao.nn.quantized.modules.normalization.LayerNorm', class extends torch.nn.modules.normalization.LayerNorm {});
  8135. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm1d', class extends torch.nn.modules.instancenorm.InstanceNorm1d {});
  8136. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm2d', class extends torch.nn.modules.instancenorm.InstanceNorm2d {});
  8137. this.registerType('torch.ao.nn.quantized.modules.normalization.InstanceNorm3d', class extends torch.nn.modules.instancenorm.InstanceNorm3d {});
  8138. this.registerType('torch.ao.nn.quantized.modules.rnn.LSTM', class {});
  8139. this.registerType('torch.ao.nn.quantized.dynamic.modules.linear.Linear', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8140. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.PackedParameter', class extends torch.nn.modules.module.Module {});
  8141. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase', class extends torch.nn.modules.module.Module {});
  8142. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.GRU', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8143. this.registerType('torch.ao.nn.quantized.dynamic.modules.rnn.LSTM', class extends torch.ao.nn.quantized.dynamic.modules.rnn.RNNBase {});
  8144. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv1d', class {});
  8145. this.registerType('torch.ao.nn.quantized.reference.modules.conv.Conv2d', class {});
  8146. this.registerType('torch.ao.nn.quantized.reference.modules.linear.Linear', class {});
  8147. this.registerType('torch.ao.nn.qat.modules.conv.Conv2d', class {});
  8148. this.registerType('torch.ao.nn.qat.modules.linear.Linear', class {});
  8149. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU1d', class extends torch.ao.nn.quantized.modules.conv.Conv1d {});
  8150. this.registerType('torch.ao.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class extends torch.ao.nn.quantized.modules.conv.Conv2d {});
  8151. this.registerType('torch.ao.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class extends torch.ao.nn.quantized.modules.linear.Linear {});
  8152. this.registerType('torch.ao.nn.intrinsic.quantized.modules.bn_relu.BNReLU2d', class extends torch.ao.nn.quantized.modules.batchnorm.BatchNorm2d {});
  8153. this.registerType('torch.ao.nn.intrinsic.modules.fused._FusedModule', class extends torch.nn.modules.container.Sequential {});
  8154. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBn2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8155. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU1d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8156. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8157. this.registerType('torch.ao.nn.intrinsic.modules.fused.LinearReLU', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8158. this.registerType('torch.ao.nn.intrinsic.modules.fused.ConvBnReLU2d', class extends torch.ao.nn.intrinsic.modules.fused._FusedModule {});
  8159. this.registerType('torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  8160. this.registerType('torch.nn.utils.prune.CustomFromMask', class {});
  8161. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  8162. this.registerType('torch.nn.utils.prune.LnStructured', class {});
  8163. this.registerType('torch.nn.utils.prune.PruningContainer', class {});
  8164. this.registerType('torch.nn.utils.prune.RandomUnstructured', class {});
  8165. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  8166. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  8167. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  8168. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  8169. this.registerFunction('torch.nn.utils.parametrize.type_before_parametrizations');
  8170. this.registerType('torch.nn.utils.parametrize.ParametrizationList', class extends torch.nn.modules.container.ModuleList {});
  8171. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  8172. this.registerType('torch.optim.optimizer.Optimizer', class {});
  8173. this.registerType('torch.optim.adam.Adam', class extends torch.optim.optimizer.Optimizer {});
  8174. this.registerType('torch.optim.adamw.AdamW', class {});
  8175. this.registerType('torch.optim.adagrad.Adagrad', class {});
  8176. this.registerType('torch.optim.adadelta.Adadelta', class {});
  8177. this.registerType('torch.optim.lbfgs.LBFGS', class {});
  8178. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  8179. this.registerType('torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', class {});
  8180. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  8181. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  8182. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  8183. this.registerType('torch.optim.lr_scheduler.LinearLR', class {});
  8184. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  8185. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  8186. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  8187. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  8188. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  8189. this.registerType('torch.optim.radam.RAdam', class extends torch.optim.optimizer.Optimizer {});
  8190. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  8191. this.registerType('torch.optim.sgd.SGD', class {});
  8192. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  8193. this.registerType('torch.optim.swa_utils.SWALR', class {});
  8194. torch.optim.RAdam = torch.optim.radam.RAdam;
  8195. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  8196. this.registerFunction('torch.quantization.fx.graph_module._save_packed_weight');
  8197. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  8198. this.registerType('torch.quantization.observer.HistogramObserver', class {});
  8199. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  8200. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  8201. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  8202. this.registerFunction('torch.quantization.observer._with_args');
  8203. this.registerType('torch.quantization.qconfig.QConfig', class {});
  8204. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  8205. this.registerType('torch.quantization.stubs.QuantStub', class {});
  8206. this.registerType('torch.utils._pytree.LeafSpec', class {});
  8207. this.registerType('torch.utils._pytree.TreeSpec', class {});
  8208. this.registerType('torch.utils._python_dispatch.TorchDispatchMode', class {
  8209. __enter__() {
  8210. return this;
  8211. }
  8212. __exit__(/* exc_type, exc_value, traceback */) {
  8213. }
  8214. });
  8215. this.registerFunction('torch.utils._pytree.tree_map');
  8216. torch.nn.Sequential = torch.nn.modules.container.Sequential;
  8217. this.registerFunction('torch.fx.experimental.sym_node.SymNode', class {
  8218. constructor(expr, shape_env, pytype, hint, constant, fx_node, optimized_summation) {
  8219. this._expr = expr;
  8220. this.shape_env = shape_env;
  8221. this.pytype = pytype;
  8222. this._optimized_summation = optimized_summation;
  8223. this._hint = hint;
  8224. this.constant = constant;
  8225. const tx_validation_en = this.shape_env && this.shape_env._translation_validation_enabled ? true : false;
  8226. this.fx_node = tx_validation_en && fx_node ? fx_node : null;
  8227. }
  8228. __str__() {
  8229. return this._expr.__str__();
  8230. }
  8231. });
  8232. this.registerType('torch.fx.experimental.symbolic_shapes.ShapeEnv', class {
  8233. constructor() {
  8234. this.var_to_val = new Map();
  8235. this.var_to_stack = new Map();
  8236. }
  8237. add_var_to_val(expr, val) {
  8238. this.var_to_val.set(expr, new sympy.core.numbers.Integer(val));
  8239. }
  8240. constrain_symbol_range(/* s, compiler_min, compiler_max */) {
  8241. }
  8242. create_symintnode(sym, hint, source) {
  8243. let out = null;
  8244. let fx_node = null;
  8245. if (this._translation_validation_enabled && source !== null) {
  8246. throw new python.Error('Not implemented.');
  8247. } else {
  8248. fx_node = null;
  8249. }
  8250. if (builtins.isinstance(sym, sympy.core.numbers.Integer)) {
  8251. out = builtins.int(sym);
  8252. if (hint !== null && out !== hint) {
  8253. throw new python.Error(`Symbolic integer has value '${out}' but expected '${hint}'.`);
  8254. }
  8255. } else {
  8256. // if free_unbacked_symbols(sym):
  8257. // hint = None
  8258. out = new torch.SymInt(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.int, hint, null, fx_node));
  8259. }
  8260. return out;
  8261. }
  8262. create_symboolnode(sym) {
  8263. return new torch.SymBool(new torch.fx.experimental.sym_node.SymNode(sym, this, builtins.bool, null));
  8264. }
  8265. });
  8266. this.registerFunction('torch.fx.experimental.symbolic_shapes.symbol_is_type', (/* sym, prefix */) => {
  8267. /*
  8268. assert isinstance(sym, sympy.Symbol)
  8269. const name_str = sym.name.toLowerCase();
  8270. if (builtins.isinstance(prefix, torch.utils._sympy.symbol.SymT)) {
  8271. return name_str.startsWith(prefix_str[prefix])
  8272. }
  8273. return name_str.startswith(tuple(prefix_str[p] for p in prefix));
  8274. */
  8275. return false;
  8276. });
  8277. this.registerType('torch.fx.proxy.TracerBase', class {
  8278. constructor() {
  8279. this.traced_func_name = 'forward';
  8280. }
  8281. });
  8282. this.registerType('torch.fx._symbolic_trace.Tracer', class extends torch.fx.proxy.TracerBase {
  8283. trace(root /*, concrete_args */) {
  8284. let fn = null;
  8285. if (root instanceof torch.nn.Module) {
  8286. // torch.fx._lazy_graph_module._LazyGraphModule.force_recompile(root)
  8287. this.root = root;
  8288. fn = builtins.getattr(new builtins.type(root), this.traced_func_name);
  8289. this.root_module_name = root._get_name();
  8290. this.submodule_paths = new builtins.dict(root.named_modules());
  8291. } else {
  8292. this.root = new torch.nn.Module();
  8293. fn = root;
  8294. }
  8295. const tracer_cls = builtins.getattr(this, '__class__', null);
  8296. this.graph = new torch.fx.graph.Graph(null, tracer_cls);
  8297. if (builtins.hasattr(this, '__code__')) {
  8298. const code = fn.__code__;
  8299. this.graph._co_fields = {
  8300. co_name: code.co_name,
  8301. co_filename: code.co_filename,
  8302. co_firstlineno: code.co_firstlineno,
  8303. };
  8304. }
  8305. return this.graph;
  8306. }
  8307. is_leaf_module(m /*, module_qualified_name */) {
  8308. return (m.__module__.startsWith('torch.nn') || m.__module__.startsWith('torch.ao.nn')) && m instanceof torch.nn.Sequential === false;
  8309. }
  8310. });
  8311. this.registerType('torch.fx.experimental.proxy_tensor.PythonKeyTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8312. this.registerType('torch.fx.experimental.proxy_tensor._ModuleStackTracer', class extends torch.fx.experimental.proxy_tensor.PythonKeyTracer {});
  8313. this.registerFunction('torch.fx._lazy_graph_module._make_graph_module', (...args) => {
  8314. const graph_module_cls = args.pop() || torch.fx.graph_module.GraphModule;
  8315. return new graph_module_cls(...args);
  8316. });
  8317. this.registerFunction('torch.fx.graph_module._deserialize_graph_module', (forward, body, graph_module_cls) => {
  8318. let tracer_cls = body.get('_tracer_cls');
  8319. if (!tracer_cls) {
  8320. tracer_cls = torch.fx._symbolic_trace.Tracer;
  8321. }
  8322. const graphmodule_cls_name = body.get('_graphmodule_cls_name', 'GraphModule');
  8323. const cls_tracer = tracer_cls;
  8324. const KeepModules = class extends cls_tracer {
  8325. is_leaf_module() {
  8326. return true;
  8327. }
  8328. };
  8329. const com = new torch.fx.graph_module._CodeOnlyModule(body);
  8330. const tracer_extras = body.get('_tracer_extras', new builtins.dict());
  8331. const graph = new KeepModules().trace(com, tracer_extras);
  8332. graph._tracer_cls = tracer_cls;
  8333. const gm = torch.fx._lazy_graph_module._make_graph_module(com, graph, graphmodule_cls_name, graph_module_cls);
  8334. for (const [k, v] of body.items()) {
  8335. if (!builtins.hasattr(gm, k)) {
  8336. builtins.setattr(gm, k, v);
  8337. }
  8338. }
  8339. return gm;
  8340. });
  8341. this.registerFunction('torch.fx.graph_module._forward_from_src', (src, globals /*, co_fields */) => {
  8342. globals = { ...globals };
  8343. const context = new python.Execution.Context(globals, null);
  8344. execution.exec(src, context);
  8345. const forward_fn = globals.forward;
  8346. delete globals.forward;
  8347. return forward_fn;
  8348. });
  8349. this.registerFunction('torch.fx.graph_module.reduce_graph_module', (body, import_block) => {
  8350. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  8351. let fn_src = null;
  8352. if (body.has('_code')) {
  8353. fn_src = body.get('_code');
  8354. } else if (body.has('code')) {
  8355. fn_src = body.get('code');
  8356. } else {
  8357. fn_src = body._code || body.code;
  8358. }
  8359. const forward = torch.fx.graph_module._forward_from_src(import_block + fn_src, {});
  8360. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8361. });
  8362. this.registerFunction('torch.fx.graph_module.reduce_package_graph_module', (importer, body, generated_module_name) => {
  8363. const forward = importer.import_module(generated_module_name).forward;
  8364. return torch.fx.graph_module._deserialize_graph_module(forward, body);
  8365. });
  8366. this.registerType('torch.fx.graph.CodeGen', class {});
  8367. this.registerType('torch.fx.graph._PyTreeInfo', class {
  8368. constructor(orig_args, in_spec, out_spec) {
  8369. this.orig_args = orig_args;
  8370. this.in_spec = in_spec;
  8371. this.out_spec = out_spec;
  8372. }
  8373. });
  8374. this.registerType('torch.fx.graph._Namespace', class {
  8375. constructor() {
  8376. this._obj_to_name = new Map();
  8377. this._unassociated_names = new Set();
  8378. this._used_names = new Set();
  8379. this._base_count = {};
  8380. }
  8381. create_name(candidate, obj) {
  8382. if (obj && this._obj_to_name.has(obj)) {
  8383. return self._obj_to_name.get(obj);
  8384. }
  8385. candidate = candidate || '_unnamed';
  8386. candidate = /^\d+$/.test(candidate) ? `_${candidate}` : candidate;
  8387. candidate = candidate.replace(/[^0-9a-zA-Z_]+/, '_');
  8388. const match = candidate.match(/(.*)_(\d+)$"/);
  8389. let base = candidate;
  8390. let num = null;
  8391. if (match) {
  8392. [, base] = match;
  8393. num = parseInt(match[2], 10);
  8394. }
  8395. candidate = num ? `${base}_${num}` : base;
  8396. if (!num) {
  8397. num = this._base_count[base] || 0;
  8398. }
  8399. while (this._used_names.has(candidate) || this._is_illegal_name(candidate, obj)) {
  8400. num += 1;
  8401. candidate = `${base}_${num}`;
  8402. }
  8403. this._used_names.add(candidate);
  8404. this._base_count[base] = num;
  8405. if (obj) {
  8406. this._obj_to_name[obj] = candidate;
  8407. } else {
  8408. this._unassociated_names.add(candidate);
  8409. }
  8410. return candidate;
  8411. }
  8412. _is_illegal_name(/* name, obj */) {
  8413. /*
  8414. if name in keyword.kwlist:
  8415. return True
  8416. if name in builtins.__dict__:
  8417. return obj is not builtins.__dict__[name]
  8418. if name in _custom_builtins:
  8419. return obj is not _custom_builtins[name].obj
  8420. */
  8421. return false;
  8422. }
  8423. associate_name_with_obj() {
  8424. }
  8425. });
  8426. this.registerType('torch.fx.node.Node', class {
  8427. constructor(graph, name, op, target, args, kwargs, return_type) {
  8428. this.graph = graph;
  8429. this.name = name;
  8430. this.op = op;
  8431. this.target = target;
  8432. this._input_nodes = new builtins.dict();
  8433. this.__update_args_kwargs(args, kwargs);
  8434. this.users = new builtins.dict();
  8435. this.type = return_type;
  8436. this._prev = this;
  8437. this._next = this;
  8438. this._erased = false;
  8439. this._repr_fn = null;
  8440. this.meta = new builtins.dict();
  8441. }
  8442. get args() {
  8443. return this._args;
  8444. }
  8445. get kwargs() {
  8446. return this._kwargs;
  8447. }
  8448. get next() {
  8449. return this._next;
  8450. }
  8451. prepend(x) {
  8452. x._remove_from_list();
  8453. const p = this._prev;
  8454. [p._next, x._prev] = [x, p];
  8455. [x._next, this._prev] = [this, x];
  8456. }
  8457. _remove_from_list() {
  8458. const [p, n] = [this._prev, this._next];
  8459. [p._next, n._prev] = [n, p];
  8460. }
  8461. __update_args_kwargs(new_args, new_kwargs) {
  8462. const update_users_and_input_nodes = (n) => {
  8463. if (n instanceof torch.fx.node.Node) {
  8464. this._input_nodes.setdefault(n);
  8465. n.users.setdefault(this);
  8466. }
  8467. return n;
  8468. };
  8469. const map_aggregate = (a, fn) => {
  8470. if (a instanceof builtins.tuple) {
  8471. const t = new builtins.tuple(a.map((elem) => map_aggregate(elem, fn)));
  8472. if (!builtins.hasattr(a, '_fields')) {
  8473. return t;
  8474. }
  8475. throw new python.Error('Not implemented.');
  8476. // return type(a)(*t);
  8477. } else if (Array.isArray(a)) {
  8478. return a.map((elem) => map_aggregate(elem, fn));
  8479. } else if (a instanceof builtins.dict) {
  8480. const rv = new builtins.dict();
  8481. for (const [k, v] of a) {
  8482. rv.__setitem__(k, map_aggregate(v, fn));
  8483. }
  8484. return rv;
  8485. } else if (a instanceof builtins.slice) {
  8486. throw new python.Error('Not implemented.');
  8487. // return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  8488. }
  8489. return fn(a);
  8490. };
  8491. for (const old_use of this._input_nodes.keys()) {
  8492. old_use.users.pop(this);
  8493. }
  8494. // object.__setattr__(self, "_input_nodes", {})
  8495. this._input_nodes = new builtins.dict();
  8496. // object.__setattr__(self, "_args", map_aggregate(new_args, update_users_and_input_nodes))
  8497. this._args = map_aggregate(new_args, update_users_and_input_nodes);
  8498. // object.__setattr__(self, "_kwargs", map_aggregate(new_kwargs, update_users_and_input_nodes))
  8499. this._kwargs = map_aggregate(new_kwargs, update_users_and_input_nodes);
  8500. }
  8501. });
  8502. torch.fx.Node = torch.fx.node.Node;
  8503. torch.fx.graph.Node = torch.fx.node.Node;
  8504. this.registerType('torch.fx.graph.Graph', class {
  8505. constructor(owning_module, tracer_cls, tracer_extras) {
  8506. this._root = new torch.fx.node.Node(self, '', 'root', '', new builtins.list(), new builtins.dict());
  8507. this._used_names = new Map();
  8508. this._len = 0;
  8509. this._graph_namespace = new torch.fx.graph._Namespace();
  8510. this._owning_module = owning_module;
  8511. this._tracer_cls = tracer_cls;
  8512. this._tracer_extras = tracer_extras;
  8513. // this._codegen = CodeGen()
  8514. // this._co_fields = {}
  8515. }
  8516. get nodes() {
  8517. const array = new Array(this._len);
  8518. let node = this._root.next;
  8519. for (let i = 0; node !== this._root; i++) {
  8520. array[i] = node;
  8521. node = node.next;
  8522. }
  8523. return array;
  8524. }
  8525. placeholder(name, type_expr /*, default_value */) {
  8526. const args = []; // () if default_value is inspect.Signature.empty else (default_value,)
  8527. const kwargs = new builtins.dict();
  8528. return this.create_node('placeholder', name, args, kwargs, type_expr);
  8529. }
  8530. create_node(op, target, args, kwargs, name, type_expr) {
  8531. args = args || new builtins.tuple();
  8532. kwargs = kwargs || new builtins.dict();
  8533. const candidate = name || this._target_to_str(target);
  8534. name = this._graph_namespace.create_name(candidate, null);
  8535. const n = new torch.fx.node.Node(this, name, op, target, args, kwargs, type_expr);
  8536. this._graph_namespace.associate_name_with_obj(name, n);
  8537. this._insert(n);
  8538. this._len += 1;
  8539. return n;
  8540. }
  8541. _insert(n) {
  8542. this._root.prepend(n);
  8543. }
  8544. output(result, type_expr) {
  8545. return this.create_node('output', 'output', new builtins.tuple(result), null, type_expr);
  8546. }
  8547. _target_to_str(target) {
  8548. if (typeof target === 'string') {
  8549. if (target.startsWith('__') && target.endsWith('__')) {
  8550. target = target.substring(2, target.length - 2);
  8551. }
  8552. } else {
  8553. target = target.__name__;
  8554. }
  8555. return this._snake_case(target);
  8556. }
  8557. _snake_case(s) {
  8558. const chars = [];
  8559. let prev_lower = false;
  8560. for (const c of s) {
  8561. const x = c.toLowerCase();
  8562. if (prev_lower && x !== c) {
  8563. chars.push('_');
  8564. } else {
  8565. prev_lower = true;
  8566. }
  8567. chars.push(x);
  8568. }
  8569. return chars.join('');
  8570. }
  8571. });
  8572. this.registerType('torch.fx.graph_module._CodeOnlyModule', class extends torch.nn.modules.module.Module {
  8573. constructor(body) {
  8574. super();
  8575. for (const [k, v] of body.items()) {
  8576. builtins.setattr(this, k, v);
  8577. }
  8578. }
  8579. });
  8580. this.registerFunction('torch.fx.graph_module._copy_attr', (from_module, to_module, target) => {
  8581. const parts = target.split('.');
  8582. const field = parts.pop();
  8583. for (const item of parts) {
  8584. const f = builtins.getattr(from_module, item);
  8585. let t = builtins.getattr(to_module, item, null);
  8586. if (f === t) {
  8587. return;
  8588. }
  8589. if (t === null) {
  8590. t = new torch.nn.modules.module.Module();
  8591. builtins.setattr(to_module, item, t);
  8592. }
  8593. from_module = f;
  8594. to_module = t;
  8595. }
  8596. const orig = builtins.getattr(from_module, field);
  8597. builtins.setattr(to_module, field, orig);
  8598. });
  8599. this.registerType('torch.fx.graph_module.GraphModule', class extends torch.nn.modules.module.Module {
  8600. constructor(root, graph, class_name) {
  8601. super();
  8602. this.__class__.__name__ = class_name || 'GraphModule';
  8603. this.graph = graph;
  8604. if (root instanceof torch.nn.modules.module.Module && graph && graph.nodes) {
  8605. for (const node of graph.nodes) {
  8606. if (node.op === 'get_attr' || node.op === 'call_module') {
  8607. torch.fx.graph_module._copy_attr(root, this, node.target);
  8608. }
  8609. }
  8610. }
  8611. }
  8612. });
  8613. torch.fx.Graph = torch.fx.graph.Graph;
  8614. torch.fx.GraphModule = torch.fx.graph_module.GraphModule;
  8615. this.registerType('torch.fx.immutable_collections.immutable_dict', class extends builtins.dict {});
  8616. this.registerType('torch.fx.immutable_collections.immutable_list', class extends builtins.list {});
  8617. this.registerFunction('torch.fx._symbolic_trace.wrap', (fn_or_name) => {
  8618. return fn_or_name;
  8619. });
  8620. this.registerFunction('torch.fx._symbolic_trace._assert_is_none');
  8621. this.registerFunction('torchvision.datasets.folder.default_loader');
  8622. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  8623. this.registerType('torchvision.datasets.mnist.FashionMNIST', class {});
  8624. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  8625. this.registerType('torchvision.datasets.video_utils.VideoClips', class {});
  8626. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  8627. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  8628. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  8629. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  8630. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  8631. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  8632. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  8633. this.registerType('torchvision.ops.misc.MLP', class extends torch.nn.modules.container.Sequential {});
  8634. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  8635. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  8636. this.registerType('torchvision.ops.misc.Permute', class {});
  8637. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  8638. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  8639. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  8640. this.registerType('torchvision.ops.roi_align.RoIAlign', class {});
  8641. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  8642. this.registerType('torchvision.models._api.Weights', class {});
  8643. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  8644. this.registerType('torchvision.models.convnext.ConvNeXt', class {});
  8645. this.registerType('torchvision.models.convnext.CNBlock', class {});
  8646. this.registerType('torchvision.models.convnext.LayerNorm2d', class {});
  8647. this.registerType('torchvision.models.densenet.DenseNet', class extends torch.nn.modules.module.Module {});
  8648. this.registerType('torchvision.models.densenet._DenseBlock', class extends torch.nn.modules.container.ModuleDict {});
  8649. this.registerType('torchvision.models.densenet._DenseLayer', class extends torch.nn.modules.module.Module {});
  8650. this.registerType('torchvision.models.densenet._Transition', class extends torch.nn.modules.container.Sequential {});
  8651. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  8652. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  8653. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  8654. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  8655. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  8656. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  8657. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  8658. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  8659. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNConvFCHead', class {});
  8660. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  8661. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  8662. this.registerType('torchvision.models.detection.fcos.FCOS', class {});
  8663. this.registerType('torchvision.models.detection.fcos.FCOSHead', class {});
  8664. this.registerType('torchvision.models.detection.fcos.FCOSClassificationHead', class {});
  8665. this.registerType('torchvision.models.detection.fcos.FCOSRegressionHead', class {});
  8666. this.registerType('torchvision.models.detection._utils.BoxLinearCoder', class {});
  8667. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  8668. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  8669. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  8670. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  8671. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  8672. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  8673. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  8674. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  8675. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  8676. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  8677. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  8678. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  8679. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  8680. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  8681. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  8682. this.registerType('torchvision.models.detection.ssd.SSDClassificationHead', class {});
  8683. this.registerType('torchvision.models.detection.ssd.SSDHead', class {});
  8684. this.registerType('torchvision.models.detection.ssd.SSDFeatureExtractorVGG', class {});
  8685. this.registerType('torchvision.models.detection.ssd.SSDRegressionHead', class {});
  8686. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  8687. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  8688. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  8689. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  8690. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  8691. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  8692. this.registerType('torchvision.models.efficientnet.EfficientNet_B3_Weights', class {});
  8693. this.registerType('torchvision.models.efficientnet.FusedMBConv', class {});
  8694. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  8695. this.registerType('torchvision.models.feature_extraction.LeafModuleAwareTracer', class extends torch.fx._symbolic_trace.Tracer {});
  8696. this.registerType('torchvision.models.feature_extraction.NodePathTracer', class extends torchvision.models.feature_extraction.LeafModuleAwareTracer {});
  8697. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  8698. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  8699. this.registerType('torchvision.models.googlenet.Inception', class {});
  8700. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  8701. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  8702. this.registerType('torchvision.models.inception.Inception3', class {});
  8703. this.registerType('torchvision.models.inception.InceptionAux', class {});
  8704. this.registerType('torchvision.models.inception.InceptionA', class {});
  8705. this.registerType('torchvision.models.inception.InceptionB', class {});
  8706. this.registerType('torchvision.models.inception.InceptionC', class {});
  8707. this.registerType('torchvision.models.inception.InceptionD', class {});
  8708. this.registerType('torchvision.models.inception.InceptionE', class {});
  8709. this.registerFunction('torchvision.models.inception.inception_v3');
  8710. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  8711. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  8712. this.registerType('torchvision.models.maxvit.MaxVit', class {});
  8713. this.registerType('torchvision.models.maxvit.MaxVitBlock', class {});
  8714. this.registerType('torchvision.models.maxvit.MaxVitLayer', class {});
  8715. this.registerType('torchvision.models.maxvit.MBConv', class {});
  8716. this.registerType('torchvision.models.maxvit.PartitionAttentionLayer', class {});
  8717. this.registerType('torchvision.models.maxvit.RelativePositionalMultiHeadAttention', class {});
  8718. this.registerType('torchvision.models.maxvit.SwapAxes', class {});
  8719. this.registerType('torchvision.models.maxvit.WindowDepartition', class {});
  8720. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  8721. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  8722. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  8723. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  8724. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  8725. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  8726. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  8727. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  8728. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  8729. this.registerType('torchvision.models.regnet.AnyStage', class extends torch.nn.modules.container.Sequential {});
  8730. this.registerType('torchvision.models.regnet.BottleneckTransform', class {});
  8731. this.registerType('torchvision.models.regnet.ResBottleneckBlock', class {});
  8732. this.registerType('torchvision.models.regnet.RegNet', class {});
  8733. this.registerType('torchvision.models.regnet.SimpleStemIN', class {});
  8734. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  8735. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  8736. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  8737. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  8738. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  8739. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  8740. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableMobileNetV3', class {});
  8741. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableInvertedResidual', class {});
  8742. this.registerType('torchvision.models.quantization.mobilenetv3.QuantizableSqueezeExcitation', class {});
  8743. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  8744. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  8745. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  8746. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  8747. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  8748. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  8749. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  8750. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  8751. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  8752. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  8753. this.registerType('torchvision.models.segmentation.lraspp.LRASPP', class {});
  8754. this.registerType('torchvision.models.segmentation.lraspp.LRASPPHead', class {});
  8755. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  8756. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  8757. this.registerType('torchvision.models.squeezenet.Fire', class {});
  8758. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  8759. this.registerType('torchvision.models.swin_transformer.PatchMerging', class {});
  8760. this.registerType('torchvision.models.swin_transformer.PatchMergingV2', class {});
  8761. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttention', class {});
  8762. this.registerType('torchvision.models.swin_transformer.ShiftedWindowAttentionV2', class {});
  8763. this.registerType('torchvision.models.swin_transformer.SwinTransformer', class {});
  8764. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlock', class {});
  8765. this.registerType('torchvision.models.swin_transformer.SwinTransformerBlockV2', class {});
  8766. this.registerType('torchvision.models.resnet.ResNet', class {});
  8767. this.registerType('torchvision.models.vgg.VGG', class {});
  8768. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  8769. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  8770. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  8771. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  8772. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  8773. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  8774. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  8775. this.registerType('torchvision.models.vision_transformer.Encoder', class extends torch.nn.modules.module.Module {});
  8776. this.registerType('torchvision.models.vision_transformer.EncoderBlock', class extends torch.nn.modules.module.Module {});
  8777. this.registerType('torchvision.models.vision_transformer.MLPBlock', class extends torchvision.ops.misc.MLP {});
  8778. this.registerType('torchvision.models.vision_transformer.VisionTransformer', class extends torch.nn.modules.module.Module {});
  8779. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  8780. this.registerType('torchvision.transforms._presets.ImageClassification', class extends torch.nn.modules.module.Module {});
  8781. this.registerType('torchvision.transforms.autoaugment.AutoAugment', class {});
  8782. this.registerType('torchvision.transforms.autoaugment.AutoAugmentPolicy', class {});
  8783. this.registerType('torchvision.transforms.autoaugment.AugMix', class {});
  8784. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  8785. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8786. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8787. this.registerFunction('torchvision.transforms.functional.adjust_brightness');
  8788. this.registerFunction('torchvision.transforms.functional.adjust_contrast');
  8789. this.registerFunction('torchvision.transforms.functional.adjust_gamma');
  8790. this.registerFunction('torchvision.transforms.functional.adjust_hue');
  8791. this.registerFunction('torchvision.transforms.functional.adjust_saturation');
  8792. this.registerType('torchvision.transforms.transforms.ColorJitter', class extends torch.nn.modules.module.Module {});
  8793. this.registerType('torchvision.transforms.transforms.Compose', class {});
  8794. this.registerType('torchvision.transforms.transforms.ConvertImageDtype', class {});
  8795. this.registerType('torchvision.transforms.transforms.CenterCrop', class extends torch.nn.modules.module.Module {});
  8796. this.registerType('torchvision.transforms.transforms.GaussianBlur', class extends torch.nn.modules.module.Module {});
  8797. this.registerType('torchvision.transforms.transforms.Grayscale', class extends torch.nn.modules.module.Module {});
  8798. this.registerType('torchvision.transforms.transforms.Lambda', class {});
  8799. this.registerType('torchvision.transforms.transforms.Normalize', class extends torch.nn.modules.module.Module {});
  8800. this.registerType('torchvision.transforms.transforms.PILToTensor', class {});
  8801. this.registerType('torchvision.transforms.transforms.RandomAffine', class extends torch.nn.modules.module.Module {});
  8802. this.registerType('torchvision.transforms.transforms.RandomApply', class extends torch.nn.modules.module.Module {});
  8803. this.registerType('torchvision.transforms.transforms.RandomCrop', class extends torch.nn.modules.module.Module {});
  8804. this.registerType('torchvision.transforms.transforms.RandomChoice', class {});
  8805. this.registerType('torchvision.transforms.transforms.RandomErasing', class {});
  8806. this.registerType('torchvision.transforms.transforms.RandomInvert', class {});
  8807. this.registerType('torchvision.transforms.transforms.RandomPerspective', class {});
  8808. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class extends torch.nn.modules.module.Module {});
  8809. this.registerType('torchvision.transforms.transforms.RandomVerticalFlip', class extends torch.nn.modules.module.Module {});
  8810. this.registerType('torchvision.transforms.transforms.RandomResizedCrop', class extends torch.nn.modules.module.Module {});
  8811. this.registerType('torchvision.transforms.transforms.RandomRotation', class extends torch.nn.modules.module.Module {});
  8812. this.registerType('torchvision.transforms.transforms.Resize', class extends torch.nn.modules.module.Module {});
  8813. this.registerType('torchvision.transforms.transforms.Scale', class extends torch.nn.modules.module.Module {});
  8814. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  8815. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  8816. this.registerType('torchvision.transforms.v2._color.Grayscale', class {});
  8817. this.registerType('torchvision.transforms.v2._color.RandomGrayscale', class {});
  8818. this.registerType('torchvision.transforms.v2._container.Compose', class {});
  8819. this.registerType('torchvision.transforms.v2._deprecated.ToTensor', class {});
  8820. this.registerType('torchvision.transforms.v2._misc.ConvertImageDtype', class {});
  8821. this.registerType('torchvision.transforms.v2._misc.Normalize', class {});
  8822. this.registerType('torchvision.transforms.v2._misc.ToDtype', class {});
  8823. this.registerType('torchvision.transforms.v2._geometry.CenterCrop', class {});
  8824. this.registerType('torchvision.transforms.v2._geometry.Resize', class {});
  8825. this.registerType('torchvision.transforms.v2._geometry.Pad', class {});
  8826. this.registerType('torchvision.transforms.v2._geometry.RandomCrop', class {});
  8827. this.registerType('torchvision.transforms.v2._transform.Transform', class extends torch.nn.modules.module.Module {});
  8828. this.registerType('torchvision.transforms.v2._type_conversion.ToImage', class extends torchvision.transforms.v2._transform.Transform {});
  8829. this.registerType('torchvision.transforms.v2._type_conversion.PILToTensor', class {});
  8830. this.registerFunction('torchvision.models.resnet.resnet18', () => {});
  8831. this.registerFunction('torchvision.models.resnet.resnet34', () => {});
  8832. this.registerFunction('torchvision.models.resnet.resnet50', () => {});
  8833. this.registerFunction('torchvision.models.resnet.resnet101', () => {});
  8834. this.registerFunction('torchvision.models.resnet.resnet152', () => {});
  8835. this.registerFunction('torchvision.models.vision_transformer.vit_h_14', () => {});
  8836. this.registerFunction('torchvision.ops.boxes.box_iou');
  8837. this.registerFunction('torchvision.ops.focal_loss.sigmoid_focal_loss');
  8838. this.registerFunction('builtins.annotate', (type, value) => {
  8839. if (type === builtins.int) {
  8840. return Number.isInteger(value) ? value : NaN;
  8841. }
  8842. if (type === builtins.float) {
  8843. return typeof value === 'number' ? value : NaN;
  8844. }
  8845. if (type === builtins.number) {
  8846. // if (pytorch.Utility.isTensor(value)) {
  8847. // value.resize_([]);
  8848. // }
  8849. }
  8850. return value;
  8851. });
  8852. this.registerFunction('builtins.uninitialized', (/* type */) => {
  8853. return undefined;
  8854. });
  8855. this.registerFunction('builtins.range', (start, stop, step) => {
  8856. if (stop === undefined && step === undefined) {
  8857. if (Number.isInteger(start)) {
  8858. return Array(start).keys();
  8859. }
  8860. if (isNaN(start)) {
  8861. return [];
  8862. }
  8863. }
  8864. throw new python.Error(`Unsupported range(${JSON.stringify(start)}, ${JSON.stringify(stop)}, ${JSON.stringify(step)})`);
  8865. });
  8866. this.registerFunction('math.trunc');
  8867. builtins.xrange = builtins.range;
  8868. this.registerFunction('torch._C._nn.gelu');
  8869. this.registerFunction('torch._C._nn.avg_pool2d');
  8870. this.registerFunction('torch._C._nn.avg_pool3d');
  8871. this.registerFunction('torch._C._nn.scaled_dot_product_attention');
  8872. this.registerFunction('torch._C._nn.softplus');
  8873. this.registerFunction('torch._native_multi_head_attention');
  8874. this.registerFunction('torch._utils._rebuild_sparse_tensor', (layout, data) => {
  8875. if (layout === torch.sparse_coo) {
  8876. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  8877. }
  8878. throw new python.Error(`Unsupported sparse tensor layout '${layout ? layout.__str__() : ''}'.`);
  8879. });
  8880. this.registerFunction('torch._utils._get_restore_location', (device) => {
  8881. return device;
  8882. });
  8883. this.registerFunction('torch._utils._rebuild_wrapper_subclass', (cls, dtype, size, stride, storage_offset, layout, device, requires_grad) => {
  8884. device = torch._utils._get_restore_location(device);
  8885. return torch.Tensor._make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad);
  8886. });
  8887. this.registerFunction('torch.from_numpy', (obj) => {
  8888. const dtypes = new Map([
  8889. ['<f2', torch.float16],
  8890. ['<f4', torch.float32],
  8891. ['<f8', torch.float64],
  8892. ['<i2', torch.int16],
  8893. ['<i4', torch.int32],
  8894. ['<i8', torch.int64],
  8895. ]);
  8896. if (!dtypes.has(obj.dtype.str)) {
  8897. throw new python.Error(`Unsupported numpy.ndarray type '${obj.dtype.str}'.`);
  8898. }
  8899. const dtype = dtypes.get(obj.dtype.str);
  8900. const strides = obj.strides.map((stride) => stride / obj.itemsize);
  8901. const storage = new torch.storage.TypedStorage(obj.size, dtype);
  8902. storage._set_cdata(obj.data);
  8903. const tensor = new torch.Tensor();
  8904. tensor.__setstate__([storage, 0, obj.shape, strides]);
  8905. return tensor;
  8906. });
  8907. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', (data, dtype, device, requires_grad) => {
  8908. const tensor = torch.from_numpy(data);
  8909. // tensor = tensor.to(dtype, device)
  8910. tensor.requires_grad = requires_grad;
  8911. return tensor;
  8912. });
  8913. this.registerFunction('torch._utils._rebuild_device_tensor_from_cpu_tensor', (data, dtype, device, requires_grad) => {
  8914. data = data.clone();
  8915. data.requires_grad = requires_grad;
  8916. return data;
  8917. });
  8918. this.registerFunction('torch._sparse_coo_tensor_unsafe', (indices, values, size) => {
  8919. const tensor = self.invoke('torch.Tensor', []);
  8920. tensor._layout = torch.sparse_coo;
  8921. tensor._indices = indices;
  8922. tensor._values = values;
  8923. tensor._shape = size;
  8924. return tensor;
  8925. });
  8926. this.registerFunction('torch._utils.set_tensor_metadata', (tensor, metadata) => {
  8927. torch._C._set_tensor_metadata(tensor, metadata);
  8928. });
  8929. this.registerFunction('torch._utils._restore_device_fake_mode', (tensor) => {
  8930. return tensor;
  8931. });
  8932. this.registerFunction('torch._utils._rebuild_meta_tensor_no_storage', (dtype, size, stride, requires_grad) => {
  8933. return torch.empty_strided(size, stride, dtype, null, 'meta', false, requires_grad);
  8934. });
  8935. this.registerFunction('torch._utils._rebuild_tensor', (storage, storage_offset, size, stride) => {
  8936. if (Array.isArray(storage) && storage.length === 5 && storage[0] === 'storage') {
  8937. const [, storage_type, , ,size] = storage;
  8938. storage = new storage_type(size);
  8939. }
  8940. const tensor = new torch.Tensor();
  8941. tensor.__setstate__([storage, storage_offset, size, stride]);
  8942. return tensor;
  8943. });
  8944. this.registerFunction('torch._utils._rebuild_tensor_v2', (storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata) => {
  8945. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride);
  8946. tensor.requires_grad = requires_grad;
  8947. if (metadata) {
  8948. torch._utils.set_tensor_metadata(tensor, metadata);
  8949. }
  8950. tensor.backward_hooks = backward_hooks;
  8951. return tensor;
  8952. });
  8953. this.registerFunction('torch._utils._rebuild_tensor_v3', (storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata) => {
  8954. const t = new torch.Tensor(null, null, dtype);
  8955. t.set_(storage, storage_offset, size, stride);
  8956. if (metadata) {
  8957. torch._utils.set_tensor_metadata(t, metadata);
  8958. }
  8959. t._backward_hooks = backward_hooks;
  8960. return torch._utils._restore_device_fake_mode(t);
  8961. });
  8962. this.registerFunction('torch._utils._rebuild_parameter', (data, requires_grad, backward_hooks) => {
  8963. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8964. param.backward_hooks = backward_hooks;
  8965. return param;
  8966. });
  8967. this.registerFunction('torch._utils._rebuild_parameter_v2', (data, requires_grad, backward_hooks, state) => {
  8968. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8969. param.backward_hooks = backward_hooks;
  8970. torch._utils._set_obj_state(param, state);
  8971. return param;
  8972. });
  8973. this.registerFunction('torch._utils._rebuild_parameter_with_state', (data, requires_grad, backward_hooks, state) => {
  8974. const _set_obj_state = (obj, state) => {
  8975. const [dict_state, slots_state] = Array.isArray(state) ? state : [state, null];
  8976. if (dict_state) {
  8977. for (const [k, v] of Object.entries(dict_state)) {
  8978. builtins.setattr(obj, k, v);
  8979. }
  8980. }
  8981. if (slots_state) {
  8982. for (const [k, v] of Object.entries(slots_state)) {
  8983. builtins.setattr(obj, k, v);
  8984. }
  8985. }
  8986. };
  8987. const param = new torch.nn.parameter.Parameter(data, requires_grad);
  8988. param._backward_hooks = backward_hooks;
  8989. _set_obj_state(param, state);
  8990. return param;
  8991. });
  8992. this.registerFunction('torch._utils._rebuild_qtensor', (storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) => {
  8993. const tensor = torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks);
  8994. tensor.quantizer_params = quantizer_params;
  8995. return tensor;
  8996. });
  8997. this.registerFunction('torch._utils._set_obj_state', (obj, state) => {
  8998. let dict_state = state;
  8999. let slots_state = null;
  9000. if (state instanceof self.builtins.tuple) {
  9001. if (state.length !== 2) {
  9002. throw new python.Error(`Invalid serialized state: '${state}'.`);
  9003. }
  9004. [dict_state, slots_state] = state;
  9005. }
  9006. if (dict_state) {
  9007. for (const [name, value] of Object.entries(dict_state)) {
  9008. builtins.setattr(obj, name, value);
  9009. }
  9010. }
  9011. if (slots_state) {
  9012. for (const [name, value] of Object.entries(slots_state)) {
  9013. builtins.setattr(obj, name, value);
  9014. }
  9015. }
  9016. return obj;
  9017. });
  9018. this.registerFunction('torch._set_item', (dict, key, value) => {
  9019. dict[key] = value;
  9020. });
  9021. this.registerFunction('torch._tensor._rebuild_from_type_v2', (func, new_type, args, state) => {
  9022. let ret = func(...args);
  9023. if (ret.__class__ !== new_type) {
  9024. // ret = ret.as_subclass(new_type);
  9025. }
  9026. const setstate = builtins.getattr(ret.__class__, '__setstate__', torch.Tensor.__setstate__);
  9027. if (setstate === torch.Tensor.__setstate__) {
  9028. ret = torch._utils._set_obj_state(ret, state);
  9029. } else {
  9030. ret.__setstate__(state);
  9031. }
  9032. return ret;
  9033. });
  9034. this.registerFunction('torch.__range_length', (lo, hi, step) => {
  9035. if (step === 0) {
  9036. throw new python.Error('range() arg 3 must not be zero');
  9037. }
  9038. if (step > 0 && lo < hi) {
  9039. return 1 + (hi - 1 - lo) / step;
  9040. } else if (step < 0 && lo > hi) {
  9041. return 1 + (lo - 1 - hi) / (0 - step);
  9042. }
  9043. return 0;
  9044. });
  9045. this.registerFunction('torch._nested_tensor_from_mask_left_aligned');
  9046. this.registerOperator('aten::_unwrap_optional', (value) => {
  9047. return value;
  9048. });
  9049. this.registerFunction('torch.get_default_dtype', () => {
  9050. torch._default_type = torch._default_type || torch.float32;
  9051. return torch._default_type;
  9052. });
  9053. this.registerFunction('torch.set_default_dtype', (value) => {
  9054. torch._default_type = value;
  9055. });
  9056. this.registerFunction('torch._prims_common.dtype_or_default', (value) => {
  9057. return value || torch.get_default_dtype();
  9058. });
  9059. this.registerFunction('torch.empty_strided', (size, stride, dtype, layout, device, pin_memory, requires_grad) => {
  9060. const shape = size;
  9061. dtype = torch._prims_common.dtype_or_default(dtype);
  9062. let storage = null;
  9063. if (size.every((d) => d instanceof torch.SymInt === false)) {
  9064. const size = shape.reduce((a, b) => a * b, 1);
  9065. storage = new torch.storage.TypedStorage(size, dtype);
  9066. }
  9067. const tensor = new torch.Tensor(storage, shape, dtype, layout, device, requires_grad);
  9068. tensor.__setstate__([storage, 0, shape, stride]);
  9069. return tensor;
  9070. });
  9071. this.registerFunction('torch.all', (input) => {
  9072. if (Array.isArray(input) && input.length === 0) {
  9073. return true;
  9074. }
  9075. throw new python.Error(`Unsupported 'torch.all' expression type.`);
  9076. });
  9077. this.registerFunction('torch.append', (list, value) => {
  9078. list.push(value);
  9079. return value;
  9080. });
  9081. this.registerFunction('torch.clear', (value) => {
  9082. if (value instanceof torch.Value) {
  9083. throw new python.Error('Invalid value.');
  9084. }
  9085. if (Object(value) === value) {
  9086. for (const key of Object.keys(value)) {
  9087. delete value[key];
  9088. }
  9089. }
  9090. });
  9091. this.registerFunction('torch.dict', (args) => {
  9092. const obj = {};
  9093. if (args) {
  9094. if (Array.isArray(args)) {
  9095. for (const [key, value] of args) {
  9096. obj[key] = value;
  9097. }
  9098. } else {
  9099. throw new python.Error("'torch.dict' arguments not supported.");
  9100. }
  9101. }
  9102. return obj;
  9103. });
  9104. this.registerOperator('aten::cosine_similarity', () => {
  9105. throw new python.Error(`'aten::cosine_similarity' not implemented.`);
  9106. });
  9107. this.registerOperator('aten::extend', (list, value) => {
  9108. list.push(...value);
  9109. });
  9110. this.registerOperator('aten::insert', (list, index, value) => {
  9111. list.splice(index, 0, value);
  9112. return value;
  9113. });
  9114. this.registerOperator('aten::replace', (value, oldvalue, newvalue /*, max */) => {
  9115. return value.replace(oldvalue, newvalue);
  9116. });
  9117. this.registerOperator('aten::add', (a, b) => {
  9118. if ((typeof a === 'number' || a instanceof Number) && (typeof b === 'number' || b instanceof Number)) {
  9119. return a + b;
  9120. }
  9121. if (typeof a === 'number' && b instanceof builtins.complex) {
  9122. return new builtins.complex(a + b.real, b.imag);
  9123. }
  9124. if (a instanceof builtins.complex && typeof b === 'number') {
  9125. return new builtins.complex(a.real + b, a.imag);
  9126. }
  9127. if (a instanceof builtins.complex && b instanceof builtins.complex) {
  9128. return new builtins.complex(a.real + b.real, a.imag + b.imag);
  9129. }
  9130. if (Array.isArray(a) && Array.isArray(b)) {
  9131. return a.concat(b);
  9132. }
  9133. if (typeof a === 'string' && typeof b === 'string') {
  9134. return a + b;
  9135. }
  9136. throw new python.Error('Unsupported aten::add expression type.');
  9137. });
  9138. this.registerOperator('aten::log', (x) => {
  9139. if (typeof x === 'number' || x instanceof Number) {
  9140. return Math.log(x);
  9141. }
  9142. throw new python.Error('Unsupported aten::log expression type.');
  9143. });
  9144. this.registerOperator('aten::dim', (tensor) => {
  9145. if (tensor && tensor.size) {
  9146. const size = tensor.size();
  9147. if (size) {
  9148. return size.length;
  9149. }
  9150. }
  9151. return NaN;
  9152. });
  9153. this.registerOperator('aten::numel', (tensor) => {
  9154. if (tensor && tensor.size) {
  9155. const size = tensor.size();
  9156. if (size) {
  9157. return size.reduce((a, b) => a * b, 1);
  9158. }
  9159. }
  9160. return NaN;
  9161. });
  9162. this.registerOperator('aten::eq', (left, right) => {
  9163. if (typeof left === 'string' && typeof right === 'string') {
  9164. return left === right;
  9165. }
  9166. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9167. if (isNaN(left) && isNaN(right)) {
  9168. return true;
  9169. }
  9170. return left === right;
  9171. }
  9172. if (left === undefined || right === undefined) {
  9173. return true;
  9174. }
  9175. if (Array.isArray(left) && Array.isArray(right)) {
  9176. return left.length === right.length && left.every((item, index) => item === right[index]);
  9177. }
  9178. throw new python.Error("Unsupported 'torch.eq' expression type.");
  9179. });
  9180. this.registerOperator('aten::floor', (value) => {
  9181. return Math.floor(value);
  9182. });
  9183. this.registerOperator('aten::ceil', (value) => {
  9184. return Math.ceil(value);
  9185. });
  9186. this.registerOperator('aten::floordiv', (left, right) => {
  9187. return Math.floor(left / right);
  9188. });
  9189. this.registerOperator('aten::format', (...args) => {
  9190. const list = args.shift().split(/({}D?)/);
  9191. return list.map((text) => {
  9192. if (text === '{}' || text === '{}D') {
  9193. const arg = args.shift();
  9194. if (Array.isArray(arg)) {
  9195. return `[${arg.map((item) => item.toString()).join(', ')}]`;
  9196. }
  9197. return arg ? arg.toString() : '?';
  9198. }
  9199. return text;
  9200. }).join('');
  9201. });
  9202. this.registerOperator('aten::strip', (self, chars) => {
  9203. chars = chars || '\\n\\t\\f\\v';
  9204. const regex = new RegExp(`[${chars}]`, 'g');
  9205. return self.replace(regex, '');
  9206. });
  9207. this.registerOperator('aten::gt', (left, right) => {
  9208. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9209. if (!isNaN(left) && !isNaN(right)) {
  9210. return left > right;
  9211. }
  9212. }
  9213. if (isNaN(left) && !isNaN(right)) {
  9214. return true;
  9215. }
  9216. throw new python.Error("Unsupported 'ops.aten.gt' expression type.");
  9217. });
  9218. this.registerOperator('aten::ge', (left, right) => {
  9219. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9220. if (!isNaN(left) && !isNaN(right)) {
  9221. return left > right;
  9222. }
  9223. }
  9224. if (isNaN(left) && !isNaN(right)) {
  9225. return true;
  9226. }
  9227. throw new python.Error("Unsupported 'ops.aten.ge' expression type.");
  9228. });
  9229. this.registerOperator('aten::is_floating_point', (tensor) => {
  9230. const type = tensor.dtype.scalar_type();
  9231. return (type === 5 || type === 6 || type === 7);
  9232. });
  9233. this.registerOperator('aten::is_grad_enabled', () => {
  9234. return false;
  9235. });
  9236. this.registerOperator('aten::is_autocast_enabled', () => {
  9237. return false;
  9238. });
  9239. this.registerOperator('aten::isfinite');
  9240. this.registerOperator('aten::set_grad_enabled', (/* value */) => {
  9241. });
  9242. this.registerFunction('torch.serialization._get_layout', (name) => {
  9243. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  9244. return value instanceof torch.layout ? value : null;
  9245. });
  9246. this.registerFunction('torch.storage._load_from_bytes', (b) => {
  9247. return torch.load(b);
  9248. });
  9249. this.registerFunction('torch.jit._pickle.build_boollist', (data) => {
  9250. return data;
  9251. });
  9252. this.registerFunction('torch.jit._pickle.build_doublelist', (data) => {
  9253. return data;
  9254. });
  9255. this.registerFunction('torch.jit._pickle.build_intlist', (data) => {
  9256. return data;
  9257. });
  9258. this.registerFunction('torch.jit._pickle.build_tensorlist', (data) => {
  9259. return data;
  9260. });
  9261. this.registerFunction('torch.jit._pickle.build_tensor_from_id', (data) => {
  9262. return self.builtins.CONSTANTS[`c${data}`];
  9263. });
  9264. this.registerFunction('torch.jit._pickle.restore_type_tag', (value /*, type_str */) => {
  9265. return value;
  9266. });
  9267. this.registerOperator('aten::keys', (dict) => {
  9268. return Object.keys(dict);
  9269. });
  9270. this.registerOperator('aten::len', (value) => {
  9271. if (Array.isArray(value)) {
  9272. return value.length;
  9273. }
  9274. if (value && value.shape && value.__len__) {
  9275. return value.__len__();
  9276. }
  9277. return NaN;
  9278. });
  9279. this.registerOperator('aten::le', (left, right) => {
  9280. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9281. if (isNaN(left) || isNaN(right)) {
  9282. return false;
  9283. }
  9284. return left <= right;
  9285. }
  9286. if (left === undefined || right === undefined) {
  9287. return true;
  9288. }
  9289. throw new python.Error("Unsupported 'torch.le' expression type.");
  9290. });
  9291. this.registerOperator('aten::list', (args) => {
  9292. return args;
  9293. });
  9294. this.registerOperator('aten::list_with_default', (size /*, defaults */) => {
  9295. return size;
  9296. });
  9297. this.registerType('torch.PyTorchFileReader', class {
  9298. constructor(entries) {
  9299. let prefix = 0;
  9300. const paths = Array.from(entries.keys()).map((path) => path.replace(/\\/g, '/').split('/').reverse());
  9301. for (let set = new Set(); set && paths.length > 0;) {
  9302. set = new Set(paths.map((path) => path.length > 1 ? path.pop() : null));
  9303. set = set.size > 1 || set.keys().next().value === null ? null : set;
  9304. prefix += set ? set.keys().next().value.length + 1 : 0;
  9305. }
  9306. this._records = new Map(Array.from(entries).map(([name, value]) => [name.substring(prefix), value]));
  9307. this._version = 0;
  9308. this.init();
  9309. }
  9310. init() {
  9311. let stream = null;
  9312. if (this.has_record('.data/version')) {
  9313. stream = this.get_record('.data/version');
  9314. } else if (this.has_record('version')) {
  9315. stream = this.get_record('version');
  9316. }
  9317. if (stream) {
  9318. const decoder = new TextDecoder('utf-8');
  9319. const buffer = stream.peek();
  9320. const text = decoder.decode(buffer);
  9321. this._version = Number(text.split('\n').shift().trim());
  9322. }
  9323. }
  9324. has_record(name) {
  9325. return this._records.has(name);
  9326. }
  9327. get_record(name) {
  9328. if (!this.has_record(name)) {
  9329. throw new python.Error(`Record '${name}' not found.`);
  9330. }
  9331. return this._records.get(name);
  9332. }
  9333. get_all_records() {
  9334. return Array.from(this._records.keys());
  9335. }
  9336. version() {
  9337. return this._version;
  9338. }
  9339. });
  9340. this.registerFunction('torch.load', (f) => {
  9341. const legacy_load = (entries) => {
  9342. const deserialized_objects = {};
  9343. if (entries.has('storages')) {
  9344. const data = entries.get('storages');
  9345. const unpickler = new pickle.Unpickler(data);
  9346. const num_storages = unpickler.load();
  9347. for (let i = 0; i < num_storages; i++) {
  9348. const args = unpickler.load();
  9349. const [key, , storage_type] = args;
  9350. const obj = storage_type._new_with_file(unpickler);
  9351. deserialized_objects[key] = obj;
  9352. }
  9353. /*
  9354. let storage_views = unpickler.load();
  9355. for target_cdata, root_cdata, offset, size in storage_views:
  9356. root = deserialized_objects[root_cdata]
  9357. deserialized_objects[target_cdata] = root[offset:offset + size]
  9358. */
  9359. }
  9360. if (entries.has('tensors')) {
  9361. const data = entries.get('tensors');
  9362. const unpickler = new pickle.Unpickler(data);
  9363. const num_tensors = unpickler.load();
  9364. const int32 = (unpickler) => {
  9365. const buffer = unpickler.read(4);
  9366. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  9367. };
  9368. const int64 = (unpickler) => {
  9369. const buffer = unpickler.read(8);
  9370. if (buffer[6] !== 0 && buffer[7] !== 0) {
  9371. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  9372. }
  9373. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  9374. };
  9375. for (let i = 0; i < num_tensors; i++) {
  9376. const args = unpickler.load();
  9377. const [key, storage_id] = args;
  9378. const storage = deserialized_objects[storage_id];
  9379. const ndim = int32(unpickler);
  9380. unpickler.read(4);
  9381. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9382. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  9383. const storage_offset = int64(unpickler);
  9384. const tensor = torch._utils._rebuild_tensor(storage, storage_offset, shape, stride);
  9385. deserialized_objects[key] = tensor;
  9386. }
  9387. }
  9388. const data = entries.get('pickle');
  9389. const unpickler = new pickle.Unpickler(data);
  9390. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  9391. return unpickler.load();
  9392. };
  9393. const _legacy_load = () => {
  9394. const unpickler = new pickle.Unpickler(f);
  9395. unpickler.load(); // magic_number
  9396. const protocol_version = unpickler.load();
  9397. if (protocol_version !== 1001) {
  9398. throw new python.Error(`Unsupported protocol version '${protocol_version}'.`);
  9399. }
  9400. const sys_info = unpickler.load();
  9401. if (sys_info.get('protocol_version') !== 1001) {
  9402. throw new python.Error(`Unsupported protocol version '${sys_info.protocol_version}'.`);
  9403. }
  9404. if (sys_info.get('little_endian') === false) {
  9405. throw new python.Error("Unsupported big-endian storage data.");
  9406. }
  9407. const module_source_map = new Map();
  9408. const deserialized_objects = new Map();
  9409. unpickler.persistent_load = (saved_id) => {
  9410. switch (saved_id[0]) {
  9411. case 'module': {
  9412. const [, module, ,source] = saved_id;
  9413. module_source_map.set(module, source);
  9414. return saved_id[1];
  9415. }
  9416. case 'storage': {
  9417. const [, storage_type, key, , size, view_metadata] = saved_id;
  9418. if (!deserialized_objects.has(key)) {
  9419. const obj = new storage_type(size);
  9420. deserialized_objects.set(key, obj);
  9421. }
  9422. if (view_metadata) {
  9423. const view_key = view_metadata.shift();
  9424. view_metadata.shift(); // view_offset
  9425. view_metadata.shift(); // view_size
  9426. if (!deserialized_objects.has(view_key)) {
  9427. const view = null; // storage.slice(view_offset, view_offset + view_size);
  9428. deserialized_objects.set(view_key, view);
  9429. }
  9430. return deserialized_objects.get(view_key);
  9431. }
  9432. return deserialized_objects.get(key);
  9433. }
  9434. default: {
  9435. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9436. }
  9437. }
  9438. };
  9439. const obj = unpickler.load();
  9440. const deserialized_storage_keys = unpickler.load();
  9441. for (const deserialized_storage_key of deserialized_storage_keys) {
  9442. const storage = deserialized_objects.get(deserialized_storage_key);
  9443. storage._set_from_file(unpickler);
  9444. }
  9445. if (!obj) {
  9446. throw new python.Error('File format is not PyTorch.');
  9447. }
  9448. if (obj === 'None') {
  9449. throw new python.Error("File contains 'None' root object.");
  9450. }
  9451. return obj;
  9452. };
  9453. const _load = (entries) => {
  9454. if (f.has('constant.pkl')) {
  9455. throw python.Error("TorchScript 'torch.load' not supported.");
  9456. }
  9457. const loaded_storages = new Map();
  9458. const persistent_load = (saved_id) => {
  9459. switch (saved_id[0]) {
  9460. case 'storage': {
  9461. const [, storage_type, key, , numel] = saved_id;
  9462. if (!loaded_storages.has(key)) {
  9463. const storage = new storage_type(numel);
  9464. if (!storage._set_cdata) {
  9465. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  9466. }
  9467. const name = `data/${key}`;
  9468. const stream = entries.get(name);
  9469. if (!stream) {
  9470. throw new python.Error(`Record '${name}' not found.`);
  9471. }
  9472. storage._set_cdata(stream);
  9473. loaded_storages.set(key, storage);
  9474. }
  9475. return loaded_storages.get(key);
  9476. }
  9477. default: {
  9478. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  9479. }
  9480. }
  9481. };
  9482. const data_file = entries.get('data.pkl');
  9483. const unpickler = new pickle.Unpickler(data_file);
  9484. unpickler.persistent_load = persistent_load;
  9485. const result = unpickler.load();
  9486. return result;
  9487. };
  9488. if (f instanceof Map) {
  9489. const reader = new torch.PyTorchFileReader(f);
  9490. const records = reader.get_all_records().map((name) => [name, reader.get_record(name)]);
  9491. f = new Map(records);
  9492. if (f.has('pickle')) {
  9493. return legacy_load(f);
  9494. }
  9495. if (f.has('data.pkl')) {
  9496. return _load(f);
  9497. }
  9498. throw new python.Error(`Unsupported 'torch.load' input '${JSON.stringify(Array.from(f.keys()))}'.`);
  9499. }
  9500. return _legacy_load(f);
  9501. });
  9502. this.registerOperator('prim::abs', (a) => {
  9503. if (typeof a === 'number' || a instanceof Number) {
  9504. return Math.abs(a);
  9505. }
  9506. if (a instanceof builtins.complex) {
  9507. return Math.hypot(a.real, a.imag);
  9508. }
  9509. throw new python.Error('Unsupported prim::abs expression type.');
  9510. });
  9511. this.registerOperator('prim::unchecked_cast', (type, value) => {
  9512. return value;
  9513. });
  9514. this.registerOperator('prim::data', (tensor) => {
  9515. return tensor;
  9516. });
  9517. this.registerOperator('prim::device', (tensor) => {
  9518. return tensor.device;
  9519. });
  9520. this.registerOperator('prim::dtype', (tensor) => {
  9521. return tensor.dtype.scalar_type();
  9522. });
  9523. this.registerOperator('prim::is_quantized', (tensor) => {
  9524. return tensor.is_quantized;
  9525. });
  9526. this.registerOperator('prim::is_cuda', (/* tensor */) => {
  9527. return false;
  9528. });
  9529. this.registerOperator('prim::is_nested', (tensor) => {
  9530. return tensor.is_nested;
  9531. });
  9532. this.registerOperator('prim::is_sparse', (tensor) => {
  9533. return tensor.is_sparse;
  9534. });
  9535. this.registerOperator('prim::unchecked_unwrap_optional', (value) => {
  9536. return value;
  9537. });
  9538. this.registerOperator('prim::NumToTensor', (value) => {
  9539. const tensor = self.invoke('torch.Tensor', []);
  9540. tensor.value = value;
  9541. return tensor;
  9542. });
  9543. this.registerOperator('prim::min', (...args) => {
  9544. if (Array.isArray(args[0])) {
  9545. return Math.min.apply(null, args[0]);
  9546. }
  9547. return Math.min.apply(null, args);
  9548. });
  9549. this.registerOperator('prim::max', (...args) => {
  9550. if (Array.isArray(args[0])) {
  9551. return Math.max.apply(null, args[0]);
  9552. }
  9553. return Math.max.apply(null, args);
  9554. });
  9555. this.registerOperator('prim::shape', (tensor) => {
  9556. return tensor && tensor.size ? tensor.size() : undefined;
  9557. });
  9558. this.registerOperator('quantized::conv_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9559. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9560. params.weight = weight;
  9561. params.bias = bias;
  9562. params.stride = stride;
  9563. params.padding = padding;
  9564. params.dilation = dilation;
  9565. params.groups = groups;
  9566. return params;
  9567. });
  9568. this.registerOperator('quantized::conv1d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9569. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9570. params.weight = weight;
  9571. params.bias = bias;
  9572. params.stride = stride;
  9573. params.padding = padding;
  9574. params.dilation = dilation;
  9575. params.groups = groups;
  9576. return params;
  9577. });
  9578. this.registerOperator('quantized::conv2d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9579. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9580. params.weight = weight;
  9581. params.bias = bias;
  9582. params.stride = stride;
  9583. params.padding = padding;
  9584. params.dilation = dilation;
  9585. params.groups = groups;
  9586. return params;
  9587. });
  9588. this.registerOperator('quantized::conv3d_prepack', (weight, bias, stride, padding, dilation, groups) => {
  9589. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  9590. params.weight = weight;
  9591. params.bias = bias;
  9592. params.stride = stride;
  9593. params.padding = padding;
  9594. params.dilation = dilation;
  9595. params.groups = groups;
  9596. return params;
  9597. });
  9598. this.registerOperator('quantized::conv_transpose1d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9599. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9600. params.weight = weight;
  9601. params.bias = bias;
  9602. params.stride = stride;
  9603. params.padding = padding;
  9604. params.output_padding = output_padding;
  9605. params.dilation = dilation;
  9606. params.groups = groups;
  9607. return params;
  9608. });
  9609. this.registerOperator('quantized::conv_transpose2d_prepack', (weight, bias, stride, padding, output_padding, dilation, groups) => {
  9610. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  9611. params.weight = weight;
  9612. params.bias = bias;
  9613. params.stride = stride;
  9614. params.padding = padding;
  9615. params.output_padding = output_padding;
  9616. params.dilation = dilation;
  9617. params.groups = groups;
  9618. return params;
  9619. });
  9620. this.registerOperator('quantized::linear_prepack', (weight, bias) => {
  9621. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  9622. params.weight = weight;
  9623. params.bias = bias;
  9624. return params;
  9625. });
  9626. this.registerOperator('prim::RaiseException', (message) => {
  9627. throw new python.Error(message);
  9628. });
  9629. this.registerOperator('prim::TupleIndex', (t, i) => {
  9630. return t.elements()[i];
  9631. });
  9632. this.registerOperator('prim::TupleUnpack', (t) => {
  9633. return t.elements();
  9634. });
  9635. this.registerOperator('aten::is_scripting', () => {
  9636. return true;
  9637. });
  9638. this.registerOperator('aten::__and__', (left, right) => {
  9639. return left && right;
  9640. });
  9641. this.registerOperator('aten::__contains__', (dict, key) => {
  9642. return builtins.hasattr(dict, key);
  9643. });
  9644. this.registerFunction('torch.__derive_index', (index, start, step) => {
  9645. return start + index * step;
  9646. });
  9647. this.registerOperator('aten::__is__', (left, right) => {
  9648. return left === right;
  9649. });
  9650. this.registerOperator('aten::__isnot__', (left, right) => {
  9651. return left !== right;
  9652. });
  9653. this.registerOperator('aten::__not__', (value) => {
  9654. if (Number.isInteger(value)) {
  9655. value = Boolean(value);
  9656. }
  9657. if (typeof value === 'boolean') {
  9658. return !value;
  9659. }
  9660. throw new python.Error("Unsupported 'ops.aten.__not__' expression type.");
  9661. });
  9662. this.registerOperator('aten::log10', (value) => {
  9663. return Math.log10(value);
  9664. });
  9665. this.registerOperator('aten::device', (type, index) => {
  9666. return new torch.device(type, index);
  9667. });
  9668. this.registerOperator('aten::lt', (left, right) => {
  9669. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9670. return left < right;
  9671. }
  9672. throw new python.Error("Unsupported 'ops.aten.lt' expression type.");
  9673. });
  9674. this.registerOperator('aten::mul', (left, right) => {
  9675. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9676. return left * right;
  9677. }
  9678. if (isNaN(left) || isNaN(right)) {
  9679. return NaN;
  9680. }
  9681. if (Array.isArray(left) && left.every((value) => typeof value === 'number' || value instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9682. return left.map((value) => value * right);
  9683. }
  9684. throw new python.Error("Unsupported 'ops.aten.mul' expression type.");
  9685. });
  9686. this.registerOperator('aten::div', (left, right) => {
  9687. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9688. return left / right;
  9689. }
  9690. if (isNaN(left) || isNaN(right)) {
  9691. return NaN;
  9692. }
  9693. throw new python.Error("Unsupported 'ops.aten.div' expression type.");
  9694. });
  9695. this.registerFunction('torch.round', (value) => {
  9696. if (typeof value === 'number' || value instanceof Number) {
  9697. return Math.round(value);
  9698. }
  9699. if (isNaN(value)) {
  9700. return value;
  9701. }
  9702. throw new python.Error("Unsupported 'torch.round' expression type.");
  9703. });
  9704. this.registerOperator('aten::remainder', (left, right) => {
  9705. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9706. return left % right;
  9707. }
  9708. if (isNaN(left) || isNaN(right)) {
  9709. return NaN;
  9710. }
  9711. throw new python.Error("Unsupported 'ops.aten.remainder' expression type.");
  9712. });
  9713. this.registerOperator('aten::ne', (left, right) => {
  9714. if (typeof left === 'boolean' && typeof right === 'boolean') {
  9715. return left !== right;
  9716. }
  9717. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9718. if (isNaN(left) || isNaN(right)) {
  9719. return false;
  9720. }
  9721. return left !== right;
  9722. }
  9723. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  9724. return false;
  9725. }
  9726. if (typeof left === 'string' && typeof right === 'string') {
  9727. return left !== right;
  9728. }
  9729. if (left === undefined || right === undefined) {
  9730. return true;
  9731. }
  9732. throw new python.Error("Unsupported 'ops.aten.ne' expression type.");
  9733. });
  9734. this.registerOperator('aten::neg', (value) => {
  9735. if (typeof value === 'number') {
  9736. return -value;
  9737. }
  9738. throw new python.Error("Unsupported 'ops.aten.neg' expression type.");
  9739. });
  9740. this.registerOperator('aten::pow', (left, right) => {
  9741. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9742. return Math.pow(left, right);
  9743. }
  9744. throw new python.Error("Unsupported 'ops.aten.pow' expression type.");
  9745. });
  9746. this.registerFunction('torch.q_scale', (/* tensor */) => {
  9747. return -1;
  9748. });
  9749. this.registerFunction('torch.t', (tensor) => {
  9750. return tensor;
  9751. });
  9752. this.registerOperator('aten::size', (tensor, dim) => {
  9753. if (tensor && tensor.size) {
  9754. const size = tensor.size();
  9755. if (Array.isArray(size)) {
  9756. if (dim === undefined) {
  9757. return size;
  9758. }
  9759. if (Number.isInteger(dim)) {
  9760. if (dim >= 0 && dim < size.length) {
  9761. return size[dim];
  9762. }
  9763. if (dim < 0 && -dim < size.length) {
  9764. return size[size.length + dim];
  9765. }
  9766. }
  9767. throw new python.Error(`Dimension out of range (expected to be in range of ${JSON.stringify(size)}, but got ${JSON.stringify(dim)}).`);
  9768. }
  9769. }
  9770. if (Number.isInteger(dim)) {
  9771. return NaN;
  9772. }
  9773. return [];
  9774. });
  9775. this.registerFunction('aten::sqrt', (x) => {
  9776. return Math.sqrt(x);
  9777. });
  9778. this.registerOperator('aten::slice', (l, start, end, step) => {
  9779. if (!Array.isArray(l)) {
  9780. throw new python.Error('Slicing expected array');
  9781. }
  9782. step = step || 1;
  9783. if (step !== 1) {
  9784. throw new python.Error('Slicing only supports step=1');
  9785. }
  9786. start = Math.max(0, start >= 0 ? start : l.length + start);
  9787. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  9788. return l.slice(start, end);
  9789. });
  9790. this.registerOperator('aten::sub', (left, right) => {
  9791. if ((typeof left === 'number' || left instanceof Number) && (typeof right === 'number' || right instanceof Number)) {
  9792. return left - right;
  9793. }
  9794. if (typeof left === 'number' && right instanceof builtins.complex) {
  9795. return new builtins.complex(left - right.real, right.imag);
  9796. }
  9797. if (left instanceof builtins.complex && typeof right === 'number') {
  9798. return new builtins.complex(left.real - right, left.imag);
  9799. }
  9800. if (left instanceof builtins.complex && right instanceof builtins.complex) {
  9801. return new builtins.complex(left.real - right.real, left.imag - right.imag);
  9802. }
  9803. throw new python.Error("Unsupported 'torch.sub' expression type.");
  9804. });
  9805. this.registerFunction('torch.sym_int');
  9806. this.registerFunction('torch.sym_float');
  9807. this.registerFunction('torch.sym_ite');
  9808. this.registerFunction('torch.sym_max');
  9809. this.registerFunction('torch.sym_min');
  9810. this.registerFunction('torch.sym_not');
  9811. this.registerFunction('torch.sym_sqrt');
  9812. this.registerFunction('torch.sym_sqrt');
  9813. this.registerFunction('torch.functional.einsum');
  9814. this.registerFunction('torch.functional.norm');
  9815. this.registerFunction('torch.functional.split');
  9816. this.registerFunction('torch.nn.init.constant_');
  9817. this.registerFunction('torch.nn.init.normal_');
  9818. this.registerFunction('torch.nn.init.xavier_uniform_');
  9819. this.registerFunction('torch.nn.functional.adaptive_avg_pool2d');
  9820. this.registerFunction('torch.nn.functional.binary_cross_entropy');
  9821. this.registerFunction('torch.nn.functional.binary_cross_entropy_with_logits');
  9822. this.registerFunction('torch.nn.functional.cross_entropy');
  9823. this.registerFunction('torch.nn.functional.elu');
  9824. this.registerFunction('torch.nn.functional.gelu');
  9825. this.registerFunction('torch.nn.functional.hardsigmoid');
  9826. this.registerFunction('torch.nn.functional.hardswish');
  9827. this.registerFunction('torch.nn.functional.hardtanh');
  9828. this.registerFunction('torch.nn.functional.interpolate');
  9829. this.registerFunction('torch.nn.functional.leaky_relu');
  9830. this.registerFunction('torch.nn.functional.l1_loss');
  9831. this.registerFunction('torch.nn.functional.linear');
  9832. this.registerFunction('torch.nn.functional.log_softmax');
  9833. this.registerFunction('torch.nn.functional._max_pool2d');
  9834. this.registerFunction('torch.nn.functional.max_pool2d_with_indices');
  9835. this.registerFunction('torch.nn.functional.mse_loss');
  9836. this.registerFunction('torch.nn.functional.pad');
  9837. this.registerFunction('torch.nn.functional.relu');
  9838. this.registerFunction('torch.nn.functional.relu6');
  9839. this.registerFunction('torch.nn.functional.sigmoid');
  9840. this.registerFunction('torch.nn.functional.silu');
  9841. this.registerFunction('torch.nn.functional.softmax');
  9842. this.registerFunction('torch.nn.functional.tanh');
  9843. this.registerFunction('torch.values', (dict) => {
  9844. return Object.values(dict);
  9845. });
  9846. this.registerFunction('torch.warn', () => {
  9847. });
  9848. this.registerType('torch._ops.OperatorBase', class {
  9849. constructor() {
  9850. this.functorch_table = {};
  9851. }
  9852. });
  9853. this.registerType('torch._ops.HigherOrderOperator', class extends torch._ops.OperatorBase {
  9854. constructor(name, cacheable) {
  9855. super();
  9856. this._name = name;
  9857. this.__name__ = name;
  9858. this._ns = 'higher_order';
  9859. this.__module__ = 'torch.ops.higher_order';
  9860. this._cacheable = cacheable;
  9861. }
  9862. get namespace() {
  9863. return this._ns;
  9864. }
  9865. get name() {
  9866. return this._name;
  9867. }
  9868. });
  9869. this.registerType('torch._higher_order_ops.wrap.WrapWithAutocast', class extends torch._ops.HigherOrderOperator {
  9870. constructor(name) {
  9871. super(name, false);
  9872. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_autocast(str device_type, ScalarType? dtype, bool enabled, bool? cache_enabled, Any wrapped_func, ...) -> Tensor');
  9873. }
  9874. });
  9875. torch.ops.higher_order.wrap_with_autocast = new torch._higher_order_ops.wrap.WrapWithAutocast('wrap_with_autocast');
  9876. this.registerType('torch._higher_order_ops.wrap.WrapWithSetGradEnabled', class extends torch._ops.HigherOrderOperator {
  9877. constructor(name) {
  9878. super(name, false);
  9879. this._schema = torch.FunctionSchema.parse('higher_order::wrap_with_set_grad_enabled(bool enable_grad, Any wrapped_func) -> Tensor');
  9880. }
  9881. });
  9882. torch.ops.higher_order.wrap_with_set_grad_enabled = new torch._higher_order_ops.wrap.WrapWithSetGradEnabled('wrap_with_set_grad_enabled');
  9883. this.registerType('torch._higher_order_ops.wrap.Wrap', class extends torch._ops.HigherOrderOperator {
  9884. constructor(name) {
  9885. super(name, false);
  9886. this._schema = torch.FunctionSchema.parse('higher_order::wrap(Any func) -> Tensor');
  9887. }
  9888. });
  9889. torch.ops.higher_order.wrap = new torch._higher_order_ops.wrap.Wrap('wrap');
  9890. this.registerType('torch._higher_order_ops.wrap.WrapActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9891. constructor(name) {
  9892. super(name, false);
  9893. }
  9894. });
  9895. torch.ops.higher_order.wrap_activation_checkpoint = new torch._higher_order_ops.wrap.WrapActivationCheckpoint('wrap_activation_checkpoint', false);
  9896. this.registerType('torch._higher_order_ops.wrap.TagActivationCheckpoint', class extends torch._ops.HigherOrderOperator {
  9897. constructor(name) {
  9898. super(name, false);
  9899. }
  9900. });
  9901. torch.ops.higher_order.tag_activation_checkpoint = new torch._higher_order_ops.wrap.TagActivationCheckpoint('tag_activation_checkpoint', false);
  9902. this.registerType('torch.Type', class {
  9903. constructor(kind, annotation_str) {
  9904. this._kind = kind;
  9905. if (annotation_str) {
  9906. this._annotation_str = annotation_str;
  9907. }
  9908. }
  9909. static get(kind, annotation_str) {
  9910. torch.Type.cache = torch.Type.cache || new Map();
  9911. if (!annotation_str) {
  9912. if (!torch.Type.cache.has(kind)) {
  9913. torch.Type.cache.set(kind, new torch.Type(kind));
  9914. }
  9915. return torch.Type.cache.get(kind);
  9916. }
  9917. return new torch.Type(kind, annotation_str);
  9918. }
  9919. kind() {
  9920. return this._kind;
  9921. }
  9922. get annotation_str() {
  9923. return this._annotation_str;
  9924. }
  9925. equals(rhs) {
  9926. return this.kind() === rhs.kind();
  9927. }
  9928. isSubtypeOf(rhs) {
  9929. if (rhs.kind() === 'AnyType' || this === rhs) {
  9930. return true;
  9931. }
  9932. if (rhs instanceof torch.OptionalType && this instanceof torch.OptionalType === false) {
  9933. return this.isSubtypeOf(rhs.getElementType());
  9934. }
  9935. if (rhs instanceof torch.UnionType) {
  9936. return rhs.containedTypes().some((inner) => this.isSubtypeOf(inner));
  9937. }
  9938. if (rhs instanceof torch._C.DynamicType) {
  9939. return torch._C.DynamicType.create(this).isSubtypeOf(rhs);
  9940. }
  9941. return this.equals(rhs);
  9942. }
  9943. containedTypes() {
  9944. return [];
  9945. }
  9946. containedType(i) {
  9947. return this.containedTypes()[i];
  9948. }
  9949. withContained(contained_types) {
  9950. const current_contained = this.containedTypes();
  9951. torch._C.TORCH_INTERNAL_ASSERT(current_contained.length > 0 && current_contained.length === contained_types.length);
  9952. if (current_contained.length === contained_types.length && current_contained.every((x, index) => x === contained_types[index])) {
  9953. return this;
  9954. }
  9955. return this.createWithContained(contained_types);
  9956. }
  9957. createWithContained(/* createWithContained */) {
  9958. throw new python.Error('Not implemented.');
  9959. }
  9960. isUnionType() {
  9961. return false;
  9962. }
  9963. hasFreeVariables() {
  9964. return false;
  9965. }
  9966. is_module() {
  9967. return false;
  9968. }
  9969. expect(type) {
  9970. torch._C.AT_ASSERT(this instanceof type);
  9971. return this;
  9972. }
  9973. str() {
  9974. if (this instanceof torch._C.VarType && this._annotation_str) {
  9975. return this._annotation_str;
  9976. } else if (this._kind === 'ScalarTypeType') {
  9977. return 'ScalarType';
  9978. } else if (this._kind === 'QSchemeType') {
  9979. return 'QScheme';
  9980. } else if (this._kind) {
  9981. return this._kind;
  9982. }
  9983. throw new python.Error(`Not implemented '${this.kind()}'.`);
  9984. }
  9985. __str__() {
  9986. return this.str();
  9987. }
  9988. toString() {
  9989. return this.__str__();
  9990. }
  9991. });
  9992. this.registerType('torch.ClassType', class extends torch.Type {
  9993. constructor(qualified_name, cu, is_module) {
  9994. super('ClassType', typeof qualified_name === 'string' ? qualified_name : qualified_name.qualifiedName());
  9995. this._name = typeof qualified_name === 'string' ? new torch._C.QualifiedName(qualified_name) : qualified_name;
  9996. this._is_module = is_module;
  9997. this._attributes = [];
  9998. this._attributeTypes = [];
  9999. this._methods = [];
  10000. this._staticmethods = new Map();
  10001. this._forward_hooks = [];
  10002. this._forward_pre_hooks = [];
  10003. this._properties = [];
  10004. this._constants = new Map();
  10005. }
  10006. static create(qualifiedName, cu, is_module /*, doc_string, unresolved_class_attributes */) {
  10007. return new torch.ClassType(qualifiedName, cu, is_module);
  10008. }
  10009. qualified_name() {
  10010. return this.annotation_str;
  10011. }
  10012. name() {
  10013. return this._name;
  10014. }
  10015. is_module() {
  10016. return this._is_module;
  10017. }
  10018. is_parameter(slot) {
  10019. return this._attributes[slot].is_parameter === true;
  10020. }
  10021. is_buffer(slot) {
  10022. return this._attributes[slot].is_buffer === true;
  10023. }
  10024. addMethod(method) {
  10025. torch._C.TORCH_CHECK(this.findMethod(method.name()) === null);
  10026. this._methods.push(method);
  10027. }
  10028. findMethod(name) {
  10029. for (const method of this._methods) {
  10030. if (name === method.name()) {
  10031. return method;
  10032. }
  10033. }
  10034. return null;
  10035. }
  10036. getMethod(name) {
  10037. const method = this.findMethod(name);
  10038. if (!method) {
  10039. throw new python.Error(`Method '${name}' not found on class '${this.str()}.`);
  10040. }
  10041. return method;
  10042. }
  10043. methods() {
  10044. return this._methods;
  10045. }
  10046. addStaticMethod(func) {
  10047. this._staticmethods.set(func.name, func);
  10048. }
  10049. findStaticMethod(name) {
  10050. return this._staticmethods.get(name);
  10051. }
  10052. findHook(name) {
  10053. let hook = this.findForwardHook(name);
  10054. if (hook === null) {
  10055. hook = this.findForwardPreHook(name);
  10056. }
  10057. return hook;
  10058. }
  10059. findForwardHook(name) {
  10060. for (const hook of this._forward_hooks) {
  10061. if (name === hook.name()) {
  10062. return hook;
  10063. }
  10064. }
  10065. return null;
  10066. }
  10067. findForwardPreHook(name) {
  10068. for (const pre_hook of this._forward_pre_hooks) {
  10069. if (name === pre_hook.name()) {
  10070. return pre_hook;
  10071. }
  10072. }
  10073. return null;
  10074. }
  10075. numAttributes() {
  10076. return this._attributes.length;
  10077. }
  10078. addAttribute(name, type, is_parameter, is_buffer) {
  10079. is_parameter = is_parameter || false;
  10080. is_buffer = is_buffer || false;
  10081. const slot = this._attributes.length;
  10082. this._attributes.push({ name, type, is_parameter, is_buffer });
  10083. this._attributeTypes.push(type);
  10084. return slot;
  10085. }
  10086. addOrCheckAttribute(name, ty, is_parameter, is_buffer) {
  10087. is_parameter = is_parameter || false;
  10088. is_buffer = is_buffer || false;
  10089. const slot_idx = this.findAttributeSlot(name);
  10090. if (slot_idx === null) {
  10091. return this.addAttribute(name, ty, is_parameter, is_buffer);
  10092. }
  10093. // TORCH_CHECK(is_parameter == this.is_parameter(*slot_idx), "Parameter field mismatch for the field '", name, "'");
  10094. // const TypePtr& atype = getAttribute(*slot_idx);
  10095. // TORCH_CHECK(ty.isSubtypeOf(*atype), ty.repr_str(), " is not compatible with the type ", atype.repr_str(), " for the field '", name, "'");
  10096. return slot_idx;
  10097. }
  10098. findAttributeSlot(name) {
  10099. for (let pos = 0; pos < this._attributes.length; pos++) {
  10100. if (name === this._attributes[pos].name) {
  10101. return pos;
  10102. }
  10103. }
  10104. return null;
  10105. }
  10106. findAttribute(name) {
  10107. const slot = this.findAttributeSlot(name);
  10108. if (slot !== null) {
  10109. return this._attributes[slot].type;
  10110. }
  10111. return null;
  10112. }
  10113. hasAttribute(name) {
  10114. return this._attributes.find((attr) => attr.name === name);
  10115. }
  10116. getAttribute(arg) {
  10117. const slot = Number.isInteger(arg) ? arg : this.findAttributeSlot(arg);
  10118. return this._attributes[slot].type;
  10119. }
  10120. getAttributeName(slot) {
  10121. return this._attributes[slot].name;
  10122. }
  10123. addConstant(name, value) {
  10124. this._constants.set(name, value);
  10125. }
  10126. hasConstant(name) {
  10127. return this._constants.has(name);
  10128. }
  10129. getProperty(name) {
  10130. for (const prop of this._properties) {
  10131. if (name === prop.name) {
  10132. return prop;
  10133. }
  10134. }
  10135. return null;
  10136. }
  10137. containedTypes() {
  10138. return this._attributeTypes;
  10139. }
  10140. createWithContained(contained_types) {
  10141. const ptr = torch.ClassType.create(this.name(), this._compilation_unit, this.is_module());
  10142. torch._C.AT_ASSERT(this.numAttributes() === contained_types.length);
  10143. for (let i = 0; i < this._attributes.length; i++) {
  10144. torch._C.AT_ASSERT(this._attributes[i].type.isSubtypeOf(contained_types[i]));
  10145. ptr.addAttribute(this._attributes[i].name, contained_types[i]);
  10146. }
  10147. for (const method of this.methods()) {
  10148. ptr.addMethod(method);
  10149. }
  10150. return ptr;
  10151. }
  10152. str() {
  10153. return this.qualified_name();
  10154. }
  10155. });
  10156. this.registerType('torch.EnumType', class extends torch.Type {
  10157. constructor(qualified_class_name, value_type, enum_names_values, cu) {
  10158. super('EnumType', qualified_class_name);
  10159. this._name = qualified_class_name;
  10160. this._value_type = value_type;
  10161. this._enum_names_values = enum_names_values;
  10162. this._cu = cu;
  10163. }
  10164. static create(qualified_class_name, value, enum_names_values, cu) {
  10165. if (value instanceof torch.IntType || value instanceof torch.FloatType || value instanceof torch.StringType) {
  10166. return new torch.EnumType(qualified_class_name, value, enum_names_values, cu);
  10167. }
  10168. torch._C.TORCH_CHECK(false);
  10169. return null;
  10170. }
  10171. name() {
  10172. return this._name;
  10173. }
  10174. get annotation_str() {
  10175. return this._name.qualifiedName();
  10176. }
  10177. enumNamesValues() {
  10178. return this._enum_names_values;
  10179. }
  10180. compilation_unit() {
  10181. return this._cu;
  10182. }
  10183. getValueType() {
  10184. return this._value_type;
  10185. }
  10186. equals(rhs) {
  10187. if (rhs instanceof torch.EnumType) {
  10188. return this.name() && this.name() === rhs.name() && this.getValueType() === rhs.getValueType() && this.compilation_unit() === rhs.compilation_unit();
  10189. }
  10190. return false;
  10191. }
  10192. isSubtypeOf(rhs) {
  10193. if (rhs instanceof torch.AnyType || rhs.kind() === 'AnyEnumType' || this === rhs) {
  10194. return true;
  10195. }
  10196. return super.isSubtypeOf(rhs);
  10197. }
  10198. });
  10199. this.registerFunction('torch._C.standardizeVectorForUnion', (...args) => {
  10200. if (args.length === 1) {
  10201. const [to_flatten] = args;
  10202. torch._C.TORCH_INTERNAL_ASSERT(to_flatten !== null);
  10203. const to_fill = [];
  10204. torch._C.standardizeVectorForUnion(to_flatten, to_fill);
  10205. to_flatten.splice(0, to_flatten.length);
  10206. to_flatten.push(...to_fill);
  10207. } else if (args.length === 2) {
  10208. const [reference, to_fill] = args;
  10209. for (const type of reference) {
  10210. torch._C.flattenUnion(type, to_fill);
  10211. }
  10212. torch._C.filterDuplicateSubtypes(to_fill);
  10213. torch._C.sortUnion(to_fill);
  10214. } else {
  10215. throw new python.Error('Not implemented.');
  10216. }
  10217. });
  10218. this.registerFunction('torch._C.flattenUnion', (type, to_fill) => {
  10219. if (type instanceof torch.UnionType) {
  10220. for (const inner of type.containedTypes()) {
  10221. torch._C.flattenUnion(inner, to_fill);
  10222. }
  10223. } else if (type instanceof torch.OptionalType) {
  10224. const inner = type.getElementType();
  10225. torch._C.flattenUnion(inner, to_fill);
  10226. to_fill.push(torch.NoneType.get());
  10227. } else if (type instanceof torch.NumberType) {
  10228. to_fill.push(torch.IntType.get());
  10229. to_fill.push(torch.FloatType.get());
  10230. to_fill.push(torch.ComplexType.get());
  10231. } else {
  10232. to_fill.push(type);
  10233. }
  10234. });
  10235. this.registerFunction('torch._C.filterDuplicateSubtypes', (types) => {
  10236. if (types.length === 0) {
  10237. // return;
  10238. }
  10239. /*
  10240. const get_supertype = [](const TypePtr& t1, const TypePtr& t2) -> std::optional<TypePtr> {
  10241. // We don't want nested Optionals. Also, prematurely unifying to
  10242. // `Optional` could prevent us from coalescing other types
  10243. if ((t1->isSubtypeOf(*NoneType::get()) && !t2->isSubtypeOf(*NoneType::get()))
  10244. || (!t1->isSubtypeOf(*NoneType::get()) && t2->isSubtypeOf(*NoneType::get()))) {
  10245. return null;
  10246. } else {
  10247. return unifyTypes(t1, t2, default_to_union=false);
  10248. }
  10249. };
  10250. size_t end_idx = types->size()-1;
  10251. for (size_t i = types->size()-1; i > 0; --i) {
  10252. for (size_t j = std::min(i-1, end_idx); ; --j) {
  10253. std::optional<TypePtr> unified;
  10254. unified = get_supertype((*types)[i], (*types)[j]);
  10255. if (unified) {
  10256. (*types)[j] = *unified;
  10257. (*types)[i] = (*types)[end_idx];
  10258. --end_idx;
  10259. break;
  10260. }
  10261. if (j == 0) {
  10262. break;
  10263. }
  10264. }
  10265. }
  10266. types.erase(types->begin() + static_cast<std::ptrdiff_t>(end_idx) + 1, types->end());
  10267. */
  10268. });
  10269. this.registerFunction('torch._C.sortUnion', (/* types */) => {
  10270. /*
  10271. std::sort(types->begin(), types->end(),
  10272. [](const TypePtr& a, const TypePtr& b) -> bool {
  10273. if (a->kind() != b->kind()) {
  10274. return a->kind() < b->kind();
  10275. }
  10276. return a->str() < b->str();
  10277. });
  10278. */
  10279. });
  10280. this.registerType('torch.UnionType', class extends torch.Type {
  10281. constructor(reference, kind) {
  10282. super(kind || 'UnionType');
  10283. torch._C.TORCH_INTERNAL_ASSERT(reference.length > 0);
  10284. this._types = [];
  10285. torch._C.standardizeVectorForUnion(reference, this._types);
  10286. if (this._types.length === 1) {
  10287. throw new python.Error('Invalid union type reference.');
  10288. }
  10289. this._can_hold_none = false;
  10290. this._has_free_variables = false;
  10291. for (const type of this._types) {
  10292. if (type instanceof torch.NoneType) {
  10293. this._can_hold_none = true;
  10294. }
  10295. if (type.hasFreeVariables()) {
  10296. this._has_free_variables = true;
  10297. }
  10298. }
  10299. }
  10300. static create(reference) {
  10301. const union_type = new torch.UnionType(reference);
  10302. /*
  10303. bool int_found = false;
  10304. bool float_found = false;
  10305. bool complex_found = false;
  10306. bool nonetype_found = false;
  10307. const update_is_opt_flags = [&](const TypePtr& t) {
  10308. if (t == IntType::get()) {
  10309. int_found = true;
  10310. } else if (t == FloatType::get()) {
  10311. float_found = true;
  10312. } else if (t == ComplexType::get()) {
  10313. complex_found = true;
  10314. } else if (t == NoneType::get()) {
  10315. nonetype_found = true;
  10316. }
  10317. };
  10318. for (const auto& t : union_type->containedTypes()) {
  10319. update_is_opt_flags(t);
  10320. }
  10321. bool numbertype_found = int_found && float_found && complex_found;
  10322. if (nonetype_found) {
  10323. if (union_type->containedTypes().size() == 4 && numbertype_found) {
  10324. return OptionalType::create(NumberType::get());
  10325. }
  10326. if (union_type->containedTypes().size() == 2) {
  10327. const not_none = union_type->containedTypes()[0] != NoneType::get()
  10328. ? union_type->containedTypes()[0]
  10329. : union_type->containedTypes()[1];
  10330. return OptionalType::create(not_none);
  10331. }
  10332. }
  10333. */
  10334. return union_type;
  10335. }
  10336. containedTypes() {
  10337. return this._types;
  10338. }
  10339. isUnionType() {
  10340. return true;
  10341. }
  10342. hasFreeVariables() {
  10343. return this._has_free_variables;
  10344. }
  10345. equals(rhs) {
  10346. if (rhs instanceof torch.UnionType) {
  10347. if (rhs.containedTypes().length !== this.containedTypes().length) {
  10348. return false;
  10349. }
  10350. return this.containedTypes().every((lhs_type) => rhs.containedTypes().some((rhs_type) => lhs_type === rhs_type));
  10351. } else if (rhs instanceof torch.OptionalType) {
  10352. if (rhs.getElementType() === torch.NumberType.get()) {
  10353. return this.containedTypes().length === 4 && this._can_hold_none && this.canHoldType(torch.NumberType.get());
  10354. }
  10355. const optional_lhs = this.toOptional();
  10356. return optional_lhs && rhs === optional_lhs.expect(torch.OptionalType);
  10357. } else if (rhs instanceof torch.NumberType) {
  10358. return this.containedTypes().length === 3 && this.canHoldType(torch.NumberType.get());
  10359. }
  10360. return false;
  10361. }
  10362. isSubtypeOf(rhs) {
  10363. const rhs_types = [];
  10364. if (rhs instanceof torch.UnionType) {
  10365. if (this.containedTypes() === rhs.containedTypes()) {
  10366. return true;
  10367. }
  10368. for (const typePtr of rhs.containedTypes()) {
  10369. rhs_types.push(typePtr);
  10370. }
  10371. } else if (rhs instanceof torch.OptionalType) {
  10372. rhs_types.push(torch.NoneType.get());
  10373. if (rhs.getElementType() === torch.NumberType.get()) {
  10374. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10375. rhs_types.push(...number_types);
  10376. } else {
  10377. rhs_types.push(rhs.getElementType());
  10378. }
  10379. } else if (rhs instanceof torch.NumberType) {
  10380. const number_types = [torch.IntType.get(), torch.FloatType.get(), torch.ComplexType.get()];
  10381. rhs_types.push(...number_types);
  10382. } else {
  10383. rhs_types.push(rhs);
  10384. }
  10385. return this.containedTypes().every((lhs_type) => rhs_types.some((rhs_type) => lhs_type.isSubtypeOf(rhs_type)));
  10386. }
  10387. });
  10388. this.registerType('torch.OptionalType', class extends torch.UnionType {
  10389. constructor(contained) {
  10390. super([contained, torch.NoneType.get()], 'OptionalType');
  10391. let is_numbertype = false;
  10392. if (contained instanceof torch.UnionType) {
  10393. is_numbertype = contained.containedTypes().length === 3 && contained.canHoldType(torch.NumberType.get());
  10394. }
  10395. if (super.containedTypes().length === 2) {
  10396. this._contained = super.containedTypes()[0] instanceof torch.NoneType ? super.containedTypes()[1] : super.containedTypes()[0];
  10397. } else if (contained === torch.NumberType.get() || is_numbertype) {
  10398. this._contained = torch.NumberType.get();
  10399. this._types.splice(0, this._types.length);
  10400. this._types.push(torch.NumberType.get());
  10401. this._types.push(torch.NoneType.get());
  10402. } else {
  10403. const to_subtract = [torch.NoneType.get()];
  10404. const without_none = this.subtractTypeSetFrom(to_subtract, this._types);
  10405. this._contained = torch.UnionType.create([without_none]);
  10406. }
  10407. this._has_free_variables = contained.hasFreeVariables();
  10408. }
  10409. static create(elem) {
  10410. return new torch.OptionalType(elem);
  10411. }
  10412. getElementType() {
  10413. return this._contained;
  10414. }
  10415. equals(rhs) {
  10416. return this.kind() === rhs.kind() && this.getElementType().equals(rhs.getElementType());
  10417. }
  10418. isSubtypeOf(rhs) {
  10419. if (rhs instanceof torch.OptionalType) {
  10420. return this.getElementType().isSubtypeOf(rhs.getElementType());
  10421. } else if (rhs instanceof torch.UnionType) {
  10422. throw new python.Error('Not implemented.');
  10423. }
  10424. // return super.isSubtypeOf(rhs);
  10425. return torch.Type.prototype.isSubtypeOf.call(this, rhs);
  10426. }
  10427. containedTypes() {
  10428. return [this._contained];
  10429. }
  10430. createWithContained(contained_types) {
  10431. torch._C.AT_ASSERT(contained_types.length === 1);
  10432. return torch.OptionalType.create(contained_types[0]);
  10433. }
  10434. subtractTypeSetFrom(to_subtract, from) {
  10435. const types = [];
  10436. const should_subtract = (lhs) => to_subtract.some((rhs) => lhs.isSubtypeOf(rhs));
  10437. for (const t of from) {
  10438. if (!should_subtract(t)) {
  10439. types.push(t);
  10440. }
  10441. }
  10442. if (types.length === 0) {
  10443. return null;
  10444. } else if (types.length === 1) {
  10445. return types[0];
  10446. }
  10447. return torch.UnionType.create(types);
  10448. }
  10449. str() {
  10450. return `${this.getElementType().str()}?`;
  10451. }
  10452. __str__() {
  10453. return `Optional[${this.getElementType().__str__()}]`;
  10454. }
  10455. });
  10456. this.registerType('torch.ListType', class extends torch.Type {
  10457. constructor(elem) {
  10458. super('ListType');
  10459. this._elem = elem;
  10460. }
  10461. static create(elem) {
  10462. return new torch.ListType(elem);
  10463. }
  10464. getElementType() {
  10465. return this._elem;
  10466. }
  10467. equals(rhs) {
  10468. if (rhs instanceof torch.ListType) {
  10469. return this.getElementType().equals(rhs.getElementType());
  10470. }
  10471. return false;
  10472. }
  10473. isSubtypeOf(rhs) {
  10474. if (super.isSubtypeOf(rhs)) {
  10475. return true;
  10476. }
  10477. if (rhs.kind() === 'AnyListType') {
  10478. return true;
  10479. }
  10480. return false;
  10481. }
  10482. containedTypes() {
  10483. return [this._elem];
  10484. }
  10485. createWithContained(contained_types) {
  10486. return new torch.ListType(contained_types[0]);
  10487. }
  10488. hasFreeVariables() {
  10489. return this.getElementType().hasFreeVariables();
  10490. }
  10491. str() {
  10492. return `${this.getElementType().str()}[]`;
  10493. }
  10494. __str__() {
  10495. return `List[${this.getElementType().__str__()}]`;
  10496. }
  10497. });
  10498. this.registerType('torch.FutureType', class extends torch.Type {
  10499. constructor(elem) {
  10500. super('FutureType');
  10501. this._elem = elem;
  10502. }
  10503. static create(elem) {
  10504. return new torch.FutureType(elem);
  10505. }
  10506. getElementType() {
  10507. return this._elem;
  10508. }
  10509. containedTypes() {
  10510. throw new python.Error('Not implemented.');
  10511. }
  10512. str() {
  10513. return `Future(${this.getElementType().str()})`;
  10514. }
  10515. __str__() {
  10516. return `Future[${this.getElementType().__str__()}]`;
  10517. }
  10518. });
  10519. this.registerType('torch.RRefType', class extends torch.Type {
  10520. constructor(elem) {
  10521. super('RRefType');
  10522. this._elem = elem;
  10523. }
  10524. static create(elem) {
  10525. return new torch.RRefType(elem);
  10526. }
  10527. getElementType() {
  10528. return this._elem;
  10529. }
  10530. containedTypes() {
  10531. throw new python.Error('Not implemented.');
  10532. }
  10533. str() {
  10534. return `RRef(${this.getElementType().str()})`;
  10535. }
  10536. __str__() {
  10537. return `RRef[${this.getElementType().__str__()}]`;
  10538. }
  10539. });
  10540. this.registerType('torch.AwaitType', class extends torch.Type {
  10541. constructor(elem) {
  10542. super('AwaitType');
  10543. this._elem = elem;
  10544. }
  10545. static get(elem) {
  10546. return new torch.AwaitType(elem);
  10547. }
  10548. getElementType() {
  10549. return this._elem;
  10550. }
  10551. containedTypes() {
  10552. throw new python.Error('Not implemented.');
  10553. }
  10554. str() {
  10555. return `Await(${this.getElementType().str()})`;
  10556. }
  10557. __str__() {
  10558. return `Await[${this.getElementType().__str__()}]`;
  10559. }
  10560. });
  10561. this.registerType('torch.TupleType', class extends torch.Type {
  10562. constructor(elements, annotation_str, schema) {
  10563. super('TupleType', annotation_str);
  10564. this._elements = elements;
  10565. this._has_free_variables = elements.some((v) => {
  10566. if (!v) {
  10567. throw new python.Error('Can not create tuple with None type');
  10568. }
  10569. return v.hasFreeVariables();
  10570. });
  10571. this._schema = schema;
  10572. }
  10573. static create(elements) {
  10574. return new torch.TupleType(elements, null, null);
  10575. }
  10576. static createNamed(qualified_name, field_names, field_types /*, field_defaults */) {
  10577. const args = [];
  10578. for (let i = 0; i < field_names.length; i++) {
  10579. const arg = new torch.Argument(field_names[i], field_types[i], field_types[i]);
  10580. args.push(arg);
  10581. }
  10582. const schema = new torch.FunctionSchema(qualified_name, '', args, []);
  10583. return new torch.TupleType(field_types, qualified_name, schema);
  10584. }
  10585. elements() {
  10586. return this._elements;
  10587. }
  10588. name() {
  10589. return this.annotation_str;
  10590. }
  10591. containedTypes() {
  10592. return this._elements;
  10593. }
  10594. createWithContained(createWithContained) {
  10595. return new torch.TupleType(createWithContained, this.name(), this.schema());
  10596. }
  10597. hasFreeVariables() {
  10598. return this._has_free_variables;
  10599. }
  10600. schema() {
  10601. return this._schema;
  10602. }
  10603. str() {
  10604. if (this._schema) {
  10605. return `NamedTuple(...)`;
  10606. }
  10607. return `(${this.elements().map((elem) => elem.str()).join(', ')})`;
  10608. }
  10609. __str__() {
  10610. if (this.annotation_str) {
  10611. return this.annotation_str;
  10612. }
  10613. return `Tuple[${this.elements().map((elem) => elem.__str__()).join(', ')}]`;
  10614. }
  10615. });
  10616. this.registerType('torch.AnyType', class extends torch.Type {
  10617. constructor() {
  10618. super('AnyType');
  10619. }
  10620. static get() {
  10621. torch.AnyType.value = torch.AnyType.value || new torch.AnyType();
  10622. return torch.AnyType.value;
  10623. }
  10624. str() {
  10625. return 'Any';
  10626. }
  10627. __str__() {
  10628. return 'Any';
  10629. }
  10630. });
  10631. this.registerType('torch.NoneType', class extends torch.Type {
  10632. constructor() {
  10633. super('NoneType');
  10634. }
  10635. static get() {
  10636. torch.NoneType.value = torch.NoneType.value || new torch.NoneType();
  10637. return torch.NoneType.value;
  10638. }
  10639. equals(rhs) {
  10640. return this.kind() === rhs.kind();
  10641. }
  10642. isSubtypeOf(rhs) {
  10643. if (rhs.kind() === 'OptionalType') {
  10644. return true;
  10645. }
  10646. return super.isSubtypeOf(rhs);
  10647. }
  10648. str() {
  10649. return 'NoneType';
  10650. }
  10651. __str__() {
  10652. return 'NoneType';
  10653. }
  10654. });
  10655. this.registerType('torch.TensorType', class extends torch.Type {
  10656. constructor() {
  10657. super('TensorType');
  10658. this._is_inferred = false;
  10659. }
  10660. static get() {
  10661. torch.TensorType.value = torch.TensorType.value || new torch.TensorType();
  10662. return torch.TensorType.value;
  10663. }
  10664. equals(rhs) {
  10665. return this.kind() === rhs.kind();
  10666. }
  10667. isInferredType() {
  10668. return this._is_inferred;
  10669. }
  10670. str() {
  10671. return 'Tensor';
  10672. }
  10673. __str__() {
  10674. return 'Tensor';
  10675. }
  10676. });
  10677. this.registerType('torch.NumberType', class extends torch.Type {
  10678. constructor() {
  10679. super('NumberType');
  10680. }
  10681. static get() {
  10682. torch.NumberType.value = torch.NumberType.value || new torch.NumberType();
  10683. return torch.NumberType.value;
  10684. }
  10685. str() {
  10686. return 'Scalar';
  10687. }
  10688. __str__() {
  10689. return 'number';
  10690. }
  10691. });
  10692. this.registerType('torch.BoolType', class extends torch.Type {
  10693. constructor() {
  10694. super('BoolType');
  10695. }
  10696. static get() {
  10697. torch.BoolType.value = torch.BoolType.value || new torch.BoolType();
  10698. return torch.BoolType.value;
  10699. }
  10700. equals(rhs) {
  10701. return this.kind() === rhs.kind();
  10702. }
  10703. str() {
  10704. return 'bool';
  10705. }
  10706. __str__() {
  10707. return 'bool';
  10708. }
  10709. });
  10710. this.registerType('torch.IntType', class extends torch.Type {
  10711. constructor() {
  10712. super('IntType');
  10713. }
  10714. static get() {
  10715. torch.IntType.value = torch.IntType.value || new torch.IntType();
  10716. return torch.IntType.value;
  10717. }
  10718. equals(rhs) {
  10719. return this.kind() === rhs.kind();
  10720. }
  10721. isSubtypeOf(rhs) {
  10722. return rhs instanceof torch.NumberType || rhs instanceof torch.FloatType || super.isSubtypeOf(rhs);
  10723. }
  10724. str() {
  10725. return 'int';
  10726. }
  10727. __str__() {
  10728. return 'int';
  10729. }
  10730. });
  10731. this.registerType('torch.SymIntType', class extends torch.Type {
  10732. constructor() {
  10733. super('SymIntType');
  10734. }
  10735. static get() {
  10736. torch.SymIntType.value = torch.SymIntType.value || new torch.SymIntType();
  10737. return torch.SymIntType.value;
  10738. }
  10739. equals(rhs) {
  10740. return this.kind() === rhs.kind();
  10741. }
  10742. str() {
  10743. return 'SymInt';
  10744. }
  10745. __str__() {
  10746. return 'int';
  10747. }
  10748. });
  10749. this.registerType('torch.FloatType', class extends torch.Type {
  10750. constructor() {
  10751. super('FloatType');
  10752. }
  10753. static get() {
  10754. torch.FloatType.value = torch.FloatType.value || new torch.FloatType();
  10755. return torch.FloatType.value;
  10756. }
  10757. equals(rhs) {
  10758. return this.kind() === rhs.kind();
  10759. }
  10760. isSubtypeOf(rhs) {
  10761. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10762. }
  10763. str() {
  10764. return 'float';
  10765. }
  10766. __str__() {
  10767. return 'float';
  10768. }
  10769. });
  10770. this.registerType('torch.StringType', class extends torch.Type {
  10771. constructor() {
  10772. super('StringType');
  10773. }
  10774. static get() {
  10775. torch.StringType.value = torch.StringType.value || new torch.StringType();
  10776. return torch.StringType.value;
  10777. }
  10778. equals(rhs) {
  10779. return this.kind() === rhs.kind();
  10780. }
  10781. str() {
  10782. return 'str';
  10783. }
  10784. __str__() {
  10785. return 'str';
  10786. }
  10787. });
  10788. this.registerType('torch.ComplexType', class extends torch.Type {
  10789. constructor() {
  10790. super('ComplexType');
  10791. }
  10792. static get() {
  10793. torch.ComplexType.value = torch.ComplexType.value || new torch.ComplexType();
  10794. return torch.ComplexType.value;
  10795. }
  10796. equals(rhs) {
  10797. return this.kind() === rhs.kind();
  10798. }
  10799. isSubtypeOf(rhs) {
  10800. return rhs.kind() === 'NumberType' || super.isSubtypeOf(rhs);
  10801. }
  10802. str() {
  10803. return 'complex';
  10804. }
  10805. __str__() {
  10806. return 'complex';
  10807. }
  10808. });
  10809. this.registerType('torch.DictType', class extends torch.Type {
  10810. constructor(key, value) {
  10811. super('DictType');
  10812. this.types = [key, value];
  10813. }
  10814. static create(key, value) {
  10815. let kind = key.kind();
  10816. if (key instanceof torch._C.DynamicType) {
  10817. kind = key.dynamicKind();
  10818. }
  10819. switch (kind) {
  10820. case 'AnyType':
  10821. case 'IntType':
  10822. case 'BoolType':
  10823. case 'FloatType':
  10824. case 'ComplexType':
  10825. case 'StringType':
  10826. case 'TensorType':
  10827. case 'DeviceObjType':
  10828. return new torch.DictType(key, value);
  10829. default:
  10830. throw new python.Error(`Invalid dict key type '${kind}'.`);
  10831. }
  10832. }
  10833. createWithContained(contained_types) {
  10834. if (contained_types.length !== 2) {
  10835. throw new python.Error('Expected 2 contained types.');
  10836. }
  10837. return torch.DictType.create(contained_types[0], contained_types[1]);
  10838. }
  10839. getKeyType() {
  10840. return this.types[0];
  10841. }
  10842. getValueType() {
  10843. return this.types[1];
  10844. }
  10845. hasFreeVariables() {
  10846. return this.getKeyType().hasFreeVariables() || this.getValueType().hasFreeVariables();
  10847. }
  10848. containedTypes() {
  10849. return this.types;
  10850. }
  10851. equals(rhs) {
  10852. if (rhs instanceof torch.DictType) {
  10853. return this.getKeyType().equals(rhs.getKeyType()) && this.getValueType().equals(rhs.getValueType());
  10854. }
  10855. return false;
  10856. }
  10857. str() {
  10858. return `Dict(${this.getKeyType().str()}, ${this.getValueType().str()})`;
  10859. }
  10860. __str__() {
  10861. return `Dict(${this.getKeyType().__str__()}, ${this.getValueType().__str__()})`;
  10862. }
  10863. });
  10864. this.registerType('torch.DeviceObjType', class extends torch.Type {
  10865. constructor() {
  10866. super('DeviceObjType');
  10867. }
  10868. static get() {
  10869. torch.DeviceObjType.value ||= new torch.DeviceObjType();
  10870. return torch.DeviceObjType.value;
  10871. }
  10872. str() {
  10873. return 'Device';
  10874. }
  10875. __str__() {
  10876. return 'Device';
  10877. }
  10878. });
  10879. this.registerType('torch.StreamObjType', class extends torch.Type {
  10880. constructor() {
  10881. super('StreamObjType');
  10882. }
  10883. str() {
  10884. return 'Stream';
  10885. }
  10886. __str__() {
  10887. return 'Stream';
  10888. }
  10889. });
  10890. this.registerType('torch._C._GeneratorType', class extends torch.Type {
  10891. constructor() {
  10892. super('GeneratorType');
  10893. }
  10894. static get() {
  10895. torch._C._GeneratorType.value = torch._C._GeneratorType.value || new torch._C._GeneratorType();
  10896. return torch._C._GeneratorType.value;
  10897. }
  10898. str() {
  10899. return 'Generator';
  10900. }
  10901. __str__() {
  10902. return 'Generator';
  10903. }
  10904. });
  10905. this.registerType('torch.InterfaceType', class extends torch.Type {
  10906. constructor() {
  10907. super('InterfaceType');
  10908. }
  10909. });
  10910. this.registerType('torch._C.DynamicType', class extends torch.Type {
  10911. constructor() {
  10912. super('DynamicType');
  10913. }
  10914. });
  10915. this.registerType('torch._C.FunctionType', class extends torch.Type {
  10916. constructor(func) {
  10917. super('FunctionType');
  10918. this._func = func;
  10919. }
  10920. static create(func) {
  10921. return new torch._C.FunctionType(func);
  10922. }
  10923. function() {
  10924. return this._func;
  10925. }
  10926. });
  10927. this.registerType('torch._C.VarType', class extends torch.Type {
  10928. constructor(name) {
  10929. super('VarType', name);
  10930. }
  10931. static create(name) {
  10932. return new torch._C.VarType(name);
  10933. }
  10934. name() {
  10935. return this._annotation_str;
  10936. }
  10937. hasFreeVariables() {
  10938. return true;
  10939. }
  10940. });
  10941. this.registerType('torch._C.AliasInfo', class {
  10942. constructor() {
  10943. this.is_write = false;
  10944. this.before_set = [];
  10945. this.after_set = [];
  10946. this.containedTypes = [];
  10947. }
  10948. addBeforeSet(value) {
  10949. this.before_set.push(value);
  10950. }
  10951. addAfterSet(value) {
  10952. this.after_set.push(value);
  10953. }
  10954. addContainedType(alias_info) {
  10955. this.containedTypes.push(alias_info);
  10956. }
  10957. str() {
  10958. const list = ['('];
  10959. list.push(this.before_set.join('|'));
  10960. if (this.after_set.length > 0) {
  10961. list.push(' -> ');
  10962. list.push(this.after_set.join('|'));
  10963. }
  10964. if (this.is_write) {
  10965. list.push('!');
  10966. }
  10967. list.push(')');
  10968. return list.join('');
  10969. }
  10970. });
  10971. this.registerFunction('torch._C.parseStringLiteral', (range, str) => {
  10972. if (str.startsWith('"') && str.endsWith('"')) {
  10973. return str.slice(1, -1);
  10974. }
  10975. if (str.startsWith("'") && str.endsWith("'")) {
  10976. return str.slice(1, -1);
  10977. }
  10978. throw new python.Error(`Invalid string literal '${str}'.`);
  10979. // inline std::string parseStringLiteral(
  10980. });
  10981. this.registerType('torch._C.Token', class {
  10982. constructor() {
  10983. this.kind = '';
  10984. this.value = '';
  10985. }
  10986. text() {
  10987. return this.value;
  10988. }
  10989. });
  10990. this.registerType('torch._C.Lexer', class {
  10991. constructor(buffer) {
  10992. this.buffer = buffer;
  10993. this.position = 0;
  10994. this.next_tokens = [new torch._C.Token(), new torch._C.Token(), new torch._C.Token(), new torch._C.Token()];
  10995. this.next();
  10996. }
  10997. cur() {
  10998. return this.next_tokens[0];
  10999. }
  11000. lookahead() {
  11001. if (!this.next_tokens[1].kind) {
  11002. this.position += this.cur().text().length;
  11003. this.lex(this.next_tokens[1]);
  11004. }
  11005. return this.next_tokens[1];
  11006. }
  11007. next() {
  11008. const [cur] = this.next_tokens;
  11009. [, this.next_tokens[0], this.next_tokens[1], this.next_tokens[2]] = this.next_tokens;
  11010. this.next_tokens[1].kind = '';
  11011. this.next_tokens[3] = cur;
  11012. const [token] = this.next_tokens;
  11013. if (token.kind) {
  11014. return cur;
  11015. }
  11016. this.position += cur.text().length;
  11017. this.lex(token);
  11018. return cur;
  11019. }
  11020. nextIf(kind) {
  11021. if (this.cur().kind !== kind) {
  11022. return false;
  11023. }
  11024. this.next();
  11025. return true;
  11026. }
  11027. expect(kind) {
  11028. if (this.cur().kind !== kind) {
  11029. throw new python.Error(`Unexpected '${this.cur().kind}' instead of '${kind}'.`);
  11030. }
  11031. return this.next();
  11032. }
  11033. lex(token) {
  11034. while (this.buffer[this.position] === ' ') {
  11035. this.position += 1;
  11036. }
  11037. let i = this.position;
  11038. if (i >= this.buffer.length) {
  11039. token.kind = '\0';
  11040. token.value = '';
  11041. } else if (this.buffer[i] === '.' && this.buffer[i + 1] === '.' && this.buffer[i + 2] === '.') {
  11042. token.kind = '...';
  11043. token.value = '...';
  11044. /* } else if (this.buffer[i] === '[' && this.buffer[i + 1] === ']') {
  11045. this.kind = '[]';
  11046. this.value = '[]'; */
  11047. } 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] === '|') {
  11048. token.kind = this.buffer[i];
  11049. token.value = this.buffer[i];
  11050. } else if ((this.buffer[i] >= 'a' && this.buffer[i] <= 'z') || (this.buffer[i] >= 'A' && this.buffer[i] <= 'Z') || this.buffer[i] === '_') {
  11051. i += 1;
  11052. 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] === '_')) {
  11053. i += 1;
  11054. }
  11055. token.kind = 'id';
  11056. token.value = this.buffer.slice(this.position, i);
  11057. } else if (this.buffer[i] === '-' && this.buffer[i + 1] === '>') {
  11058. token.kind = '->';
  11059. token.value = '->';
  11060. } else if ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '-') {
  11061. i += 1;
  11062. while (i < this.buffer.length && ((this.buffer[i] >= '0' && this.buffer[i] <= '9') || this.buffer[i] === '.' || this.buffer[i] === 'e' || this.buffer[i] === '-')) {
  11063. i += 1;
  11064. }
  11065. token.kind = '#';
  11066. token.value = this.buffer.slice(this.position, i);
  11067. } else if (this.buffer[i] === "'" || this.buffer[i] === '"') {
  11068. const quote = this.buffer[i];
  11069. i += 1;
  11070. while (i < this.buffer.length && this.buffer[i] !== quote) {
  11071. i += (this.buffer[i] === '\\' && (this.buffer[i + 1] === "'" || this.buffer[i + 1] === '"' || this.buffer[i + 1] === '\\')) ? 2 : 1;
  11072. }
  11073. i += 1;
  11074. token.kind = 'string';
  11075. token.value = this.buffer.slice(this.position, i);
  11076. } else {
  11077. throw new python.Error(`Unsupported token at '${this.position}'.`);
  11078. }
  11079. }
  11080. });
  11081. this.registerType('torch._C.SchemaTypeParser', class {
  11082. constructor(L, complete_tensor_types, allow_typevars) {
  11083. this.L = L;
  11084. this.complete_tensor_types = complete_tensor_types;
  11085. this._allow_typevars = allow_typevars;
  11086. }
  11087. parseType() {
  11088. const r = this.parseFakeAndRealType();
  11089. return { first: r[0], second: r[2] };
  11090. }
  11091. parseBaseType() {
  11092. const L = this.L;
  11093. const tok = L.cur();
  11094. const text = tok.text();
  11095. L.next();
  11096. switch (text) {
  11097. case 'Tensor': return torch.TensorType.get();
  11098. case 'bool': return torch.BoolType.get();
  11099. case 'int': return torch.IntType.get();
  11100. case 'float': return torch.FloatType.get();
  11101. case 'complex': return torch.ComplexType.get();
  11102. case 'str': return torch.StringType.get();
  11103. case 'SymInt': return torch.SymIntType.get();
  11104. case 'Scalar': return torch.NumberType.get();
  11105. case 'ScalarType': return torch.Type.get('ScalarTypeType');
  11106. case 'Device': return torch.DeviceObjType.get();
  11107. case 'Layout': return torch.Type.get('Layout');
  11108. case 'MemoryFormat': return torch.Type.get('MemoryFormat');
  11109. case 'Generator': return torch._C._GeneratorType.get();
  11110. case 't': case 't1': case 't2': case 'tVal': return torch._C.VarType.create(text);
  11111. case 'Any': return torch.AnyType.get();
  11112. case 'AnyEnumType': return torch.Type.get('AnyEnumType');
  11113. case 'Dimname': return torch.StringType.get();
  11114. case 'QScheme': return torch.Type.get('QSchemeType');
  11115. case 'Stream': return torch.StreamObjType.get();
  11116. case 'Storage': return torch.Type.get('Storage');
  11117. case 'AnyClassType': return torch.Type.get('AnyClassType');
  11118. case 'NoneType': return torch.NoneType.get();
  11119. default: throw new python.Error(`Unsupported type '${text}'.`);
  11120. }
  11121. }
  11122. parseFakeAndRealType() {
  11123. const L = this.L;
  11124. let fake_value = null;
  11125. let real_value = null;
  11126. let alias_info = null;
  11127. if (L.nextIf('(')) {
  11128. const types = [];
  11129. while (!L.nextIf(')')) {
  11130. const r = this.parseType();
  11131. types.push(r.first);
  11132. if (alias_info && r.second) {
  11133. alias_info.addContainedType(r.second);
  11134. }
  11135. L.nextIf(',');
  11136. }
  11137. real_value = torch.TupleType.create(types);
  11138. fake_value = real_value;
  11139. } else if (L.cur().text() === 'Future') {
  11140. L.next();
  11141. L.expect('(');
  11142. const p = this.parseType();
  11143. const subtype = p.first;
  11144. // const subalias = p.second;
  11145. L.expect(')');
  11146. real_value = torch.FutureType.create(subtype);
  11147. fake_value = real_value;
  11148. } else if (L.cur().text() === 'Await') {
  11149. L.next();
  11150. L.expect('(');
  11151. const p = this.parseType();
  11152. const subtype = p.first;
  11153. // const subalias = p.second;
  11154. L.expect(')');
  11155. real_value = torch.AwaitType.get(subtype);
  11156. fake_value = real_value;
  11157. } else if (L.cur().text() === 'RRef') {
  11158. L.next();
  11159. L.expect('(');
  11160. const p = this.parseType();
  11161. const subtype = p.first;
  11162. // const subalias = p.second;
  11163. L.expect(')');
  11164. real_value = torch.RRefType.create(subtype);
  11165. fake_value = real_value;
  11166. } else if (L.cur().text() === 'Tensor') {
  11167. L.next();
  11168. real_value = torch.TensorType.get();
  11169. fake_value = real_value;
  11170. alias_info = this.parseAliasAnnotation();
  11171. } else if (L.cur().text() === 'Dict') {
  11172. L.next();
  11173. L.expect('(');
  11174. const key_type = this.parseType().first;
  11175. L.expect(',');
  11176. const value_type = this.parseType().first;
  11177. L.expect(')');
  11178. alias_info = this.parseAliasAnnotation();
  11179. real_value = torch.DictType.create(key_type, value_type);
  11180. fake_value = real_value;
  11181. } else if (L.nextIf('Union')) {
  11182. L.next();
  11183. L.expect('(');
  11184. const types = [];
  11185. types.push(this.parseType().first);
  11186. while (L.cur().kind !== ')') {
  11187. L.expect(',');
  11188. types.push(this.parseType().first);
  11189. }
  11190. L.expect(')');
  11191. alias_info = this.parseAliasAnnotation();
  11192. real_value = new torch.UnionType(types);
  11193. fake_value = real_value;
  11194. /* } else if (complete_tensor_types && L.cur().kind == TK_IDENT && parseTensorDType(L.cur().text())) {
  11195. fake_value = real_value = parseRefinedTensor();
  11196. alias_info = parseAliasAnnotation(); */
  11197. } else if (L.cur().kind === 'id' && L.cur().text() === '__torch__') {
  11198. L.next();
  11199. L.expect('.');
  11200. const torch_tok = L.expect('id');
  11201. if (torch_tok.text() !== 'torch') {
  11202. throw new python.Error('Expected classes namespace.');
  11203. }
  11204. L.expect('.');
  11205. const classes_tok = L.expect('id');
  11206. if (classes_tok.text() !== 'classes') {
  11207. throw new python.Error('Expected classes namespace.');
  11208. }
  11209. L.expect('.');
  11210. const ns_tok = L.expect('id');
  11211. L.expect('.');
  11212. const class_tok = L.expect('id');
  11213. real_value = torch._C.getCustomClass(`__torch__.torch.classes.${ns_tok.text()}.${class_tok.text()}`);
  11214. fake_value = real_value;
  11215. if (!fake_value) {
  11216. throw new python.Error(`Unknown custom class type '${ns_tok.text()}.${class_tok.text()}'.`);
  11217. }
  11218. } else {
  11219. real_value = this.parseBaseType();
  11220. fake_value = real_value;
  11221. if (real_value.kind() === 'ScalarTypeType' ||
  11222. real_value.kind() === 'MemoryFormat' ||
  11223. real_value.kind() === 'Layout' ||
  11224. real_value.kind() === 'SymIntType') {
  11225. fake_value = torch.IntType.get();
  11226. }
  11227. alias_info = this.parseAliasAnnotation();
  11228. }
  11229. while (true) {
  11230. if (L.cur().kind === '[' && L.lookahead().kind === ']') {
  11231. L.expect('[');
  11232. L.expect(']');
  11233. fake_value = torch.ListType.create(fake_value);
  11234. real_value = torch.ListType.create(real_value);
  11235. let container = this.parseAliasAnnotation();
  11236. if (alias_info) {
  11237. if (!container) {
  11238. container = new torch._C.AliasInfo();
  11239. container.is_write = alias_info.is_write;
  11240. }
  11241. container.addContainedType(alias_info);
  11242. }
  11243. alias_info = container;
  11244. } else if (L.nextIf('?')) {
  11245. fake_value = torch.OptionalType.create(fake_value);
  11246. real_value = torch.OptionalType.create(real_value);
  11247. } else {
  11248. break;
  11249. }
  11250. }
  11251. return [fake_value, real_value, alias_info];
  11252. }
  11253. parseAliasAnnotation() {
  11254. const L = this.L;
  11255. let alias_info = null;
  11256. if (L.nextIf('(')) {
  11257. alias_info = new torch._C.AliasInfo();
  11258. do {
  11259. alias_info.addBeforeSet(L.cur().text());
  11260. L.next();
  11261. if (L.nextIf('!')) {
  11262. alias_info.is_write = true;
  11263. }
  11264. }
  11265. while (L.nextIf('|'));
  11266. if (L.nextIf('->')) {
  11267. do {
  11268. alias_info.addAfterSet(L.cur().text());
  11269. L.next();
  11270. }
  11271. while (L.nextIf('|'));
  11272. }
  11273. L.expect(')');
  11274. }
  11275. return alias_info;
  11276. }
  11277. });
  11278. this.registerType('torch.Argument', class {
  11279. constructor(...args) {
  11280. // torch/aten/src/ATen/core/function_schema.h
  11281. this.N = null;
  11282. this.default_value = null;
  11283. this.kwarg_only = false;
  11284. this.alias_info = null;
  11285. if (args.length === 2) {
  11286. [this.name, this.type] = args;
  11287. this.real_type = this.type;
  11288. } else if (args.length === 3 && args[1] instanceof torch.Type && args[2] instanceof torch.Type) {
  11289. [this.name, this.type, this.real_type] = args;
  11290. } else if (args.length === 6) {
  11291. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only] = args;
  11292. } else if (args.length === 7) {
  11293. [this.name, this.type, this.real_type, this.N, this.default_value, this.kwarg_only, this.alias_info] = args;
  11294. } else {
  11295. throw new python.Error('Invalid arguments.');
  11296. }
  11297. const is_alias = this.alias_info && this.alias_info.is_write;
  11298. this.is_out = this.kwarg_only && is_alias;
  11299. }
  11300. has_default_value() {
  11301. return this.default_value !== undefined;
  11302. }
  11303. is_inferred_type() {
  11304. if (this.type instanceof torch.TensorType) {
  11305. return this.type.isInferredType();
  11306. }
  11307. return false;
  11308. }
  11309. str() {
  11310. const list = [];
  11311. const type = this.real_type;
  11312. const is_opt = type instanceof torch.OptionalType;
  11313. const unopt_type = is_opt ? type.getElementType() : type;
  11314. if (unopt_type instanceof torch.ListType) {
  11315. list.push(unopt_type.getElementType().str());
  11316. if (this.alias_info && this.alias_info.containedTypes.length > 0) {
  11317. list.push(this.alias_info.containedTypes[0].str());
  11318. }
  11319. list.push(this.N === null ? `[]` : `[${this.N}]`);
  11320. } else {
  11321. list.push(unopt_type.str());
  11322. }
  11323. if (this.alias_info && this.alias_info.before_set.length > 0) {
  11324. list.push(this.alias_info.str());
  11325. }
  11326. if (is_opt) {
  11327. list.push('?');
  11328. }
  11329. if (this.name) {
  11330. list.push(' ');
  11331. list.push(this.name);
  11332. }
  11333. if (this.default_value !== undefined) {
  11334. const value = this.default_value;
  11335. if (value === null) {
  11336. list.push('=None');
  11337. } else if (typeof value === 'boolean') {
  11338. list.push('=');
  11339. list.push(value ? 'True' : 'False');
  11340. } else if (typeof value === 'string') {
  11341. list.push(`="${value}"`);
  11342. } else if (typeof value === 'number') {
  11343. list.push(`=${value}`);
  11344. if (Number.isInteger(value) && this.real_type instanceof torch.FloatType) {
  11345. list.push(`.`);
  11346. }
  11347. } else if (Array.isArray(value)) {
  11348. list.push(`=[${value.join(', ')}]`);
  11349. }
  11350. }
  11351. return list.join('');
  11352. }
  11353. });
  11354. torch._C.TypeKind = {
  11355. StringType: 'StringType',
  11356. NumberType: 'NumberType',
  11357. IntType: 'IntType',
  11358. BoolType: 'BoolType',
  11359. DynamicType: 'DynamicType',
  11360. OptionalType: 'OptionalType',
  11361. FloatType: 'FloatType',
  11362. ComplexType: 'ComplexType',
  11363. ListType: 'ListType',
  11364. };
  11365. this.registerType('torch._C.List', class extends Array {
  11366. constructor(type, elements) {
  11367. super(elements ? elements.length : 0);
  11368. if (Array.isArray(elements)) {
  11369. for (let i = 0; i < elements.length; i++) {
  11370. this[i] = elements[i];
  11371. }
  11372. }
  11373. this.type = type;
  11374. }
  11375. elementType() {
  11376. return this.type;
  11377. }
  11378. });
  11379. this.registerFunction('torch._C.builtin_cast_method_to_scalar_type', () => {
  11380. return new Map();
  11381. });
  11382. this.registerFunction('torch._C.string_to_type_lut', () => {
  11383. if (!torch._C.string_to_type_lut.basePythonTypes) {
  11384. const map = new Map();
  11385. map.set('Tensor', torch.TensorType.get());
  11386. map.set('int', torch.IntType.get());
  11387. map.set('float', torch.FloatType.get());
  11388. map.set('bool', torch.BoolType.get());
  11389. map.set('complex', torch.ComplexType.get());
  11390. map.set('str', torch.StringType.get());
  11391. map.set('Device', torch.DeviceObjType.get());
  11392. map.set('number', torch.NumberType.get());
  11393. map.set('None', torch.NoneType.get());
  11394. map.set('NoneType', torch.NoneType.get());
  11395. map.set('Any', torch.AnyType.get());
  11396. map.set('list', torch.Type.get('AnyListType'));
  11397. map.set('tuple', torch.Type.get('AnyTupleType'));
  11398. torch._C.string_to_type_lut.basePythonTypes = map;
  11399. }
  11400. return torch._C.string_to_type_lut.basePythonTypes;
  11401. });
  11402. this.registerType('torch._C.ScriptTypeParser', class {
  11403. constructor(resolver) {
  11404. this._resolver = resolver;
  11405. }
  11406. parseSchemaFromDef(def, skip_self) {
  11407. const name = def.name;
  11408. const args = this.parseArgsFromDecl(def, skip_self);
  11409. const returns = this.parseReturnFromDecl(def);
  11410. return new torch.FunctionSchema(name, '', args, returns, false, false);
  11411. }
  11412. parseArgsFromDecl(decl, skip_self) {
  11413. const retval = [];
  11414. if (decl.args.posonlyargs.length > 0 || decl.args.kwonlyargs.length > 0) {
  11415. throw new python.Error('Unsupported function argument.');
  11416. }
  11417. const params = decl.args.args.slice();
  11418. const kwonlyargs = new Set(Array.from(decl.args.kwonlyargs));
  11419. const start = skip_self ? 1 : 0;
  11420. for (let i = start; i < params.length; i++) {
  11421. const decl_arg = params[i];
  11422. const N = null;
  11423. const default_value = undefined;
  11424. const type = decl_arg.annotation ? this.parseTypeFromExpr(decl_arg.annotation) : null;
  11425. const arg = new torch.Argument(decl_arg.arg, type, type, N, default_value, kwonlyargs.has(decl_arg), null);
  11426. retval.push(arg);
  11427. }
  11428. return retval;
  11429. }
  11430. parseReturnFromDecl(decl) {
  11431. if (!decl.returns) {
  11432. return [];
  11433. }
  11434. if (this.parseBroadcastList(decl.returns)) {
  11435. throw new python.Error('Broadcastable lists cannot appear as a return type.');
  11436. }
  11437. const parsed_type = this.parseTypeFromExpr(decl.returns);
  11438. return [new torch.Argument('', parsed_type, parsed_type, null, undefined, false)];
  11439. }
  11440. parseTypeFromExpr(expr) {
  11441. if (this._resolver) {
  11442. if (expr instanceof ast.Name) {
  11443. const type = this._resolver.resolveType(expr.id);
  11444. if (type) {
  11445. return type;
  11446. }
  11447. }
  11448. }
  11449. return this.parseTypeFromExprImpl(expr);
  11450. }
  11451. parseTypeFromExprImpl(expr) {
  11452. if (expr instanceof ast.Subscript) {
  11453. const value_name = this.parseBaseTypeName(expr.value);
  11454. if (!value_name) {
  11455. throw new python.Error('Subscripted type must be a type identifier.');
  11456. }
  11457. return this.subscriptToType(value_name, expr);
  11458. }
  11459. const name = this.parseBaseTypeName(expr);
  11460. if (name) {
  11461. const itr = torch._C.string_to_type_lut().get(name);
  11462. if (itr) {
  11463. return itr;
  11464. }
  11465. if (this._resolver) {
  11466. const typePtr = this._resolver.resolveType(name, expr);
  11467. if (typePtr) {
  11468. return typePtr;
  11469. }
  11470. }
  11471. }
  11472. throw new python.Error(`Unknown type name '${name}'.`);
  11473. }
  11474. parseBaseTypeName(expr) {
  11475. if (expr instanceof ast.Name) {
  11476. return expr.id;
  11477. } else if (expr instanceof ast.Constant && expr.value === null) {
  11478. return 'None';
  11479. } else if (expr instanceof ast.Attribute) {
  11480. const name = expr.attr;
  11481. const tensor_subtypes = new Set(['Tensor', 'LongTensor', 'FloatTensor', 'DoubleTensor', 'IntTensor', 'ShortTensor', 'HalfTensor', 'CharTensor', 'ByteTensor', 'BoolTensor']);
  11482. if (torch._C.isTorch(expr.value) && tensor_subtypes.has(name)) {
  11483. return name;
  11484. }
  11485. return torch._C.collectQualname(expr);
  11486. }
  11487. throw new python.Error(`Unsupported type '${expr.__class__.__name__}'.`);
  11488. }
  11489. parseBroadcastList(/* expr */) {
  11490. return null;
  11491. }
  11492. parseType(str) {
  11493. const expr = ast.parse(str);
  11494. return this.parseTypeFromExpr(expr.body[0].value);
  11495. }
  11496. subscriptToType(typeName, subscript) {
  11497. if (typeName === 'Tuple' || typeName === 'tuple') {
  11498. const subscript_expr_types = [];
  11499. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11500. for (const expr of elts) {
  11501. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11502. }
  11503. return torch.TupleType.create(subscript_expr_types);
  11504. } else if (typeName === 'List' || typeName === 'list') {
  11505. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11506. throw new python.Error('List type must have exactly one element type.');
  11507. }
  11508. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11509. return torch.ListType.create(elem_type);
  11510. } else if (typeName === 'Optional') {
  11511. if (subscript.slice instanceof ast.Slice || subscript.slice instanceof ast.Tuple) {
  11512. throw new python.Error('Optional type must have exactly one element type.');
  11513. }
  11514. const elem_type = this.parseTypeFromExprImpl(subscript.slice);
  11515. return torch.OptionalType.create(elem_type);
  11516. } else if (typeName === 'Union') {
  11517. const subscript_expr_types = [];
  11518. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11519. for (const expr of elts) {
  11520. subscript_expr_types.push(this.parseTypeFromExprImpl(expr));
  11521. }
  11522. return torch.UnionType.create(subscript_expr_types);
  11523. } else if (typeName === 'Future' || typeName === 'torch.jit.Future') {
  11524. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11525. if (elts.length !== 1) {
  11526. throw new python.Error('Future type must have exactly one element type.');
  11527. }
  11528. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11529. return torch.FutureType.create(elem_type);
  11530. } else if (typeName === 'Await' || typeName === 'torch.jit._Await') {
  11531. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11532. if (elts.length !== 1) {
  11533. throw new python.Error('Await type must have exactly one element type.');
  11534. }
  11535. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11536. return torch.AwaitType.create(elem_type);
  11537. } else if (typeName === 'RRef') {
  11538. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11539. if (elts.length !== 1) {
  11540. throw new python.Error('RRef type must have exactly one element type.');
  11541. }
  11542. const elem_type = this.parseTypeFromExprImpl(elts[0]);
  11543. return torch.RRefType.create(elem_type);
  11544. } else if (typeName === 'Dict' || typeName === 'dict') {
  11545. const elts = subscript.slice instanceof ast.Tuple ? subscript.slice.elts : [subscript.slice];
  11546. if (elts.length !== 2) {
  11547. throw new python.Error('Dict type must have exactly two element types.');
  11548. }
  11549. const key_type = this.parseTypeFromExprImpl(elts[0]);
  11550. const value_type = this.parseTypeFromExprImpl(elts[1]);
  11551. return torch.DictType.create(key_type, value_type);
  11552. }
  11553. throw new python.Error(`Unknown type constructor '${typeName}'.`);
  11554. }
  11555. });
  11556. this.registerFunction('torch._C.isTorch', (expr) => {
  11557. return expr instanceof ast.Name && expr.id === 'torch';
  11558. });
  11559. this.registerFunction('torch._C.collectQualname', (select) => {
  11560. const base = select.value;
  11561. if (base instanceof ast.Name) {
  11562. return `${base.id}.${select.attr}`;
  11563. }
  11564. const basename = torch._C.collectQualname(base);
  11565. return `${basename}.${select.attr}`;
  11566. });
  11567. this.registerType('torch._ops.OpOverload', class extends torch._ops.OperatorBase {
  11568. constructor(overloadpacket, op, op_dk, schema, tags) {
  11569. super();
  11570. this._op = op;
  11571. this._op_dk = op_dk;
  11572. this._schema = schema;
  11573. this._overloadpacket = overloadpacket;
  11574. this._tags = tags;
  11575. this._overloadname = schema.overload_name === '' ? 'default' : schema.overload_name;
  11576. this._name = this._schema.name;
  11577. this._name = schema.overload_name ? `${this._name}.${schema.overload_name}` : this._name;
  11578. this.__name__ = `${this._schema.name.split('::')[1]}.${this._overloadname}`;
  11579. this.__module__ = overloadpacket.__module__;
  11580. op.__module__ = overloadpacket.__module__;
  11581. this.__qualname__ = self._name;
  11582. this.__annotations__ = {};
  11583. // this._defined_in_python = this.__qualname__ in torch.library._defs
  11584. let is_write = null;
  11585. for (const a of this._schema.arguments) {
  11586. if (a.alias_info) {
  11587. is_write = is_write === null ? a.alias_info.is_write : a.alias_info.is_write || is_write;
  11588. }
  11589. }
  11590. this.is_view = is_write !== null && !is_write;
  11591. }
  11592. name() {
  11593. return this._name;
  11594. }
  11595. });
  11596. this.registerType('torch._ops.OpOverloadPacket', class {
  11597. constructor(qualified_op_name, op_name, op, overload_names) {
  11598. this._qualified_op_name = qualified_op_name;
  11599. this.__name__ = op_name;
  11600. this._op = op;
  11601. this._overload_names = overload_names;
  11602. this._dir = [];
  11603. this._has_torchbind_op_overload = this._schemas.some((schema) => this._has_script_object_arg(schema));
  11604. }
  11605. get _schemas() {
  11606. return this._overload_names.map((overload_name) => torch._C._get_schema(this._qualified_op_name, overload_name));
  11607. }
  11608. __getattr__(key) {
  11609. key = key === 'default' ? '' : key;
  11610. const op_dk_tags = torch._C._get_operation_overload(this._qualified_op_name, key);
  11611. const [op_, op_dk_, tags] = op_dk_tags;
  11612. const schema = torch._C._get_schema(this._qualified_op_name, key);
  11613. const overload = this._has_script_object_arg(schema) ?
  11614. new torch._ops.TorchBindOpOverload(this, op_, op_dk_, schema, tags) :
  11615. new torch._ops.OpOverload(this, op_, op_dk_, schema, tags);
  11616. builtins.setattr(self, key, overload);
  11617. this._dir.push(key);
  11618. return overload;
  11619. }
  11620. _has_script_object_arg(schema) {
  11621. return schema.arguments.some((arg) => arg.type instanceof torch.ClassType);
  11622. }
  11623. __call__(...args) {
  11624. const fn = execution._operators.get(this._qualified_op_name);
  11625. if (!fn) {
  11626. throw new python.Error(`Operator call '${this._qualified_op_name}' is not registered.`);
  11627. }
  11628. return fn(...args);
  11629. }
  11630. });
  11631. this.registerType('torch._ops._OpNamespace', class extends types.ModuleType {
  11632. constructor(name) {
  11633. super(`torch.ops.${name}`);
  11634. this.name = name;
  11635. this._dir = [];
  11636. }
  11637. __getattr__(op_name) {
  11638. const namespace_name = this.name;
  11639. const qualified_op_name = `${namespace_name}::${op_name}`;
  11640. const module_name = `${this.__module__}.${namespace_name}`;
  11641. let op = null;
  11642. let overload_names = null;
  11643. try {
  11644. [op, overload_names] = this._get_packet(qualified_op_name, module_name);
  11645. } catch {
  11646. // continue regardless of error
  11647. }
  11648. if (!op) {
  11649. throw new python.Error(`Unknown operator type '${qualified_op_name}'.`);
  11650. }
  11651. op.__module__ = module_name;
  11652. const opoverloadpacket = new torch._ops.OpOverloadPacket(qualified_op_name, op_name, op, overload_names);
  11653. opoverloadpacket.__module__ = `${this.__module__}.${namespace_name}`;
  11654. builtins.setattr(this, op_name, opoverloadpacket);
  11655. this._dir.push(op_name);
  11656. return opoverloadpacket;
  11657. }
  11658. _get_packet(qualname, op_module) {
  11659. const [op, overload_names] = torch._C._jit_get_operation(qualname);
  11660. if (op) {
  11661. // torch.jit._builtins._register_builtin(op, qualname);
  11662. }
  11663. op.__module__ = op_module;
  11664. return [op, overload_names];
  11665. }
  11666. });
  11667. this.registerType('torch._C.graph_node_list', class {
  11668. constructor(head) {
  11669. this.head = head;
  11670. }
  11671. front() {
  11672. return this.head.next;
  11673. }
  11674. end() {
  11675. return this.head.prev;
  11676. }
  11677. [Symbol.iterator]() {
  11678. let current = this.head.next;
  11679. const prev = this.head.prev;
  11680. return {
  11681. next() {
  11682. if (current !== prev) {
  11683. const value = current;
  11684. current = current.next;
  11685. return { value, done: false };
  11686. }
  11687. return { done: true };
  11688. }
  11689. };
  11690. }
  11691. });
  11692. this.registerType('torch.Graph', class {
  11693. constructor() {
  11694. this._next_unique = 0;
  11695. this._unique_names = new Map();
  11696. this._name_base_suffix = new Map();
  11697. this.all_nodes = new Set();
  11698. this.all_values = new Set();
  11699. this.all_blocks = new Set();
  11700. this._block = new torch.Block(this, null);
  11701. this._insert_before = this.return_node();
  11702. }
  11703. insert(opname, args, kwargs, range) {
  11704. return torch._C.emitBuiltinCall(range, this, opname, args, kwargs);
  11705. }
  11706. create(kind, ...args) {
  11707. let inputs = null;
  11708. let num_outputs = 1;
  11709. if (args.length === 2 && Array.isArray(args[0]) && typeof args[1] === 'number') {
  11710. [inputs, num_outputs] = args;
  11711. } else if (args.length === 1) {
  11712. if (typeof args[0] === 'number') {
  11713. [num_outputs] = args;
  11714. } else if (Array.isArray(args[0])) {
  11715. [inputs] = args;
  11716. }
  11717. }
  11718. const n = new torch.Node(this, kind);
  11719. if (inputs) {
  11720. for (const i of inputs) {
  11721. n.addInput(i);
  11722. }
  11723. }
  11724. for (let i = 0; i < num_outputs; i++) {
  11725. n.addOutput();
  11726. }
  11727. return n;
  11728. }
  11729. createClone(n, value_map, copy_blocks) {
  11730. copy_blocks = copy_blocks === undefined ? true : copy_blocks;
  11731. const r = n.allocNewInstance(this);
  11732. for (const o of n.outputs()) {
  11733. r.addOutput().copyMetadata(o);
  11734. }
  11735. r.cloneFrom(n);
  11736. for (const i of n.inputs()) {
  11737. r.addInput(value_map(i));
  11738. }
  11739. if (copy_blocks) {
  11740. for (const b of n.blocks()) {
  11741. r.addBlock().cloneFrom(b, value_map);
  11742. }
  11743. }
  11744. return r;
  11745. }
  11746. createNone() {
  11747. const n = this.create('prim::Constant');
  11748. n.output().setType(torch.NoneType.get());
  11749. return n;
  11750. }
  11751. createUninitialized(typ) {
  11752. const n = this.create('prim::Uninitialized');
  11753. n.output().setType(typ);
  11754. return n;
  11755. }
  11756. createEnumValue(e) {
  11757. const enum_type = e.type().expect(torch.EnumType);
  11758. const n = this.create('prim::EnumValue', [e]);
  11759. n.output().setType(enum_type.getValueType());
  11760. return n;
  11761. }
  11762. createList(contained_type, values) {
  11763. const n = this.create('prim::ListConstruct', values);
  11764. for (const v of values) {
  11765. if (!v.type().isSubtypeOf(contained_type)) {
  11766. throw new python.Error('Invalid list item.');
  11767. }
  11768. }
  11769. n.output().setType(torch.ListType.create(contained_type));
  11770. return n;
  11771. }
  11772. createListUnpack(v, size) {
  11773. const list_type = v.type().expect(torch.ListType);
  11774. const elem_type = list_type.getElementType();
  11775. const n = this.create('prim::ListUnpack', [v], 0);
  11776. for (let i = 0; i < size; i++) {
  11777. n.addOutput().setType(elem_type);
  11778. }
  11779. return n;
  11780. }
  11781. createTuple(values, tuple_type) {
  11782. if (!tuple_type) {
  11783. const types = values.map((v) => v.type());
  11784. tuple_type = torch.TupleType.create(types);
  11785. }
  11786. const n = this.create('prim::TupleConstruct', values);
  11787. n.output().setType(tuple_type);
  11788. return n;
  11789. }
  11790. createTupleUnpack(v) {
  11791. const tt = v.type().expect(torch.TupleType);
  11792. const n = this.create('prim::TupleUnpack', [v], 0);
  11793. for (const element of tt.elements()) {
  11794. n.addOutput().setType(element);
  11795. }
  11796. return n;
  11797. }
  11798. createTupleIndex(tup, idx, output_type) {
  11799. const n = this.create('prim::TupleIndex', [tup, idx]);
  11800. n.output().setType(output_type);
  11801. return n;
  11802. }
  11803. createTupleSlice(tup, beg, step_size, num_values) {
  11804. const new_vals = [];
  11805. const tt = tup.type().expect(torch.TupleType);
  11806. let i = beg;
  11807. for (let j = 0; j < num_values; j++) {
  11808. const idx = this.insertConstant(new torch._C.IValue(i, 'Int'));
  11809. const tupleIndex = this.insertNode(this.createTupleIndex(tup, idx, tt.elements()[i]));
  11810. new_vals.push(tupleIndex.output());
  11811. i += step_size;
  11812. }
  11813. const n = this.createTuple(new_vals);
  11814. return n;
  11815. }
  11816. createDict(key_type, value_type, keys, values) {
  11817. if (keys.length !== values.length) {
  11818. throw new python.Error('Invalid dictionary size.');
  11819. }
  11820. const n = this.create('prim::DictConstruct');
  11821. const length = keys.length;
  11822. for (let i = 0; i < length; i++) {
  11823. if (!keys[i].type().isSubtypeOf(key_type)) {
  11824. throw new python.Error('Invalid key.');
  11825. }
  11826. if (!values[i].type().isSubtypeOf(value_type)) {
  11827. throw new python.Error('Invalid value.');
  11828. }
  11829. n.addInput(keys[i]);
  11830. n.addInput(values[i]);
  11831. }
  11832. n.output().setType(torch.DictType.create(key_type, value_type));
  11833. return n;
  11834. }
  11835. createObject(type) {
  11836. const node = this.create('prim::CreateObject');
  11837. node.output().setType(type);
  11838. return node;
  11839. }
  11840. createIsInstance(v, types) {
  11841. const n = this.create('prim::isinstance', [v], 1);
  11842. n.tys_('types', types);
  11843. n.output().setType(torch.BoolType.get());
  11844. return n;
  11845. }
  11846. createSetAttr(obj, field, newValue) {
  11847. const n = this.create('prim::SetAttr', [obj, newValue], 0);
  11848. n.s_('name', field);
  11849. return n;
  11850. }
  11851. createGetAttr(obj, field) {
  11852. const n = this.create('prim::GetAttr', [obj]);
  11853. n.s_('name', field);
  11854. const classType = obj.type();
  11855. const outputType = classType.getAttribute(field);
  11856. n.output().setType(outputType);
  11857. n.output().setDebugName(torch._C.normalizeAttrName(field));
  11858. return n;
  11859. }
  11860. createLoad(name, type) {
  11861. const n = this.create('prim::Load', [], 1);
  11862. n.s_('name', name);
  11863. n.output().setType(type);
  11864. return n;
  11865. }
  11866. createStore(name, v) {
  11867. const n = this.create('prim::Store', [v], 0);
  11868. n.s_('name', name);
  11869. return n;
  11870. }
  11871. inputs() {
  11872. return this._block.inputs();
  11873. }
  11874. outputs() {
  11875. return this._block.outputs();
  11876. }
  11877. nodes() {
  11878. return this._block.nodes();
  11879. }
  11880. param_node() {
  11881. return this._block.param_node();
  11882. }
  11883. return_node() {
  11884. return this._block.return_node();
  11885. }
  11886. block() {
  11887. return this._block;
  11888. }
  11889. addInput(name) {
  11890. return this._block.addInput(name);
  11891. }
  11892. insertNode(node) {
  11893. torch._C.AT_ASSERT(this._insert_before.inBlockList());
  11894. return node.insertBefore(this._insert_before);
  11895. }
  11896. insertConstant(val, loc, scope) {
  11897. return torch._C.insertConstant(this, val, loc, scope);
  11898. }
  11899. insertMethodCall(method_name, matched) {
  11900. const result = this.insertNode(this.create('prim::CallMethod', matched.inputs))
  11901. .s_('name', method_name)
  11902. .output().setType(matched.return_types[0]);
  11903. return result;
  11904. }
  11905. insertUncheckedCast(v, type) {
  11906. const n = this.create('prim::unchecked_cast', [v]);
  11907. this.insertNode(n);
  11908. n.output().setType(type);
  11909. return n.output();
  11910. }
  11911. insertToList(v, type) {
  11912. let dim = 0;
  11913. let ptr = type;
  11914. while (ptr instanceof torch.ListType) {
  11915. ptr = ptr.getElementType();
  11916. dim += 1;
  11917. }
  11918. let elem_ty = 0;
  11919. if (ptr instanceof torch.IntType) {
  11920. elem_ty = 0;
  11921. } else if (ptr instanceof torch.FloatType) {
  11922. elem_ty = 1;
  11923. } else if (ptr instanceof torch.BoolType) {
  11924. elem_ty = 2;
  11925. } else if (ptr instanceof torch.ComplexType) {
  11926. elem_ty = 3;
  11927. } else {
  11928. throw new python.Error(`Unsupported list type '${type.kind()}'.`);
  11929. }
  11930. const dim_val = this.insertConstant(dim);
  11931. const elem_ty_val = this.insertConstant(elem_ty);
  11932. const n = this.insertNode(this.create('prim::tolist', [v, dim_val, elem_ty_val]));
  11933. n.output().setType(type);
  11934. return n.output();
  11935. }
  11936. insertFunctionCall(callee, matched) {
  11937. const func_name = callee.name();
  11938. const fn_constant = this.insertNode(this.create('prim::Constant')).s_('name', func_name).output().setType(torch._C.FunctionType.create(callee));
  11939. const inputs = [fn_constant, ...matched.inputs];
  11940. const result = this.insertNode(this.create('prim::CallFunction', inputs)).output().setType(matched.return_types[0]);
  11941. return result;
  11942. }
  11943. insertPoint() {
  11944. return this._insert_before;
  11945. }
  11946. setInsertPoint(node) {
  11947. if (node instanceof torch.Block) {
  11948. node = node.return_node();
  11949. }
  11950. this._insert_before = node;
  11951. }
  11952. freeNode(n) {
  11953. this.all_nodes.delete(n);
  11954. }
  11955. freeValue(v) {
  11956. v.setDebugName('');
  11957. this.all_values.delete(v);
  11958. }
  11959. freeBlock(b) {
  11960. this.all_blocks.delete(b);
  11961. }
  11962. copy() {
  11963. const new_g = new torch.Graph();
  11964. new_g.cloneFrom(this);
  11965. return new_g;
  11966. }
  11967. cloneFrom(src) {
  11968. const env = (v) => {
  11969. throw new python.Error(`Use of value '${v.debugName()}' not in scope.`);
  11970. };
  11971. this.block().cloneFrom(src.block(), env);
  11972. }
  11973. set_op_version(version) {
  11974. this._op_version = version;
  11975. }
  11976. get_op_version() {
  11977. return this._op_version;
  11978. }
  11979. print(out, print_source_locations) {
  11980. out.write('graph(');
  11981. torch._C.const_value_list_with_types(out, this.inputs(), ',\n ');
  11982. out.write('):\n');
  11983. const groups = [];
  11984. for (const node of this.nodes()) {
  11985. node.print(out, 1, groups, print_source_locations);
  11986. }
  11987. out.write(' return (');
  11988. torch._C.printValueRefs(out, this.outputs());
  11989. out.write(')\n');
  11990. for (let i = 0; i < groups.length; i++) {
  11991. const fg = groups[i];
  11992. out.write('with ');
  11993. out.write(fg.kind());
  11994. out.write(`_${i} = `);
  11995. out.write(fg.g('Subgraph'));
  11996. }
  11997. return out;
  11998. }
  11999. toString() {
  12000. const out = new io.StringIO();
  12001. this.print(out, true);
  12002. return out.toString();
  12003. }
  12004. });
  12005. this.registerType('torch.Block', class {
  12006. constructor(graph, node) {
  12007. this._graph = graph;
  12008. this._input = graph.create('prim::Param', 0);
  12009. this._output = graph.create('prim::Return', 0);
  12010. this._owning_node = node;
  12011. this._input.next = this._output;
  12012. this._input.prev = this._output;
  12013. this._output.next = this._input;
  12014. this._output.prev = this._input;
  12015. this._graph.all_blocks.add(this);
  12016. this._output._owning_block = this;
  12017. // output_.topo_position_ = kUpperBound;
  12018. this._input._owning_block = this;
  12019. // input_.topo_position_ = kLowerBound;
  12020. }
  12021. inputs() {
  12022. return this._input.outputs();
  12023. }
  12024. outputs() {
  12025. return this._output.inputs();
  12026. }
  12027. nodes() {
  12028. return new torch._C.graph_node_list(this._input);
  12029. }
  12030. return_node() {
  12031. return this._output;
  12032. }
  12033. param_node() {
  12034. return this._input;
  12035. }
  12036. owningNode() {
  12037. return this._owning_node;
  12038. }
  12039. owningGraph() {
  12040. return this._graph;
  12041. }
  12042. addInput(name) {
  12043. const value = this._input.addOutput();
  12044. value.setDebugName(name || '');
  12045. return value;
  12046. }
  12047. registerOutput(value) {
  12048. this._output.addInput(value);
  12049. return this.outputs().length - 1;
  12050. }
  12051. appendNode(n) {
  12052. if (n._graph !== this._graph || n.inBlockList()) {
  12053. throw new python.Error('Node not in graph.');
  12054. }
  12055. n.insertBefore(this._output);
  12056. return n;
  12057. }
  12058. cloneFrom(src, value_map) {
  12059. const local_map = new Map();
  12060. const env = (v) => {
  12061. if (local_map.has(v)) {
  12062. return local_map.get(v);
  12063. }
  12064. return value_map(v);
  12065. };
  12066. const graph = this.owningGraph();
  12067. for (const input of src.inputs()) {
  12068. local_map.set(input, this.addInput().copyMetadata(input));
  12069. }
  12070. for (const node of src.nodes()) {
  12071. const new_node = this.appendNode(graph.createClone(node, env));
  12072. for (let i = 0; i < node.outputs().length; i++) {
  12073. const oo = node.outputs()[i];
  12074. const no = new_node.outputs()[i];
  12075. local_map.set(oo, no);
  12076. no.copyMetadata(oo);
  12077. }
  12078. }
  12079. for (const output of src.outputs()) {
  12080. this.registerOutput(env(output));
  12081. }
  12082. }
  12083. eraseOutput(i) {
  12084. this._output.removeInput(i);
  12085. }
  12086. destroy() {
  12087. this._output.removeAllInputs();
  12088. for (const n of this.nodes()) {
  12089. n.destroy();
  12090. }
  12091. this._output.destroy();
  12092. this._input.destroy();
  12093. this._graph.freeBlock(this);
  12094. }
  12095. });
  12096. this.registerType('torch.Node', class {
  12097. constructor(graph, kind) {
  12098. this._kind = kind;
  12099. this._graph = graph;
  12100. this._owning_block = null;
  12101. this._values = new Map();
  12102. this._inputs = [];
  12103. this._outputs = [];
  12104. this._blocks = [];
  12105. this._graph.all_nodes.add(this);
  12106. this._prev = null;
  12107. this._next = null;
  12108. this._source_range = null;
  12109. this._op = null;
  12110. }
  12111. owningGraph() {
  12112. return this._graph;
  12113. }
  12114. owningBlock() {
  12115. return this._owning_block;
  12116. }
  12117. kind() {
  12118. return this._kind;
  12119. }
  12120. schema() {
  12121. if (this._op) {
  12122. return this._op.schema();
  12123. }
  12124. // Node::schema() throws while torch.Node.schema() does not.
  12125. const op = this.maybeOperator();
  12126. if (op) {
  12127. return op.schema();
  12128. }
  12129. return null;
  12130. // return this.getOperator().schema();
  12131. }
  12132. hasNamedInput(name) {
  12133. for (const argument of this.schema().arguments) {
  12134. if (argument.name === name) {
  12135. return true;
  12136. }
  12137. }
  12138. return false;
  12139. }
  12140. matches(schema) {
  12141. if (torch._C.isBlockListedSchema(schema)) {
  12142. return false;
  12143. }
  12144. if (this.kind() !== schema.name) {
  12145. return false;
  12146. }
  12147. const actuals = this.inputs();
  12148. const formals = schema.arguments;
  12149. if (actuals.length < formals.length) {
  12150. return false;
  12151. }
  12152. const type_env = new Map();
  12153. for (let i = 0; i < formals.length; i++) {
  12154. let formal = formals[i].type;
  12155. const matched_type = torch._C.matchTypeVariables(formal, actuals[i].type(), type_env);
  12156. if (!matched_type.success()) {
  12157. return false;
  12158. }
  12159. const resolved = torch._C.tryEvalTypeVariables(formal, type_env);
  12160. if (resolved) {
  12161. formal = resolved;
  12162. }
  12163. if (!actuals[i].type().isSubtypeOf(formal)) {
  12164. return false;
  12165. }
  12166. }
  12167. if (!schema.is_vararg && actuals.length !== formals.length) {
  12168. return false;
  12169. }
  12170. return true;
  12171. }
  12172. mustBeNone() {
  12173. return this._kind === 'prim::AutogradZero' ||
  12174. (this.outputs().length === 1 && this.output().type() === torch.NoneType.get()) ||
  12175. (this._kind === 'prim::Constant' && !this.hasAttributes() && this.output().type() instanceof torch.OptionalType);
  12176. }
  12177. maybeSchema() {
  12178. const op = this.maybeOperator();
  12179. if (op) {
  12180. return op.schema();
  12181. }
  12182. return null;
  12183. }
  12184. maybeOperator() {
  12185. if (!this._op) {
  12186. const candidates = torch._C.getAllOperatorsFor(this.kind());
  12187. for (const candidate of candidates) {
  12188. if (this.matches(candidate.schema())) {
  12189. this._op = candidate;
  12190. break;
  12191. }
  12192. }
  12193. }
  12194. return this._op;
  12195. }
  12196. getOperator() {
  12197. const maybe = this.maybeOperator();
  12198. if (maybe) {
  12199. return maybe;
  12200. }
  12201. throw new python.Error(`Schema not found for node '${this.kind()}'.`);
  12202. }
  12203. getOperation() {
  12204. return this.getOperator().getOperation(this);
  12205. }
  12206. isNondeterministic() {
  12207. const schema = this.maybeSchema();
  12208. if (!this.kind().startsWith('aten::')) {
  12209. return false;
  12210. }
  12211. if (!schema) {
  12212. return false;
  12213. }
  12214. const schema_info = new torch._C.SchemaInfo(schema);
  12215. if (this.hasNamedInput('train')) {
  12216. throw new python.Error('Not Implemented.');
  12217. // const value = constant_as<bool>(this.namedInput("train"));
  12218. // if (value) {
  12219. // schema_info.addArgumentValue('train', value);
  12220. // }
  12221. }
  12222. return schema_info.is_nondeterministic();
  12223. }
  12224. hasSideEffects() {
  12225. switch (this._kind) {
  12226. case 'prim::PythonOp':
  12227. case 'prim::IgnoredPythonOp':
  12228. case 'prim::Print':
  12229. case 'prim::RaiseException':
  12230. case 'aten::warn':
  12231. case 'aten::save':
  12232. case 'aten::manual_seed':
  12233. case 'prim::AddStatValue':
  12234. case 'prim::TimePoint':
  12235. case 'prim::CallFunction':
  12236. case 'prim::CallMethod':
  12237. case 'prim::BailoutTemplate':
  12238. case 'prim::BailOut':
  12239. case 'prim::rpc_async':
  12240. case 'prim::rpc_sync':
  12241. case 'prim::rpc_remote':
  12242. case 'aten::wait':
  12243. case 'cuda::set_stream':
  12244. case 'cuda::_set_device':
  12245. case 'cuda::_current_device':
  12246. case 'cuda::synchronize':
  12247. case 'prim::Enter':
  12248. case 'prim::Exit':
  12249. return true;
  12250. default:
  12251. break;
  12252. }
  12253. const op = this.maybeOperator();
  12254. if (!op) {
  12255. torch._C.TORCH_INTERNAL_ASSERT(this._kind.startsWith('prim::'));
  12256. return false;
  12257. }
  12258. if (this._kind.startsWith('prim::') || this._kind.startsWith('aten::') || this._kind.startsWith('cuda::')) {
  12259. torch._C.TORCH_INTERNAL_ASSERT(
  12260. op.aliasAnalysisKind() === 'INTERNAL_SPECIAL_CASE' ||
  12261. op.aliasAnalysisKind() === 'FROM_SCHEMA' ||
  12262. op.aliasAnalysisKind() === 'CONSERVATIVE');
  12263. }
  12264. switch (op.aliasAnalysisKind()) {
  12265. case 'PURE_FUNCTION':
  12266. case 'FROM_SCHEMA':
  12267. case 'INTERNAL_SPECIAL_CASE':
  12268. return false;
  12269. case 'CONSERVATIVE':
  12270. return true;
  12271. default:
  12272. break;
  12273. }
  12274. torch._C.TORCH_INTERNAL_ASSERT(false);
  12275. return false;
  12276. }
  12277. inputs() {
  12278. return this._inputs;
  12279. }
  12280. outputs() {
  12281. return this._outputs;
  12282. }
  12283. input(i) {
  12284. if (i === undefined) {
  12285. torch._C.AT_ASSERT(this._inputs.length === 1);
  12286. return this._inputs[0];
  12287. }
  12288. return this._inputs[i];
  12289. }
  12290. output(i) {
  12291. if (i === undefined) {
  12292. torch._C.AT_ASSERT(this._outputs.length === 1);
  12293. return this._outputs[0];
  12294. }
  12295. return this._outputs[i];
  12296. }
  12297. hasUses() {
  12298. for (const o of this.outputs()) {
  12299. if (o.uses().length > 0) {
  12300. return true;
  12301. }
  12302. }
  12303. return false;
  12304. }
  12305. blocks() {
  12306. return this._blocks;
  12307. }
  12308. insertInput(i, value) {
  12309. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12310. this._op = null;
  12311. for (let use_itr = i; use_itr < this._inputs.length; use_itr++) {
  12312. const use = this.findUseForInput(use_itr);
  12313. use.offset += 1;
  12314. }
  12315. this._inputs.splice(i, 0, value);
  12316. value._uses.push(new torch.Use(this, i));
  12317. return value;
  12318. }
  12319. addInput(value) {
  12320. torch._C.AT_ASSERT(this._graph === value.owningGraph());
  12321. this._op = null;
  12322. const use = new torch.Use(this, this._inputs.length);
  12323. value.uses().push(use);
  12324. this._inputs.push(value);
  12325. return value;
  12326. }
  12327. addOutput() {
  12328. const value = new torch.Value(this, this._outputs.length);
  12329. this._outputs.push(value);
  12330. return value;
  12331. }
  12332. addBlock() {
  12333. this._op = null;
  12334. this._blocks.push(new torch.Block(this.owningGraph(), this));
  12335. return this._blocks[this._blocks.length - 1];
  12336. }
  12337. get prev() {
  12338. return this._prev;
  12339. }
  12340. set prev(value) {
  12341. this._prev = value;
  12342. }
  12343. get next() {
  12344. return this._next;
  12345. }
  12346. set next(value) {
  12347. this._next = value;
  12348. }
  12349. insertBefore(n) {
  12350. if (!n.inBlockList()) {
  12351. throw new python.Error('Node not in block.');
  12352. }
  12353. this.insertAfter(n.prev);
  12354. return this;
  12355. }
  12356. insertAfter(n) {
  12357. torch._C.AT_ASSERT(!this.inBlockList() || n.inBlockList());
  12358. torch._C.AT_ASSERT(n.owningBlock());
  12359. torch._C.TORCH_INTERNAL_ASSERT(n.kind() !== 'prim::Return');
  12360. this._owning_block = n.owningBlock();
  12361. const next = n.next;
  12362. n.next = this;
  12363. this.prev = n;
  12364. this.next = next;
  12365. next.prev = this;
  12366. // this.assignTopoPosition();
  12367. return this;
  12368. }
  12369. allocNewInstance(g) {
  12370. return new torch.Node(g, this.kind());
  12371. }
  12372. cloneFrom(s) {
  12373. this._source_range = s._source_range;
  12374. if (s._scope && !s._scope.isBlank()) {
  12375. this._scope = s._scope;
  12376. }
  12377. this.copyAttributes(s);
  12378. this._callstack = s._callstack;
  12379. }
  12380. copyAttributes(rhs) {
  12381. this._values = new Map(rhs._values);
  12382. return this;
  12383. }
  12384. dropInput(i) {
  12385. torch._C.AT_ASSERT(i < this._inputs.length);
  12386. const input_node = this._inputs[i];
  12387. const use_it = this.findUseForInput(i);
  12388. input_node._uses = input_node._uses.filter((use) => use !== use_it);
  12389. this._inputs[i] = null;
  12390. return input_node;
  12391. }
  12392. eraseOutput(i) {
  12393. torch._C.AT_ASSERT(i < this._outputs.length);
  12394. // torch._C.AT_ASSERT(this._outputs[i].uses().length === 0);
  12395. this._op = null;
  12396. const n = this._outputs[i];
  12397. this._outputs.splice(i, 1);
  12398. this.owningGraph().freeValue(n);
  12399. for (let j = i; j < this._outputs.length; j++) {
  12400. this._outputs[j]._offset--;
  12401. }
  12402. }
  12403. eraseBlock(i) {
  12404. this._op = null;
  12405. const n = this._blocks[i];
  12406. this._blocks.splice(i, 1);
  12407. n.destroy();
  12408. }
  12409. findUseForInput(i) {
  12410. const input_uses = this._inputs[i]._uses;
  12411. for (const use_it of input_uses) {
  12412. if (use_it.user === this && use_it.offset === i) {
  12413. return use_it;
  12414. }
  12415. }
  12416. throw new python.Error('Input use not found.');
  12417. }
  12418. moveBefore(n) {
  12419. this.removeFromList();
  12420. this.insertBefore(n);
  12421. }
  12422. removeInput(i) {
  12423. this._op = null;
  12424. this.dropInput(i);
  12425. for (let j = i + 1; j < this._inputs.length; j++) {
  12426. const it = this.findUseForInput(j);
  12427. it.offset--;
  12428. }
  12429. this._inputs.splice(i, 1);
  12430. }
  12431. removeAllInputs() {
  12432. this._op = null;
  12433. for (let i = 0; i < this._inputs.length; i++) {
  12434. this.dropInput(i);
  12435. }
  12436. this._inputs = [];
  12437. }
  12438. inBlockList() {
  12439. return this.next !== null;
  12440. }
  12441. removeFromList() {
  12442. this._owning_block = null;
  12443. const next = this.next;
  12444. const prev = this.prev;
  12445. prev.next = next;
  12446. next.prev = prev;
  12447. this.next = null;
  12448. this.prev = null;
  12449. }
  12450. destroy() {
  12451. while (this.outputs().length > 0) {
  12452. this.eraseOutput(this.outputs().length - 1);
  12453. }
  12454. while (this.blocks().length > 0) {
  12455. this.eraseBlock(this.blocks().length - 1);
  12456. }
  12457. this.removeAllInputs();
  12458. if (this.inBlockList()) {
  12459. this.removeFromList();
  12460. }
  12461. this._graph.freeNode(this);
  12462. }
  12463. replaceAllUsesWith(n) {
  12464. torch._C.AT_ASSERT(this.outputs().length === n.outputs().length);
  12465. const nOutputs = this.outputs().length;
  12466. for (let i = 0; i < nOutputs; i++) {
  12467. this.outputs()[i].replaceAllUsesWith(n.outputs()[i]);
  12468. }
  12469. }
  12470. s_(name, value) {
  12471. this._values.set(name, [value, 's']);
  12472. return this;
  12473. }
  12474. s(name) {
  12475. return this._values.get(name)[0];
  12476. }
  12477. ss_(name, value) {
  12478. this._values.set(name, [value, 'ss']);
  12479. return this;
  12480. }
  12481. ss(name) {
  12482. return this._values.get(name)[0];
  12483. }
  12484. i_(name, value) {
  12485. this._values.set(name, [value, 'i']);
  12486. return this;
  12487. }
  12488. i(name) {
  12489. return this._values.get(name)[0];
  12490. }
  12491. f_(name, value) {
  12492. this._values.set(name, [value, 'f']);
  12493. return this;
  12494. }
  12495. f(name) {
  12496. return this._values.get(name)[0];
  12497. }
  12498. c_(name, value) {
  12499. this._values.set(name, [value, 'c']);
  12500. return this;
  12501. }
  12502. c(name) {
  12503. return this._values.get(name)[0];
  12504. }
  12505. t_(name, value) {
  12506. this._values.set(name, [value, 't']);
  12507. return this;
  12508. }
  12509. t(name) {
  12510. return this._values.get(name)[0];
  12511. }
  12512. tys_(name, value) {
  12513. this._values.set(name, [value, 'tys']);
  12514. return this;
  12515. }
  12516. tys(name) {
  12517. return this._values.get(name)[0];
  12518. }
  12519. ival_(name, value) {
  12520. this._values.set(name, [value, 'ival']);
  12521. return this;
  12522. }
  12523. ival(name) {
  12524. return this._values.get(name)[0];
  12525. }
  12526. hasAttribute(name) {
  12527. return this._values.has(name);
  12528. }
  12529. hasAttributes() {
  12530. return this._values.size > 0;
  12531. }
  12532. attributeNames() {
  12533. return Array.from(this._values.keys());
  12534. }
  12535. kindOf(name) {
  12536. return this._values.get(name)[1];
  12537. }
  12538. setSourceRange(r) {
  12539. torch._C.AT_ASSERT(r instanceof torch._C.SourceRange);
  12540. this._source_range = r;
  12541. return this;
  12542. }
  12543. sourceRange() {
  12544. if (this._source_range) {
  12545. return this._source_range;
  12546. }
  12547. return new torch._C.SourceRange();
  12548. }
  12549. print_attributes(out, ignore_subgraph) {
  12550. ignore_subgraph = ignore_subgraph || false;
  12551. out.write('[');
  12552. const names = this.attributeNames();
  12553. for (let i = 0; i < names.length; i++) {
  12554. const name = names[i];
  12555. if (ignore_subgraph && name === 'Subgraph') {
  12556. continue;
  12557. }
  12558. if (i > 0) {
  12559. out.write(', ');
  12560. }
  12561. out.write(`${name}=`);
  12562. this.printAttrValue(out, name);
  12563. }
  12564. out.write(']');
  12565. }
  12566. printTypeList(out, items) {
  12567. out.write('[');
  12568. for (let i = 0; i < items.length; i++) {
  12569. const item = items[i];
  12570. if (i++ > 0) {
  12571. out.write(', ');
  12572. }
  12573. out.write(item.str());
  12574. }
  12575. out.write(']');
  12576. }
  12577. printAttrValue(out, name) {
  12578. const kind = this.kindOf(name);
  12579. switch (kind) {
  12580. case 'c': case 'cs': case 'f': case 'fs': case 'i': case 'is':
  12581. case 'ss': case 'ival': case 'ty':
  12582. out.write(this[kind](name));
  12583. break;
  12584. case 's':
  12585. out.write(`"${this.s(name)}"`);
  12586. break;
  12587. case 't':
  12588. out.write(`"{}"`);
  12589. break;
  12590. case 'ts': out.write('[<Tensors>]'); break;
  12591. case 'g': out.write('[<Graph>]'); break;
  12592. case 'gs': out.write('[<Graphs>]'); break;
  12593. case 'tys': this.printTypeList(out, this.tys(name)); break;
  12594. default: throw new python.Error(`Unknown attribute kind '${kind}'.`);
  12595. }
  12596. }
  12597. print(out, level, groups, print_source_locations, print_attributes, print_scopes, print_body) {
  12598. print_source_locations = print_source_locations === false ? false : true;
  12599. print_attributes = print_attributes === false ? false : true;
  12600. print_scopes = print_scopes === false ? false : true;
  12601. print_body = print_body === false ? false : true;
  12602. const outs = this.outputs();
  12603. torch._C.indent(out, level);
  12604. torch._C.const_value_list_with_types(out, outs, ', ');
  12605. out.write(' = ');
  12606. if (this.kind() === 'prim::PythonOp') {
  12607. throw new python.Error('Not implemented.');
  12608. } else if (this.hasAttribute('Subgraph') && groups) {
  12609. throw new python.Error('Not implemented.');
  12610. } else {
  12611. out.write(this.kind());
  12612. if (print_attributes && this.hasAttributes()) {
  12613. this.print_attributes(out);
  12614. }
  12615. }
  12616. out.write('(');
  12617. torch._C.printValueRefs(out, this.inputs());
  12618. out.write(')');
  12619. if (print_scopes) {
  12620. //
  12621. }
  12622. if (print_source_locations) {
  12623. let r = this.sourceRange();
  12624. if (r.source()) {
  12625. const orig = this.sourceRange().source().findSourceRangeThatGenerated(r);
  12626. if (orig) {
  12627. r = orig;
  12628. }
  12629. }
  12630. const file_line_col = r.file_line_col();
  12631. if (file_line_col !== null) {
  12632. const [filename, line, col] = file_line_col;
  12633. out.write(` # ${filename}:${line}:${col}`);
  12634. }
  12635. }
  12636. if (!print_body) {
  12637. return out;
  12638. }
  12639. out.write('\n');
  12640. for (let i = 0; i < this.blocks().length; i++) {
  12641. const b = this.blocks().at(i);
  12642. torch._C.indent(out, level + 1);
  12643. out.write(`block${i}(`);
  12644. torch._C.const_value_list_with_types(out, b.inputs());
  12645. out.write('):\n');
  12646. for (const nested of b.nodes()) {
  12647. nested.print(out, level + 2, groups);
  12648. }
  12649. torch._C.indent(out, level + 2);
  12650. out.write('-> (');
  12651. torch._C.printValueRefs(out, b.outputs());
  12652. out.write(')\n');
  12653. }
  12654. return out;
  12655. }
  12656. toString() {
  12657. const out = new io.StringIO();
  12658. this.print(out, 0, true);
  12659. return out.toString();
  12660. }
  12661. });
  12662. this.registerType('torch.Value', class {
  12663. constructor(node, offset) {
  12664. this._node = node;
  12665. this._offset = offset;
  12666. this._unique = node._graph._next_unique++;
  12667. this._uses = [];
  12668. this._node._graph.all_values.add(this);
  12669. }
  12670. unique() {
  12671. return this._unique;
  12672. }
  12673. node() {
  12674. return this._node;
  12675. }
  12676. owningGraph() {
  12677. return this._node.owningGraph();
  12678. }
  12679. uses() {
  12680. return this._uses;
  12681. }
  12682. hasUses() {
  12683. return this._uses.length > 0;
  12684. }
  12685. mustBeNone() {
  12686. return this.type() instanceof torch.NoneType || this._node.mustBeNone();
  12687. }
  12688. mustNotBeNone() {
  12689. return this._node.kind() !== 'prim::AutogradAdd' &&
  12690. this.type() !== torch.NoneType.get() &&
  12691. !(this.type() instanceof torch.OptionalType) &&
  12692. !(this.type() instanceof torch.UnionType && this.type().expect(torch.UnionType).canHoldType(torch.NoneType.get()));
  12693. }
  12694. isValidName(name) {
  12695. if (name.length === 0) {
  12696. return true;
  12697. }
  12698. if (torch._C.isNumber(name)) {
  12699. return false;
  12700. }
  12701. return true;
  12702. }
  12703. hasDebugName() {
  12704. return this._unique_name && this._unique_name.length > 0;
  12705. }
  12706. setDebugName(name) {
  12707. if (!this.isValidName(name)) {
  12708. throw new python.Error(`Invalid name '${name}'.`);
  12709. }
  12710. const names = this.node().owningGraph()._unique_names;
  12711. if (this.hasDebugName()) {
  12712. names.delete(this._unique_name);
  12713. this._unique_name = '';
  12714. }
  12715. if (!name) {
  12716. return this;
  12717. }
  12718. const old_owner_of_name = names.get(name);
  12719. if (old_owner_of_name) {
  12720. let suffix = 1;
  12721. let name_base = name;
  12722. const last_dot_pos = name.lastIndexOf('.');
  12723. if (last_dot_pos !== -1) {
  12724. if (/^\d+$/.test(name.substring(last_dot_pos + 1))) {
  12725. suffix = Number(name.substring(last_dot_pos + 1));
  12726. name_base = name.substring(0, last_dot_pos);
  12727. }
  12728. }
  12729. const names_suffixes = this.node().owningGraph()._name_base_suffix;
  12730. if (names_suffixes.has(name_base)) {
  12731. suffix = Math.max(suffix, names_suffixes.get(name_base));
  12732. }
  12733. let replacement_name = null;
  12734. do {
  12735. replacement_name = `${name_base}.${suffix++}`;
  12736. } while (names.has(replacement_name));
  12737. names_suffixes.set(name_base, suffix);
  12738. old_owner_of_name.setDebugName(replacement_name);
  12739. }
  12740. names.set(name, this);
  12741. this._unique_name = name;
  12742. return this;
  12743. }
  12744. debugName() {
  12745. if (this.hasDebugName()) {
  12746. return this._unique_name;
  12747. }
  12748. return this.unique().toString();
  12749. }
  12750. type() {
  12751. return this._type;
  12752. }
  12753. setType(type) {
  12754. // torch._C.AT_ASSERT(type instanceof torch.Type);
  12755. if (type instanceof torch._C.DynamicType) {
  12756. type = type.fallback();
  12757. }
  12758. this._type = type;
  12759. for (const use of this._uses) {
  12760. use.user._op = null;
  12761. }
  12762. return this;
  12763. }
  12764. set value(value) { // remove
  12765. if (value instanceof torch.Value) {
  12766. throw new python.Error('Value cannot be a value.');
  12767. }
  12768. this._value = value;
  12769. }
  12770. get value() { // remove
  12771. return this._value;
  12772. }
  12773. replaceFirstUseWith(newValue) {
  12774. torch._C.AT_ASSERT(this.owningGraph() === newValue.owningGraph());
  12775. const [u] = this.uses();
  12776. u.user._inputs[u.offset] = newValue;
  12777. newValue._uses.push(u);
  12778. this._uses.shift();
  12779. }
  12780. replaceAllUsesWith(newValue) {
  12781. while (this.uses().length > 0) {
  12782. this.replaceFirstUseWith(newValue);
  12783. }
  12784. }
  12785. copyMetadata(from) {
  12786. this.setType(from.type());
  12787. if (from.hasDebugName()) {
  12788. this.setDebugName(from.debugName());
  12789. }
  12790. return this;
  12791. }
  12792. toString() {
  12793. return `${this.debugName()} : ${this.type().toString()}`;
  12794. }
  12795. });
  12796. this.registerType('torch.Use', class {
  12797. constructor(user, offset) {
  12798. this.user = user;
  12799. this.offset = offset;
  12800. }
  12801. });
  12802. this.registerType('torch._C.IValue', class {
  12803. constructor(value, tag) {
  12804. this.value = value;
  12805. if (tag) {
  12806. this.tag = tag;
  12807. } else if (value === undefined) {
  12808. this.tag = 'None';
  12809. this.value = null;
  12810. } else if (typeof value === 'boolean') {
  12811. this.tag = 'Bool';
  12812. } else if (typeof value === 'string') {
  12813. this.tag = 'String';
  12814. } else if (value instanceof torch.Tensor) {
  12815. this.tag = 'Tensor';
  12816. } else if (value instanceof torch.ScriptObject) {
  12817. this.tag = 'Object';
  12818. } else if (Array.isArray(value)) {
  12819. this.tag = 'GenericList';
  12820. } else if (value instanceof torch._C.Tuple) {
  12821. this.tag = 'Tuple';
  12822. } else if (value instanceof torch.device) {
  12823. this.tag = 'Device';
  12824. } else if (Number.isInteger(value)) {
  12825. this.tag = 'Int';
  12826. } else if (typeof value === 'number') {
  12827. this.tag = 'Double';
  12828. } else if (value instanceof builtins.complex) {
  12829. this.tag = 'ComplexDouble';
  12830. } else if (value instanceof torch._C.EnumHolder) {
  12831. this.tag = 'Enum';
  12832. } else {
  12833. throw new python.Error('Unsupported type.');
  12834. }
  12835. }
  12836. isNone() {
  12837. return this.tag === 'None';
  12838. }
  12839. isBool() {
  12840. return this.tag === 'Bool';
  12841. }
  12842. toBool() {
  12843. return this.value;
  12844. }
  12845. isObject() {
  12846. return this.tag === 'Object';
  12847. }
  12848. toObject() {
  12849. return this.value;
  12850. }
  12851. isTensor() {
  12852. return this.tag === 'Tensor';
  12853. }
  12854. toTensor() {
  12855. return this.value;
  12856. }
  12857. isDouble() {
  12858. return this.tag === 'Double';
  12859. }
  12860. toDouble() {
  12861. return this.value;
  12862. }
  12863. isComplexDouble() {
  12864. return this.tag === 'ComplexDouble' || this.tag === 'Complex';
  12865. }
  12866. toComplexDouble() {
  12867. return this.value;
  12868. }
  12869. isInt() {
  12870. return this.tag === 'Int';
  12871. }
  12872. toInt() {
  12873. if (this.isInt()) {
  12874. return this.value;
  12875. } else if (this.isSymInt()) {
  12876. return this.toSymInt().guard_int(/* __FILE__, __LINE__ */);
  12877. }
  12878. throw new python.Error('Expected int.');
  12879. }
  12880. isString() {
  12881. return this.tag === 'String';
  12882. }
  12883. toStringRef() {
  12884. return this.value;
  12885. }
  12886. isList() {
  12887. return this.tag === 'GenericList';
  12888. }
  12889. toList() {
  12890. return this.value;
  12891. }
  12892. toListRef() {
  12893. return this.value;
  12894. }
  12895. isBoolList() {
  12896. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.BoolType;
  12897. }
  12898. isIntList() {
  12899. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.IntType;
  12900. }
  12901. isDoubleList() {
  12902. return this.value instanceof torch._C.List && this.value.elementType() instanceof torch.FloatType;
  12903. }
  12904. isDevice() {
  12905. return this.tag === 'Device';
  12906. }
  12907. toDevice() {
  12908. return this.value;
  12909. }
  12910. isGenerator() {
  12911. return this.tag === 'Generator';
  12912. }
  12913. isStream() {
  12914. return this.tag === 'Stream';
  12915. }
  12916. isGenericDict() {
  12917. return this.tag === 'GenericDict';
  12918. }
  12919. isEnum() {
  12920. return this.tag === 'Enum';
  12921. }
  12922. toEnumHolder() {
  12923. return this.value;
  12924. }
  12925. isTuple() {
  12926. return this.tag === 'Tuple';
  12927. }
  12928. toTupleRef() {
  12929. return this.value;
  12930. }
  12931. isCustomClass() {
  12932. return torch._C.isCustomClass(this);
  12933. }
  12934. equals(rhs) {
  12935. switch (this.tag) {
  12936. case 'None': return rhs.isNone();
  12937. case 'Bool': return rhs.isBool() && this.toBool() === rhs.toBool();
  12938. case 'Int': return rhs.isInt() && this.toInt() === rhs.toInt();
  12939. case 'Double': return rhs.isDouble() && this.toDouble() === rhs.toDouble();
  12940. case 'String': return rhs.isString() && this.toString() === rhs.toString();
  12941. case 'Tensor': return rhs.isTensor() && this.toTensor() === rhs.toTensor();
  12942. case 'Object': return rhs.isObject() && this.toObject() === rhs.toObject();
  12943. case 'Device': return rhs.isObject() && this.toDevice() === rhs.toDevice();
  12944. case 'GenericList': {
  12945. if (rhs.isList()) {
  12946. const a = this.toList();
  12947. const b = rhs.toList();
  12948. return (a.length === b.length) && a.every((v, i) => v === b[i]);
  12949. }
  12950. return false;
  12951. }
  12952. default: throw new python.Error(`IValue.equals() not implemented for '${this.tag}.`);
  12953. }
  12954. }
  12955. is(rhs) {
  12956. return this.equals(rhs);
  12957. }
  12958. type() {
  12959. switch (this.tag) {
  12960. case 'None': return torch.NoneType.get();
  12961. case 'Bool': return torch.BoolType.get();
  12962. case 'Int': return torch.IntType.get();
  12963. case 'Double': return torch.FloatType.get();
  12964. case 'String': return torch.StringType.get();
  12965. case 'Device': return torch.DeviceObjType.get();
  12966. case 'Tuple': return torch.TupleType.create(this.value.elements().map((ivalue) => ivalue.type()));
  12967. case 'Enum': return this.toEnumHolder().type();
  12968. case 'GenericList': return torch.ListType.create(this.toList().elementType());
  12969. default: throw new python.Error(`IValue.type('${this.tag}') not implemented.`);
  12970. }
  12971. }
  12972. });
  12973. this.registerFunction('torch._C.indent', (out, level) => {
  12974. for (let i = 0; i < level; i++) {
  12975. out.write(' ');
  12976. }
  12977. return out;
  12978. });
  12979. this.registerFunction('torch._C.printValueRef', (out, n) => {
  12980. out.write(`%${n.debugName()}`);
  12981. });
  12982. this.registerFunction('torch._C.printValueRefs', (out, nodes) => {
  12983. for (let i = 0; i < nodes.length; i++) {
  12984. const n = nodes[i];
  12985. if (i > 0) {
  12986. out.write(', ');
  12987. }
  12988. torch._C.printValueRef(out, n);
  12989. }
  12990. return out;
  12991. });
  12992. this.registerFunction('torch._C.const_value_list_with_types', (out, values, delim) => {
  12993. for (let i = 0; i < values.length; i++) {
  12994. const n = values[i];
  12995. if (i > 0) {
  12996. out.write(delim);
  12997. }
  12998. torch._C.printValueRef(out, n);
  12999. out.write(' : ');
  13000. out.write(n.type().str());
  13001. }
  13002. });
  13003. this.register('torch.jit._script');
  13004. this.register('torch.jit._trace');
  13005. this.registerType('torch._C.Parser', class {
  13006. constructor(source) {
  13007. this.L = source;
  13008. }
  13009. parse() {
  13010. const p = ast.parse(this.L.text_str(), this.L.filename());
  13011. return p;
  13012. }
  13013. parseExp() {
  13014. const expr = ast.parse(this.L.text_str());
  13015. return expr.body[0].value;
  13016. }
  13017. });
  13018. this.registerType('torch._C.StringCordView', class {
  13019. });
  13020. this.registerType('torch._C.Source', class {
  13021. constructor(text_view, filename, starting_line_no, gen_ranges /*, copies_str */) {
  13022. if (text_view instanceof Uint8Array) {
  13023. const decoder = new TextDecoder('utf-8');
  13024. this._text_view = decoder.decode(text_view);
  13025. } else if (typeof text_view === 'string') {
  13026. this._text_view = text_view;
  13027. } else {
  13028. throw new python.Error('Invalid text view.');
  13029. }
  13030. this._filename = filename;
  13031. this._starting_line_no = starting_line_no;
  13032. this._gen_ranges = gen_ranges;
  13033. this.calc_line_start_offsets();
  13034. }
  13035. text_str() {
  13036. return this._text_view;
  13037. }
  13038. size() {
  13039. return this._text_view.length;
  13040. }
  13041. filename() {
  13042. return this._filename;
  13043. }
  13044. calc_line_start_offsets() {
  13045. let pos = 0;
  13046. this._line_starting_offsets = [0];
  13047. while ((pos = this._text_view.indexOf('\n', pos)) !== -1) {
  13048. pos += 1;
  13049. this._line_starting_offsets.push(pos);
  13050. }
  13051. }
  13052. offset_for_line(line) {
  13053. return this._line_starting_offsets[line];
  13054. }
  13055. lineno_for_offset(offset) {
  13056. const iter = this._line_starting_offsets.findIndex((value) => value > offset);
  13057. return (iter === -1 ? this._line_starting_offsets.length : iter) - 1;
  13058. }
  13059. lineno_to_source_lineno(lineno) {
  13060. if (this._filename) {
  13061. return lineno + this._starting_line_no;
  13062. }
  13063. return lineno;
  13064. }
  13065. findSourceRangeThatGenerated(range) {
  13066. if (!this._gen_ranges) {
  13067. return null;
  13068. }
  13069. return this._gen_ranges.findSourceRangeThatGenerated(range);
  13070. }
  13071. });
  13072. this.registerType('torch._C.SourceRange', class {
  13073. constructor(...args) {
  13074. if (args.length === 0) {
  13075. this._source_view = null;
  13076. } else if (args.length === 2) {
  13077. let node = null;
  13078. [this._source_view, node] = args;
  13079. this._start = this._source_view.offset_for_line(node.lineno - 1) + (node.col_offset - 1);
  13080. this._end = this._source_view.offset_for_line(node.end_lineno - 1) + (node.end_col_offset - 1);
  13081. } else if (args.length === 3) {
  13082. [this._source_view, this._start, this._end] = args;
  13083. } else {
  13084. throw new python.Error('Not implemented.');
  13085. }
  13086. }
  13087. source() {
  13088. return this._source_view;
  13089. }
  13090. file_line_col() {
  13091. if (!this._source_view || this.source().filename() === null) {
  13092. return null;
  13093. }
  13094. const lineno = this._source_view.lineno_for_offset(this._start);
  13095. const col_offset = this._start - this._source_view.offset_for_line(lineno);
  13096. return [this._source_view.filename(), this._source_view.lineno_to_source_lineno(lineno), col_offset];
  13097. }
  13098. start() {
  13099. return this._start;
  13100. }
  13101. toString() {
  13102. const loc = this.file_line_col();
  13103. return loc ? `${loc[0]}:${loc[1]}:${loc[2]}` : '';
  13104. }
  13105. });
  13106. this.registerType('torch._C.QualifiedName', class {
  13107. constructor(...args) {
  13108. let name = null;
  13109. if (args.length === 1 && typeof args[0] === 'string') {
  13110. [name] = args;
  13111. } else if (args.length === 1 && Array.isArray(args[0]) && args[0].every((arg) => typeof arg === 'string')) {
  13112. name = args[0].join('.');
  13113. } else {
  13114. name = `${args[0].qualifiedName()}.${args[1]}`;
  13115. }
  13116. const index = name.lastIndexOf('.');
  13117. this._qualifiedName = name;
  13118. this._prefix = index === -1 ? '' : name.substring(0, index);
  13119. this._name = index === -1 ? name : name.substring(index + 1);
  13120. }
  13121. qualifiedName() {
  13122. return this._qualifiedName; // "foo.bar.baz"
  13123. }
  13124. prefix() {
  13125. return this._prefix; // "foo.bar"
  13126. }
  13127. name() {
  13128. return this._name; // "baz"
  13129. }
  13130. atoms() {
  13131. return this._qualifiedName.split('.');
  13132. }
  13133. });
  13134. this.registerType('torch._C.Resolver', class {
  13135. resolveValue() {
  13136. throw new python.Error('Not implemented.');
  13137. }
  13138. resolveType() {
  13139. throw new python.Error('Not implemented.');
  13140. }
  13141. });
  13142. this.registerFunction('torch._C.registerCustomClass', (class_type) => {
  13143. torch._C.customClasses = torch._C.customClasses || new Map();
  13144. torch._C.TORCH_INTERNAL_ASSERT(class_type.name());
  13145. const name = class_type.name().qualifiedName();
  13146. torch._C.TORCH_CHECK(!torch._C.customClasses.has(name));
  13147. torch._C.customClasses.set(name, class_type);
  13148. });
  13149. this.registerFunction('torch._C.getCustomClass', (class_name) => {
  13150. torch._C.customClasses = torch._C.customClasses || new Map();
  13151. const ret = torch._C.customClasses.has(class_name) ? torch._C.customClasses.get(class_name) : null;
  13152. return ret;
  13153. });
  13154. this.registerFunction('torch._C.isCustomClass', (v) => {
  13155. return v.isObject() && v.toObject().type().name() && torch._C.getCustomClass(v.toObject().type().name().qualifiedName());
  13156. });
  13157. this.registerType('torch._C.SourceImporter', class extends torch._C.Resolver {
  13158. constructor(cu, constant_table, source_loader, version) {
  13159. super();
  13160. this._cu = cu;
  13161. this._constant_table = constant_table;
  13162. this._source_loader = source_loader;
  13163. this._version = version;
  13164. this._loaded_sources = new Set();
  13165. this._sources = new Map();
  13166. const sources = this._sources;
  13167. ast.AST.prototype.range = function() {
  13168. if (!this._range) {
  13169. if (sources.has(this.filename)) {
  13170. const source_view = sources.get(this.filename);
  13171. this._range = new torch._C.SourceRange(source_view, this);
  13172. } else {
  13173. this._range = new torch._C.SourceRange();
  13174. }
  13175. }
  13176. return this._range;
  13177. };
  13178. this._to_be_defined = new Map();
  13179. this._env = new Map([
  13180. ['torch', new torch._C.BuiltinModule('aten', version)],
  13181. ['ops', new torch._C.OpsValue(version)],
  13182. ['CONSTANTS', new torch._C.ConstantTableValue(constant_table)],
  13183. ['fork', torch._C.SpecialFormValue.create('prim::fork')],
  13184. ['awaitable', torch._C.SpecialFormValue.create('prim::awaitable')],
  13185. ['annotate', torch._C.SpecialFormValue.create('prim::annotate')],
  13186. ['unchecked_cast', torch._C.SpecialFormValue.create('prim::unchecked_cast')],
  13187. ['uninitialized', torch._C.SpecialFormValue.create('prim::Uninitialized')],
  13188. ]);
  13189. }
  13190. loadType(name) {
  13191. const type_parser = new torch._C.ScriptTypeParser(this);
  13192. return type_parser.parseType(name.qualifiedName());
  13193. }
  13194. resolveType(name) {
  13195. name = new torch._C.QualifiedName(name);
  13196. return this.findNamedType(name);
  13197. }
  13198. resolveValue(name, m, loc) {
  13199. if (this._env.has(name)) {
  13200. return this._env.get(name);
  13201. }
  13202. const graph = m.graph();
  13203. switch (name) {
  13204. case 'inf': return new torch._C.SimpleValue(graph.insertConstant(Infinity /* 'std::numeric_limits<double>::infinity()' */, loc));
  13205. case 'nan': return new torch._C.SimpleValue(graph.insertConstant(NaN /* 'std::numeric_limits<double>::quiet_NaN()' */, loc));
  13206. case 'infj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::infinity())', loc));
  13207. case 'nanj': return new torch._C.SimpleValue(graph.insertConstant('c10::complex<double>(0, std::numeric_limits<double>::quiet_NaN()', loc));
  13208. case '__torch__': return new torch._C.ClassNamespaceValue(new torch._C.QualifiedName(name), this);
  13209. default: return null;
  13210. }
  13211. }
  13212. findNamedType(name) {
  13213. const custom_class = torch._C.getCustomClass(name.qualifiedName());
  13214. if (custom_class) {
  13215. return custom_class;
  13216. }
  13217. this.parseSourceIfNeeded(name.prefix());
  13218. const key = name.qualifiedName();
  13219. const it = this._to_be_defined.get(key);
  13220. if (it && it instanceof ast.ClassDef) {
  13221. this._to_be_defined.delete(key);
  13222. this.importNamedType(name.prefix(), it);
  13223. }
  13224. return this._cu.get_type(name);
  13225. }
  13226. importNamedType(qualifier, class_def) {
  13227. const qualified_name = new torch._C.QualifiedName(`${qualifier}.${class_def.name}`);
  13228. if (class_def.bases.length === 0) {
  13229. this.importClass(qualified_name, class_def, false);
  13230. return;
  13231. }
  13232. const superclass_name = class_def.bases[0].id;
  13233. if (superclass_name === 'Module') {
  13234. this.importClass(qualified_name, class_def, true);
  13235. } else if (superclass_name === 'NamedTuple') {
  13236. this.importNamedTuple(qualified_name, class_def);
  13237. } else if (superclass_name === 'Interface') {
  13238. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=false);
  13239. } else if (superclass_name === 'ModuleInterface') {
  13240. // this._cu.define_interface(qualified_name, class_def, shared_from_this(), is_module=true);
  13241. } else if (superclass_name === 'Enum') {
  13242. this.importEnum(qualified_name, class_def);
  13243. } else {
  13244. throw new python.Error('TorchScript does not support class inheritance.');
  13245. }
  13246. }
  13247. importClass(qualified_classname, class_def, is_module) {
  13248. if (qualified_classname.prefix().startsWith('__torch__.torch.classes')) {
  13249. return;
  13250. }
  13251. const parameter_names = new Set();
  13252. const buffer_names = new Set();
  13253. const methods = [];
  13254. const method_resolvers = [];
  13255. const attributes = [];
  13256. const constants = [];
  13257. const pre_hook_names = new Set();
  13258. const pre_hook_def_map = new Map();
  13259. const hook_names = new Set();
  13260. const hook_def_map = new Map();
  13261. const class_type = torch.ClassType.create(qualified_classname.qualifiedName(), this._cu, is_module);
  13262. for (const stmt of class_def.body) {
  13263. if (stmt instanceof ast.Assign || stmt instanceof ast.AnnAssign) {
  13264. let target = null;
  13265. let annotation = null;
  13266. let value = null;
  13267. if (stmt instanceof ast.Assign) {
  13268. [target] = stmt.targets;
  13269. value = stmt.value;
  13270. } else {
  13271. target = stmt.target;
  13272. annotation = stmt.annotation;
  13273. value = stmt.value;
  13274. }
  13275. if (target instanceof ast.Name) {
  13276. const name = this._cu.execution.identifier(target);
  13277. switch (name) {
  13278. case '__annotations__': {
  13279. continue;
  13280. }
  13281. case '__parameters__': {
  13282. for (const elt of value.elts) {
  13283. parameter_names.add(elt.value);
  13284. }
  13285. break;
  13286. }
  13287. case '__buffers__': {
  13288. for (const elt of value.elts) {
  13289. buffer_names.add(elt.value);
  13290. }
  13291. break;
  13292. }
  13293. case '__forward_pre_hooks__': {
  13294. for (const elt of value.elts) {
  13295. pre_hook_names.add(elt.value);
  13296. }
  13297. break;
  13298. }
  13299. case '__forward_hooks__': {
  13300. for (const elt of value.elts) {
  13301. hook_names.add(elt.value);
  13302. }
  13303. break;
  13304. }
  13305. default: {
  13306. const fixed_up = this.attributeAssignmentSpecialHandlingHack(qualified_classname, stmt);
  13307. if (fixed_up) {
  13308. attributes.push({ name: fixed_up.target.id, value: fixed_up.value, annotation: fixed_up.annotation });
  13309. } else if (value) {
  13310. constants.push({ name, value, annotation });
  13311. } else {
  13312. attributes.push({ name, value, annotation });
  13313. }
  13314. break;
  13315. }
  13316. }
  13317. } else if (target instanceof ast.Subscript && target.value instanceof ast.Name && target.value.id === '__annotations__') {
  13318. const name = target.slice.value;
  13319. attributes.push({ name, value, annotation: stmt.value });
  13320. continue;
  13321. } else {
  13322. throw new python.Error('Unexpected statement kind in module metadata.');
  13323. }
  13324. } else if (stmt instanceof ast.FunctionDef) {
  13325. const def = stmt;
  13326. const def_name = def.name;
  13327. if (pre_hook_names.has(def_name)) {
  13328. pre_hook_def_map.set(def_name, def);
  13329. } else if (hook_names.has(def_name)) {
  13330. hook_def_map.set(def_name, def);
  13331. } else {
  13332. methods.push(def);
  13333. method_resolvers.push(this);
  13334. }
  13335. } else {
  13336. throw new python.Error('Unexpected statement kind in class body.');
  13337. }
  13338. }
  13339. const type_parser = new torch._C.ScriptTypeParser(this);
  13340. for (const assign of attributes) {
  13341. const name = assign.name;
  13342. const annotation = type_parser.parseTypeFromExpr(assign.annotation);
  13343. const is_parameter = parameter_names.has(name);
  13344. const is_buffer = buffer_names.has(name);
  13345. class_type.addAttribute(name, annotation, is_parameter, is_buffer);
  13346. }
  13347. for (const constant of constants) {
  13348. class_type.addConstant(constant.name, constant.value);
  13349. }
  13350. this._cu.register_type(class_type);
  13351. const self = new torch._C.SimpleSelf(class_type);
  13352. this._cu.define(qualified_classname, [], [], methods, method_resolvers, self, false, this._version);
  13353. }
  13354. importEnum(qualified_name, enum_def) {
  13355. const names_values = [];
  13356. let value_type = null;
  13357. const set_or_check_type = (t) => {
  13358. if (!value_type) {
  13359. value_type = t;
  13360. } else if (value_type !== t) {
  13361. throw new python.Error('Enum class with varying value types are not supported.');
  13362. }
  13363. };
  13364. for (const stmt of enum_def.body) {
  13365. if (stmt instanceof ast.Assign === false) {
  13366. throw new python.Error('Unexpected statement in Enum class body.');
  13367. }
  13368. const assign = stmt;
  13369. const name = assign.targets[0].id;
  13370. let ivalue = null;
  13371. const rhs = assign.value;
  13372. switch (rhs.type) {
  13373. case 'str':
  13374. ivalue = new torch._C.IValue(rhs.value, 'String');
  13375. set_or_check_type(torch.StringType.get());
  13376. break;
  13377. case 'int':
  13378. ivalue = new torch._C.IValue(rhs.value, 'Int');
  13379. set_or_check_type(torch.IntType.get());
  13380. break;
  13381. case 'float':
  13382. ivalue = new torch._C.IValue(rhs.value, 'Double');
  13383. set_or_check_type(torch.FloatType.get());
  13384. break;
  13385. default:
  13386. throw new python.Error(`Unsupported enum value type '${rhs.type}'.`);
  13387. }
  13388. names_values.push([name, ivalue]);
  13389. }
  13390. if (!value_type) {
  13391. throw new python.Error('No enum values defined.');
  13392. }
  13393. const enum_type = torch.EnumType.create(qualified_name, value_type, names_values, this._cu);
  13394. this._cu.register_type(enum_type);
  13395. }
  13396. importNamedTuple(qualified_name, named_tuple_def) {
  13397. const type_parser = new torch._C.ScriptTypeParser(this);
  13398. const field_names = [];
  13399. const field_types = [];
  13400. const field_defaults = [];
  13401. for (const stmt of named_tuple_def.body) {
  13402. if (stmt instanceof ast.AnnAssign === false) {
  13403. throw new python.Error('Unexpected statement in NamedTuple body.');
  13404. }
  13405. const assign = stmt;
  13406. const target = this._cu.execution.identifier(stmt.target);
  13407. // const annotation = this._cu.execution.type(stmt.annotation);
  13408. const type = type_parser.parseTypeFromExpr(assign.annotation);
  13409. field_names.push(target);
  13410. // field_types.push(annotation);
  13411. field_types.push(type);
  13412. }
  13413. const tt = torch.TupleType.createNamed(qualified_name.qualifiedName(), field_names, field_types, field_defaults);
  13414. this._cu.register_type(tt);
  13415. }
  13416. importFunction(qualifier, def) {
  13417. const definitions = [def];
  13418. const resolvers = [this];
  13419. this._cu.define(new torch._C.QualifiedName(qualifier), /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, null);
  13420. }
  13421. parseSourceIfNeeded(qualifier) {
  13422. if (!qualifier || this._loaded_sources.has(qualifier)) {
  13423. return;
  13424. }
  13425. this._loaded_sources.add(qualifier);
  13426. const src = this._source_loader(qualifier);
  13427. if (!src) {
  13428. return;
  13429. }
  13430. this._sources.set(src.filename(), src);
  13431. const p = new torch._C.Parser(src);
  13432. const L = p.parse();
  13433. this.parsePossibleVersionNumber(p);
  13434. for (const stmt of L.body) {
  13435. if (stmt instanceof ast.ClassDef) {
  13436. const name = `${qualifier}.${stmt.name}`;
  13437. this._to_be_defined.set(name, stmt);
  13438. } else if (stmt instanceof ast.FunctionDef) {
  13439. const name = `${qualifier}.${stmt.name}`;
  13440. this._to_be_defined.set(name, stmt);
  13441. }
  13442. }
  13443. }
  13444. parsePossibleVersionNumber(/* p */) {
  13445. }
  13446. parseImports(/* p */) {
  13447. }
  13448. attributeAssignmentSpecialHandlingHack(qualified_classname, assign) {
  13449. const replacements = new Map([
  13450. ['__torch__.torch.ao.nn.quantized.modules.linear.LinearPackedParams', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13451. ['__torch__.torch.ao.nn.quantized.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13452. ['__torch__.torch.ao.nn.quantized.dynamic.modules.linear.Linear', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.LinearPackedParamsBase']],
  13453. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13454. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv2dPackedParamsBase']],
  13455. ['__torch__.torch.ao.nn.quantized.modules.conv.Conv3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13456. ['__torch__.torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU3d', ['_packed_params', 'Tensor', '__torch__.torch.classes.quantized.Conv3dPackedParamsBase']],
  13457. ['__torch__.torch.nn.quantized.modules.linear.LinearPackedParams', ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13458. ["__torch__.torch.nn.quantized.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]],
  13459. ["__torch__.torch.nn.quantized.modules.conv.Conv2d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv2dPackedParamsBase"]],
  13460. ["__torch__.torch.nn.quantized.modules.conv.Conv3d", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.Conv3dPackedParamsBase"]],
  13461. ["__torch__.torch.nn.quantized.dynamic.modules.linear.Linear", ["_packed_params", "Tensor", "__torch__.torch.classes.quantized.LinearPackedParamsBase"]]
  13462. ]);
  13463. const mangleRe = /\.___torch_mangle_\d+/g;
  13464. const demangled_classname = qualified_classname.qualifiedName().replace(mangleRe, '');
  13465. if (replacements.has(demangled_classname)) {
  13466. const lhs = assign.target;
  13467. if (!assign.annotation || assign.annotation instanceof ast.Name === false) {
  13468. return null;
  13469. }
  13470. const type = assign.annotation.id;
  13471. const [attr_name, expected_type, replacement_type] = replacements.get(demangled_classname);
  13472. if (lhs.id === attr_name && type === expected_type) {
  13473. const p = new torch._C.Parser(new torch._C.Source(replacement_type));
  13474. const typename_expr = p.parseExp();
  13475. return new ast.AnnAssign(lhs, typename_expr, assign.value, lhs instanceof ast.Name);
  13476. }
  13477. }
  13478. return null;
  13479. }
  13480. LEGACY_import_methods(mod, src) {
  13481. const self = new torch._C.SimpleSelf(mod.type());
  13482. const prefix = mod.type().name();
  13483. const p = new torch._C.Parser(src);
  13484. const L = p.parse();
  13485. this.parsePossibleVersionNumber(L);
  13486. this.parseImports(L);
  13487. const definitions = [];
  13488. const resolvers = [];
  13489. for (const def of L.body) {
  13490. if (def instanceof ast.FunctionDef) {
  13491. definitions.push(def);
  13492. resolvers.push(this);
  13493. }
  13494. }
  13495. this._cu.define(prefix, /*properties=*/[], /*propResolvers=*/[], definitions, resolvers, self);
  13496. }
  13497. findFunction(name) {
  13498. this.parseSourceIfNeeded(name.prefix());
  13499. const key = name.qualifiedName();
  13500. const it = this._to_be_defined.get(key);
  13501. if (it && it instanceof ast.FunctionDef) {
  13502. this._to_be_defined.delete(key);
  13503. this.importFunction(name.prefix(), it);
  13504. }
  13505. return this._cu.find_function(name);
  13506. }
  13507. });
  13508. this.registerType('torch._C.FunctionResolver', class extends torch._C.Resolver {
  13509. constructor(otherResolver, functionTable) {
  13510. super();
  13511. this._otherResolver = otherResolver;
  13512. this._functionTable = functionTable;
  13513. }
  13514. resolveValue(name, m, loc) {
  13515. const it = this._functionTable.get(name);
  13516. if (it) {
  13517. return new torch._C.FunctionValue(it);
  13518. }
  13519. return this._otherResolver.resolveValue(name, m, loc);
  13520. }
  13521. resolveType(name, loc) {
  13522. return this._otherResolver.resolveType(name, loc);
  13523. }
  13524. });
  13525. this.registerType('torch._C.SourceRangeDeserializer', class {
  13526. constructor(text_table) {
  13527. this.cached_sources = new Map();
  13528. this._text_table = text_table || [];
  13529. }
  13530. deserialize(iv) {
  13531. torch._C.TORCH_INTERNAL_ASSERT(iv.length === 3);
  13532. const [file, start, end] = iv;
  13533. const source = this.deserialize_source(file);
  13534. return new torch._C.SourceRange(source, start, end);
  13535. }
  13536. deserialize_source(iv) {
  13537. const tup = iv;
  13538. if (this.cached_sources.has(tup)) {
  13539. return this.cached_sources.get(tup);
  13540. }
  13541. let source = null;
  13542. const tup_elems = tup;
  13543. torch._C.TORCH_INTERNAL_ASSERT(tup_elems.length === 3);
  13544. if (this._text_table.length > 0) {
  13545. const [textIndex, fnameIndex, starting_line_no] = tup_elems;
  13546. torch._C.TORCH_CHECK(fnameIndex < this._text_table.length);
  13547. const filename = this._text_table[fnameIndex];
  13548. const pieces = [];
  13549. const strs = [];
  13550. for (const i of textIndex) {
  13551. pieces.push(this._text_table[i]);
  13552. strs.push(this._text_table[i]);
  13553. }
  13554. // const str_cord = new torch._C.StringCordView(pieces, strs);
  13555. source = new torch._C.Source(pieces.join(''), filename, starting_line_no);
  13556. } else {
  13557. const [text, filename, starting_line_no] = tup_elems;
  13558. source = new torch._C.Source(text, filename, starting_line_no);
  13559. }
  13560. this.cached_sources.set(tup, source);
  13561. return source;
  13562. }
  13563. });
  13564. this.registerType('torch._C.SourceRangeUnpickler', class {
  13565. });
  13566. this.registerType('torch._C.ConcreteSourceRangeUnpickler', class extends torch._C.SourceRangeUnpickler {
  13567. constructor (data) {
  13568. super();
  13569. this.data = data;
  13570. this.deserializer = null;
  13571. this.unpickled_records = null;
  13572. }
  13573. unpickle() {
  13574. if (this.unpickled_records) {
  13575. return;
  13576. }
  13577. const unpickler = new pickle.Unpickler(this.data);
  13578. const ivalues = unpickler.load();
  13579. torch._C.TORCH_CHECK(ivalues.length > 0);
  13580. this.unpickled_records = [];
  13581. let lines = null;
  13582. if (ivalues[0] === 'FORMAT_WITH_STRING_TABLE') {
  13583. this.deserializer = new torch._C.SourceRangeDeserializer(ivalues[1]);
  13584. lines = ivalues[2];
  13585. } else {
  13586. this.deserializer = new torch._C.SourceRangeDeserializer();
  13587. lines = ivalues;
  13588. }
  13589. for (const tup_elems of lines) {
  13590. const [offset, range] = tup_elems;
  13591. const source_range = this.deserializer.deserialize(range);
  13592. this.unpickled_records.push([offset, source_range]);
  13593. }
  13594. }
  13595. findSourceRangeThatGenerated(range) {
  13596. this.unpickle();
  13597. const start = range.start();
  13598. const records = this.unpickled_records;
  13599. for (let i = 0; i < records.length; i++) {
  13600. const [offset, target] = records[i];
  13601. const next = i < records.length - 1 ? records[i + 1][0] : range.source().size();
  13602. if (start >= offset && start < next) {
  13603. return target;
  13604. }
  13605. }
  13606. return null;
  13607. }
  13608. });
  13609. this.registerFunction('torch._C.qualifierToArchivePath', (qualifier, export_prefix) => {
  13610. return `${export_prefix}${qualifier.replace(/\./g, '/')}.py`;
  13611. });
  13612. this.registerFunction('torch._C.findSourceInArchiveFromQualifier', (reader, export_prefix, qualifier) =>{
  13613. const path = torch._C.qualifierToArchivePath(qualifier, export_prefix);
  13614. if (!reader.has_record(path)) {
  13615. return null;
  13616. }
  13617. const stream = reader.get_record(path);
  13618. let gen_ranges = null;
  13619. const debug_file = `${path}.debug_pkl`;
  13620. if (reader.has_record(debug_file)) {
  13621. const debug_stream = reader.get_record(debug_file);
  13622. gen_ranges = new torch._C.ConcreteSourceRangeUnpickler(debug_stream.peek());
  13623. }
  13624. return new torch._C.Source(stream.peek(), path, 1, gen_ranges);
  13625. });
  13626. this.registerType('torch._C.ScriptModuleDeserializer', class {
  13627. constructor(cu, reader, pickle_dir_prefix, tensor_dir_prefix, storage_context) {
  13628. this._compilation_unit = cu;
  13629. this._reader = reader;
  13630. this._storage_context = storage_context;
  13631. this._code_prefix = !pickle_dir_prefix && !tensor_dir_prefix ? 'code/' : '.data/ts_code/code/';
  13632. this._pickle_dir_prefix = pickle_dir_prefix || '';
  13633. this._tensor_dir_prefix = tensor_dir_prefix || '';
  13634. this._constant_table = [];
  13635. const SourceLoader = (qualifier) => {
  13636. return torch._C.findSourceInArchiveFromQualifier(this._reader, this._code_prefix, qualifier);
  13637. };
  13638. this._source_importer = new torch._C.SourceImporter(this._compilation_unit, this._constant_table, SourceLoader, reader.version());
  13639. }
  13640. deserialize() {
  13641. const execution = this._compilation_unit.execution;
  13642. const code_prefix = this._code_prefix;
  13643. for (const name of this._reader.get_all_records()) {
  13644. if (name.startsWith(code_prefix) && name.endsWith('.py')) {
  13645. const file = name.substring(code_prefix.length);
  13646. const stream = this._reader.get_record(name);
  13647. const buffer = stream.peek();
  13648. execution.add(file, buffer);
  13649. }
  13650. }
  13651. const torch = execution.import('torch');
  13652. execution.builtins.torch = torch;
  13653. execution.builtins.Tensor = torch.Tensor;
  13654. execution.builtins.ops = torch.ops;
  13655. execution.builtins.inf = torch.inf;
  13656. execution.builtins.CONSTANTS = {};
  13657. execution._resolver = this._source_importer;
  13658. if (this._reader.has_record('model.json')) {
  13659. return this.LEGACY_deserialize();
  13660. }
  13661. const constants = this.readArchive('constants');
  13662. for (let i = 0; i < constants.length; i++) {
  13663. let val = constants[i];
  13664. if (val && val.__class__ && val.__class__.__module__.startsWith('__torch__.torch.classes.')) {
  13665. const type = this._source_importer.resolveType(`${val.__class__.__module__}.${val.__class__.__name__}`);
  13666. const obj = torch.ScriptObject.create(type);
  13667. obj._ivalue = val;
  13668. val = obj;
  13669. }
  13670. execution.builtins.CONSTANTS[`c${i}`] = val;
  13671. this._constant_table.push(val);
  13672. }
  13673. const obj = this.readArchive('data');
  13674. const convertObject = (obj) => {
  13675. if (obj.__class__) {
  13676. const name = `${obj.__class__.__module__}.${obj.__class__.__name__}`;
  13677. const type = this._source_importer.loadType(new torch._C.QualifiedName(name));
  13678. const module = type.is_module() ? new torch.ScriptModule(type, this._compilation_unit) : new torch.ScriptObject(type);
  13679. for (let i = 0; i < type.numAttributes(); i++) {
  13680. const k = type.getAttributeName(i);
  13681. const t = type.getAttribute(i);
  13682. const v = obj[k];
  13683. if (t instanceof torch.ClassType) {
  13684. module.__setattr__(k, convertObject(v));
  13685. } else {
  13686. if (t instanceof torch.TensorType && v && v.__class__ && v instanceof torch.Tensor === false && v.__class__.__module__ === '__torch__.torch.classes.quantized') {
  13687. const name = `${v.__class__.__module__}.${v.__class__.__name__}`;
  13688. type._attributes[i].type = this._source_importer.resolveType(name);
  13689. }
  13690. module.__setattr__(k, obj[k]);
  13691. }
  13692. }
  13693. for (const [key, value] of Object.entries(Object.getPrototypeOf(obj))) {
  13694. if (value && value.__class__ === builtins.method) {
  13695. module[key] = value;
  13696. }
  13697. }
  13698. return module;
  13699. }
  13700. throw new python.Error('Module class not found.');
  13701. };
  13702. return convertObject(obj);
  13703. }
  13704. LEGACY_deserialize() {
  13705. // https://github.com/pytorch/pytorch/blob/5e69e11d098a2cfccc8a59377c431e9c71cab9a8/torch/csrc/jit/serialization/import_legacy.cpp#L88
  13706. const execution = this._compilation_unit.execution;
  13707. const caffe2 = execution.proto.caffe2;
  13708. const torch = execution.import('torch');
  13709. const stream = this._reader.get_record('model.json');
  13710. const buffer = stream.peek();
  13711. const decoder = new TextDecoder('utf-8');
  13712. const content = decoder.decode(buffer);
  13713. const obj = JSON.parse(content);
  13714. const model = execution.proto.torch.ModelDef.decodeJson(obj);
  13715. const tensorTypeMap = new Map([
  13716. [caffe2.TensorProto.DataType.FLOAT, 'Float'],
  13717. [caffe2.TensorProto.DataType.FLOAT16, 'Half'],
  13718. [caffe2.TensorProto.DataType.DOUBLE, 'Double'],
  13719. [caffe2.TensorProto.DataType.INT8, 'Char'],
  13720. [caffe2.TensorProto.DataType.INT32, 'Int'],
  13721. [caffe2.TensorProto.DataType.INT64, 'Long']
  13722. ]);
  13723. const tensor_table = (model.tensors || []).map((constant) => {
  13724. const key = constant.data.key;
  13725. if (!tensorTypeMap.has(constant.data_type)) {
  13726. throw new python.Error(`Unsupported tensor data type '${constant.data_type}'.`);
  13727. }
  13728. const type = tensorTypeMap.get(constant.data_type);
  13729. const shape = constant.dims ? constant.dims.map((dim) => parseInt(dim, 10)) : null;
  13730. const strides = constant.strides ? constant.strides.map((dim) => parseInt(dim, 10)) : null;
  13731. const storage_type = execution.resolve(`torch.${type}Storage`);
  13732. const size = (shape || []).reduce((a, b) => a * b, 1);
  13733. const offset = parseInt(constant.offset, 10) || 0;
  13734. const storage = new storage_type(size);
  13735. const itemsize = storage.dtype.itemsize();
  13736. const stream = this._reader.get_record(key);
  13737. if (stream) {
  13738. const buffer = stream.peek();
  13739. const length = size * itemsize;
  13740. const data = buffer.slice(offset, offset + length);
  13741. storage._set_cdata(data);
  13742. }
  13743. const tensor = torch._utils._rebuild_tensor(storage, 0, shape, strides);
  13744. tensor.name = key;
  13745. return tensor;
  13746. });
  13747. execution.builtins.CONSTANTS = {};
  13748. for (let i = 0; i < tensor_table.length; i++) {
  13749. execution.builtins.CONSTANTS[`c${i}`] = tensor_table[i];
  13750. }
  13751. const attributes = [];
  13752. if (this._reader.has_record('attributes.pkl')) {
  13753. const stream = this._reader.get_record('attributes.pkl');
  13754. const buffer = stream.peek();
  13755. const unpickler = new pickle.Unpickler(buffer);
  13756. const obj = unpickler.load();
  13757. attributes.push(...obj);
  13758. }
  13759. this._LEGACY_moduleStack = ['__torch__'];
  13760. const module_def = model.main_module;
  13761. for (const tensor of tensor_table) {
  13762. this._constant_table.push(tensor);
  13763. }
  13764. return this.LEGACY_convertModule(module_def);
  13765. }
  13766. LEGACY_convertModule(module_def) {
  13767. const atoms = new torch._C.QualifiedName(module_def.name).atoms();
  13768. const numPushed = atoms.length;
  13769. for (const atom of atoms) {
  13770. const sanitized = /^\d+$/.test(atom) ? `_${atom}` : atom;
  13771. this._LEGACY_moduleStack.push(sanitized);
  13772. }
  13773. const qn = new torch._C.QualifiedName(this._LEGACY_moduleStack);
  13774. const module = new torch.ScriptModule(qn, this._compilation_unit);
  13775. for (const sub_def of module_def.submodules || []) {
  13776. const submodule = this.LEGACY_convertModule(sub_def);
  13777. module.register_module(sub_def.name, submodule);
  13778. }
  13779. for (const param_def of module_def.parameters || []) {
  13780. const tensor = this._constant_table[Number(param_def.tensor_id)];
  13781. if (param_def.isBuffer) {
  13782. module.register_buffer(param_def.name, tensor);
  13783. } else {
  13784. module.register_parameter(param_def.name, tensor, false);
  13785. }
  13786. }
  13787. // const typeParser = new torch._C.ScriptTypeParser(this._source_importer);
  13788. for (const attr_def of module_def.attributes || []) {
  13789. if (module.hasattr(attr_def.name)) {
  13790. continue;
  13791. }
  13792. throw new python.Error('Not implemented.');
  13793. // IValue ivalue;
  13794. // if (attr_def.id() >= 0) {
  13795. // ivalue = LEGACY_pickled_ivalues_.at(attr_def.id());
  13796. // }
  13797. // module.register_attribute(attr_def.name, typeParser.parseType(attr_def.type), ivalue);
  13798. }
  13799. if (module_def.torchscript_arena) {
  13800. const key = module_def.torchscript_arena.key;
  13801. const file = key.substring('code/'.length);
  13802. const name = file.replace(/\.py$/, '').split('/').join('.');
  13803. const code = execution.import(name);
  13804. if (code.forward.__class__ === execution.builtins.function) {
  13805. module.forward = code.forward;
  13806. }
  13807. }
  13808. // let gen_ranges = null;
  13809. if (module_def.torchscript_debug_arena) {
  13810. throw new python.Error('Not implemented.');
  13811. //const [data, size] = reader_->getRecord(module_def.torchscript_debug_arena().key());
  13812. //gen_ranges = std::make_shared<ConcreteSourceRangeUnpickler>(std::move(data), size);
  13813. }
  13814. if (module_def.torchscript_arena) {
  13815. const filename = module_def.torchscript_arena.key;
  13816. const stream = this._reader.get_record(filename);
  13817. const data = stream.peek();
  13818. const src = new torch._C.Source(data, filename);
  13819. this._source_importer.LEGACY_import_methods(module, src);
  13820. }
  13821. if (module_def.get_state_attribute_id) {
  13822. throw new python.Error('Not implemented.');
  13823. // LEGACY_moduleSetState(module, LEGACY_pickled_ivalues_.at(module_def.get_state_attribute_id()));
  13824. }
  13825. /*
  13826. const module_type = module._ivalue().type();
  13827. const N = module_type.numAttributes();
  13828. for (let i = 0; i < N; ++i) {
  13829. const v = module._ivalue().getSlot(i);
  13830. if (module_type.getAttribute(i) instanceof torch.OptionalType === false) {
  13831. torch._C.TORCH_CHECK(!v.isNone());
  13832. }
  13833. }
  13834. */
  13835. for (let i = 0; i < numPushed; i++) {
  13836. this._LEGACY_moduleStack.pop();
  13837. }
  13838. return module;
  13839. }
  13840. readArchive(archive_name) {
  13841. const type_resolver = (qn) => {
  13842. const cls = this._source_importer.loadType(qn);
  13843. return cls;
  13844. };
  13845. const ObjLoaderFunc = (/* type, ivalue */) => {
  13846. };
  13847. return this.readArchiveAndTensors(archive_name, this._pickle_dir_prefix, this._tensor_dir_prefix, type_resolver, ObjLoaderFunc, this._device, this._reader, null, this._storage_context);
  13848. }
  13849. readArchiveAndTensors(archive_name, pickle_prefix, tensor_prefix, type_resolver, obj_loader, device, stream_reader, type_parser, storage_context) {
  13850. const picklename = `${pickle_prefix + archive_name}.pkl`;
  13851. const stream = stream_reader.get_record(picklename);
  13852. if (!stream) {
  13853. throw new python.Error(`File '${picklename}' is not found.`);
  13854. }
  13855. const buffer = stream.peek();
  13856. const tensor_dir_path = tensor_prefix ? tensor_prefix : `${archive_name}/`;
  13857. const read_record = (name) => {
  13858. const stream = stream_reader.get_record(tensor_dir_path + name);
  13859. return stream.length <= 0x40000 ? stream.peek() : stream;
  13860. };
  13861. const execution = this._compilation_unit.execution;
  13862. const pickle = execution.__import__('pickle');
  13863. const Unpickler = class extends pickle.Unpickler {
  13864. find_class(module, name) {
  13865. return super.find_class(module, name);
  13866. }
  13867. };
  13868. const unpickler = new Unpickler(buffer);
  13869. unpickler.persistent_load = (saved_id) => {
  13870. if (saved_id[0] !== 'storage') {
  13871. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  13872. }
  13873. const [, storage_type, key, , size] = saved_id;
  13874. if (storage_context && storage_context.has_storage(key)) {
  13875. return storage_context.get_storage(key);
  13876. }
  13877. const storage = new storage_type(size);
  13878. if (!storage._set_cdata) {
  13879. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  13880. }
  13881. const storage_ptr = read_record(key);
  13882. storage._set_cdata(storage_ptr);
  13883. if (storage_context) {
  13884. storage_context.add_storage(key);
  13885. }
  13886. return storage;
  13887. };
  13888. return unpickler.load();
  13889. }
  13890. });
  13891. this.registerType('torch._C.WithInsertPoint', class {
  13892. constructor(...args) {
  13893. let n = null;
  13894. if (args.length === 1 && args[0] instanceof torch.Block) {
  13895. const [b] = args;
  13896. n = b.return_node();
  13897. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  13898. [n] = args;
  13899. } else {
  13900. throw new python.Error('Invalid arguments.');
  13901. }
  13902. this._prev = n.owningGraph().insertPoint();
  13903. n.owningGraph().setInsertPoint(n);
  13904. }
  13905. dispose() {
  13906. this._prev.owningGraph().setInsertPoint(this._prev);
  13907. }
  13908. });
  13909. this.registerType('torch._C.Environment', class {
  13910. constructor(method, resolver, b, next) {
  13911. this.method = method;
  13912. this.resolver = resolver;
  13913. this.b = b;
  13914. this.next = next;
  13915. this.value_table = new Map();
  13916. this.type_table = new Map();
  13917. this.error_messages = new Map();
  13918. }
  13919. setVariableTypeError(name, msg) {
  13920. /* eslint-disable consistent-this */
  13921. let runner = this;
  13922. /* eslint-enable consistent-this */
  13923. while (runner.next) {
  13924. runner = runner.next;
  13925. }
  13926. runner.error_messages.set(name, msg);
  13927. }
  13928. insertLoad(name, type) {
  13929. const g = this.b.owningGraph();
  13930. const load = g.insertNode(g.createLoad(name, type));
  13931. if (torch._C.meaningfulName(name)) {
  13932. load.output().setDebugName(name);
  13933. }
  13934. return new torch._C.SimpleValue(load.output());
  13935. }
  13936. insertStore(name, loc, v, type) {
  13937. const g = this.b.owningGraph();
  13938. g.insertNode(g.createStore(name, v)).setSourceRange(loc);
  13939. this.type_table.set(name, type);
  13940. }
  13941. findInThisFrame(name) {
  13942. if (this.value_table.has(name)) {
  13943. return this.value_table.get(name);
  13944. }
  13945. if (this.type_table.has(name)) {
  13946. return this.insertLoad(name, this.type_table.get(name));
  13947. }
  13948. return null;
  13949. }
  13950. findInParentFrame(name) {
  13951. return this.next ? this.next.findInAnyFrame(name) : null;
  13952. }
  13953. setType(name, type) {
  13954. this.type_table.set(name, type);
  13955. }
  13956. findInAnyFrame(name) {
  13957. /* eslint-disable consistent-this */
  13958. const self = this;
  13959. /* eslint-enable consistent-this */
  13960. for (let runner = self; runner; runner = runner.next) {
  13961. const r = runner.findInThisFrame(name);
  13962. if (r) {
  13963. return r;
  13964. }
  13965. }
  13966. return null;
  13967. }
  13968. block() {
  13969. return this.b;
  13970. }
  13971. setVar(loc, name, value) {
  13972. this.setSugaredVar(loc, name, new torch._C.SimpleValue(value), null);
  13973. }
  13974. setSugaredVar(loc, name, value, annotated_type) {
  13975. let as_simple_value = torch._C.asSimple(value);
  13976. if (as_simple_value && !as_simple_value.hasDebugName() && torch._C.meaningfulName(name) && as_simple_value.node().owningBlock() === this.block()) {
  13977. as_simple_value.setDebugName(name);
  13978. }
  13979. const parent = this.findInParentFrame(name);
  13980. if (parent) {
  13981. if (annotated_type) {
  13982. throw new python.Error('Type already defined in an outer block.');
  13983. }
  13984. if (!as_simple_value) {
  13985. throw new python.Error('Only reassignments to first-class values are allowed.');
  13986. }
  13987. const simple_parent = torch._C.asSimple(parent);
  13988. if (!simple_parent) {
  13989. throw new python.Error('Only reassignments to first-class values are allowed.');
  13990. }
  13991. const parent_type = torch._C.unshapedType(simple_parent.type());
  13992. as_simple_value = torch._C.tryConvertToType(loc, this.b.owningGraph(), parent_type, as_simple_value, /*allow_conversions=*/true);
  13993. if (!as_simple_value.type().isSubtypeOf(parent_type)) {
  13994. throw new python.Error('Incompatible types.');
  13995. }
  13996. }
  13997. if (as_simple_value) {
  13998. if (annotated_type && !as_simple_value.type().isSubtypeOf(annotated_type)) {
  13999. throw new python.Error('Invalid type.');
  14000. }
  14001. const value_store_type = annotated_type ? annotated_type : as_simple_value.type();
  14002. this.insertStore(name, loc, as_simple_value, value_store_type);
  14003. } else {
  14004. this.value_table.set(name, value);
  14005. }
  14006. }
  14007. getSugaredVar(ident, range, required) {
  14008. required = required || true;
  14009. let retval = this.findInAnyFrame(ident);
  14010. if (!retval) {
  14011. torch._C.Environment.globals = torch._C.Environment.globals || new Map([
  14012. ['print', new torch._C.PrintValue()],
  14013. ['tuple', torch._C.SpecialFormValue.create('prim::TupleConstruct')],
  14014. ['float', new torch._C.MagicMethod('__float__', new torch._C.CastValue(torch.FloatType.get(), 'aten::Float'))],
  14015. ['int', new torch._C.MagicMethod('__int__', new torch._C.CastValue(torch.IntType.get(), 'aten::Int'))],
  14016. ['bool', new torch._C.MagicMethod('__bool__', new torch._C.CastValue(torch.BoolType.get(), 'aten::Bool'))],
  14017. ['str', new torch._C.MagicMethod('__str__', new torch._C.CastValue(torch.StringType.get(), 'aten::str'))],
  14018. ['getattr', torch._C.SpecialFormValue.create('prim::GetAttr')],
  14019. ['hasattr', torch._C.SpecialFormValue.create('prim::HasAttr')],
  14020. ['isinstance', torch._C.SpecialFormValue.create('prim::isinstance')],
  14021. ['range', torch._C.SpecialFormValue.create('prim::range')],
  14022. ['sorted', new torch._C.BuiltinFunction('aten::sorted', null)],
  14023. ]);
  14024. if (torch._C.Environment.globals.has(ident)) {
  14025. retval = torch._C.Environment.globals.get(ident);
  14026. }
  14027. }
  14028. if (!retval) {
  14029. const type = this.resolver.resolveType(ident, range);
  14030. if (type instanceof torch.TupleType) {
  14031. retval = new torch.jit.NamedTupleConstructor(type);
  14032. }
  14033. }
  14034. if (!retval) {
  14035. retval = this.resolver.resolveValue(ident, this.method, range);
  14036. }
  14037. if (!retval) {
  14038. const type = this.resolver.resolveType(ident, range);
  14039. if (type instanceof torch.ClassType) {
  14040. retval = new torch.jit.ClassValue(type);
  14041. }
  14042. }
  14043. if (!retval && required) {
  14044. throw new python.Error(`The name '${ident}' is not defined.`);
  14045. }
  14046. return retval;
  14047. }
  14048. getVar(ident, range) {
  14049. return this.getSugaredVar(ident, range).asValue(range, this.method);
  14050. }
  14051. definedVariables() {
  14052. return Array.from(this.type_table.keys());
  14053. }
  14054. });
  14055. this.registerType('torch._C.Refinement', class {
  14056. constructor(identifier, type) {
  14057. this._identifier = identifier;
  14058. this._type = type;
  14059. }
  14060. identifier() {
  14061. return this._identifier;
  14062. }
  14063. type() {
  14064. return this._type;
  14065. }
  14066. });
  14067. this.registerType('torch._C.RefinementSet', class {
  14068. constructor(...args) {
  14069. if (args.length === 1 && args[0] instanceof torch._C.Refinement) {
  14070. this._true_refinements = [args[0]];
  14071. this._false_refinements = [];
  14072. } else if (args.length === 2 && args[0] instanceof torch._C.Refinement && args[1] instanceof torch._C.Refinement) {
  14073. this._true_refinements = [args[0]];
  14074. this._false_refinements = [args[1]];
  14075. } else if (args.length === 2 && Array.isArray(args[0]) && Array.isArray(args[1])) {
  14076. [this._true_refinements, this._false_refinements] = args;
  14077. } else {
  14078. throw new python.Error('Not implemented.');
  14079. }
  14080. }
  14081. Not() {
  14082. return new torch._C.RefinementSet(this._false_refinements, this._true_refinements);
  14083. }
  14084. activeRefinements() {
  14085. return this._true_refinements;
  14086. }
  14087. });
  14088. this.registerFunction('torch._C.CondValue', class {
  14089. constructor(...args) {
  14090. if (args.length === 3) {
  14091. [this._value, this._refinements, this._static_if] = args;
  14092. } else if (args.length === 4) {
  14093. const [g, loc, static_value, refinements] = args;
  14094. this._value = g.insertConstant(static_value, loc);
  14095. this._refinements = refinements;
  14096. this._static_if = static_value;
  14097. } else {
  14098. throw new python.Error('Invalid number of arguments.');
  14099. }
  14100. }
  14101. value() {
  14102. return this._value;
  14103. }
  14104. staticIf() {
  14105. return this._static_if;
  14106. }
  14107. refinements() {
  14108. return this._refinements;
  14109. }
  14110. });
  14111. this.registerFunction('torch._C.asSimple', (value) => {
  14112. if (value instanceof torch._C.SimpleValue) {
  14113. return value.getValue();
  14114. }
  14115. return null;
  14116. });
  14117. this.registerFunction('torch._C.isNumber', (str) => {
  14118. return /^[0-9]+$/.test(str);
  14119. });
  14120. this.registerFunction('torch._C.normalizeAttrName', (field) => {
  14121. if (torch._C.isNumber(field)) {
  14122. return `_${field}`;
  14123. }
  14124. return field;
  14125. });
  14126. this.registerFunction('torch._C.meaningfulName', (name) => {
  14127. if (name.length === 0) {
  14128. return false;
  14129. }
  14130. if (name[0] === '$') {
  14131. return false;
  14132. }
  14133. if (name[0] !== '_') {
  14134. return true;
  14135. }
  14136. return !/\d+/.test(name.slice(1));
  14137. });
  14138. this.registerFunction('torch._C.materializeConstant', (val, graph, r, map) => {
  14139. const key = `${val.value}:${val.tag}`;
  14140. const existing_constant = map.get(key);
  14141. if (existing_constant) {
  14142. return existing_constant;
  14143. }
  14144. const guard = new torch._C.WithInsertPoint(graph.block().nodes().front());
  14145. const new_constant = graph.insertConstant(val, r);
  14146. map.set(key, new_constant);
  14147. guard.dispose();
  14148. return new_constant;
  14149. });
  14150. this.registerFunction('torch._C.getFullSchemaName', (schema) => {
  14151. if (schema.overload_name) {
  14152. return `${schema.name}.${schema.overload_name}`;
  14153. }
  14154. return schema.name;
  14155. });
  14156. this.registerFunction('torch._C.insertGraph', (g, callee, inputs, value_map) => {
  14157. const value_map_func = (v) => value_map.get(v);
  14158. torch._C.AT_ASSERT(callee.inputs().length === inputs.length);
  14159. for (let i = 0; i < inputs.length; i++) {
  14160. value_map.set(callee.inputs()[i], inputs[i]);
  14161. }
  14162. for (const node of callee.nodes()) {
  14163. const new_node = g.insertNode(g.createClone(node, value_map_func));
  14164. for (let i = 0; i < node.outputs().length; i++) {
  14165. value_map.set(node.outputs()[i], new_node.outputs()[i]);
  14166. }
  14167. }
  14168. const outputs = [];
  14169. for (const output of callee.outputs()) {
  14170. outputs.push(value_map_func(output));
  14171. }
  14172. return outputs;
  14173. });
  14174. this.registerType('TemplateEnv', class {
  14175. });
  14176. this.registerType('torch._C.BuiltinFunctionRegistry', class {
  14177. constructor() {
  14178. this.state = 'UNINITIALIZED';
  14179. this._builtins_by_name = new Map();
  14180. }
  14181. getAllBuiltinFunctionsFor(name) {
  14182. if (this.state === 'UNINITIALIZED') {
  14183. this.loadBuiltinFunctions();
  14184. this.state = 'INITIALIZED';
  14185. }
  14186. if (!this._builtins_by_name.has(name)) {
  14187. return [];
  14188. }
  14189. return this._builtins_by_name.get(name);
  14190. }
  14191. loadBuiltinFunctions() {
  14192. /*
  14193. for (const scalar of ['float', 'int', 'complex']) {
  14194. const env = new torch.C.TemplateEnv();
  14195. env.s('Scalar', scalar);
  14196. this.loadSource(scalar_operators_source.format(env), 'aten');
  14197. }
  14198. for (const scalar of ['float', 'int']) {
  14199. const env = new torch.C.TemplateEnv();
  14200. env.s('Scalar', scalar);
  14201. loadSource(scalar_operators_no_complex_source.format(env), 'aten');
  14202. }
  14203. using str_pair = std::pair<std::string, std::string>;
  14204. const std::vector<str_pair> name_len = {
  14205. str_pair('single', '1'),
  14206. str_pair('pair', '2'),
  14207. str_pair('triple', '3'),
  14208. str_pair('quadruple', '4'),
  14209. };
  14210. for (const auto scalar : {'float', 'int'}) {
  14211. for (const auto& pair : name_len) {
  14212. const env = new torch.C.TemplateEnv();
  14213. env.s('Scalar', scalar);
  14214. env.s('name', pair.first);
  14215. env.s('Length', pair.second);
  14216. this.loadSource(_ntuple_ops.format(env), 'aten');
  14217. }
  14218. }
  14219. for (auto rhs : {'number', 'Tensor'}) {
  14220. at::jit::TemplateEnv env;
  14221. env.s('Rhs_Type', rhs);
  14222. this.loadSource(floordiv.format(env), 'aten');
  14223. }
  14224. this.loadSource(aten_ops, 'aten');
  14225. this.loadSource(aten_ops_additional, 'aten');
  14226. this.loadSource(tensor_properties, 'prim');
  14227. */
  14228. }
  14229. loadSource(/* source, the_namespace */) {
  14230. }
  14231. });
  14232. this.registerFunction('torch._C.getAllBuiltinFunctionsFor', (name) => {
  14233. torch._C.registry = torch._C.registry || new torch._C.BuiltinFunctionRegistry();
  14234. return torch._C.registry.getAllBuiltinFunctionsFor(name);
  14235. });
  14236. this.registerFunction('torch._C.get_operator_version_map', () => {
  14237. return new Map();
  14238. });
  14239. this.registerFunction('torch._C.varargsCanBeUsedAsList', (schema, arg_index, arg) => {
  14240. const is_last_argument = arg_index + 1 === schema.arguments.length || schema.arguments[arg_index + 1].kwarg_only;
  14241. let arg_type = arg.type;
  14242. if (arg_type instanceof torch._C.DynamicType) {
  14243. arg_type = arg_type.fallback();
  14244. }
  14245. const argument_is_list = arg_type instanceof torch.ListType;
  14246. const typevar_list = argument_is_list && arg_type.getElementType() instanceof torch._C.VarType;
  14247. const arg_is_broadcasting_list = arg.N > 0;
  14248. return is_last_argument && argument_is_list && !arg_is_broadcasting_list && !typevar_list;
  14249. });
  14250. this.registerFunction('torch._C.isBlockListedSchema', (schema) => {
  14251. if ((schema.name === 'aten::view' && schema.overload_name === 'dtype') ||
  14252. (schema.name === 'aten::max' && schema.overload_name === 'unary_out') ||
  14253. (schema.name === 'aten::min' && schema.overload_name === 'unary_out')) {
  14254. return true;
  14255. }
  14256. return false;
  14257. });
  14258. this.registerFunction('torch._C.unwrapOptional', (opt_type) => {
  14259. if (opt_type instanceof torch._C.DynamicType) {
  14260. return torch._C.unwrapOptional(opt_type.fallback());
  14261. }
  14262. if (opt_type instanceof torch.OptionalType) {
  14263. return opt_type.getElementType();
  14264. }
  14265. return opt_type;
  14266. });
  14267. this.registerFunction('torch._C.loadPossibleHistoricOps', (name, version) => {
  14268. const possibleSchemas = [];
  14269. if (version === undefined) {
  14270. return possibleSchemas;
  14271. }
  14272. for (const entry of torch._C.get_operator_version_map()) {
  14273. const old_symbol_name = entry.first;
  14274. const base_name = old_symbol_name.substring(0, old_symbol_name.find('.'));
  14275. if (base_name === name) {
  14276. const possibleUpgrader = torch._C.findUpgrader(entry.second, version.value());
  14277. if (possibleUpgrader.has_value()) {
  14278. possibleSchemas.push_back(possibleUpgrader.value().old_schema);
  14279. }
  14280. }
  14281. }
  14282. return possibleSchemas;
  14283. });
  14284. this.registerFunction('torch._C.isOpCurrentBasedOnUpgraderEntries', (upgraders_for_schema, current_version) => {
  14285. const latest_update = upgraders_for_schema[upgraders_for_schema.length - 1].bumped_at_version;
  14286. return current_version < latest_update;
  14287. });
  14288. this.registerFunction('torch._C.isOpSymbolCurrent', (name, current_version) => {
  14289. const it = torch._C.get_operator_version_map().get(name);
  14290. if (it) {
  14291. return torch._C.isOpCurrentBasedOnUpgraderEntries(it, current_version);
  14292. }
  14293. return true;
  14294. });
  14295. this.registerFunction('torch._C.packOutputs', (g, values, field_names) => {
  14296. if (values.length === 1) {
  14297. return values[0];
  14298. }
  14299. let named_tuple = null;
  14300. if (field_names) {
  14301. const types = values.map((v) => v.type());
  14302. named_tuple = torch.TupleType.createNamed(null, field_names.value(), types);
  14303. }
  14304. return g.insertNode(g.createTuple(values, named_tuple)).output();
  14305. });
  14306. this.registerFunction('torch._C.isIntOrFloatUsedAsList', (value, arg) => {
  14307. const v_type = value.type();
  14308. if (v_type !== torch.FloatType.get() && v_type !== torch.IntType.get()) {
  14309. return false;
  14310. }
  14311. const arg_type = torch._C.unwrapOptional(arg.type);
  14312. return arg_type instanceof torch.ListType && arg_type.getElementType() === v_type && arg.N;
  14313. });
  14314. this.registerFunction('torch._C.convertibleToList', (type, list_type_) => {
  14315. const list_type = list_type_;
  14316. if (list_type instanceof torch.ListType === false) {
  14317. return false;
  14318. }
  14319. if (type.isSubtypeOf(list_type_)) {
  14320. return true;
  14321. }
  14322. if (type instanceof torch.TupleType) {
  14323. return type.elements().every((t) => t.isSubtypeOf(list_type.getElementType()));
  14324. }
  14325. return false;
  14326. });
  14327. this.registerFunction('torch._C.findInputWithName', (name, kwargs, is_aten) => {
  14328. for (let i = 0; i < kwargs.length; i++) {
  14329. if (is_aten && name === 'self' && kwargs[i].name() === 'input') {
  14330. return i;
  14331. }
  14332. if (kwargs[i].name() === name) {
  14333. return i;
  14334. }
  14335. }
  14336. return null;
  14337. });
  14338. this.registerFunction('torch._C.tryCreateList', (elem_type, graph, loc, varargs, failure_messages, err, convert_tensor_to_num, type_env) => {
  14339. const elem_arg = new torch.Argument('<varargs>', elem_type);
  14340. const list_elements = [];
  14341. for (const named_value of varargs) {
  14342. const matched_value = torch._C.tryMatchArgument(/*arg=*/elem_arg, graph, loc, named_value, failure_messages, err, /*allow_conversions=*/convert_tensor_to_num, type_env);
  14343. if (!matched_value) {
  14344. return null;
  14345. }
  14346. list_elements.push(matched_value);
  14347. }
  14348. return graph.insertNode(graph.createList(elem_type, list_elements)).output();
  14349. });
  14350. this.registerType('torch._C.MatchTypeReturn', class {
  14351. constructor(reason) {
  14352. this._reason = reason;
  14353. }
  14354. static Success() {
  14355. return new torch._C.MatchTypeReturn(null);
  14356. }
  14357. success() {
  14358. return this._reason === null;
  14359. }
  14360. });
  14361. this.registerFunction('torch._C.matchTypeVariables', (formal, actual, type_env) => {
  14362. if (!formal.hasFreeVariables()) {
  14363. if (formal instanceof torch._C.DynamicType) {
  14364. return torch._C.matchTypeVariables(formal.fallback(), actual, type_env);
  14365. }
  14366. return torch._C.MatchTypeReturn.Success();
  14367. }
  14368. if (formal instanceof torch._C.VarType) {
  14369. const it = type_env.has(formal.name()) ? type_env.get(formal.name()) : null;
  14370. if (it === null) {
  14371. type_env.set(formal.name(), actual);
  14372. return torch._C.MatchTypeReturn.Success();
  14373. } else if (torch._C.unifyTypes(it, actual)) {
  14374. return torch._C.MatchTypeReturn.Success();
  14375. }
  14376. return new torch._C.MatchTypeReturn('Cannot match var.');
  14377. } else if (formal instanceof torch.ListType) {
  14378. if (actual instanceof torch.ListType) {
  14379. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14380. if (!innerMatch.success()) {
  14381. return innerMatch;
  14382. }
  14383. return torch._C.MatchTypeReturn.Success();
  14384. } else if (actual instanceof torch.TupleType) {
  14385. const maybe_tuple_unified = torch._C.unifyTypeList(actual.elements(), '');
  14386. if (maybe_tuple_unified) {
  14387. return torch._C.matchTypeVariables(formal.getElementType(), maybe_tuple_unified, type_env);
  14388. }
  14389. }
  14390. return new torch._C.MatchTypeReturn('Cannot match list.');
  14391. } else if (formal instanceof torch.TupleType) {
  14392. if (actual instanceof torch.TupleType) {
  14393. if (formal.elements().length !== actual.elements().length) {
  14394. return torch._C.MatchTypeReturn('Cannot match tuples of mismatched size.');
  14395. }
  14396. for (let i = 0; i < formal.elements().length; i++) {
  14397. const result = torch._C.matchTypeVariables(formal.elements()[i], actual.elements()[i], type_env);
  14398. if (!result.success()) {
  14399. return result;
  14400. }
  14401. }
  14402. return torch._C.MatchTypeReturn.Success();
  14403. }
  14404. return new torch._C.MatchTypeReturn('Cannot match tuple.');
  14405. } else if (formal instanceof torch.FutureType) {
  14406. if (actual instanceof torch.FutureType) {
  14407. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14408. if (!innerMatch.success()) {
  14409. return innerMatch;
  14410. }
  14411. return torch._C.MatchTypeReturn.Success();
  14412. }
  14413. return new torch._C.MatchTypeReturn('Cannot match future.');
  14414. } else if (formal instanceof torch.AwaitType) {
  14415. if (actual instanceof torch.AwaitType) {
  14416. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14417. if (!innerMatch.success()) {
  14418. return innerMatch;
  14419. }
  14420. return torch._C.MatchTypeReturn.Success();
  14421. }
  14422. return new torch._C.MatchTypeReturn('Cannot match await.');
  14423. } else if (formal instanceof torch.RRefType) {
  14424. if (actual instanceof torch.RRefType) {
  14425. const innerMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14426. if (!innerMatch.success()) {
  14427. return innerMatch;
  14428. }
  14429. return torch._C.MatchTypeReturn.Success();
  14430. }
  14431. return new torch._C.MatchTypeReturn('Cannot match rref.');
  14432. } else if (formal instanceof torch.OptionalType) {
  14433. if (actual instanceof torch.OptionalType) {
  14434. const optionedMatch = torch._C.matchTypeVariables(formal.getElementType(), actual.getElementType(), type_env);
  14435. if (!optionedMatch.success()) {
  14436. return optionedMatch;
  14437. }
  14438. } else if (!actual.isSubtypeOf(torch.NoneType.get())) {
  14439. return torch._C.matchTypeVariables(formal.getElementType(), actual, type_env);
  14440. }
  14441. return torch._C.MatchTypeReturn.Success();
  14442. } else if (formal instanceof torch.DictType) {
  14443. if (actual instanceof torch.DictType) {
  14444. const key_match = torch._C.matchTypeVariables(formal.getKeyType(), actual.getKeyType(), type_env);
  14445. if (!key_match.success()) {
  14446. return key_match;
  14447. }
  14448. const value_match = torch._C.matchTypeVariables(formal.getValueType(), actual.getValueType(), type_env);
  14449. if (!value_match.success()) {
  14450. return value_match;
  14451. }
  14452. return torch._C.MatchTypeReturn.Success();
  14453. }
  14454. return new torch._C.MatchTypeReturn('Cannot match dict.');
  14455. }
  14456. throw new python.Error('Unhandled free variable container.');
  14457. });
  14458. this.registerFunction('torch._C.tryMatchArgument', (arg, graph, loc, named_value, failure_messages, err, allow_conversions, type_env) => {
  14459. let value = named_value.value(graph);
  14460. if (torch._C.isIntOrFloatUsedAsList(value, arg)) {
  14461. const repeated = Array(arg.N).fill(value);
  14462. value = graph.insertNode(graph.createList(value.type(), repeated)).output();
  14463. }
  14464. const matched = torch._C.matchTypeVariables(arg.type, value.type(), type_env);
  14465. if (!matched.success()) {
  14466. if (failure_messages) {
  14467. throw new python.Error(`Could not match type ${value.type().repr_str()} to ${arg.type().repr_str()} in argument '${arg.name()}'.`);
  14468. }
  14469. return null;
  14470. }
  14471. const concrete_type = torch._C.tryEvalTypeVariables(arg.type, type_env);
  14472. if (!concrete_type) {
  14473. if (failure_messages) {
  14474. throw new python.Error(`Could not infer type for argument '${arg.name}'.`);
  14475. }
  14476. return null;
  14477. }
  14478. value = torch._C.tryConvertToType(loc, graph, concrete_type, value, allow_conversions);
  14479. if (!value.type().isSubtypeOf(concrete_type)) {
  14480. if (failure_messages) {
  14481. throw new python.Error(`Could not match type in argument '${arg.name()}'.`);
  14482. }
  14483. return null;
  14484. }
  14485. return value;
  14486. });
  14487. this.registerFunction('torch._C.tryConvertToType', (loc, graph, concrete_type, value, allow_conversions) => {
  14488. if (concrete_type instanceof torch.OptionalType) {
  14489. const op = concrete_type;
  14490. if (value.type() instanceof torch.OptionalType === false && !value.type().isSubtypeOf(torch.NoneType.get())) {
  14491. return torch._C.tryConvertToType(loc, graph, op.getElementType(), value, allow_conversions);
  14492. }
  14493. }
  14494. if (value.node().kind() === 'prim::EmptyListLiteral' && concrete_type instanceof torch.ListType) {
  14495. value = graph.insertNode(graph.createList(concrete_type.getElementType(), [])).output();
  14496. }
  14497. if (value.type() instanceof torch.TupleType) {
  14498. const value_tuple = value.type();
  14499. if (torch._C.convertibleToList(value.type(), torch._C.unwrapOptional(concrete_type))) {
  14500. const unpacked = torch._C.createTupleUnpack(value);
  14501. const elem_type = torch._C.unwrapOptional(concrete_type).expect(torch.ListType).getElementType();
  14502. value = graph.insertNode(graph.createList(elem_type, unpacked)).output();
  14503. }
  14504. if (concrete_type instanceof torch.TupleType) {
  14505. const concrete_tuple = concrete_type;
  14506. if (!value_tuple.isSubtypeOf(concrete_tuple) &&
  14507. concrete_tuple.elements().length === value_tuple.elements().length) {
  14508. const unpacked = torch._C.createTupleUnpack(value);
  14509. const converted = [];
  14510. for (let i = 0; i < concrete_tuple.elements().length; i++) {
  14511. converted.push(torch._C.tryConvertToType(loc, graph, concrete_tuple.elements()[i], unpacked[i], allow_conversions));
  14512. }
  14513. value = graph.insertNode(graph.createTuple(converted)).output();
  14514. }
  14515. }
  14516. }
  14517. if (allow_conversions) {
  14518. const value_isa_tensor = value.type().isSubtypeOf(torch.TensorType.get());
  14519. const value_equals_number = value.type() === torch.NumberType.get();
  14520. const concrete_float = concrete_type === torch.FloatType.get();
  14521. const concrete_complex = concrete_type === torch.ComplexType.get();
  14522. const concrete_int = concrete_type === torch.IntType.get();
  14523. const concrete_number = concrete_type === torch.NumberType.get();
  14524. if (value_isa_tensor) {
  14525. if (concrete_float) {
  14526. value = graph.insert('aten::FloatImplicit', [new torch._C.NamedValue(value)], [], loc);
  14527. } else if (concrete_complex) {
  14528. value = graph.insert('aten::ComplexImplicit', [new torch._C.NamedValue(value)], [], loc);
  14529. } else if (concrete_int) {
  14530. value = graph.insert('aten::IntImplicit', [new torch._C.NamedValue(value)], [], loc);
  14531. } else if (concrete_number) {
  14532. value = graph.insert('aten::ScalarImplicit', [new torch._C.NamedValue(value)], [], loc);
  14533. }
  14534. } else if (value_equals_number) {
  14535. if (concrete_float) {
  14536. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14537. } else if (concrete_complex) {
  14538. value = graph.insert('aten::Complex', [new torch._C.NamedValue(value)], [], loc);
  14539. } else if (concrete_int) {
  14540. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14541. }
  14542. } else if (value.type() === torch.BoolType.get()) {
  14543. if (concrete_float) {
  14544. value = graph.insert('aten::Float', [new torch._C.NamedValue(value)], [], loc);
  14545. } else if (concrete_int || concrete_number) {
  14546. value = graph.insert('aten::Int', [new torch._C.NamedValue(value)], [], loc);
  14547. }
  14548. }
  14549. if (value.type().isSubtypeOf(torch.StringType.get()) && concrete_type.isSubtypeOf(torch.DeviceObjType.get())) {
  14550. return graph.insert('aten::device', [new torch._C.NamedValue(value)], [], loc);
  14551. }
  14552. }
  14553. return value;
  14554. });
  14555. this.registerFunction('torch._C.tryEvalTypeVariables', (type, type_env) => {
  14556. if (!type.hasFreeVariables()) {
  14557. if (type instanceof torch._C.DynamicType) {
  14558. return torch._C.tryEvalTypeVariables(type.fallback(), type_env);
  14559. }
  14560. return type;
  14561. }
  14562. if (type instanceof torch._C.VarType) {
  14563. return type_env.get(type.annotation_str);
  14564. }
  14565. const contained = type.containedTypes();
  14566. if (contained.length === 0) {
  14567. return type;
  14568. }
  14569. const new_contained = [];
  14570. for (const t of contained) {
  14571. const r = torch._C.tryEvalTypeVariables(t, type_env);
  14572. if (!r) {
  14573. return null;
  14574. }
  14575. new_contained.push(r);
  14576. }
  14577. return type.withContained(new_contained);
  14578. });
  14579. this.registerFunction('torch._C.tryMatchSchema', (schema, loc, graph, args, kwargs, self, failure_messages, allow_conversions) => {
  14580. if (torch._C.isBlockListedSchema(schema)) {
  14581. return null;
  14582. }
  14583. const err = null;
  14584. const type_env = new Map();
  14585. const positional_inputs = [];
  14586. const used_kwarg = kwargs.map(() => false);
  14587. const is_aten = schema.name.startsWith('aten::');
  14588. let used_args = 0;
  14589. for (let schema_i = 0; schema_i < schema.arguments.length; schema_i++) {
  14590. const arg = schema.arguments[schema_i];
  14591. let actual_named_value = null;
  14592. if (arg.name === 'self' && self) {
  14593. actual_named_value = self;
  14594. self = null;
  14595. } else if (!arg.kwarg_only && used_args < args.length) {
  14596. if (allow_conversions && torch._C.varargsCanBeUsedAsList(schema, schema_i, arg)) {
  14597. const value = args[used_args].value(graph);
  14598. const actual_type = value.type();
  14599. if (actual_type instanceof torch.ListType === false && !torch._C.convertibleToList(actual_type, torch._C.unwrapOptional(arg.type))) {
  14600. const formal_type = torch._C.unwrapOptional(arg.type).expect(torch.ListType).getElementType();
  14601. const list = torch._C.tryCreateList(formal_type, graph, loc, args.slice(used_args), failure_messages, err, allow_conversions, type_env);
  14602. if (!list) {
  14603. return null;
  14604. }
  14605. used_args = args.length;
  14606. positional_inputs.push(list);
  14607. continue;
  14608. }
  14609. }
  14610. actual_named_value = args[used_args];
  14611. used_args++;
  14612. } else {
  14613. const kwarg_idx = torch._C.findInputWithName(arg.name, kwargs, is_aten);
  14614. if (Number.isInteger(kwarg_idx)) {
  14615. const nv = kwargs[kwarg_idx];
  14616. if (used_kwarg[kwarg_idx]) {
  14617. if (failure_messages) {
  14618. throw new python.Error(`Argument '${nv.name()}' specified twice in schema.`);
  14619. }
  14620. return null;
  14621. }
  14622. used_kwarg[kwarg_idx] = true;
  14623. actual_named_value = nv;
  14624. } else if (arg.has_default_value()) {
  14625. actual_named_value = new torch._C.NamedValue(arg.default_value);
  14626. } else {
  14627. if (failure_messages) {
  14628. throw new python.Error(`Argument '${arg.name}' not provided.`);
  14629. }
  14630. return null;
  14631. }
  14632. }
  14633. const positional = torch._C.tryMatchArgument(arg, graph, loc, actual_named_value, failure_messages, err, allow_conversions, type_env);
  14634. if (!positional) {
  14635. return null;
  14636. }
  14637. positional_inputs.push(positional);
  14638. }
  14639. if (self !== null) {
  14640. if (failure_messages) {
  14641. throw new python.Error('Provided self argument not used in schema.');
  14642. }
  14643. return null;
  14644. }
  14645. if (schema.is_vararg) {
  14646. for (; used_args < args.length; used_args++) {
  14647. positional_inputs.push(args[used_args].value(graph));
  14648. }
  14649. }
  14650. if (used_args < args.length) {
  14651. if (failure_messages) {
  14652. throw new python.Error('Too many positional arguments.');
  14653. }
  14654. return null;
  14655. }
  14656. for (let i = 0; i < kwargs.length; i++) {
  14657. const nv = kwargs[i];
  14658. if (!used_kwarg[i]) {
  14659. if (failure_messages) {
  14660. if (schema.argumentIndexWithName(nv.name()) === null) {
  14661. throw new python.Error('Keyword argument unknown.');
  14662. } else {
  14663. throw new python.Error('Keyword argument specified twice.');
  14664. }
  14665. }
  14666. return null;
  14667. }
  14668. }
  14669. const returns = schema.returns;
  14670. const return_types = returns.map((r) => {
  14671. const result = torch._C.tryEvalTypeVariables(r.type, type_env);
  14672. if (!result) {
  14673. throw new python.Error('Unbound type variable.');
  14674. }
  14675. return result;
  14676. });
  14677. const return_has_field_names = returns.every((r) => !r.name);
  14678. let return_field_names = null;
  14679. if (return_has_field_names) {
  14680. return_field_names = returns.map((r) => r.name);
  14681. }
  14682. const schema_name = torch._C.getFullSchemaName(schema);
  14683. return new torch._C.MatchedSchema(positional_inputs, return_types, return_field_names, schema_name);
  14684. });
  14685. this.registerFunction('torch._C.matchSchema', (schema, loc, graph, args, kwargs, self) => {
  14686. self = self || null;
  14687. const result = torch._C.tryMatchSchema(schema, loc, graph, args, kwargs, self, null, true);
  14688. if (result) {
  14689. return result;
  14690. }
  14691. throw new python.Error(`No matching schema '${schema.name}' found.`);
  14692. });
  14693. this.registerFunction('torch._C.matchSchemas', (schemas, loc, graph, args, kwargs, self, render_errors) => {
  14694. self = self || null;
  14695. render_errors = render_errors || false;
  14696. torch._C.TORCH_INTERNAL_ASSERT(schemas.length > 0);
  14697. if (schemas.length === 1) {
  14698. return [0, torch._C.matchSchema(schemas[0], loc, graph, args, kwargs, self)];
  14699. }
  14700. for (const allow_conversions of [false, true]) {
  14701. for (let i = 0; i < schemas.length; i++) {
  14702. const matched_schema = torch._C.tryMatchSchema(schemas[i], loc, graph, args, kwargs, self, null, allow_conversions);
  14703. if (matched_schema) {
  14704. return [i, matched_schema];
  14705. }
  14706. }
  14707. }
  14708. if (!render_errors) {
  14709. return torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self, /*render_errors=*/true);
  14710. }
  14711. throw new python.Error(`No matching schema '${schemas[0].name}' found.`);
  14712. });
  14713. this.registerFunction('torch._C.emitBuiltinCall', (loc, graph, name, args, kwargs, self) => {
  14714. const variants = torch._C.getAllOperatorsFor(name);
  14715. const builtin_functions = torch._C.getAllBuiltinFunctionsFor(name);
  14716. const graph_version = graph.get_op_version();
  14717. const schemas = [];
  14718. const upgrader_schemas = [];
  14719. for (const op of variants) {
  14720. let found_upgrader = false;
  14721. const op_name = torch._C.getFullSchemaName(op.schema());
  14722. if (Number.isInteger(graph_version)) {
  14723. const version_entry = torch._C.get_operator_version_map().get(op_name);
  14724. if (version_entry) {
  14725. const old_schema_entry = torch._C.findUpgrader(version_entry.second, graph_version.value());
  14726. if (old_schema_entry.has_value()) {
  14727. const old_schema = torch._C.parseSchema(old_schema_entry.value().old_schema);
  14728. upgrader_schemas.push(old_schema);
  14729. found_upgrader = true;
  14730. } else if (!torch._C.isOpCurrentBasedOnUpgraderEntries(version_entry.second, graph_version.value())) {
  14731. throw new python.Error('Valid upgrader must be present.');
  14732. }
  14733. }
  14734. }
  14735. if (!found_upgrader) {
  14736. schemas.push(op.schema());
  14737. }
  14738. }
  14739. if (variants.length === 0) {
  14740. const oldSchemas = torch._C.loadPossibleHistoricOps(name, graph_version);
  14741. for (const old_schema_entry of oldSchemas) {
  14742. const old_schema = torch._C.parseSchema(old_schema_entry);
  14743. upgrader_schemas.push(old_schema);
  14744. }
  14745. }
  14746. for (const schema of upgrader_schemas) {
  14747. schemas.push(schema);
  14748. }
  14749. for (const method of builtin_functions) {
  14750. method.ensure_defined();
  14751. schemas.push(method.getSchema());
  14752. }
  14753. if (schemas.length === 0) {
  14754. const user_function_name = name;
  14755. throw new python.Error(`Unknown built-in function '${user_function_name}'.`);
  14756. }
  14757. const matched = torch._C.matchSchemas(schemas, loc, graph, args, kwargs, self);
  14758. if (matched[0] < variants.length + upgrader_schemas.length) {
  14759. return torch._C.emitBuiltinNode(matched[1], loc, graph, name, graph_version);
  14760. }
  14761. const fn = builtin_functions[matched.first - variants.size()];
  14762. return torch._C.insertGraph(graph, torch._C.toGraphFunction(fn).graph(), matched.second.inputs, new Map())[0];
  14763. });
  14764. this.registerFunction('torch._C.emitBuiltinNode', (matched_schema, loc, graph, name, version) => {
  14765. const n = graph.insertNode(graph.create(name, matched_schema.inputs, 0)).setSourceRange(loc);
  14766. for (const ret of matched_schema.return_types) {
  14767. n.addOutput().setType(ret);
  14768. }
  14769. if (!Number.isInteger(version) || torch._C.isOpSymbolCurrent(matched_schema.schema_name, version)) {
  14770. n.getOperation();
  14771. } else {
  14772. n.setHistoricSchemaName(matched_schema.schema_name);
  14773. }
  14774. return torch._C.packOutputs(graph, n.outputs(), matched_schema.return_field_names);
  14775. });
  14776. this.registerFunction('torch._C.unshapedType', (type) => {
  14777. if (type.isSubtypeOf(torch.TensorType.get())) {
  14778. return torch.TensorType.get();
  14779. }
  14780. const contained = type.containedTypes();
  14781. if (contained.length === 0) {
  14782. return type;
  14783. }
  14784. return type.withContained(contained.map((t) => torch._C.unshapedType(t)));
  14785. });
  14786. this.registerFunction('torch._C.unifyTypesImpl', (t1, t2, default_to_union, type_hint) => {
  14787. default_to_union = default_to_union || false;
  14788. type_hint = type_hint || null;
  14789. if (t1.isSubtypeOf(t2)) {
  14790. return t2;
  14791. } else if (t2.isSubtypeOf(t1)) {
  14792. return t1;
  14793. }
  14794. if (t1.kind() === 'TensorType' && t2.kind() === 'TensorType') {
  14795. return t1.merge(t2);
  14796. }
  14797. if (t1.isSubtypeOf(torch.NoneType.get()) && !t2.isSubtypeOf(torch.NoneType.get())) {
  14798. return torch.OptionalType.create(t2);
  14799. } else if (t2.isSubtypeOf(torch.NoneType.get()) && !t1.isSubtypeOf(torch.NoneType.get())) {
  14800. return torch.OptionalType.create(t1);
  14801. }
  14802. if (t1 instanceof torch.OptionalType) {
  14803. const elem = torch._C.unifyTypes(t1.getElementType(), t2);
  14804. if (elem) {
  14805. return torch.OptionalType.create(elem);
  14806. }
  14807. } else if (t2 instanceof torch.OptionalType) {
  14808. const elem = torch._C.unifyTypes(t2.getElementType(), t1);
  14809. if (elem) {
  14810. return torch.OptionalType.create(elem);
  14811. }
  14812. }
  14813. if (t1 instanceof torch.TupleType && t2 instanceof torch.TupleType) {
  14814. if (t1.elements().size() !== t2.elements().size()) {
  14815. return null;
  14816. }
  14817. const elements = [];
  14818. for (let i = 0; i < t1.elements().length; i++) {
  14819. const elem = torch._C.unifyTypes(t1.elements()[i], t2.elements()[i], default_to_union);
  14820. if (elem) {
  14821. elements.push(elem);
  14822. } else {
  14823. return null;
  14824. }
  14825. }
  14826. return torch.TupleType.create(elements);
  14827. }
  14828. if (t1 instanceof torch.FutureType && t2 instanceof torch.FutureType) {
  14829. const elem = torch._C.unifyTypes(t1.getElementType(), t2.getElementType());
  14830. if (elem) {
  14831. return torch.FutureType.create(elem);
  14832. }
  14833. }
  14834. const t1_unshaped = torch._C.unshapedType(t1);
  14835. const t2_unshaped = torch._C.unshapedType(t2);
  14836. if (t1_unshaped.isSubtypeOf(t2_unshaped)) {
  14837. return t2_unshaped;
  14838. } else if (t2_unshaped.isSubtypeOf(t1_unshaped)) {
  14839. return t1_unshaped;
  14840. }
  14841. if (type_hint && t1.isSubtypeOf(type_hint) && t2.isSubtypeOf(type_hint)) {
  14842. return type_hint;
  14843. }
  14844. return null;
  14845. });
  14846. this.registerFunction('torch._C.unifyTypes', (t1, t2, default_to_union, type_hint) => {
  14847. const unified = torch._C.unifyTypesImpl(t1, t2, default_to_union, type_hint);
  14848. if (default_to_union && !unified) {
  14849. return torch.UnionType.create([t1, t2]);
  14850. }
  14851. return unified;
  14852. });
  14853. this.registerFunction('torch._C.unifyTypeList', (elements, why_not, default_to_union, type_hint) => {
  14854. if (elements.length === 0) {
  14855. return null;
  14856. }
  14857. let [ret_type] = elements;
  14858. for (let i = 1; i < elements.length && ret_type; i++) {
  14859. const maybe_unified = torch._C.unifyTypes(ret_type, elements[i], default_to_union, type_hint);
  14860. if (!maybe_unified) {
  14861. return null;
  14862. }
  14863. ret_type = maybe_unified;
  14864. }
  14865. return ret_type;
  14866. });
  14867. this.registerFunction('torch._C.insertableTensor', (ten) => {
  14868. return !ten.requires_grad() && ten.has_storage() && !ten.is_nested();
  14869. });
  14870. this.registerFunction('torch._C.insertableIValue', (ivalue) => {
  14871. if (ivalue.isInt() || ivalue.isNone() || ivalue.isBool() ||
  14872. ivalue.isDouble() || ivalue.isComplexDouble() || ivalue.isString() ||
  14873. ivalue.isDevice() || ivalue.isEnum()) {
  14874. return true;
  14875. }
  14876. if (ivalue.isTensor()) {
  14877. return torch._C.insertableTensor(ivalue.toTensor());
  14878. }
  14879. if (ivalue.isList() || ivalue.isTuple()) {
  14880. let elems = [];
  14881. if (ivalue.isTuple()) {
  14882. elems = ivalue.toTupleRef().elements();
  14883. } else {
  14884. elems = ivalue.toListRef();
  14885. }
  14886. return elems.every((tup_elem) => torch._C.insertableIValue(tup_elem));
  14887. }
  14888. if (ivalue.isGenericDict()) {
  14889. const dict = ivalue.toGenericDict();
  14890. return dict.every((entry) => torch._C.insertableIValue(entry.key()) && torch._C.insertableIValue(entry.value()));
  14891. }
  14892. return false;
  14893. });
  14894. this.registerFunction('torch._C.insertConstant', (g, val, loc, scope) => {
  14895. loc = loc || null;
  14896. scope = scope || null;
  14897. const value = torch._C.tryInsertConstant(g, val, loc, scope);
  14898. if (value !== undefined) {
  14899. return value;
  14900. }
  14901. throw new python.Error('Unsupported value kind.');
  14902. });
  14903. this.registerFunction('torch._C.tryInsertConstant', (g, val, loc, scope) => {
  14904. if (val instanceof torch._C.IValue) {
  14905. const n = g.create('prim::Constant');
  14906. if (val.isTensor()) {
  14907. const ref = val.toTensor();
  14908. if (!torch._C.insertableTensor(val.toTensor())) {
  14909. n.destroy();
  14910. return null;
  14911. }
  14912. if (!ref.defined()) {
  14913. n.destroy();
  14914. return g.insertNode(g.createNone()).output();
  14915. }
  14916. torch._C.TORCH_INTERNAL_ASSERT(!ref.requires_grad());
  14917. n.output().inferTypeFrom(ref); // note: before t_ because of std::move(ref)
  14918. n.t_('value', ref);
  14919. } else if (val.isInt()) {
  14920. n.i_('value', val.toInt());
  14921. n.output().setType(torch.IntType.get());
  14922. } else if (val.isDouble()) {
  14923. n.f_('value', val.toDouble());
  14924. n.output().setType(torch.FloatType.get());
  14925. } else if (val.isComplexDouble()) {
  14926. n.c_('value', val.toComplexDouble());
  14927. n.output().setType(torch.ComplexType.get());
  14928. } else if (val.isBool()) {
  14929. n.i_('value', val.toBool());
  14930. n.output().setType(torch.BoolType.get());
  14931. } else if (val.isList()) {
  14932. const fast_path_list = val.isBoolList() || val.isIntList() || val.isDoubleList();
  14933. if (fast_path_list || torch._C.insertableIValue(val)) {
  14934. n.ival_('value', val);
  14935. n.output().setType(val.type());
  14936. } else {
  14937. n.destroy();
  14938. return null;
  14939. }
  14940. } else if (val.isString()) {
  14941. n.s_('value', val.toStringRef());
  14942. n.output().setType(torch.StringType.get());
  14943. } else if (val.isDevice()) {
  14944. n.s_('value', val.toDevice().__str__());
  14945. n.output().setType(torch.DeviceObjType.get());
  14946. } else if (val.isGenerator()) {
  14947. n.ival_('value', val.toGenerator());
  14948. n.output().setType(torch._C_._GeneratorType.get());
  14949. } else if (val.isStream()) {
  14950. n.ival_('value', val);
  14951. n.output().setType(torch.StreamObjType.get());
  14952. } else if (val.isNone()) {
  14953. n.output().setType(torch.NoneType.get());
  14954. // n.ival_('value', null); // remove
  14955. } else if (val.isTuple()) {
  14956. if (torch._C.insertableIValue(val)) {
  14957. n.ival_('value', val);
  14958. n.output().setType(val.type());
  14959. } else {
  14960. n.destroy();
  14961. return null;
  14962. }
  14963. } else if (val.isObject()) {
  14964. const ref = val.toObjectRef();
  14965. // see: [Constant Object Weak CompilationUnit Reference]
  14966. if (!ref.type().is_module() && (ref.is_weak_compilation_ref() || ref.is_empty_strong_compilation_ref())) {
  14967. n.ival_('value', val);
  14968. n.output().setType(val.type());
  14969. } else {
  14970. n.destroy();
  14971. return null;
  14972. }
  14973. } else if ((val.isGenericDict() && torch._C.insertableIValue(val)) || (val.isEnum())) {
  14974. n.ival_('value', val);
  14975. n.output().setType(val.type());
  14976. } else {
  14977. n.destroy();
  14978. return null;
  14979. }
  14980. if (loc) {
  14981. n.setSourceRange(loc);
  14982. }
  14983. if (scope) {
  14984. n.setScope(scope);
  14985. }
  14986. return g.insertNode(n).output();
  14987. }
  14988. const n = g.create('prim::Constant');
  14989. let type = null;
  14990. if (val === null) {
  14991. n.ival_('value', val);
  14992. type = torch.NoneType.get();
  14993. } else if (typeof val === 'string') {
  14994. n.s_('value', val);
  14995. type = torch.StringType.get();
  14996. } else if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
  14997. n.ss_('value', val);
  14998. type = torch.ListType.create(torch.StringType.get());
  14999. } else if (typeof val === 'boolean') {
  15000. n.i_('value', val === true ? 1 : 0);
  15001. type = torch.BoolType.get();
  15002. } else if ((!val.type && Number.isInteger(val)) || val.type === 'int') {
  15003. n.i_('value', val);
  15004. type = torch.IntType.get();
  15005. } else if ((!val.type && typeof val === 'number') || val.type === 'float') {
  15006. n.f_('value', val);
  15007. type = torch.FloatType.get();
  15008. } else if (val instanceof torch.Tensor) {
  15009. n.t_('value', val);
  15010. type = torch.TensorType.get();
  15011. } else if (val instanceof torch.ScriptObject) {
  15012. n.ival_('value', val);
  15013. type = val.type();
  15014. } else if (Array.isArray(val) && val.every((item) => Number.isInteger(item))) {
  15015. n.ival_('value', val);
  15016. type = torch.ListType.create(torch.IntType.get());
  15017. } else {
  15018. throw new python.Error(`Unsupported value type '${typeof val}'.`);
  15019. }
  15020. if (type) {
  15021. n.output().setType(type);
  15022. }
  15023. if (loc) {
  15024. n.setSourceRange(loc);
  15025. }
  15026. if (scope) {
  15027. n.setScope(scope);
  15028. }
  15029. return g.insertNode(n).output();
  15030. });
  15031. this.registerFunction('torch._C.toIValue', (v) => {
  15032. if (v.node().kind() !== 'prim::Constant' || v.type() instanceof torch._C.FunctionType) {
  15033. return null;
  15034. }
  15035. const node = v.node();
  15036. const type = v.type();
  15037. if (type.isSubtypeOf(torch.TensorType.get())) {
  15038. return new torch._C.IValue(node.t('value'), 'Tensor');
  15039. } else if (type.isSubtypeOf(torch.BoolType.get())) {
  15040. return new torch._C.IValue(Boolean(node.i('value'), 'Bool'));
  15041. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'i') {
  15042. return new torch._C.IValue(node.i('value'), 'Int');
  15043. } else if (type.isSubtypeOf(torch.NumberType.get()) && node.kindOf('value') === 'f') {
  15044. return new torch._C.IValue(node.f('value'), 'Double');
  15045. } else if (type.isSubtypeOf(torch.ComplexType.get()) && node.kindOf('value') === 'c') {
  15046. return new torch._C.IValue(node.c('value'), 'Complex');
  15047. } else if (type instanceof torch.ListType && node.kindOf('value') === 'ival') {
  15048. let list = node.ival('value');
  15049. list = list.isList ? list : new torch._C.IValue(list); // remove
  15050. torch._C.TORCH_INTERNAL_ASSERT(list.isList());
  15051. return list;
  15052. } else if (type instanceof torch.DictType && node.kindOf('value') === 'ival') {
  15053. const dict = node.ival('value');
  15054. torch._C.TORCH_INTERNAL_ASSERT(dict.isGenericDict());
  15055. return dict;
  15056. } else if (type instanceof torch.TupleType && node.kindOf('value') === 'ival') {
  15057. const tup = node.ival('value');
  15058. torch._C.TORCH_INTERNAL_ASSERT(tup.isTuple());
  15059. return tup;
  15060. } else if (type === torch.StringType.get()) {
  15061. const s = new torch._C.IValue(node.s('value'), 'String');
  15062. return s;
  15063. } else if (type === torch.DeviceObjType.get()) {
  15064. const d = new torch.device(node.s('value'));
  15065. return new torch._C.IValue(d);
  15066. } else if (type === torch._C._GeneratorType.get()) {
  15067. throw new python.Error('Not implemented.');
  15068. // const generator = node.ival('value').toGenerator();
  15069. // return generator;
  15070. } else if (type === torch.StreamObjType.get()) {
  15071. throw new python.Error('Not implemented.');
  15072. // const s = node.ival('value').toStream();
  15073. // return s;
  15074. } else if (node.mustBeNone()) {
  15075. return new torch._C.IValue();
  15076. } else if (type.kind() === 'EnumType') {
  15077. const enum_val = node.ival('value');
  15078. return enum_val;
  15079. } else if (type instanceof torch.ClassType && !type.is_module()) {
  15080. const class_val = node.ival('value');
  15081. return new torch._C.IValue(class_val, 'Object');
  15082. }
  15083. throw new python.Error('Unsupported constant literal.');
  15084. });
  15085. this.registerFunction('torch._C.constant_as', (v, target, default_value) => {
  15086. const ivalue = torch._C.toIValue(v);
  15087. if (ivalue) {
  15088. return ivalue[target]();
  15089. }
  15090. return default_value === undefined ? null : default_value;
  15091. });
  15092. this.registerType('torch._C.NamedValue', class {
  15093. constructor(...args) {
  15094. if (args.length === 1) {
  15095. if (args[0] instanceof torch.Value) {
  15096. [this._value] = args;
  15097. } else {
  15098. [this._ivalue] = args;
  15099. }
  15100. } else if (args.length === 3 && typeof args[1] === 'string' && args[2] instanceof torch.Value) {
  15101. [this._loc, this._name, this._value] = args;
  15102. } else {
  15103. throw new python.Error('Invalid argument.');
  15104. }
  15105. }
  15106. name() {
  15107. return this._name;
  15108. }
  15109. value(g) {
  15110. if (!this._value) {
  15111. return torch._C.insertConstant(g, this._ivalue);
  15112. }
  15113. return this._value;
  15114. }
  15115. type() {
  15116. if (this._value) {
  15117. return this._value.type();
  15118. }
  15119. return this._ivalue.type();
  15120. }
  15121. });
  15122. this.registerType('torch._C.SugaredValue', class {
  15123. kind() {
  15124. throw new python.Error('Not implemented.');
  15125. }
  15126. shouldEmitUnrolled() {
  15127. return this.staticLen() !== null;
  15128. }
  15129. });
  15130. this.registerType('torch._C.SimpleValue', class extends torch._C.SugaredValue {
  15131. constructor(value) {
  15132. super();
  15133. this._value = value;
  15134. }
  15135. kind() {
  15136. return `value of type '${this._value.type().annotation_str}'`;
  15137. }
  15138. asValue(/* range, m */) {
  15139. return this._value;
  15140. }
  15141. getValue() {
  15142. return this._value;
  15143. }
  15144. asTuple(loc, m, size_hint) {
  15145. const make_simple_value = (v) => new torch._C.SimpleValue(v);
  15146. if (this._value.type() instanceof torch.TupleType) {
  15147. const outputs = torch._C.createTupleUnpack(this._value);
  15148. return outputs.map((v) => make_simple_value(v));
  15149. } else if (this._value.type() instanceof torch.ListType) {
  15150. if (!size_hint) {
  15151. throw new python.Error('Cannot statically infer the expected size of a list in this context.');
  15152. }
  15153. const graph = this._value.owningGraph();
  15154. const unpack = graph.insertNode(graph.createListUnpack(this._value, size_hint));
  15155. return unpack.outputs().map((v) => make_simple_value(v));
  15156. } else if (this._value.type().kind() === 'AnyTupleType') {
  15157. throw new python.Error('Provided tuple is not fully defined including its element types.');
  15158. }
  15159. throw new python.Error(`Cannot use '${this._value.type().toString()}' as tuple.`);
  15160. }
  15161. attr(loc, m, field) {
  15162. if (this._value.type().isSubtypeOf(torch.TensorType.get())) {
  15163. if (torch._C.builtin_cast_method_to_scalar_type().has(field)) {
  15164. return new torch._C.TensorCastValue(torch._C.builtin_cast_method_to_scalar_type().get(field), new torch._C.NamedValue(loc, 'self', this._value));
  15165. }
  15166. }
  15167. if (this._value.type() instanceof torch.TupleType) {
  15168. throw new python.Error('Not implemented.');
  15169. }
  15170. if (this._value.type() instanceof torch.AwaitType) {
  15171. throw new python.Error('Not implemented.');
  15172. }
  15173. if (this._value.type() instanceof torch.ClassType) {
  15174. const classType = this._value.type();
  15175. if (classType.findMethod(field)) {
  15176. return new torch._C.MethodValue(this.getValue(), [field]);
  15177. }
  15178. if (classType.hasAttribute(field)) {
  15179. const g = m.graph();
  15180. const n = g.insertNode(g.createGetAttr(this._value, field));
  15181. return new torch._C.SimpleValue(n.output());
  15182. }
  15183. const prop = classType.getProperty(field);
  15184. if (prop) {
  15185. return new torch._C.MethodValue(this._value, [prop.getter.name()]).call(loc, m, {}, {}, /*n_binders=*/1);
  15186. }
  15187. } else if (this._value.type() instanceof torch.InterfaceType) {
  15188. throw new python.Error('Not implemented.');
  15189. } else if (this._value.type() instanceof torch.EnumType) {
  15190. const g = m.graph();
  15191. if (field === 'name') {
  15192. const n = g.insertNode(g.createEnumName(this._value));
  15193. return new torch._C.SimpleValue(n.output());
  15194. }
  15195. if (field === 'value') {
  15196. const n = g.insertNode(g.createEnumValue(this._value));
  15197. return new torch._C.SimpleValue(n.output());
  15198. }
  15199. }
  15200. if (field === 'type') {
  15201. const builtin = torch._C.BuiltinFunction.tryCreate('aten::to', new torch._C.NamedValue(loc, 'self', this._value));
  15202. if (builtin) {
  15203. return builtin;
  15204. }
  15205. }
  15206. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15207. if (builtin) {
  15208. return builtin;
  15209. }
  15210. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === 'tolist') {
  15211. return torch._C.SpecialFormValue.create('prim::tolist');
  15212. }
  15213. if (this._value.type().isSubtypeOf(torch.TensorType.get()) && field === '__getitem__') {
  15214. return torch._C.SpecialFormValue.create('aten::index');
  15215. }
  15216. if (this._value.type() instanceof torch._C._GeneratorType && (field === 'manual_seed' || field === 'initial_seed' || field === 'seed')) {
  15217. const builtin = torch._C.BuiltinFunction.tryCreate(`aten::${field}`, new torch._C.NamedValue(loc, 'self', this._value));
  15218. if (builtin) {
  15219. return builtin;
  15220. }
  15221. }
  15222. throw new python.Error('Object has no attribute or method.');
  15223. }
  15224. setAttr(loc, m, field, newValue) {
  15225. const type = this._value.type();
  15226. if (type instanceof torch.ClassType === false) {
  15227. throw new python.Error('Cannot set attribute on non-class type.');
  15228. }
  15229. const classType = type;
  15230. let expectedType = classType.findAttribute(field);
  15231. if (!expectedType) {
  15232. const isInitializing = m.name() === '__init__' && m.graph().inputs().length > 0 && m.graph().inputs()[0].type() === classType;
  15233. if (isInitializing) {
  15234. if (this.isRecursive(classType, newValue.type())) {
  15235. throw new python.Error('Classes that recursively contain instances of themselves are not supported.');
  15236. }
  15237. classType.addAttribute(field, newValue.type());
  15238. expectedType = newValue.type();
  15239. const insertPoint = m.graph().insertPoint();
  15240. const topLevelBlock = m.graph().block();
  15241. if (insertPoint.owningBlock() !== topLevelBlock) {
  15242. throw new python.Error('First assignment cannot be in a control-flow block.');
  15243. }
  15244. } else {
  15245. const prop = classType.getProperty(field);
  15246. if (prop && prop.setter) {
  15247. new torch._C.MethodValue(this._value, prop.setter.name()).call(loc, m, [newValue], [], /*n_binders=*/1);
  15248. return;
  15249. }
  15250. if (prop && !prop.setter) {
  15251. throw new python.Error('Tried to set read-only attribute.');
  15252. }
  15253. throw new python.Error('Tried to set nonexistent attribute.');
  15254. }
  15255. }
  15256. torch._C.AT_ASSERT(expectedType);
  15257. const newType = newValue.type();
  15258. if (!newType.isSubtypeOf(expectedType)) {
  15259. throw new python.Error('Wrong type for attribute assignment.');
  15260. }
  15261. const g = m.graph();
  15262. g.insertNode(g.createSetAttr(this._value, field, newValue));
  15263. }
  15264. getitem(loc, m, idx, type_hint) {
  15265. const val = this.getValue();
  15266. const val_type = val.type();
  15267. const g = m.graph();
  15268. if (val_type instanceof torch.ListType || val_type instanceof torch.StringType) {
  15269. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15270. } else if (val_type instanceof torch.DictType) {
  15271. return new torch._C.SimpleValue(g.insert('aten::__getitem__', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc));
  15272. } else if (val_type.isSubtypeOf(torch.TensorType.get())) {
  15273. 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));
  15274. } else if (val_type instanceof torch.ClassType) {
  15275. const class_type = val_type;
  15276. if (class_type.is_module() && type_hint) {
  15277. const res = g.insert('prim::ModuleContainerIndex', [new torch._C.NamedValue(val), new torch._C.NamedValue(idx)], [], loc);
  15278. res.setType(type_hint);
  15279. return new torch._C.SimpleValue(res);
  15280. }
  15281. return this.attr(loc, m, '__getitem__').call(loc, m, [new torch._C.NamedValue(idx)], [], 1);
  15282. }
  15283. throw new python.Error('Object is not subscriptable.');
  15284. }
  15285. });
  15286. this.registerType('torch._C.MethodValue', class extends torch._C.SugaredValue {
  15287. constructor(self, method_names) {
  15288. super();
  15289. this._self = self;
  15290. this._method_names = method_names;
  15291. }
  15292. call(loc, f, args, kwargs /*, n_binders */) {
  15293. const argsWithSelf = [new torch._C.NamedValue(this._self), ...args];
  15294. const schemas = [];
  15295. for (const method_name of this._method_names) {
  15296. const type = this._self.type();
  15297. if (type instanceof torch.ClassType) {
  15298. const class_type = type;
  15299. const method = class_type.getMethod(method_name);
  15300. method.ensure_defined();
  15301. schemas.push(method.getSchema());
  15302. } else if (type instanceof torch.InterfaceType) {
  15303. const interface_type = type;
  15304. schemas.push(interface_type.getMethod(method_name));
  15305. } else {
  15306. throw new python.Error('Method constructed that is not a class or interface.');
  15307. }
  15308. }
  15309. const match = torch._C.matchSchemas(schemas, loc, f.graph(), argsWithSelf, kwargs);
  15310. const output = f.graph().insertMethodCall(this._method_names[match[0]], match[1]);
  15311. output.node().setSourceRange(loc);
  15312. return new torch._C.SimpleValue(output);
  15313. }
  15314. });
  15315. this.registerType('torch._C.ClassValue', class extends torch._C.SugaredValue {
  15316. constructor(type) {
  15317. super();
  15318. this._type = type;
  15319. }
  15320. attr(loc, m, field) {
  15321. const hook = this._type.findHook(field);
  15322. if (hook) {
  15323. return new torch._C.FunctionValue(hook);
  15324. }
  15325. if (field !== '__new__') {
  15326. throw new python.Error('Tried to lookup unknown attribute on class.');
  15327. }
  15328. return torch._C.SpecialFormValue.create('prim::CreateObject');
  15329. }
  15330. });
  15331. this.registerType('torch._C.NamedTupleConstructor', class extends torch._C.SugaredValue {
  15332. constructor(type) {
  15333. super();
  15334. this._type = type;
  15335. }
  15336. call(loc, m, args, kwargs /*, n_binders */) {
  15337. const g = m.graph();
  15338. const schema = this._type.schema();
  15339. torch._C.TORCH_INTERNAL_ASSERT(schema);
  15340. const matched_schema = torch._C.matchSchema(schema, loc, g, args, kwargs);
  15341. const self = g.insertNode(g.createTuple(matched_schema.inputs, this._type).setSourceRange(loc)).output();
  15342. self.setType(this._type);
  15343. return new torch._C.SimpleValue(self);
  15344. }
  15345. });
  15346. this.registerType('torch._C.SugaredEnumClass', class extends torch._C.SugaredValue {
  15347. constructor(enum_type) {
  15348. super();
  15349. this._enum_type = enum_type;
  15350. }
  15351. attr(loc, m, field) {
  15352. const names_values = this._enum_type.enumNamesValues();
  15353. const it = names_values.find((nv) => nv[0] === field);
  15354. if (it === null) {
  15355. throw new python.Error(`Enum '${this._enum_type.name()}' has no attribute '${field}'.`);
  15356. }
  15357. const enum_holder = new torch._C.EnumHolder(this._enum_type, it[0], it[1]);
  15358. return new torch._C.SimpleValue(m.graph().insertConstant(new torch._C.IValue(enum_holder), loc));
  15359. }
  15360. });
  15361. this.registerType('torch._C.EnumHolder', class {
  15362. constructor(type, name, value) {
  15363. this._type = type;
  15364. this._name = name;
  15365. this._value = value;
  15366. }
  15367. name() {
  15368. return this._name;
  15369. }
  15370. type() {
  15371. return this._type;
  15372. }
  15373. });
  15374. this.registerType('torch._C.FunctionValue', class extends torch._C.SugaredValue {
  15375. constructor(...args) {
  15376. super();
  15377. if (args.length === 1 && args[0] instanceof torch._C.Function) {
  15378. this._callees = [args[0]];
  15379. } else {
  15380. throw new python.Error('Not implemented.');
  15381. }
  15382. }
  15383. call(loc, f, args, kwargs /*, n_binders */) {
  15384. const schemas = [];
  15385. for (const callee of this._callees) {
  15386. callee.ensure_defined();
  15387. schemas.push(callee.getSchema());
  15388. }
  15389. const match = torch._C.matchSchemas(schemas, loc, f.graph(), args, kwargs);
  15390. const output = f.graph().insertFunctionCall(this._callees[match[0]], match[1]);
  15391. output.node().setSourceRange(loc);
  15392. return new torch._C.SimpleValue(output);
  15393. }
  15394. });
  15395. this.registerType('torch._C.NoneValue', class extends torch._C.SugaredValue {
  15396. });
  15397. this.registerType('torch._C.PrintValue', class extends torch._C.SugaredValue {
  15398. call(loc, m, args, kwargs /*, n_binders */) {
  15399. const g = m.graph();
  15400. if (kwargs.length > 0) {
  15401. throw new python.Error(`Print doesn't accept any keyword arguments at ${loc}.`);
  15402. }
  15403. const lowered_inputs = torch._C.toValues(m.graph(), args);
  15404. g.insertNode(g.create('prim::Print', lowered_inputs, 0).setSourceRange(loc));
  15405. return new torch._C.NoneValue();
  15406. }
  15407. });
  15408. this.registerType('torch._C.SpecialFormValue', class extends torch._C.SugaredValue {
  15409. constructor(form) {
  15410. super();
  15411. this._form = form;
  15412. }
  15413. form() {
  15414. return this._form;
  15415. }
  15416. static create(form) {
  15417. return new torch._C.SpecialFormValue(form);
  15418. }
  15419. });
  15420. this.registerFunction('torch._C.makeMagic', (name, base) => {
  15421. return new torch._C.MagicMethod(name, base);
  15422. });
  15423. this.registerType('torch._C.BuiltinFunction', class extends torch._C.SugaredValue {
  15424. constructor(symbol, self) {
  15425. super();
  15426. this.symbol = symbol;
  15427. this.self = self;
  15428. }
  15429. call(loc, m, args, kwargs /*, n_binders */) {
  15430. return new torch._C.SimpleValue(torch._C.emitBuiltinCall(loc, m.graph(), this.symbol, args, kwargs, this.self));
  15431. }
  15432. static tryCreate(symbol, self) {
  15433. for (const op of torch._C.getAllOperatorsFor(symbol)) {
  15434. if (!self) {
  15435. return new torch._C.BuiltinFunction(symbol, null);
  15436. }
  15437. const index = op.schema().argumentIndexWithName('self');
  15438. if (index) {
  15439. const type_env = new Map();
  15440. const formal_type = op.schema().arguments()[index].type();
  15441. const matched = torch._C.matchTypeVariables(formal_type, self.type(), type_env);
  15442. if (!matched.success()) {
  15443. continue;
  15444. }
  15445. const concrete_type = torch._C.tryEvalTypeVariables(formal_type, type_env);
  15446. if (!concrete_type || !self.type().isSubtypeOf(concrete_type)) {
  15447. continue;
  15448. }
  15449. return new torch._C.BuiltinFunction(symbol, self);
  15450. }
  15451. }
  15452. return null;
  15453. }
  15454. });
  15455. this.registerType('torch._C.BuiltinModule', class extends torch._C.SugaredValue {
  15456. constructor(name, version) {
  15457. super();
  15458. this.name = name;
  15459. this.version = version || null;
  15460. }
  15461. attr(loc, m, field) {
  15462. if (field === 'autograd') {
  15463. return new torch._C.BuiltinModule('aten', this.version);
  15464. }
  15465. const sym = `${this.name}::${field}`;
  15466. return new torch._C.BuiltinFunction(sym, null);
  15467. }
  15468. });
  15469. this.registerType('torch._C.OpsValue', class extends torch._C.SugaredValue {
  15470. constructor(version) {
  15471. super();
  15472. this._version = version;
  15473. }
  15474. attr(loc, m, field) {
  15475. return new torch._C.BuiltinModule(field, this._version);
  15476. }
  15477. });
  15478. this.registerType('torch._C.ConstantTableValue', class extends torch._C.SugaredValue {
  15479. constructor(constants) {
  15480. super();
  15481. this._constants = constants;
  15482. this.non_holding_object_cache = new Map();
  15483. }
  15484. attr(loc, m, field) {
  15485. const offset = parseInt(field.substring(1), 10);
  15486. if (!Number.isInteger(offset)) {
  15487. throw new python.Error(`Invalid constant identifier '${field}.`);
  15488. }
  15489. if (offset < 0 || offset >= this._constants.length) {
  15490. throw new python.Error('Invalid constant index.');
  15491. }
  15492. const ivalue = new torch._C.IValue(this._constants[offset]); // remove IValue
  15493. let value = null;
  15494. if (ivalue.isObject() && !ivalue.toObject().is_weak_compilation_ref()) {
  15495. const obj = ivalue.toObject();
  15496. if (!this.non_holding_object_cache.has(obj)) {
  15497. this.non_holding_object_cache.set(obj, obj.copy_to_weak_compilation_ref());
  15498. }
  15499. value = m.graph().insertConstant(this.non_holding_object_cache[obj], loc);
  15500. } else {
  15501. value = m.graph().insertConstant(this._constants[offset], loc);
  15502. }
  15503. value.setType(torch._C.unshapedType(value.type()));
  15504. return new torch._C.SimpleValue(value);
  15505. }
  15506. });
  15507. this.registerType('torch._C.CastValue', class extends torch._C.BuiltinFunction {
  15508. constructor(type, method) {
  15509. super(method, null);
  15510. this._type = type;
  15511. }
  15512. call(loc, m, args, kwargs, n_binders) {
  15513. if (args.length === 1 && kwargs.length === 0) {
  15514. const len_op = new torch._C.BuiltinFunction('aten::len', null);
  15515. const gt_op = new torch._C.BuiltinFunction('aten::gt', null);
  15516. const zero = m.graph().insertConstant(new torch._C.IValue(0, 'Int'));
  15517. const v = args[0].value(m.graph());
  15518. if (v.type().isSubtypeOf(this._type)) {
  15519. return new torch._C.SimpleValue(v);
  15520. } 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)) {
  15521. const len = len_op.call(loc, m, [v], [], 1);
  15522. return gt_op.call(loc, m, [len.asValue(loc, m), zero], [], 1);
  15523. }
  15524. }
  15525. return super.call(loc, m, args, kwargs, n_binders);
  15526. }
  15527. });
  15528. this.registerType('torch._C.MagicMethod', class extends torch._C.SugaredValue {
  15529. constructor(desugared_name, base) {
  15530. super();
  15531. this._base_value = base;
  15532. this._desugared_name = desugared_name;
  15533. }
  15534. call(loc, m, args, kwargs, n_binders) {
  15535. if (args.length > 0) {
  15536. const self = args[0].value(m.graph());
  15537. if (self.type() instanceof torch.ClassType) {
  15538. return new torch._C.SimpleValue(self)
  15539. .attr(loc, m, this._desugared_name)
  15540. .call(loc, m, args.slice(1), kwargs, n_binders);
  15541. }
  15542. }
  15543. if (!this._base_value) {
  15544. throw new python.Error('Invalid magic method.');
  15545. }
  15546. return this._base_value.call(loc, m, args, kwargs, n_binders);
  15547. }
  15548. });
  15549. this.registerType('torch._C.RangeValue', class extends torch._C.SugaredValue {
  15550. constructor(loc, m, inputs, static_len) {
  15551. super();
  15552. static_len = static_len || null;
  15553. if (inputs.length === 0 || inputs.length > 3 || !inputs.every((value) => value.type() instanceof torch.IntType)) {
  15554. throw new python.Error('Invalid range inputs.');
  15555. }
  15556. const g = m.graph();
  15557. if (inputs.length === 1) {
  15558. [this._end] = inputs;
  15559. this._start = g.insertConstant(0, loc);
  15560. this._step = g.insertConstant(1, loc);
  15561. this._has_only_end = true;
  15562. } else {
  15563. [this._start, this._end] = inputs;
  15564. this._step = inputs.length === 3 ? inputs[2] : g.insertConstant(1, loc);
  15565. this._has_only_end = false;
  15566. }
  15567. this._static_len = static_len;
  15568. }
  15569. staticLen() {
  15570. return this._static_len;
  15571. }
  15572. iter() {
  15573. return this;
  15574. }
  15575. len(loc, m) {
  15576. if (this._static_len) {
  15577. return torch._C.insertConstant(m.graph(), this._static_len, loc);
  15578. }
  15579. if (this._has_only_end) {
  15580. return this._end;
  15581. }
  15582. const g = m.graph();
  15583. return g.insert('aten::__range_length', [this._start, this._end, this._step], [], loc);
  15584. }
  15585. getitem(loc, m, idx /*, type_hint */) {
  15586. if (this._has_only_end) {
  15587. return new torch._C.SimpleValue(idx);
  15588. }
  15589. const g = m.graph();
  15590. return new torch._C.SimpleValue(g.insert('aten::__derive_index', [idx, this._start, this._step], [], loc));
  15591. }
  15592. });
  15593. this.registerType('torch._C.SliceValue', class extends torch._C.SugaredValue {
  15594. });
  15595. this.registerType('torch._C.ClassNamespaceValue', class extends torch._C.SugaredValue {
  15596. constructor(name, si) {
  15597. super();
  15598. this._basename = name;
  15599. this._si = si;
  15600. }
  15601. attr(loc, m, name) {
  15602. const fullName = new torch._C.QualifiedName(this._basename, name);
  15603. const serializable_type = this._si.findNamedType(fullName);
  15604. if (serializable_type) {
  15605. if (serializable_type instanceof torch.ClassType) {
  15606. return new torch._C.ClassValue(serializable_type);
  15607. } else if (serializable_type instanceof torch.TupleType) {
  15608. return new torch._C.NamedTupleConstructor(serializable_type);
  15609. } else if (serializable_type instanceof torch.EnumType) {
  15610. return new torch._C.SugaredEnumClass(serializable_type);
  15611. }
  15612. }
  15613. const fn = this._si.findFunction(fullName);
  15614. if (fn) {
  15615. return new torch._C.FunctionValue(fn);
  15616. }
  15617. return new torch._C.ClassNamespaceValue(fullName, this._si);
  15618. }
  15619. });
  15620. this.registerType('torch.package.PackageImporter', class {
  15621. constructor(reader) {
  15622. this.zip_reader = reader;
  15623. }
  15624. load_pickle(module, resource) {
  15625. const name = `${module.replace(/\./, '/')}/${resource}`;
  15626. const stream = this.zip_reader.get_record(name);
  15627. const loaded_reduces = new Map();
  15628. this.storage_context = new torch._C.DeserializationStorageContext();
  15629. const unpickler = new pickle.Unpickler(stream);
  15630. unpickler.persistent_load = (saved_id) => {
  15631. switch (saved_id[0]) {
  15632. case 'storage': {
  15633. const [, storage_type, key, , size] = saved_id;
  15634. if (!this.storage_context.has_storage(key)) {
  15635. const storage = new storage_type(size);
  15636. if (!storage._set_cdata) {
  15637. throw new python.Error(`'${storage_type.__name__}._set_cdata' is not a function.`);
  15638. }
  15639. const stream = this.zip_reader.get_record(`.data/${key}.storage`);
  15640. const buffer = stream.peek();
  15641. storage._set_cdata(buffer);
  15642. this.storage_context.add_storage(key, storage);
  15643. }
  15644. return this.storage_context.get_storage(key);
  15645. }
  15646. case 'reduce_package': {
  15647. if (saved_id.length === 2) {
  15648. const [, func, args] = saved_id;
  15649. return execution.invoke(func, args);
  15650. }
  15651. const [, reduce_id, func, args] = saved_id;
  15652. if (!loaded_reduces.has(reduce_id)) {
  15653. const value = execution.invoke(func, [this].concat(args));
  15654. loaded_reduces.set(reduce_id, value);
  15655. }
  15656. return loaded_reduces.get(reduce_id);
  15657. }
  15658. default: {
  15659. throw new python.Error(`Unknown package typename '${saved_id[0]}'.`);
  15660. }
  15661. }
  15662. };
  15663. const obj = unpickler.load();
  15664. this.storage_context = null;
  15665. return obj;
  15666. }
  15667. import_module(name) {
  15668. return execution.import(name);
  15669. }
  15670. });
  15671. this.registerFunction('torch.jit.load', (file, map_location, extra_files) => {
  15672. const cu = new torch.jit.CompilationUnit();
  15673. cu.execution = execution;
  15674. const cpp_module = torch._C.import_ir_module(cu, file, map_location, extra_files);
  15675. const module = torch.jit._script.wrap_cpp_module(cpp_module);
  15676. module.forward = cpp_module.forward; // remove
  15677. return module;
  15678. });
  15679. this.registerFunction('torch._C.import_ir_module', function(cu, reader, ...args) {
  15680. switch (arguments.length) {
  15681. case 4: {
  15682. const [device, extra_files] = args;
  15683. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader);
  15684. return deserializer.deserialize(device, extra_files);
  15685. }
  15686. case 5: {
  15687. const [storage_context, device, ts_id] = args;
  15688. const deserializer = new torch._C.ScriptModuleDeserializer(cu, reader, `.data/ts_code/${ts_id}/`, '.data/', storage_context);
  15689. return deserializer.deserialize(device, null);
  15690. }
  15691. default: {
  15692. throw new python.Error("Invalid 'torch._C.import_ir_module' signature.");
  15693. }
  15694. }
  15695. });
  15696. this.registerFunction('torch._C._import_ir_module_from_package', (cu, reader, storage_context, map_location, ts_id) => {
  15697. return torch._C.import_ir_module(cu, reader, storage_context, null, ts_id);
  15698. });
  15699. this.registerFunction('torch._C.tryToGraphFunction', (value) => {
  15700. if (value instanceof torch.Node) {
  15701. const n = value;
  15702. if (n.kind() === 'prim::CallFunction') {
  15703. torch._C.AT_ASSERT(n.input(0).node().kind() === 'prim::Constant');
  15704. const function_constant = n.input(0).node();
  15705. const fun_type = function_constant.output().type().expect(torch._C.FunctionType);
  15706. return torch._C.tryToGraphFunction(fun_type.function());
  15707. }
  15708. if (n.kind() === 'prim::CallMethod') {
  15709. const name = n.s('name');
  15710. const class_type = n.input(0).type();
  15711. if (class_type instanceof torch.ClassType) {
  15712. const fn = class_type.getMethod(name);
  15713. return torch._C.tryToGraphFunction(fn);
  15714. }
  15715. }
  15716. return null;
  15717. } else if (value instanceof torch._C.Function) {
  15718. const fn = value;
  15719. if (!fn.isGraphFunction()) {
  15720. return null;
  15721. }
  15722. return fn;
  15723. }
  15724. throw new python.Error('Not implemented.');
  15725. });
  15726. this.registerType('torch._C.ModuleInstanceInfo', class {
  15727. constructor(module_type, instance_name) {
  15728. this._module_type = module_type;
  15729. this._instance_name = instance_name;
  15730. }
  15731. });
  15732. this.registerFunction('torch._C.slice_indices_adjust', (length, start, stop, step) => {
  15733. torch._C.TORCH_CHECK(step !== 0);
  15734. torch._C.TORCH_CHECK(step >= -Number.MAX_SAFE_INTEGER); // INT64_MAX
  15735. if (start._ === Number.MAX_SAFE_INTEGER) {
  15736. start._ = (step < 0) ? Number.MAX_SAFE_INTEGER : 0;
  15737. }
  15738. if (stop._ === Number.MAX_SAFE_INTEGER) {
  15739. stop._ = (step < 0) ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
  15740. }
  15741. if (start._ < 0) {
  15742. start._ += length;
  15743. if (start._ < 0) {
  15744. start._ = (step < 0) ? -1 : 0;
  15745. }
  15746. } else if (start._ >= length) {
  15747. start._ = (step < 0) ? length - 1 : length;
  15748. }
  15749. if (stop._ < 0) {
  15750. stop._ += length;
  15751. if (stop._ < 0) {
  15752. stop._ = (step < 0) ? -1 : 0;
  15753. }
  15754. } else if (stop._ >= length) {
  15755. stop._ = (step < 0) ? length - 1 : length;
  15756. }
  15757. if (step < 0) {
  15758. if (stop._ < start._) {
  15759. return Math.floor((start._ - stop._ - 1) / (-step) + 1);
  15760. }
  15761. } else if (start._ < stop._) {
  15762. return Math.floor((stop._ - start._ - 1) / step + 1);
  15763. }
  15764. return 0;
  15765. });
  15766. this.registerFunction('torch._C.createTupleUnpack', (v) => {
  15767. if (v.node().kind() === 'prim::TupleConstruct') {
  15768. return v.node().inputs();
  15769. }
  15770. const g = v.owningGraph();
  15771. return g.insertNode(g.createTupleUnpack(v)).outputs();
  15772. });
  15773. this.registerFunction('torch._C.inlineCallStackOfNode', (/* new_node, new_cs_entriesm, callee, to_replace, m_info */) => {
  15774. /*
  15775. const new_node_cs = new_node.callstack();
  15776. const raw_callstack_ptr = new_node_cs ? new_node_cs : nullptr;
  15777. if (!new_cs_entries.has(raw_callstack_ptr)) {
  15778. if (new_node_cs) {
  15779. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(*new_node_cs, callee, to_replace.sourceRange(), m_info));
  15780. } else {
  15781. new_cs_entries.set(raw_callstack_ptr, c10::make_intrusive<InlinedCallStack>(callee, to_replace.sourceRange(), m_info);
  15782. }
  15783. }
  15784. new_node.setCallStack(new_cs_entries.at(raw_callstack_ptr));
  15785. for (const block of new_node.blocks()) {
  15786. torch._C.inlineCallStackOfBlock(block, new_cs_entries, callee, to_replace, m_info);
  15787. }
  15788. */
  15789. });
  15790. this.registerFunction('torch._C.inlineCallTo', (to_replace, callee, arg) => {
  15791. if (arg === undefined || typeof arg === 'boolean') {
  15792. const inline_optimized_graph = arg === undefined ? true : arg;
  15793. const graph = inline_optimized_graph ? callee.optimized_graph() : callee.graph();
  15794. return torch._C.inlineCallTo(to_replace, callee, graph);
  15795. }
  15796. if (arg instanceof torch.Graph === false) {
  15797. throw new python.Error('Invalid argument.');
  15798. }
  15799. const callee_graph = arg;
  15800. const guard = new torch._C.WithInsertPoint(to_replace);
  15801. const value_map = new Map();
  15802. const new_outputs = torch._C.insertGraph(to_replace.owningGraph(), callee_graph, to_replace.inputs(), value_map);
  15803. const new_callstack_entries = new Map();
  15804. let module_instance_info = null;
  15805. if (to_replace.kind() === 'prim::CallMethod') {
  15806. const class_type_ptr = to_replace.input(0).type();
  15807. if (to_replace.input(0).node().kind() === 'prim::GetAttr') {
  15808. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, to_replace.input(0).node().s('name'));
  15809. } else if (to_replace.owningGraph().inputs().length > 0 && to_replace.input(0) === to_replace.owningGraph().inputs()[0]) {
  15810. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'SELF');
  15811. } else {
  15812. module_instance_info = new torch._C.ModuleInstanceInfo(class_type_ptr, 'INSTANCE_NAME_UNKNOWN');
  15813. }
  15814. }
  15815. const updated_nodes = new Set();
  15816. for (const kv of value_map) {
  15817. const is_graph_input = callee_graph.inputs().indexOf(kv[0]);
  15818. if (is_graph_input === -1) {
  15819. continue;
  15820. }
  15821. const new_node = kv[1].node();
  15822. if (updated_nodes.has(new_node)) {
  15823. continue;
  15824. }
  15825. updated_nodes.add(new_node);
  15826. torch._C.inlineCallStackOfNode(new_node, new_callstack_entries, callee, to_replace, module_instance_info);
  15827. }
  15828. const old_outputs = to_replace.outputs();
  15829. torch._C.AT_ASSERT(new_outputs.length === old_outputs.length);
  15830. for (let i = 0; i < old_outputs.length; i++) {
  15831. if (old_outputs[i].hasDebugName()) {
  15832. new_outputs[i].setDebugName(old_outputs[i].debugName());
  15833. }
  15834. old_outputs[i].replaceAllUsesWith(new_outputs[i]);
  15835. }
  15836. to_replace.destroy();
  15837. guard.dispose();
  15838. return new_outputs;
  15839. });
  15840. this.registerFunction('torch._C.inlineCalls', (block) => {
  15841. for (const cur of block.nodes()) {
  15842. switch (cur.kind()) {
  15843. case 'prim::CallFunction': {
  15844. const graphFunction = torch._C.tryToGraphFunction(cur);
  15845. if (graphFunction) {
  15846. const function_constant = cur.input(0).node();
  15847. // const fun_type = function_constant.output().type().expect(torch.FunctionType);
  15848. cur.removeInput(0);
  15849. let g = null;
  15850. const fallback = function_constant.hasAttribute('fallback');
  15851. if (fallback && graphFunction.get_executor().isOptimized()) {
  15852. const exec_plans = graphFunction.get_executor().getDebugState().execution_plans;
  15853. if (!exec_plans.empty()) {
  15854. g = exec_plans.begin().second.graph;
  15855. torch._C.Inline(g);
  15856. }
  15857. }
  15858. if (g === null) {
  15859. g = graphFunction.optimized_graph();
  15860. }
  15861. torch._C.inlineCallTo(cur, graphFunction, g);
  15862. }
  15863. break;
  15864. }
  15865. case 'prim::CallMethod': {
  15866. const graphFunction = torch._C.tryToGraphFunction(cur);
  15867. if (graphFunction) {
  15868. torch._C.inlineCallTo(cur, graphFunction);
  15869. }
  15870. break;
  15871. }
  15872. default: {
  15873. for (const b of cur.blocks()) {
  15874. torch._C.inlineCalls(b);
  15875. }
  15876. }
  15877. }
  15878. }
  15879. });
  15880. this.registerFunction('torch._C.Inline', (graph) => {
  15881. torch._C.inlineCalls(graph.block());
  15882. });
  15883. this.registerFunction('torch._C._jit_pass_inline', (graph) => {
  15884. torch._C.Inline(graph);
  15885. });
  15886. this.registerFunction('torch._C._set_tensor_metadata', (/* tensor, metadata */) => {
  15887. });
  15888. this.registerFunction('torch.jit._script.unpackage_script_module', (importer, script_module_id) => {
  15889. const cu = new torch.jit.CompilationUnit();
  15890. cu.execution = execution;
  15891. const cpp_module = torch._C._import_ir_module_from_package(cu, importer.zip_reader, importer.storage_context, importer.last_map_location, script_module_id);
  15892. return torch.jit._script.wrap_cpp_module(cpp_module);
  15893. });
  15894. this.registerFunction('torch.jit._script.wrap_cpp_module', (cpp_module) => {
  15895. const init_fn = (script_module) => {
  15896. for (const [name, module] of new torch.ModuleDict(script_module._c).items()) {
  15897. script_module.__setattr__(name, torch.jit._script.wrap_cpp_module(module));
  15898. }
  15899. };
  15900. return torch.jit._script.RecursiveScriptModule._construct(cpp_module, init_fn);
  15901. });
  15902. this.registerType('torch._C.DeserializationStorageContext', class extends Map {
  15903. has_storage(name) {
  15904. return this.has(name);
  15905. }
  15906. get_storage(name) {
  15907. return this.get(name);
  15908. }
  15909. add_storage(name, storage) {
  15910. return this.set(name, storage);
  15911. }
  15912. });
  15913. this.registerType('torch.ScriptFunction', class {
  15914. constructor(name, graph /*, function_creator */) {
  15915. this._name = name;
  15916. this._graph = graph;
  15917. }
  15918. });
  15919. this.registerType('torch.ScriptMethod', class {
  15920. constructor(owner, value) {
  15921. this._owner = owner;
  15922. this._function = value;
  15923. }
  15924. get name() {
  15925. return this._function.name();
  15926. }
  15927. get owner() {
  15928. return this._owner;
  15929. }
  15930. __call__(/* args, kwargs */) {
  15931. throw new python.Error("'torch.ScriptMethod.__call__' not implemented.");
  15932. }
  15933. get graph() {
  15934. return this._function.graph();
  15935. }
  15936. get schema() {
  15937. // return this.function().getSchema();
  15938. throw new python.Error("'torch.ScriptMethod.schema' not implemented.");
  15939. }
  15940. get code() {
  15941. throw new python.Error("'torch.ScriptMethod.code' not implemented.");
  15942. }
  15943. get code_with_constants() {
  15944. throw new python.Error("'torch.ScriptMethod.code_with_constants' not implemented.");
  15945. }
  15946. });
  15947. this.registerType('torch.ScriptObject', class {
  15948. constructor(type) {
  15949. this._typ = type;
  15950. this._ivalue = {};
  15951. }
  15952. static create(type) {
  15953. if (type.is_module()) {
  15954. return new torch.ScriptModule(type);
  15955. }
  15956. return new torch.ScriptObject(type);
  15957. }
  15958. type() {
  15959. return this._typ;
  15960. }
  15961. _type() {
  15962. return this._typ; // torch.ClassType
  15963. }
  15964. __setstate__(state) {
  15965. const [attrs, qualname] = state;
  15966. this._typ = torch._C.getCustomClass(qualname);
  15967. if (!this._typ) {
  15968. throw new python.Error(`Unsupported custom class '${qualname}'.`);
  15969. }
  15970. for (let i = 0; i < this._typ.numAttributes(); i++) {
  15971. const name = this._typ.getAttributeName(i);
  15972. this.__setattr__(name, attrs[i]);
  15973. }
  15974. }
  15975. find_method(basename) {
  15976. for (const fn of this.type().methods()) {
  15977. if (fn.name() === basename) {
  15978. return new torch.ScriptMethod(this /* _value() */, fn);
  15979. }
  15980. }
  15981. return null;
  15982. }
  15983. _get_method(name) {
  15984. const method = this.find_method(name);
  15985. if (method) {
  15986. return method;
  15987. }
  15988. torch._C.TORCH_CHECK(false, `Method '${name}' is not defined.`);
  15989. return null;
  15990. }
  15991. _has_method(name) {
  15992. return this.find_method(name) ? true : false;
  15993. }
  15994. _method_names() {
  15995. return this.type().methods().map((fn) => fn.name());
  15996. }
  15997. __setattr__(name, value) {
  15998. // if (this._type.hasContant(name))
  15999. this._ivalue[name] = value;
  16000. }
  16001. __getattr__(name) {
  16002. return this._ivalue[name];
  16003. }
  16004. hasattr(name) {
  16005. return this._typ.hasAttribute(name) || this._typ.hasConstant(name);
  16006. }
  16007. getattr(name) {
  16008. return this.__getattr__(name);
  16009. }
  16010. _properties() {
  16011. throw new python.Error("'torch.ScriptObject._properties' not implemented.");
  16012. }
  16013. is_weak_compilation_ref() {
  16014. return true; // not implemented
  16015. }
  16016. });
  16017. this.registerType('torch.ScriptModule', class extends torch.ScriptObject {
  16018. constructor(...args) {
  16019. if (args[0] instanceof torch._C.QualifiedName && args[1] instanceof torch.jit.CompilationUnit) {
  16020. const [class_name, cu, shouldMangle] = args;
  16021. super(...torch.ScriptModule.create_module_object(class_name, cu, shouldMangle));
  16022. } else {
  16023. super(...args);
  16024. }
  16025. }
  16026. get qualified_name() {
  16027. return this.type().qualified_name();
  16028. }
  16029. get code_with_constants() {
  16030. const const_map = {};
  16031. const_map.const_mapping = new Map(Object.entries(execution.builtins.CONSTANTS));
  16032. return [null, const_map];
  16033. }
  16034. get graph() {
  16035. if (!this._graph) {
  16036. const fn = this._typ.getMethod('forward');
  16037. this._graph = fn.graph();
  16038. }
  16039. return this._graph;
  16040. }
  16041. static create_module_object(class_name, cu, shouldMangle) {
  16042. shouldMangle = shouldMangle || false;
  16043. if (!class_name.prefix()) {
  16044. class_name = new torch._C.QualifiedName('__torch__', class_name.name());
  16045. }
  16046. if (shouldMangle && cu.get_class(class_name)) {
  16047. class_name = cu.mangle(class_name);
  16048. }
  16049. const cls = torch.ClassType.create(class_name, cu, true);
  16050. cu.register_type(cls);
  16051. return [cls, cu];
  16052. }
  16053. register_module(name, module) {
  16054. this.type().addOrCheckAttribute(name, module.type());
  16055. this.__setattr__(name, module); // _ivalue()->setAttr(name, module._ivalue());
  16056. }
  16057. register_buffer(name, v) {
  16058. this.type().addOrCheckAttribute(name, torch.TensorType.get(), false, true);
  16059. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16060. }
  16061. register_parameter(name, v, is_buffer) {
  16062. this.type().addOrCheckAttribute(name, torch.TensorType.get(), !is_buffer, is_buffer);
  16063. this.__setattr__(name, v); // _ivalue()->setAttr(name, std::move(v));
  16064. }
  16065. register_attribute(name, t, v, is_param, is_buffer) {
  16066. this.type().addOrCheckAttribute(name, t, is_param, is_buffer);
  16067. // _ivalue()->setAttr(name, v);
  16068. }
  16069. });
  16070. this.registerType('torch.ModuleDict', class {
  16071. constructor(mod) {
  16072. this._module = mod;
  16073. }
  16074. items() {
  16075. const result = new Map();
  16076. const type = this._module.type();
  16077. for (let i = 0; i < type.numAttributes(); i++) {
  16078. const k = type.getAttributeName(i);
  16079. const t = type.getAttribute(i);
  16080. if (t && t.is_module()) {
  16081. result.set(k, this._module.__getattr__(k));
  16082. }
  16083. }
  16084. return result;
  16085. }
  16086. });
  16087. this.registerType('torch.ParameterDict', class {
  16088. constructor(mod) {
  16089. this._module = mod;
  16090. }
  16091. items() {
  16092. const result = new Map();
  16093. const type = this._module.type();
  16094. for (let i = 0; i < type.numAttributes(); i++) {
  16095. if (type.is_parameter(i)) {
  16096. const k = type.getAttributeName(i);
  16097. const v = this._module.__getattr__(k);
  16098. if (v instanceof torch.Tensor) {
  16099. result.set(k, v);
  16100. }
  16101. }
  16102. }
  16103. return result;
  16104. }
  16105. });
  16106. this.registerType('torch.BufferDict', class {
  16107. constructor(mod) {
  16108. this._module = mod;
  16109. }
  16110. items() {
  16111. const result = new Map();
  16112. const type = this._module.type();
  16113. for (let i = 0; i < type.numAttributes(); i++) {
  16114. if (type.is_buffer(i)) {
  16115. const t = type.getAttribute(i);
  16116. if (t.isSubtypeOf(torch.TensorType.get())) {
  16117. const k = type.getAttributeName(i);
  16118. const v = this._module.__getattr__(k);
  16119. result.set(k, v);
  16120. }
  16121. }
  16122. }
  16123. return result;
  16124. }
  16125. });
  16126. this.registerType('torch._C.to_ir', class {
  16127. constructor(def, _resolver, self, method) {
  16128. this.method = method;
  16129. this.graph = method.graph();
  16130. this.resolver = _resolver;
  16131. this.integral_constants = new Map();
  16132. this.fp_constants = new Map();
  16133. this.complex_constants = new Map();
  16134. this.exit_blocks = new Set();
  16135. this._typeParser = new torch._C.ScriptTypeParser(this.resolver);
  16136. this._loop_status = 'NOT_IN_LOOP';
  16137. this.environment_stack = null;
  16138. this._def_stack = [];
  16139. this._temp_name_count = 0;
  16140. torch._C.AT_ASSERT(this.resolver);
  16141. this.pushFrame(this.graph.block(), true);
  16142. if (self && def && def.args.args.length === 0) {
  16143. throw new python.Error('Method must have a self argument.');
  16144. }
  16145. method.setSchema(this.emitDef(def, self, this.graph.block()));
  16146. // torch._C.ReplaceOldOperatorsWithUpgraders(this.graph);
  16147. torch._C.ConvertToSSA(this.graph);
  16148. torch._C.CanonicalizeModifiedLoops(this.graph);
  16149. torch._C.NormalizeOps(this.graph.block());
  16150. torch._C.runCleanupPasses(this.graph);
  16151. }
  16152. pushFrame(b, starts_def) {
  16153. starts_def = starts_def || false;
  16154. if (starts_def) {
  16155. this._def_stack.push({});
  16156. }
  16157. this.environment_stack = new torch._C.Environment(this.method, this.resolver, b, this.environment_stack);
  16158. }
  16159. popFrame(ends_def) {
  16160. const old_frame = this.environment_stack;
  16161. this.environment_stack = this.environment_stack.next;
  16162. if (ends_def) {
  16163. this._def_stack.pop();
  16164. }
  16165. return old_frame;
  16166. }
  16167. emitDef(def, self, block) {
  16168. const schema = this._typeParser.parseSchemaFromDef(def, self !== null);
  16169. if (schema.returns.length === 1) {
  16170. this._def_stack[this._def_stack.length - 1]._declared_return_type = schema.returns[0].type;
  16171. }
  16172. const args = this.emitFormalArguments(def, self, schema, block);
  16173. this.emitStatements(def.body);
  16174. this.handleMaybeNoReturn(def, block);
  16175. const returns = [this.emitOutput(def, schema, block)];
  16176. return new torch.FunctionSchema(def.name, '', args, returns);
  16177. }
  16178. emitFormalArguments(def, self, schema, block) {
  16179. const args = [];
  16180. const params = def.args.args;
  16181. const expected_annotation_size = self ? def.args.args.length - 1 : def.args.args.length;
  16182. if (schema.arguments.length !== expected_annotation_size) {
  16183. throw new python.Error('Invalid formal arguments.');
  16184. }
  16185. let it = 0;
  16186. if (self) {
  16187. const param = params[it];
  16188. const name = param.arg;
  16189. const new_input = block.addInput().setDebugName(name);
  16190. this.environment_stack.setSugaredVar(param.range(), name, self.makeSugared(new_input), null);
  16191. args.push(new torch.Argument(name, new_input.type()));
  16192. it++;
  16193. }
  16194. const shouldDeriveType = this.shouldDeriveSetStateType(def, schema);
  16195. let arg_annotation_idx = 0;
  16196. for (; it < params.length; it++) {
  16197. const param = params[it];
  16198. const name = param.arg;
  16199. const new_input = block.addInput();
  16200. if (torch._C.meaningfulName(name)) {
  16201. new_input.setDebugName(name);
  16202. }
  16203. let arg = schema.arguments[arg_annotation_idx++];
  16204. if (shouldDeriveType) {
  16205. if (schema.arguments.length === 1) {
  16206. throw new python.Error('Invalid schema.');
  16207. }
  16208. const inferredStateType = this.getTypeForSetStateArg(def, self);
  16209. arg = arg.cloneWithType(inferredStateType);
  16210. }
  16211. args.push(arg);
  16212. new_input.setType(arg.type);
  16213. this.environment_stack.setVar(param.range(), name, new_input);
  16214. }
  16215. return args;
  16216. }
  16217. emitOutput(range, schema, block) {
  16218. const ret_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16219. const placeholder_return = this.graph.insertNode(this.graph.createUninitialized(ret_type)).output();
  16220. block.registerOutput(placeholder_return);
  16221. return new torch.Argument('', this._def_stack[this._def_stack.length - 1]._merged_return_type);
  16222. }
  16223. emitStatements(stmts) {
  16224. for (let i = 0; i < stmts.length; i++) {
  16225. const stmt = stmts[i];
  16226. if (stmt instanceof ast.If) {
  16227. this.emitIf(stmt);
  16228. } else if (stmt instanceof ast.While) {
  16229. this.emitWhile(stmt);
  16230. } else if (stmt instanceof ast.For) {
  16231. this.emitFor(stmt);
  16232. } else if (stmt instanceof ast.Assign) {
  16233. this.emitAssignment(stmt);
  16234. } else if (stmt instanceof ast.AnnAssign) {
  16235. this.emitAssignment(stmt);
  16236. } else if (stmt instanceof ast.Expr) {
  16237. this.emitSugaredExpr(stmt.value, 0);
  16238. } else if (stmt instanceof ast.Return) {
  16239. this.emitReturn(stmt);
  16240. } else if (stmt instanceof ast.Pass) {
  16241. // pass
  16242. } else if (stmt instanceof ast.With) {
  16243. this.emitWith(stmt);
  16244. } else {
  16245. throw new python.Error(`Unrecognized statement kind '${stmt.__class__.__name__}'.`);
  16246. }
  16247. if (this.exit_blocks.has(this.environment_stack.block())) {
  16248. return;
  16249. }
  16250. }
  16251. }
  16252. emitWith(stmt) {
  16253. const targets = stmt.items;
  16254. const entered = [];
  16255. for (const target of targets) {
  16256. const e = target.context_expr;
  16257. const rhs = this.emitExpr(e);
  16258. const n = this.graph.insertNode(this.graph.create('prim::Enter', [rhs]));
  16259. entered.push(rhs);
  16260. if (rhs.type() instanceof torch.ClassType === false) {
  16261. throw new python.Error('With item expression must return an object.');
  16262. }
  16263. const rhsClass = rhs.type();
  16264. const enterMethod = rhsClass.findMethod('__enter__');
  16265. const exitMethod = rhsClass.findMethod('__exit__');
  16266. if (!enterMethod || !exitMethod) {
  16267. throw new python.Error('Object returned by with item expression does not define __enter__ and __exit__ methods.');
  16268. }
  16269. const enterSchema = enterMethod.getSchema();
  16270. if (enterSchema.arguments.length !== 1) {
  16271. throw new python.Error('__enter__ must have only one argument and one return value.');
  16272. }
  16273. const exitSchema = exitMethod.getSchema();
  16274. if (exitSchema.arguments.length === 4) {
  16275. for (let i = 1; i < 4; i++) {
  16276. if (exitSchema.arguments[i].type !== torch.AnyType.get()) {
  16277. throw new python.Error('Argument of __exit__ must have Any type.');
  16278. }
  16279. }
  16280. } else {
  16281. throw new python.Error('__exit__ must have four arguments');
  16282. }
  16283. n.output(0).setType(enterSchema.returns[0].type);
  16284. if (target.optional_vars) {
  16285. throw new python.Error('Not implemented.');
  16286. // Var i = target.var().get();
  16287. // this.environment_stack.setVar(i.range(), i.name().name(), n.output(0));
  16288. }
  16289. }
  16290. this.emitStatements(stmt.body);
  16291. while (entered.length > 0) {
  16292. const input = entered.pop();
  16293. const n = this.graph.create('prim::Exit');
  16294. this.graph.insertNode(n);
  16295. n.addInput(input);
  16296. }
  16297. }
  16298. emitLoopCommon(range, emit_body, iter_val, targets, cond) {
  16299. let max_trip_count_val = null;
  16300. if (iter_val === null) {
  16301. max_trip_count_val = torch._C.materializeConstant(Number.MAX_SAFE_INTEGER /*std::numeric_limits<int64_t>::max()*/, this.graph, range, this.integral_constants);
  16302. } else {
  16303. max_trip_count_val = iter_val.len(range, this.method);
  16304. }
  16305. const n = this.graph.insertNode(this.create('prim::Loop', range, 0));
  16306. const body_block = n.addBlock();
  16307. {
  16308. const condition_block = n.addBlock();
  16309. this.pushFrame(condition_block);
  16310. let out = null;
  16311. if (cond) {
  16312. const insert = new torch._C.WithInsertPoint(condition_block);
  16313. out = this.emitToBool(cond.range(), this.emitExpr(cond));
  16314. insert.dispose();
  16315. } else {
  16316. const insert = new torch._C.WithInsertPoint(n);
  16317. out = this.graph.insertConstant(true, range);
  16318. insert.dispose();
  16319. }
  16320. condition_block.registerOutput(out);
  16321. this.popFrame();
  16322. }
  16323. n.addInput(max_trip_count_val);
  16324. const loop_guard = new torch._C.WithLoopStatus(this, 'IN_LOOP');
  16325. const trip_count = body_block.addInput().setType(torch.IntType.get());
  16326. {
  16327. this.pushFrame(body_block);
  16328. const guard = new torch._C.WithInsertPoint(body_block);
  16329. if (iter_val !== null && targets) {
  16330. const cur_elem = iter_val.getitem(range, this.method, trip_count).asValue(range, this.method);
  16331. const sv = new torch._C.SimpleValue(cur_elem);
  16332. const target_exprs = targets;
  16333. this.validateAssignLhsExpr(target_exprs, range);
  16334. if (target_exprs.length > 1) {
  16335. throw new python.Error('Not implemented.');
  16336. // const tl = torch.TupleLiteral.create(range, target_exprs);
  16337. // target_exprs = ListExpr.create(range, [tl]);
  16338. }
  16339. this.emitExprsAssign(target_exprs, [sv], range, /*n_binders=*/1);
  16340. }
  16341. emit_body();
  16342. this.popFrame();
  16343. guard.dispose();
  16344. }
  16345. loop_guard.dispose();
  16346. }
  16347. emitFor(...args) {
  16348. if (args.length === 1 && args[0] instanceof ast.For) {
  16349. const [stmt] = args;
  16350. const emit_body = () => this.emitStatements(stmt.body);
  16351. this.emitFor(stmt.target, stmt.iter, stmt.range(), emit_body);
  16352. } else if (args.length === 4) {
  16353. const [targets, itrs, loc, emit_body] = args;
  16354. if (itrs instanceof ast.Tuple) {
  16355. throw new python.Error('List of iterables is not supported currently.');
  16356. }
  16357. const sv = this.emitSugaredExpr(itrs, 1);
  16358. const iterable = sv.iter(loc, this.method);
  16359. if (iterable.shouldEmitUnrolled()) {
  16360. this.emitUnrolledLoop(loc, emit_body, iterable, targets);
  16361. } else {
  16362. this.emitLoopCommon(loc, emit_body, iterable, [targets], null);
  16363. }
  16364. } else {
  16365. throw new python.Error('Not implemented.');
  16366. }
  16367. }
  16368. emitWhile(stmt) {
  16369. const cond = stmt.test;
  16370. const emit_body = () => this.emitStatements(stmt.body);
  16371. this.emitLoopCommon(stmt.range(), emit_body, null, [], cond);
  16372. }
  16373. emitIsInstance(obj, classinfo) {
  16374. const lhs_val = this.emitExpr(obj);
  16375. const lhs_types = [];
  16376. const rhs_types = [];
  16377. const gather_rhs = (expr) => {
  16378. if (expr instanceof ast.Tuple) {
  16379. for (const e of expr.elts) {
  16380. gather_rhs(e);
  16381. }
  16382. return;
  16383. }
  16384. const type = this._typeParser.parseTypeFromExpr(expr);
  16385. rhs_types.push(type);
  16386. };
  16387. lhs_types.push(lhs_val.type());
  16388. gather_rhs(classinfo);
  16389. torch._C.standardizeVectorForUnion(lhs_types);
  16390. torch._C.standardizeVectorForUnion(rhs_types);
  16391. let refinement = new torch._C.RefinementSet([], []);
  16392. let unified_true = null;
  16393. let unified_false = null;
  16394. const isinstance_types = [];
  16395. const not_isinstance_types = [];
  16396. let true_refinements = [];
  16397. let false_refinements = [];
  16398. let all_lhs_subtype_some_rhs = true;
  16399. for (const lhs_type of lhs_types) {
  16400. if (lhs_type === torch.AnyType.get()) {
  16401. isinstance_types.push(...rhs_types);
  16402. not_isinstance_types.push(torch.AnyType.get());
  16403. if (isinstance_types.length !== 1 || isinstance_types[0] !== torch.AnyType.get()) {
  16404. all_lhs_subtype_some_rhs = false;
  16405. }
  16406. break;
  16407. }
  16408. const get_smaller_type = (t1, t2) => {
  16409. if (t1.isSubtypeOf(t2)) {
  16410. return t1;
  16411. } else if (t2.isSubtypeOf(t1)) {
  16412. return t2;
  16413. }
  16414. return null;
  16415. };
  16416. let found_refinement = null;
  16417. for (const rhs_type of rhs_types) {
  16418. const maybe_smaller_type = get_smaller_type(lhs_type, rhs_type);
  16419. if (!maybe_smaller_type) {
  16420. continue;
  16421. } else if (maybe_smaller_type === lhs_type) {
  16422. found_refinement = lhs_type;
  16423. } else if (maybe_smaller_type === rhs_type) {
  16424. found_refinement = found_refinement ? torch._C.unifyTypes(found_refinement, rhs_type) : rhs_type;
  16425. }
  16426. }
  16427. if (found_refinement) {
  16428. if (found_refinement === lhs_type) {
  16429. all_lhs_subtype_some_rhs &= true;
  16430. }
  16431. isinstance_types.push(found_refinement);
  16432. } else {
  16433. not_isinstance_types.push(lhs_type);
  16434. all_lhs_subtype_some_rhs = false;
  16435. }
  16436. }
  16437. if (isinstance_types.length > 0) {
  16438. unified_true = torch._C.unifyTypeList(isinstance_types, null, /*default_to_union=*/true);
  16439. }
  16440. if (obj instanceof ast.Name && unified_true) {
  16441. const ident = obj.id;
  16442. true_refinements = [new torch._C.Refinement(ident, unified_true)];
  16443. }
  16444. if (not_isinstance_types.length > 0) {
  16445. unified_false = torch._C.unifyTypeList(not_isinstance_types, null, /*default_to_union=*/true);
  16446. }
  16447. if (obj instanceof ast.Name && unified_false) {
  16448. const ident = obj.id;
  16449. false_refinements = [new torch._C.Refinement(ident, unified_false)];
  16450. }
  16451. refinement = new torch._C.RefinementSet(true_refinements, false_refinements);
  16452. const is_statically_false = isinstance_types.length === 0;
  16453. if (all_lhs_subtype_some_rhs) {
  16454. return new torch._C.CondValue(this.graph, obj.range(), true, refinement);
  16455. }
  16456. if (is_statically_false) {
  16457. return new torch._C.CondValue(this.graph, obj.range(), false, refinement);
  16458. }
  16459. const result = this.graph.insertNode(this.graph.createIsInstance(lhs_val, rhs_types)).output();
  16460. return new torch._C.CondValue(result, refinement, null);
  16461. }
  16462. emitIf(stmt) {
  16463. const cond_value = this.emitCondExpr(stmt.test);
  16464. this.emitIfElseBlocks(stmt.range(), cond_value, stmt.body, stmt.orelse);
  16465. }
  16466. emitCondExpr(expr) {
  16467. /*
  16468. switch (expr.kind()) {
  16469. case TK_AND:
  16470. case TK_OR: {
  16471. const binop = BinOp(expr);
  16472. return emitShortCircuitLogical(
  16473. binop.range(), binop.lhs(), binop.rhs(), expr.kind() == TK_OR);
  16474. }
  16475. case TK_NOT: {
  16476. CondValue v = emitCondExpr(Expr(expr.tree().trees()[0]));
  16477. Value* result = emitBuiltinCall(
  16478. expr.range(), *graph, aten::__not__, {v.value()}, {});
  16479. std::optional<bool> static_if;
  16480. if (v.staticIf()) {
  16481. static_if = !*v.staticIf();
  16482. }
  16483. return CondValue(result, v.refinements().Not(), static_if);
  16484. } break;
  16485. case TK_IS:
  16486. case TK_ISNOT: {
  16487. // meta programming on AST for is/is not cases and emit branches base on
  16488. const cond_op = BinOp(expr);
  16489. Value* lhs_val = emitExpr(cond_op.lhs());
  16490. Value* rhs_val = emitExpr(cond_op.rhs());
  16491. const lhs_none = canBeNone(lhs_val);
  16492. const rhs_none = canBeNone(rhs_val);
  16493. // Dispatch logic (A: ALWAYS, N: NEVER, M: MAYBE):
  16494. // AA, -> statically IS always holds, IS_NOT never holds
  16495. // AN , NA-> statically IS_NOT always holds, IS never holds
  16496. // MA, MM, MN, NM, NN, AM -> cannot prove anything statically
  16497. bool its_is = expr.kind() == TK_IS;
  16498. if (lhs_none == ALWAYS && rhs_none == ALWAYS) {
  16499. return CondValue(*graph, expr.range(), its_is, {});
  16500. } else if (
  16501. (lhs_none == ALWAYS && rhs_none == NEVER) ||
  16502. (lhs_none == NEVER && rhs_none == ALWAYS)) {
  16503. // lhs_val/rhs_val with A/M: only emit never_none_branch
  16504. return CondValue(*graph, expr.range(), !its_is, {});
  16505. } else {
  16506. const kind = getNodeKind(expr.kind(), expr.get()->trees().size());
  16507. Value* cond_value = emitBuiltinCall(
  16508. expr.get()->range(),
  16509. *method.graph(),
  16510. kind,
  16511. {lhs_val, rhs_val},
  16512. {});
  16513. const refinements = RefinementSet(findIsNoneRefinements(
  16514. cond_op.lhs(), lhs_val, cond_op.rhs(), rhs_val, expr.kind()));
  16515. return CondValue(cond_value, refinements, null);
  16516. }
  16517. } break;
  16518. */
  16519. if (expr instanceof ast.UnaryOp) {
  16520. throw new python.Error('Not implemented.');
  16521. }
  16522. if (expr instanceof ast.Call) {
  16523. const apply = expr;
  16524. const callee = expr.func;
  16525. if (callee instanceof ast.Name) {
  16526. if (callee.id === 'isinstance') {
  16527. this.checkApplyNumInputs(apply, 2);
  16528. return this.emitIsInstance(apply.args[0], apply.args[1]);
  16529. }
  16530. if (callee.id === 'hasattr') {
  16531. this.checkApplyNumInputs(apply, 2);
  16532. return this.emitHasAttr(apply.args[0], apply.args[1]);
  16533. }
  16534. const sv = this.emitSugaredExpr(callee, 1);
  16535. if (sv instanceof torch._C.SpecialFormValue) {
  16536. if (sv.form() === 'prim::isinstance') {
  16537. this.checkApplyNumInputs(apply, 2);
  16538. return this.emitIsInstance(apply.inputs()[0], apply.inputs()[1]);
  16539. }
  16540. }
  16541. }
  16542. }
  16543. const expr_out = this.emitToBool(expr, this.emitExpr(expr));
  16544. let static_if = null;
  16545. const kind = expr_out.node().kind();
  16546. if (kind === 'aten::is_scripting') {
  16547. static_if = true;
  16548. } else if (kind === 'aten::has_torch_function') {
  16549. static_if = false;
  16550. }
  16551. const maybe_ivalue = torch._C.toIValue(expr_out);
  16552. if (maybe_ivalue) {
  16553. static_if = maybe_ivalue.toBool();
  16554. }
  16555. return new torch._C.CondValue(expr_out, new torch._C.RefinementSet([], []), static_if);
  16556. }
  16557. emitIfElseBlocks(loc, cond_value, trueBranch, falseBranch) {
  16558. if (cond_value.staticIf() !== null) {
  16559. if (cond_value.staticIf()) {
  16560. this.insertRefinements(loc, cond_value.refinements());
  16561. this.emitStatements(trueBranch);
  16562. } else {
  16563. this.insertRefinements(loc, cond_value.refinements().Not());
  16564. this.emitStatements(falseBranch);
  16565. }
  16566. return;
  16567. }
  16568. const n = this.graph.insertNode(this.create('prim::If', loc, 0));
  16569. n.addInput(cond_value.value());
  16570. const true_block = n.addBlock();
  16571. const false_block = n.addBlock();
  16572. const save_true = this.emitSingleIfBranch(true_block, trueBranch, cond_value.refinements());
  16573. const save_false = this.emitSingleIfBranch(false_block, falseBranch, cond_value.refinements().Not());
  16574. const true_exits = this.exit_blocks.has(true_block);
  16575. const false_exits = this.exit_blocks.has(false_block);
  16576. if (true_exits && false_exits) {
  16577. this.exit_blocks.add(n.owningBlock());
  16578. }
  16579. const mutated_variables = new Set();
  16580. for (const v of save_true.definedVariables()) {
  16581. const insert = new torch._C.WithInsertPoint(false_block);
  16582. if (save_false.findInAnyFrame(v) || false_exits) {
  16583. mutated_variables.add(v);
  16584. } else {
  16585. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the false branch.');
  16586. }
  16587. insert.dispose();
  16588. }
  16589. for (const v of save_false.definedVariables()) {
  16590. const insert = new torch._C.WithInsertPoint(true_block);
  16591. if (save_true.findInAnyFrame(v) || true_exits) {
  16592. mutated_variables.add(v);
  16593. } else {
  16594. this.environment_stack.setVariableTypeError(v, () => 'Value is not defined in the true branch.');
  16595. }
  16596. insert.dispose();
  16597. }
  16598. for (const x of mutated_variables) {
  16599. let tv = null;
  16600. let fv = null;
  16601. {
  16602. const insert = new torch._C.WithInsertPoint(true_block);
  16603. if (!true_exits) {
  16604. tv = save_true.getVar(x, loc);
  16605. }
  16606. insert.dispose();
  16607. }
  16608. {
  16609. const insert = new torch._C.WithInsertPoint(false_block);
  16610. if (!false_exits) {
  16611. fv = save_false.getVar(x, loc);
  16612. }
  16613. insert.dispose();
  16614. }
  16615. if (true_exits && false_exits) {
  16616. continue;
  16617. } else if (true_exits) {
  16618. tv = this.graph.createUninitialized(fv.type()).insertBefore(true_block.return_node()).output();
  16619. this.graph.createStore(x, tv).insertBefore(true_block.return_node());
  16620. } else if (false_exits) {
  16621. fv = this.graph.createUninitialized(tv.type()).insertBefore(false_block.return_node()).output();
  16622. this.graph.createStore(x, fv).insertBefore(false_block.return_node());
  16623. }
  16624. const maybe_sugared_x = this.environment_stack.findInAnyFrame(x);
  16625. let full_type = null;
  16626. if (maybe_sugared_x) {
  16627. const maybe_simple = torch._C.asSimple(maybe_sugared_x);
  16628. if (maybe_simple) {
  16629. full_type = maybe_simple.type();
  16630. }
  16631. }
  16632. const default_to_union = full_type && (full_type instanceof torch.UnionType || full_type instanceof torch.OptionalType || full_type instanceof torch.NumberType);
  16633. const unified = torch._C.unifyTypes(tv.type(), fv.type(), /*default_to_union=*/default_to_union);
  16634. if (!unified) {
  16635. if (save_true.findInParentFrame(x) || save_false.findInParentFrame(x)) {
  16636. throw new python.Error('Type mismatch.');
  16637. } else {
  16638. this.environment_stack.setVariableTypeError(x, () => 'Type mismatch.');
  16639. continue;
  16640. }
  16641. }
  16642. this.environment_stack.setType(x, unified);
  16643. }
  16644. }
  16645. emitSingleIfBranch(b, branch, refinements) {
  16646. this.pushFrame(b);
  16647. const guard = new torch._C.WithInsertPoint(b);
  16648. this.insertRefinements(branch, refinements);
  16649. this.emitStatements(branch);
  16650. const frame = this.popFrame();
  16651. guard.dispose();
  16652. return frame;
  16653. }
  16654. create(kind, loc, n_outputs) {
  16655. return this.graph.create(kind, n_outputs).setSourceRange(loc);
  16656. }
  16657. refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint_ptr, all_candidates, match_repr, src, type_match, do_if_match, do_if_anytype, is_dict_constructor) {
  16658. is_dict_constructor = is_dict_constructor || false;
  16659. if (refined_type_hint_ptr._ instanceof torch.UnionType) {
  16660. const candidate_types = refined_type_hint_ptr._.containedTypes().filter((type_ptr) => type_match(type_ptr));
  16661. if (!is_dict_constructor && candidate_types.length === 0) {
  16662. throw new python.Error("No matching types found in Union type annotation.");
  16663. } else if (candidate_types.length === 1) {
  16664. [refined_type_hint_ptr._] = candidate_types;
  16665. } else {
  16666. all_candidates._ = candidate_types;
  16667. }
  16668. } else if (refined_type_hint_ptr._ instanceof torch.OptionalType) {
  16669. refined_type_hint_ptr._ = refined_type_hint_ptr._.getElementType();
  16670. }
  16671. if (is_dict_constructor) {
  16672. return;
  16673. }
  16674. if (all_candidates._.length === 0) {
  16675. if (type_match(refined_type_hint_ptr._)) {
  16676. do_if_match();
  16677. } else if (refined_type_hint_ptr._.kind() === 'AnyType') {
  16678. do_if_anytype();
  16679. } else {
  16680. throw new python.Error('Invalid annotation type.');
  16681. }
  16682. }
  16683. }
  16684. emitToBool(loc, v) {
  16685. let out = null;
  16686. const bool_cast = this.environment_stack.getSugaredVar('bool', loc);
  16687. out = torch._C.asSimple(bool_cast.call(loc, this.method, [new torch._C.NamedValue(v)], [], 0));
  16688. if (!out) {
  16689. throw new python.Error('Could not cast value to bool.');
  16690. }
  16691. if (!out.type().isSubtypeOf(torch.BoolType.get())) {
  16692. throw new python.Error('Expected a bool expression for condition.');
  16693. }
  16694. return out;
  16695. }
  16696. emitUnaryOp(tree, magicMethod, opSymbol) {
  16697. const inputs = [tree.operand];
  16698. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  16699. const val = torch._C.asSimple(torch._C.makeMagic(magicMethod, new torch._C.BuiltinFunction(opSymbol, null)).call(tree.range(), this.method, named_values, [], 0));
  16700. if (val.node().kind() !== opSymbol) {
  16701. return val;
  16702. }
  16703. const maybe_out_stack = torch._C.runNodeIfInputsAreConstant(val.node());
  16704. if (!maybe_out_stack) {
  16705. return val;
  16706. }
  16707. torch._C.TORCH_INTERNAL_ASSERT(maybe_out_stack.length === 1);
  16708. return this.graph.insertConstant(maybe_out_stack[0], tree);
  16709. }
  16710. emitAssignment(stmt) {
  16711. if (stmt instanceof ast.AnnAssign) {
  16712. return this.emitSingleAssignment(stmt);
  16713. }
  16714. if (stmt.targets.length === 1) {
  16715. const entries = Object.entries(stmt).filter(([key]) => key !== 'targets' && key !== 'value' && key !== 'ctx');
  16716. const assign = new ast.AnnAssign(stmt.targets[0], null, stmt.value, stmt.targets[0] instanceof ast.Name);
  16717. for (const [key, value] of entries) {
  16718. assign[key] = value;
  16719. }
  16720. return this.emitSingleAssignment(assign);
  16721. }
  16722. if (stmt.targets.length <= 1) {
  16723. throw new python.Error('Invalid assignment.');
  16724. }
  16725. throw new python.Error('Not implemented.');
  16726. /*
  16727. const tmp_name = this.createTempName('$tmp_assign_');
  16728. this.environment_stack.setSugaredVar(stmt.value, tmp_name, this.emitSugaredExpr(stmt.value, 1), annotated_type=null);
  16729. const ident = new ast.Name(tmp_name);
  16730. for (const expr of lhs_list) {
  16731. const assign = new ast.Assign(targets, value, ctx);
  16732. this.emitSingleAssignment(Assign.create(stmt,
  16733. List<Expr>.create(expr.range(), [expr]),
  16734. Maybe<Expr>::create(stmt.rhs().range(), ident),
  16735. Maybe<Expr>::create(stmt.range())));
  16736. }
  16737. */
  16738. }
  16739. emitSingleAssignment(stmt) {
  16740. torch._C.AT_ASSERT(stmt instanceof ast.AnnAssign);
  16741. const rhs = stmt.value;
  16742. const lhs = stmt.target;
  16743. if (lhs instanceof ast.Name) {
  16744. let type = null;
  16745. if (stmt.annotation) {
  16746. type = this._typeParser.parseTypeFromExpr(stmt.annotation);
  16747. }
  16748. const rhs_sugared_val = this.emitSugaredExpr(rhs, 1, type);
  16749. // BC HACK
  16750. this.environment_stack.setSugaredVar(stmt.range(), lhs.id, rhs_sugared_val, /*annotated_type=*/type);
  16751. } else if (lhs instanceof ast.Tuple) {
  16752. this.emitTupleAssign(lhs, rhs);
  16753. } else if (lhs instanceof ast.Attribute) {
  16754. this.emitSelectAssign(lhs, rhs, null, stmt.range());
  16755. } else {
  16756. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16757. }
  16758. }
  16759. emitSelectAssign(lhs, rhs, type, loc) {
  16760. if (!rhs) {
  16761. throw new python.Error('Expected RHS for assignment.');
  16762. }
  16763. let type_hint = null;
  16764. if (type) {
  16765. type_hint = this._typeParser.parseTypeFromExpr(type);
  16766. }
  16767. const lhsObject = this.emitSugaredExpr(lhs.value, 1);
  16768. const rhsValue = this.emitSugaredExpr(rhs, 1, type_hint).asValue(rhs.range(), this.method);
  16769. lhsObject.setAttr(loc, this.method, lhs.attr, rhsValue);
  16770. }
  16771. emitTupleAssign(...args) {
  16772. if (args.length === 2) {
  16773. const [tl, rhs] = args;
  16774. let n_binders = tl.elts.length;
  16775. const starred_unpack = this.validateAssignLhsExpr(tl.elts, tl);
  16776. if (starred_unpack) {
  16777. n_binders--;
  16778. }
  16779. const output = this.emitSugaredExpr(rhs, n_binders);
  16780. this.emitTupleAssign(tl, output, rhs.range(), n_binders, starred_unpack);
  16781. } else if (args.length === 5) {
  16782. const [tl, rhs_output, rhs_loc, n_binders, starred_unpack] = args;
  16783. const outputs = rhs_output.asTuple(rhs_loc, this.method, starred_unpack ? null : n_binders);
  16784. if (outputs.length < n_binders) {
  16785. throw new python.Error('Not enough values to unpack.');
  16786. }
  16787. if (outputs.length > n_binders && !starred_unpack) {
  16788. throw new python.Error('Too many values to unpack.');
  16789. }
  16790. this.emitExprsAssign(tl.elts, outputs, rhs_loc, n_binders);
  16791. } else {
  16792. throw new python.Error('Not implemented.');
  16793. }
  16794. }
  16795. emitExprsAssign(lhs_exprs, outputs /*, rhs_loc, n_binders */) {
  16796. let i = 0;
  16797. for (const assignee of lhs_exprs) {
  16798. if (assignee instanceof ast.Subscript) {
  16799. throw new python.Error('Not implemented.');
  16800. /*
  16801. this.emitSubscriptAssign(
  16802. rhs_loc,
  16803. Subscript(assignee),
  16804. NamedValue(rhs_loc, outputs.at(i).asValue(rhs_loc, method)));
  16805. i++;
  16806. */
  16807. } else if (assignee instanceof ast.Name) {
  16808. this.environment_stack.setSugaredVar(assignee.range(), assignee.id, outputs[i], /*annotated_type=*/null);
  16809. i++;
  16810. } else if (assignee instanceof ast.Starred) {
  16811. throw new python.Error('Not implemented.');
  16812. /*
  16813. const var = Starred(assignee).expr();
  16814. if (var.kind() != TK_VAR) {
  16815. throw(
  16816. ErrorReport(var) << 'Cannot pack a tuple into a non-variable');
  16817. }
  16818. size_t n_matched = outputs.size() - n_binders;
  16819. ArrayRef<std::shared_ptr<SugaredValue>> outputs_ref = outputs;
  16820. const values = fmap(
  16821. outputs_ref.slice(i, n_matched),
  16822. [&](const std::shared_ptr<SugaredValue>& v) {
  16823. return v.asValue(assignee.range(), method);
  16824. });
  16825. const tup = graph.insertNode(graph.createTuple(values)).output();
  16826. environment_stack.setVar(var.range(), Var(var).name().name(), tup);
  16827. i += n_matched;
  16828. */
  16829. } else if (assignee instanceof ast.Tuple) {
  16830. throw new python.Error('Not implemented.');
  16831. /*
  16832. // recursively emit tuple assignments on tuple literal input
  16833. TupleLiteral sub_tl = TupleLiteral(assignee);
  16834. size_t sub_n_binders = sub_tl.inputs().length;
  16835. bool sub_starred_unpack =
  16836. validateAssignLhsExpr(sub_tl.inputs(), sub_tl.range());
  16837. if (sub_starred_unpack)
  16838. sub_n_binders--;
  16839. emitTupleAssign(
  16840. sub_tl,
  16841. outputs.at(i),
  16842. rhs_loc,
  16843. sub_n_binders,
  16844. sub_starred_unpack);
  16845. i++;
  16846. */
  16847. } else if (assignee instanceof ast.Attribute) {
  16848. throw new python.Error('Not implemented.');
  16849. /*
  16850. emitSelectAssign(assignee, outputs.at(i), rhs_loc);
  16851. i++;
  16852. */
  16853. } else {
  16854. throw new python.Error('Unexpected expression on left-hand side of assignment.');
  16855. }
  16856. }
  16857. }
  16858. emitReturn(stmt) {
  16859. let declared_return_type = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  16860. let actual_return = this.emitExpr(stmt.value, declared_return_type);
  16861. if (declared_return_type) {
  16862. if (!(actual_return.type().isSubtypeOf(torch.TensorType.get()) && actual_return.type().isSubtypeOf(torch.NoneType.get()))) {
  16863. actual_return = torch._C.tryConvertToType(stmt, this.graph, declared_return_type, actual_return, /*allow_conversions=*/true);
  16864. }
  16865. if (!actual_return.type().isSubtypeOf(declared_return_type)) {
  16866. throw new python.Error(`Invalid return type.`);
  16867. }
  16868. } else {
  16869. declared_return_type = this._def_stack[this._def_stack.length - 1]._merged_return_type;
  16870. if (!declared_return_type) {
  16871. declared_return_type = actual_return.type();
  16872. }
  16873. const merged_return_type = torch._C.unifyTypes(declared_return_type, actual_return.type());
  16874. if (!merged_return_type) {
  16875. throw new python.Error(`Invalid return type.`);
  16876. }
  16877. declared_return_type = merged_return_type;
  16878. }
  16879. this._def_stack[this._def_stack.length - 1]._merged_return_type = declared_return_type;
  16880. if (declared_return_type === torch.AnyType.get() && actual_return.type() !== torch.AnyType.get()) {
  16881. actual_return = this.graph.insertUncheckedCast(actual_return, declared_return_type);
  16882. }
  16883. this.graph.insertNode(this.graph.create('prim::ReturnStmt', [actual_return], 0));
  16884. this.exit_blocks.add(this.environment_stack.block());
  16885. }
  16886. getNamedValues(trees, maybe_unpack) {
  16887. const values = [];
  16888. for (const tree of trees) {
  16889. if (maybe_unpack && tree instanceof ast.Starred) {
  16890. throw new python.Error('Starred argument not supported.');
  16891. } else {
  16892. values.push(new torch._C.NamedValue(this.emitExpr(tree)));
  16893. }
  16894. }
  16895. return values;
  16896. }
  16897. getValues(trees, maybe_unpack) {
  16898. return this.getNamedValues(trees, maybe_unpack).map((value) => value.value(this.graph));
  16899. }
  16900. emitExpr(tree, type_hint) {
  16901. type_hint = type_hint || null;
  16902. let out_val = this.emitSugaredExpr(tree, 1, type_hint).asValue(tree, this.method);
  16903. if (type_hint === torch.AnyType.get() && out_val.type() !== torch.AnyType.get()) {
  16904. out_val = this.graph.insertUncheckedCast(out_val, type_hint);
  16905. }
  16906. return out_val;
  16907. }
  16908. emitSugaredExpr(tree, n_binders, type_hint) {
  16909. if (tree instanceof ast.Name) { // TK_VAR
  16910. return this.environment_stack.getSugaredVar(tree.id);
  16911. } else if (tree instanceof ast.Attribute) {
  16912. const sv = this.emitSugaredExpr(tree.value, 1);
  16913. return sv.attr(tree.range(), this.method, tree.attr);
  16914. } else if (tree instanceof ast.Call) { // TK_APPLY
  16915. return this.emitApplyExpr(tree, n_binders, type_hint);
  16916. } if (tree instanceof ast.Subscript) {
  16917. return this.emitSubscript(tree, type_hint);
  16918. }
  16919. return new torch._C.SimpleValue(this.emitSimpleExpr(tree, type_hint));
  16920. }
  16921. emitApplyExpr(apply, n_binders, type_hint) {
  16922. type_hint = type_hint || null;
  16923. const sv = this.emitSugaredExpr(apply.func, 1);
  16924. const loc = apply.func.range();
  16925. if (sv instanceof torch._C.SpecialFormValue) {
  16926. return this.emitApplySpecialForm(sv.form(), apply, sv, type_hint);
  16927. }
  16928. const args = this.getNamedValues(apply.args, true);
  16929. const kwargs = this.emitAttributes(apply.keywords);
  16930. return sv.call(loc, this.method, args, kwargs, n_binders);
  16931. }
  16932. emitAttributes(attributes) {
  16933. return attributes.map((attr) => new torch._C.NamedValue(attr.range(), attr.arg, this.emitExpr(attr.value)));
  16934. }
  16935. emitApplySpecialForm(form, apply, sv, type_hint) {
  16936. switch (form) {
  16937. case 'prim::fork': {
  16938. throw new python.Error('Not implemented.');
  16939. }
  16940. case 'prim::awaitable': {
  16941. throw new python.Error('Not implemented.');
  16942. }
  16943. case 'prim::annotate': {
  16944. this.checkApplyNumInputs(apply, 2);
  16945. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16946. let expr = torch._C.tryConvertToType(apply.range(), this.graph, type, this.emitExpr(apply.args[1], type), /*allow_conversions=*/true);
  16947. if (!expr.type().isSubtypeOf(type)) {
  16948. throw new python.Error('Invalid expression type.');
  16949. }
  16950. if ((type instanceof torch.OptionalType || (type instanceof torch.UnionType && type.expect(torch.UnionType).canHoldType(torch.NoneType.get()))) && expr.type().isSubtypeOf(torch.NoneType.get())) {
  16951. const none = this.graph.createNone();
  16952. none.output().setType(type);
  16953. this.graph.insertNode(none);
  16954. expr = none.output();
  16955. }
  16956. return new torch._C.SimpleValue(expr);
  16957. }
  16958. case 'prim::unchecked_cast': {
  16959. this.checkApplyNumInputs(apply, 2);
  16960. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16961. let v = this.emitExpr(apply.args[1]);
  16962. if (v.node().kind() !== 'prim::unchecked_cast' || v.type() !== type) {
  16963. v = this.graph.insertUncheckedCast(v, type);
  16964. }
  16965. return new torch._C.SimpleValue(v);
  16966. }
  16967. case 'prim::GetAttr': {
  16968. this.checkApplyNumInputsRange(apply, 2, 3);
  16969. const obj = this.emitSugaredExpr(apply.args[0], 1);
  16970. if (apply.args[1] instanceof ast.Constant === false || typeof apply.args[1].value !== 'string') {
  16971. throw new python.Error('Invalid argument.');
  16972. }
  16973. const name = apply.args[1].value;
  16974. if (apply.args.length === 2) {
  16975. return obj.attr(apply, this.method, name);
  16976. } else if (obj.hasAttr(apply, this.method, name)) {
  16977. return obj.attr(apply, this.method, name);
  16978. }
  16979. return this.emitSugaredExpr(apply.inputs()[2], 1);
  16980. }
  16981. case 'prim::Uninitialized': {
  16982. this.checkApplyNumInputs(apply, 1);
  16983. const type = this._typeParser.parseTypeFromExpr(apply.args[0]);
  16984. const out = this.graph.insertNode(this.graph.createUninitialized(type)).setSourceRange(apply.range());
  16985. return new torch._C.SimpleValue(out.output());
  16986. }
  16987. case 'prim::TupleConstruct': {
  16988. throw new python.Error('Not implemented.');
  16989. }
  16990. case 'prim::isinstance': {
  16991. this.checkApplyNumInputs(apply, 2);
  16992. const result = this.emitIsInstance(apply.args[0], apply.args[1]);
  16993. return new torch._C.SimpleValue(result.value());
  16994. }
  16995. case 'prim::tolist': {
  16996. const value = apply.func.value;
  16997. const operand = this.emitSugaredExpr(value, 1);
  16998. if (!type_hint) {
  16999. throw new python.Error('Expected type hint for result of tolist().');
  17000. }
  17001. return new torch._C.SimpleValue(this.graph.insertToList(operand.asValue(value.range(), this.method), type_hint));
  17002. }
  17003. case 'prim::HasAttr': {
  17004. throw new python.Error('Not implemented.');
  17005. }
  17006. case 'prim::CreateObject': {
  17007. if (apply.args.length !== 1) {
  17008. throw python.Error('Only one argument to __new__ allowed.');
  17009. }
  17010. const arg = this.emitSugaredExpr(apply.args[0], 1);
  17011. if (arg instanceof torch._C.ClassValue === false) {
  17012. throw python.Error('Expected class value as argument to __new__.');
  17013. }
  17014. const class_arg = arg;
  17015. const createNode = this.graph.insertNode(this.graph.createObject(class_arg._type));
  17016. createNode.setSourceRange(apply.range());
  17017. return new torch._C.SimpleValue(createNode.output());
  17018. }
  17019. case 'prim::range': {
  17020. const input_vals = this.getValues(apply.args, true);
  17021. return new torch._C.RangeValue(apply.range(), this.method, input_vals);
  17022. }
  17023. case 'prim::enumerate': {
  17024. throw new python.Error('Not implemented.');
  17025. }
  17026. case 'prim::zip': {
  17027. throw new python.Error('Not implemented.');
  17028. }
  17029. case 'prim::list': {
  17030. throw new python.Error('Not implemented.');
  17031. }
  17032. case 'prim::dict': {
  17033. throw new python.Error('Not implemented.');
  17034. }
  17035. case 'aten::index': {
  17036. throw new python.Error('Not implemented.');
  17037. }
  17038. default: {
  17039. throw new python.Error(`Unsupported special form '${sv.from()}'.`);
  17040. }
  17041. }
  17042. }
  17043. emitSimpleExpr(tree, type_hint) {
  17044. if (tree instanceof ast.Constant) {
  17045. if (tree.value === true) {
  17046. return this.graph.insertConstant(new torch._C.IValue(true, 'Bool'), tree.range());
  17047. } else if (tree.value === false) {
  17048. return this.graph.insertConstant(new torch._C.IValue(false, 'Bool'), tree.range());
  17049. } else if (tree.value === null) {
  17050. return this.graph.insertConstant(new torch._C.IValue(), tree.range());
  17051. } else if (typeof tree.value === 'string') {
  17052. return this.emitStringLiteral(tree);
  17053. }
  17054. return this.emitConst(tree);
  17055. } else if (tree instanceof ast.List) {
  17056. return this.emitListLiteral(tree, type_hint);
  17057. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Name && tree.operand.id === 'inf') {
  17058. return this.emitConst(new ast.Constant(-Infinity, 'float'));
  17059. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub && tree.operand instanceof ast.Constant) {
  17060. const c = tree.operand;
  17061. if (c.type === 'complex') {
  17062. return this.emitConst(new ast.Constant(new builtins.complex(-c.value.real, -c.value.imag), 'complex'));
  17063. }
  17064. return this.emitConst(new ast.Constant(-c.value, c.type));
  17065. } else if (tree instanceof ast.UnaryOp && tree.op instanceof ast.USub) {
  17066. return this.emitUnaryOp(tree, '__neg__', 'aten::neg');
  17067. } else if (tree instanceof ast.BinOp) {
  17068. return this.emitBinaryOp(tree);
  17069. } else if (tree instanceof ast.Dict) {
  17070. return this.emitDictLiteral(tree, type_hint);
  17071. } else if (tree instanceof ast.Tuple) {
  17072. const values = this.getValues(tree.elts, /*maybe_unpack=*/true);
  17073. return this.graph.insertNode(this.graph.createTuple(values)).output();
  17074. }
  17075. throw new python.Error(`Simple expression '${tree.__class__.__name__}' not implemented.`);
  17076. }
  17077. getNodeKind(kind /*, ninputs */) {
  17078. if (kind instanceof ast.Add) {
  17079. return 'aten::add';
  17080. } else if (kind instanceof ast.Sub) {
  17081. return 'aten::sub';
  17082. } else if (kind instanceof ast.Mult) {
  17083. return 'aten::mul';
  17084. }
  17085. /*
  17086. case TK_UNARY_MINUS: return 'aten::neg';
  17087. case TK_POW: return 'aten::pow';
  17088. case '@': return 'aten::matmul';
  17089. case TK_STARRED: return 'prim::Starred';
  17090. case '/': return 'aten::div';
  17091. case '%': return 'aten::remainder';
  17092. case TK_NE: return 'aten::ne';
  17093. case TK_EQ: return 'aten::eq';
  17094. case '<': return 'aten::lt';
  17095. case '>': return 'aten::gt';
  17096. case TK_LE: return 'aten::le';
  17097. case TK_GE: return 'aten::ge';
  17098. case TK_AND: return 'aten::__and__';
  17099. case TK_OR: return 'aten::__or__';
  17100. case TK_IS: return 'aten::__is__';
  17101. case TK_ISNOT: return 'aten::__isnot__';
  17102. case TK_NOT: return 'aten::__not__';
  17103. case TK_FLOOR_DIV: return 'aten::floordiv';
  17104. case TK_LSHIFT: return 'aten::__lshift__';
  17105. case TK_RSHIFT: return 'aten::__rshift__';
  17106. case '&': return 'aten::__and__';
  17107. case '|': return 'aten::__or__';
  17108. case '^': return 'aten::__xor__';
  17109. case TK_IN: return 'aten::__contains__';
  17110. */
  17111. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17112. }
  17113. getOperatorOverload(kind /*, ninputs */) {
  17114. if (kind instanceof ast.Add) {
  17115. return '__add__';
  17116. } else if (kind instanceof ast.Sub) {
  17117. return '__sub__';
  17118. } else if (kind instanceof ast.Mult) {
  17119. return '__mul__';
  17120. }
  17121. /*
  17122. case TK_UNARY_MINUS: return "__neg__";
  17123. case '~': return "__invert__";
  17124. case TK_POW: return "__pow__";
  17125. case '/': return "__truediv__";
  17126. case '%': return "__mod__";
  17127. case TK_NE: return "__ne__";
  17128. case TK_EQ: return "__eq__";
  17129. case '<': return "__lt__";
  17130. case '>': return "__gt__";
  17131. case TK_LE: return "__le__";
  17132. case TK_GE: return "__ge__";
  17133. case '&': return "__and__";
  17134. case '|': return "__or__";
  17135. case '^': return "__xor__";
  17136. case TK_IN: return "__contains__";
  17137. case TK_LSHIFT: return "__lshift__";
  17138. case TK_RSHIFT: return "__rshift__";
  17139. */
  17140. throw new python.Error(`Unknown kind '${kind.__class__.__name__}'.`);
  17141. }
  17142. emitBinaryOp(tree) {
  17143. const inputs = [tree.left, tree.right];
  17144. const kind = this.getNodeKind(tree.op, inputs.length);
  17145. const overload = this.getOperatorOverload(tree.op, inputs.length);
  17146. const named_values = this.getNamedValues(inputs, /*maybe_unpack=*/false);
  17147. if (tree.op instanceof ast.In) {
  17148. // std::iter_swap(named_values.begin() + 0, named_values.begin() + 1);
  17149. throw new python.Error('Not implemented.');
  17150. }
  17151. if (named_values[0].type() instanceof torch.TupleType &&
  17152. named_values[1].type() instanceof torch.TupleType &&
  17153. kind === 'aten::add') {
  17154. const first_tuple = torch._C.createTupleUnpack(named_values[0].value(this.graph)).vec();
  17155. const second_tuple = torch._C.createTupleUnpack(named_values[1].value(this.graph)).vec();
  17156. first_tuple.insert(first_tuple.end(), second_tuple.begin(), second_tuple.end());
  17157. return this.graph.insertNode(this.graph.createTuple(first_tuple)).output();
  17158. }
  17159. return torch._C.asSimple(torch._C.makeMagic(overload, new torch._C.BuiltinFunction(kind, null)).call(tree.range(), this.method, named_values, [], 0));
  17160. }
  17161. emitDictLiteral(dl, type_hint) {
  17162. const key_trees = dl.keys;
  17163. const value_trees = dl.values;
  17164. torch._C.AT_ASSERT(key_trees.length === value_trees.length);
  17165. const keys = [];
  17166. const values = [];
  17167. let rhs_value_type = null;
  17168. for (let i = 0; i < key_trees.length; i++) {
  17169. keys.push(this.emitExpr(key_trees[i]));
  17170. values.push(this.emitExpr(value_trees[i]));
  17171. if (i === 0) {
  17172. rhs_value_type = values[i].type();
  17173. } else {
  17174. if (keys[i - 1].type().kind() !== keys[i].type().kind()) {
  17175. throw new python.Error('Dict keys must contain only a single type.');
  17176. }
  17177. rhs_value_type = torch._C.unifyTypes(rhs_value_type, values[i].type(), /*default_to_union=*/true);
  17178. }
  17179. }
  17180. const refined_type_hint = { _: type_hint };
  17181. const annotated_union_type = type_hint && type_hint.isUnionType() ? type_hint : null;
  17182. const all_candidates = { _: [] };
  17183. const default_refined_type_hint_setter = () => {
  17184. if (keys.length === 0) {
  17185. refined_type_hint._ = torch.DictType.create(torch.StringType.get(), torch.TensorType.get());
  17186. } else {
  17187. refined_type_hint._ = torch.DictType.create(keys[0].type(), rhs_value_type);
  17188. if (rhs_value_type instanceof torch.UnionType) {
  17189. throw new python.Error('Dict values consist of heterogeneous types.');
  17190. }
  17191. }
  17192. };
  17193. if (type_hint) {
  17194. const type_match = (t) => t instanceof torch.DictType;
  17195. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'Dict', dl, type_match, () => [], default_refined_type_hint_setter);
  17196. if (all_candidates._.length > 0 && values.length === 0) {
  17197. throw new python.Error('Cannot assign an empty dict.');
  17198. }
  17199. } else {
  17200. default_refined_type_hint_setter();
  17201. }
  17202. torch._C.TORCH_INTERNAL_ASSERT(all_candidates._.length > 0 || refined_type_hint._);
  17203. if (values.length > 0) {
  17204. if (all_candidates._.length > 0) {
  17205. this.refineAndSetDictTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint, keys[0].type(), rhs_value_type, dl);
  17206. }
  17207. if (refined_type_hint._.getKeyType() !== keys[0].type()) {
  17208. throw new python.Error('Type annotation does not match key type.');
  17209. }
  17210. if (!rhs_value_type.isSubtypeOf(refined_type_hint._.getValueType())) {
  17211. throw new python.Error('Type annotation does not match value type.');
  17212. }
  17213. }
  17214. let result = this.graph.insertNode(this.graph.createDict(refined_type_hint._.getKeyType(), refined_type_hint._.getValueType(), keys, values));
  17215. if (annotated_union_type) {
  17216. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17217. n.output().setType(annotated_union_type);
  17218. result = n;
  17219. }
  17220. return result.output();
  17221. }
  17222. emitStringLiteral(c) {
  17223. return torch._C.insertConstant(this.graph, c.value, c.range());
  17224. }
  17225. emitConst(c) {
  17226. if (c.type === 'int') {
  17227. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Int'), this.graph, c.range(), this.integral_constants);
  17228. } else if (c.type === 'complex') {
  17229. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Complex'), this.graph, c.range(), this.complex_constants);
  17230. } else if (c.type === 'float') {
  17231. return torch._C.materializeConstant(new torch._C.IValue(c.value, 'Double'), this.graph, c.range(), this.fp_constants);
  17232. }
  17233. throw new python.Error(`Unsupported constant type.`);
  17234. }
  17235. emitListLiteral(ll, type_hint) {
  17236. type_hint = type_hint || null;
  17237. const values = this.getValues(ll.elts, true);
  17238. if (values.length === 0 && type_hint === null) {
  17239. throw new python.Error('Not implemented.');
  17240. }
  17241. let inferred_elem_type = torch.TensorType.get();
  17242. const refined_type_hint = { _: type_hint };
  17243. const annotated_union_type = refined_type_hint._ && refined_type_hint._.isUnionType() ? refined_type_hint._ : null;
  17244. const all_candidates = { _: [] };
  17245. if (refined_type_hint._) {
  17246. const do_if_type_match = () => {
  17247. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17248. };
  17249. const type_match = (t) => t.isSubtypeOf(torch.Type.get('AnyListType'));
  17250. this.refineAndSetUnionTypeHintOrPopulateCandidatesVector(type_hint, refined_type_hint, all_candidates, 'List', ll, type_match, do_if_type_match, do_if_type_match);
  17251. if (all_candidates._.length > 0 && values.len === 0) {
  17252. throw new python.Error('Cannot assign an empty list.');
  17253. }
  17254. }
  17255. if (values.length !== 0) {
  17256. const types = values.map((v) => v.type());
  17257. const elem_type_hint = refined_type_hint._ && refined_type_hint._.kind() === 'ListType' ? refined_type_hint._.getElementType() : null;
  17258. const unified_elem_type = torch._C.unifyTypeList(types, null /*nowhere*/, /*default_to_union=*/true, elem_type_hint);
  17259. if (!refined_type_hint._ && unified_elem_type.kind() === 'UnionType') {
  17260. throw new python.Error('Not implemented.');
  17261. }
  17262. if (all_candidates._.length === 0 && refined_type_hint._ && !unified_elem_type.isSubtypeOf(inferred_elem_type)) {
  17263. throw new python.Error('Not implemented.');
  17264. }
  17265. if (all_candidates._.length !== 0) {
  17266. this.refineAndSetListTypeHintFromCandidatesVector(all_candidates, type_hint, refined_type_hint._, unified_elem_type, ll);
  17267. inferred_elem_type = refined_type_hint._.expect(torch.ListType).getElementType();
  17268. }
  17269. if (!refined_type_hint._) {
  17270. inferred_elem_type = unified_elem_type;
  17271. }
  17272. }
  17273. let result = this.graph.insertNode(this.graph.createList(inferred_elem_type, values));
  17274. if (annotated_union_type) {
  17275. const n = this.graph.insertNode(this.graph.create('prim::unchecked_cast', [result.output()]));
  17276. n.output().setType(annotated_union_type);
  17277. result = n;
  17278. }
  17279. return result.output();
  17280. }
  17281. insertRefinements(loc, ref) {
  17282. for (const r of ref.activeRefinements()) {
  17283. const v = this.environment_stack.getVar(r.identifier(), loc);
  17284. const new_v = this.graph.insertUncheckedCast(v, r.type());
  17285. this.environment_stack.setVar(loc, r.identifier(), new_v);
  17286. }
  17287. }
  17288. shouldDeriveSetStateType(def, schema) {
  17289. const noTypeAnnotations = schema.arguments.every((arg) => arg.is_inferred_type());
  17290. const shouldInfer = def.name === '__setstate__' && noTypeAnnotations;
  17291. if (!shouldInfer) {
  17292. return false;
  17293. }
  17294. if (def.name !== '__setstate__' && def.args.args.length !== 2) {
  17295. throw new python.Error(`Invalid '__setstate' method.`);
  17296. }
  17297. return true;
  17298. }
  17299. checkApplyNumInputs(apply, expected_inputs) {
  17300. if (apply.args.length !== expected_inputs) {
  17301. throw new python.Error('Invalid number of arguments.');
  17302. }
  17303. if (apply.keywords.length > 0) {
  17304. throw new python.Error('Invalid number of keyword arguments.');
  17305. }
  17306. }
  17307. checkApplyNumInputsRange(apply, min_expected_inputs, max_expected_inputs) {
  17308. const position_arg_size = apply.args.length;
  17309. if (position_arg_size < min_expected_inputs || position_arg_size > max_expected_inputs) {
  17310. throw new python.Error('Invalid number of arguments.');
  17311. }
  17312. if (apply.keywords.length > 0) {
  17313. throw new python.Error('Invalid number of keyword arguments.');
  17314. }
  17315. }
  17316. validateAssignLhsExpr(lhs /*, r */) {
  17317. let num_normal_assign = 0;
  17318. let num_starred = 0;
  17319. for (const assignee of lhs) {
  17320. if (assignee instanceof ast.Name || assignee instanceof ast.Subscript || assignee instanceof ast.Tuple || assignee instanceof ast.Attribute) {
  17321. num_normal_assign++;
  17322. } else if (assignee instanceof ast.Starred) {
  17323. num_starred++;
  17324. } else {
  17325. throw new python.Error('Assignment must be a variable, subscript, or starred expression.');
  17326. }
  17327. }
  17328. if (num_starred > 1) {
  17329. throw new python.Error('Only one starred expression is allowed.');
  17330. }
  17331. if (num_starred > 0 && num_normal_assign === 0) {
  17332. throw new python.Error('Invalid starred expression.');
  17333. }
  17334. return num_starred;
  17335. }
  17336. createTempName(prefix) {
  17337. return `${prefix}${this._temp_name_count++}`;
  17338. }
  17339. handleMaybeNoReturn(def, block) {
  17340. const decl_ret = this._def_stack[this._def_stack.length - 1]._declared_return_type;
  17341. if (this.exit_blocks.size === 0) {
  17342. if (decl_ret && decl_ret !== torch.NoneType.get()) {
  17343. throw new python.Error('Function was not annotated as having type None, but does not return along all paths.');
  17344. }
  17345. const b = new torch._C.WithInsertPoint(block.nodes().end());
  17346. // this.emitReturn(Return::create(def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
  17347. b.dispose();
  17348. throw new python.Error("'torch._C.to_ir.handleMaybeNoReturn' not implemented.");
  17349. } else if (this._def_stack[this._def_stack.length - 1]._merged_return_type === null) {
  17350. this._def_stack[this._def_stack.length - 1]._merged_return_type = decl_ret === null ? torch.NoneType.get() : decl_ret;
  17351. }
  17352. }
  17353. getAdjTupleIndex(loc, tuple_type, input_index, allow_out_of_bounds) {
  17354. let adj_index = input_index;
  17355. const tuple_len = tuple_type.elements().length;
  17356. if (input_index < 0) {
  17357. adj_index = tuple_len + input_index;
  17358. }
  17359. if (!allow_out_of_bounds && (adj_index >= tuple_len || adj_index < 0)) {
  17360. throw new python.Error(`Tuple index out of range at ${loc}.`);
  17361. }
  17362. return adj_index;
  17363. }
  17364. emitTupleIndex(loc, tuple_val, idx_val) {
  17365. const tuple_typ = tuple_val.type();
  17366. const elems = tuple_typ.elements();
  17367. let output_type = null;
  17368. if (idx_val.type() !== torch.IntType.get()) {
  17369. throw new python.Error('Tuple index must be an integer.');
  17370. }
  17371. const idx = torch._C.toIValue(idx_val);
  17372. if (idx) {
  17373. const adj_index = this.getAdjTupleIndex(loc, tuple_typ, idx.toInt(), /*allow_out_of_bounds*/ false);
  17374. output_type = elems[adj_index];
  17375. } else {
  17376. if (elems.length === 0 || !torch._C.convertibleToList(tuple_typ, torch.ListType.create(elems[0]))) {
  17377. throw new python.Error('Cannot index into a tuple with a non-integer literal.');
  17378. }
  17379. [output_type] = elems;
  17380. }
  17381. return this.graph.insertNode(this.graph.createTupleIndex(tuple_val, idx_val, output_type)).output();
  17382. }
  17383. getSliceInd(idx_val, loc) {
  17384. const ivalue = torch._C.toIValue(idx_val);
  17385. if (ivalue && ivalue.isInt()) {
  17386. return ivalue.toInt();
  17387. }
  17388. throw new python.Error(`Tuple slice indices must be integer constants at '${loc}'.`);
  17389. }
  17390. emitTupleSlice(loc, tuple_val, tuple_args) {
  17391. const tuple_type = tuple_val.value(this.graph).type().expect(torch.TupleType);
  17392. const tuple_len = tuple_type.elements().length;
  17393. const [beg_val, end_val, step] = tuple_args;
  17394. let step_size = 1;
  17395. if (step) {
  17396. const val = torch._C.toIValue(step.value(this.graph));
  17397. torch._C.TORCH_CHECK(val.isInt());
  17398. step_size = val.toInt();
  17399. }
  17400. let beg = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17401. if (beg_val) {
  17402. beg = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(beg_val.value(this.graph), loc), true) };
  17403. }
  17404. let end = { _: Number.MAX_SAFE_INTEGER }; // std::numeric_limits<int64_t>::max();
  17405. if (end_val) {
  17406. end = { _: this.getAdjTupleIndex(loc, tuple_type, this.getSliceInd(end_val.value(this.graph), loc), true) };
  17407. }
  17408. const num_values = torch._C.slice_indices_adjust(tuple_len, beg, end, step_size);
  17409. return this.graph.insertNode(this.graph.createTupleSlice(tuple_val.value(this.graph), beg._, step_size, num_values)).output();
  17410. }
  17411. emitSliceOp(loc, sliceable, dim, start, end, step) {
  17412. const args = [];
  17413. args.push(new torch._C.NamedValue(loc, 'self', sliceable));
  17414. if (dim) {
  17415. torch._C.AT_ASSERT(sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17416. args.emplace_back(new torch._C.NamedValue(dim));
  17417. } else {
  17418. torch._C.AT_ASSERT(!sliceable.type().isSubtypeOf(torch.TensorType.get()));
  17419. }
  17420. if (sliceable.type() instanceof torch.TupleType) {
  17421. const tuple_args = [];
  17422. tuple_args.push(start ? new torch._C.NamedValue(start) : null);
  17423. tuple_args.push(end ? new torch._C.NamedValue(end) : null);
  17424. tuple_args.push(step ? new torch._C.NamedValue(step) : null);
  17425. return this.emitTupleSlice(loc, args[0], tuple_args);
  17426. }
  17427. if (!step) {
  17428. step = this.graph.insertConstant(1, loc);
  17429. }
  17430. args.push(new torch._C.NamedValue(loc, 'start', start));
  17431. args.push(new torch._C.NamedValue(loc, 'end', end));
  17432. args.push(new torch._C.NamedValue(loc, 'step', step));
  17433. return this.emitBuiltinCall(loc, this.graph, 'aten::slice', args, []);
  17434. }
  17435. emitSlice(loc, input, dim, slice) {
  17436. let start = null;
  17437. let end = null;
  17438. let step = null;
  17439. if (slice.lower) {
  17440. start = this.emitExpr(slice.lower);
  17441. }
  17442. if (slice.upper) {
  17443. end = this.emitExpr(slice.upper);
  17444. }
  17445. if (slice.step) {
  17446. step = this.emitExpr(slice.step);
  17447. }
  17448. return this.emitSliceOp(loc, input, dim, start, end, step);
  17449. }
  17450. emitBasicSlice(loc, sliceable, subscript_exprs) {
  17451. torch._C.AT_ASSERT(subscript_exprs instanceof ast.Slice);
  17452. const slice_exp = subscript_exprs;
  17453. let maybe_dim = null;
  17454. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17455. maybe_dim = this.graph.insertConstant(0, loc);
  17456. }
  17457. return this.emitSlice(loc, sliceable, maybe_dim, slice_exp);
  17458. }
  17459. emitSubscript(subscript, type_hint) {
  17460. type_hint = type_hint === undefined ? null : type_hint;
  17461. const sv = this.emitSugaredExpr(subscript.value, 1);
  17462. const subscript_exprs = subscript.slice;
  17463. const range = subscript.range();
  17464. const val_range = subscript.value;
  17465. if (subscript_exprs instanceof ast.Tuple) {
  17466. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sv.asValue(val_range, this.method), subscript_exprs));
  17467. }
  17468. if (subscript_exprs instanceof ast.Slice) {
  17469. if (sv.kind() === 'module') {
  17470. const s_tuple_val = sv.asTupleValue(val_range, this.method).asValue(val_range, this.method);
  17471. const [slice] = subscript_exprs;
  17472. const tuple_args = [];
  17473. if (slice.start().present()) {
  17474. const begin = new torch._C.NamedValue(val_range, 'begin', this.emitExpr(slice.start().get()));
  17475. tuple_args.push(begin);
  17476. } else {
  17477. tuple_args.push(null);
  17478. }
  17479. if (slice.end().present()) {
  17480. const end = new torch._C.NamedValue(val_range, 'end', this.emitExpr(slice.end().get()));
  17481. tuple_args.push(end);
  17482. } else {
  17483. tuple_args.push(null);
  17484. }
  17485. if (slice.step().present()) {
  17486. const step = new torch._C.NamedValue(val_range, 'step', this.emitExpr(slice.step().get()));
  17487. tuple_args.push(step);
  17488. } else {
  17489. tuple_args.push(null);
  17490. }
  17491. const tupleSliceValue = this.emitTupleSlice(val_range, s_tuple_val, tuple_args);
  17492. return new torch._C.SimpleValue(tupleSliceValue);
  17493. }
  17494. return new torch._C.SimpleValue(this.emitBasicSlice(range, sv.asValue(val_range, this.method), subscript_exprs));
  17495. }
  17496. const sliceable = sv.asValue(val_range, this.method);
  17497. const subscript_sv = this.emitSugaredExpr(subscript_exprs, 1);
  17498. if (subscript_sv instanceof torch._C.SliceValue) {
  17499. const slice_value = subscript_sv;
  17500. let dim = null;
  17501. if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17502. dim = this.method.graph().insertConstant(0, val_range);
  17503. }
  17504. const sliced = this.emitSliceOp(val_range, sliceable, dim, slice_value.start(), slice_value.stop(), slice_value.step());
  17505. return new torch._C.SimpleValue(sliced);
  17506. }
  17507. const idx = subscript_sv.asValue(val_range, this.method);
  17508. if (sliceable.type() instanceof torch.TupleType) {
  17509. return new torch._C.SimpleValue(this.emitTupleIndex(range, sv.asValue(val_range, this.method), idx));
  17510. } else if (sliceable.type().isSubtypeOf(torch.TensorType.get())) {
  17511. return new torch._C.SimpleValue(this.emitMultidimSlicing(range, sliceable, subscript_exprs));
  17512. }
  17513. return sv.getitem(range, this.method, idx, type_hint);
  17514. }
  17515. });
  17516. this.registerType('torch.jit.CompilationUnit', class {
  17517. constructor() {
  17518. this._functions = new Map();
  17519. this._classes = new Map();
  17520. }
  17521. register_type(namedType) {
  17522. this._classes.set(namedType.annotation_str, namedType);
  17523. }
  17524. register_function(fn) {
  17525. const name = fn.qualname().qualifiedName();
  17526. torch._C.TORCH_CHECK(!this._functions.has(name));
  17527. this._functions.set(name, fn);
  17528. return fn;
  17529. }
  17530. define(...args) {
  17531. if (Array.isArray(args[1])) {
  17532. const [prefix, properties, propResolvers, definitions, defResolvers, self, shouldMangle, operator_set_version] = args;
  17533. torch._C.TORCH_INTERNAL_ASSERT(definitions.length === defResolvers.length);
  17534. torch._C.TORCH_INTERNAL_ASSERT(properties.length === propResolvers.length);
  17535. const functions = [];
  17536. const function_table = new Map();
  17537. const record_function = (fn) => {
  17538. function_table.set(fn.name(), fn);
  17539. functions.push(fn);
  17540. this.register_function(fn);
  17541. };
  17542. for (let i = 0; i < properties.length; i++) {
  17543. const property_fns = this.define_property(prefix, properties[i], propResolvers[i], self, function_table, shouldMangle);
  17544. const getter_fn = property_fns.getGetter();
  17545. const setter_fn = property_fns.getSetter();
  17546. record_function(getter_fn);
  17547. if (setter_fn) {
  17548. record_function(setter_fn);
  17549. }
  17550. }
  17551. for (let i = 0; i < definitions.length; i++) {
  17552. const fn = this.define(prefix, definitions[i], defResolvers[i], self, function_table, shouldMangle, 'Method', operator_set_version);
  17553. record_function(fn);
  17554. }
  17555. for (const [name, fn] of function_table) {
  17556. if (name === '__init__') {
  17557. fn.ensure_defined();
  17558. }
  17559. }
  17560. for (const fn of functions) {
  17561. fn.ensure_defined();
  17562. }
  17563. return functions;
  17564. } else if (args[1] instanceof ast.FunctionDef) {
  17565. const [prefix, def, resolver, self, function_table, shouldMangle, type, operator_set_version] = args;
  17566. const _resolver = self ? resolver : new torch._C.FunctionResolver(resolver, function_table);
  17567. const creator = (method) => {
  17568. return new torch._C.to_ir(def, _resolver, self, method);
  17569. };
  17570. let name = prefix ? new torch._C.QualifiedName(prefix, def.name) : new torch._C.QualifiedName(def.name);
  17571. if (shouldMangle && this.find_function(name)) {
  17572. name = this.mangle(name);
  17573. }
  17574. const graph = new torch.Graph();
  17575. graph.set_op_version(operator_set_version);
  17576. const fn = new torch._C.GraphFunction(name, graph, creator);
  17577. fn.__ast__ = def; // remove
  17578. if (self) {
  17579. if (type === 'hook') {
  17580. self.getClassType().addForwardHook(fn);
  17581. } else if (type === 'prehook') {
  17582. self.getClassType().addPreHook(fn);
  17583. } else {
  17584. self.getClassType().addMethod(fn);
  17585. }
  17586. }
  17587. return fn;
  17588. }
  17589. throw new python.Error('Invalid arguments.');
  17590. }
  17591. get_type(name) {
  17592. return this._classes.get(name.qualifiedName());
  17593. }
  17594. get_class(name) {
  17595. return this.get_type(name);
  17596. }
  17597. find_function(name) {
  17598. const key = name.qualifiedName();
  17599. return this._functions.get(key);
  17600. }
  17601. });
  17602. this.registerFunction('torch._C.ConvertToSSA', (graph) => {
  17603. const ctrl = new torch._C.ControlFlowLoadStores();
  17604. ctrl.run(graph);
  17605. const exit_vars = new torch._C.LoopContinuations();
  17606. exit_vars.run(graph);
  17607. torch._C.InlineLoopCondition(graph);
  17608. const erase_loads_stores = new torch._C.EraseLoadStores();
  17609. erase_loads_stores.run(graph);
  17610. torch._C.TransformExits(graph);
  17611. });
  17612. this.registerFunction('torch._C.canonicalizeModifiedLoop', (/* n */) => {
  17613. /*
  17614. LoopView loop(n);
  17615. if (loop.loopType() != LoopView::ModifiedLoop) {
  17616. return;
  17617. }
  17618. const g = n.owningGraph();
  17619. WithInsertPoint node_insert(n);
  17620. const zero = g.insertConstant(0);
  17621. const one = g.insertConstant(1);
  17622. const max_trip_count = loop.maxTripCount();
  17623. const condition = g.insert(aten::gt, {max_trip_count, zero});
  17624. loop.replaceMaxTripCount(g.insertConstant(std::numeric_limits<int64_t>::max()));
  17625. const inp_condition = toIValue(loop.inputCond());
  17626. if (inp_condition == null || inp_condition.toBool() == false) {
  17627. condition = g.insert(aten::__and__, {condition, loop.inputCond()});
  17628. }
  17629. loop.replaceInputCondition(condition);
  17630. n.addOutput().setType(IntType::get());
  17631. WithInsertPoint loop_insert(loop.bodyBlock());
  17632. n.addInput(zero);
  17633. const new_iter = loop.bodyBlock().addInput().setType(IntType::get());
  17634. // unset unique name for jitter, its replacement does not have a name
  17635. loop.currentTripCount().setDebugName('').replaceAllUsesWith(new_iter);
  17636. const inc_iter = g.insert(aten::add, {new_iter, one});
  17637. loop.bodyBlock().registerOutput(inc_iter);
  17638. const less_than_max_trip = g.insert(aten::lt, {inc_iter, max_trip_count});
  17639. const loop_continue = loop.nextCond();
  17640. const new_condition =
  17641. g.insert(aten::__and__, {less_than_max_trip, loop_continue});
  17642. loop.bodyBlock().eraseOutput(0);
  17643. loop.bodyBlock().insertOutput(0, new_condition);
  17644. */
  17645. });
  17646. this.registerFunction('torch._C.canonicalizeModifiedLoops', (block) => {
  17647. for (const n of block.nodes()) {
  17648. for (const b of n.blocks()) {
  17649. torch._C.canonicalizeModifiedLoops(b);
  17650. }
  17651. if (n.kind() === 'prim::Loop') {
  17652. torch._C.canonicalizeModifiedLoop(n);
  17653. }
  17654. }
  17655. });
  17656. this.registerFunction('torch._C.CanonicalizeModifiedLoops', (graph) => {
  17657. torch._C.canonicalizeModifiedLoops(graph.block());
  17658. });
  17659. this.registerType('torch._C.MiniEnvironment', class {
  17660. constructor(b, next) {
  17661. this.next = next || null;
  17662. this.table = new Map();
  17663. }
  17664. setVar(name, value) {
  17665. this.table.set(name, value);
  17666. }
  17667. definedVariables() {
  17668. const result = Array.from(this.table.keys());
  17669. return result.sort();
  17670. }
  17671. findInThisFrame(name) {
  17672. if (this.table.has(name)) {
  17673. return this.table.get(name);
  17674. }
  17675. return null;
  17676. }
  17677. findInAnyFrame(name) {
  17678. /* eslint-disable consistent-this */
  17679. const self = this;
  17680. /* eslint-enable consistent-this */
  17681. for (let runner = self; runner; runner = runner.next) {
  17682. const r = runner.findInThisFrame(name);
  17683. if (r) {
  17684. return r;
  17685. }
  17686. }
  17687. return null;
  17688. }
  17689. });
  17690. this.registerType('torch._C.ValueEnvironment', class extends torch._C.MiniEnvironment {
  17691. });
  17692. this.registerType('torch._C.TypeEnvironment', class extends torch._C.MiniEnvironment {
  17693. });
  17694. this.registerType('torch._C.ControlFlowLoadStores', class {
  17695. constructor() {
  17696. this.environment_stack = null;
  17697. }
  17698. pushFrame(b) {
  17699. this.environment_stack = new torch._C.TypeEnvironment(b, this.environment_stack);
  17700. }
  17701. popFrame() {
  17702. const old_frame = this.environment_stack;
  17703. this.environment_stack = this.environment_stack.next;
  17704. return old_frame;
  17705. }
  17706. addBlockInput(b, type, name) {
  17707. const g = b.owningGraph();
  17708. g.createStore(name, b.addInput(name).setType(type)).insertAfter(b.param_node());
  17709. }
  17710. addBlockOutput(exit_block, type, name) {
  17711. const insert = new torch._C.WithInsertPoint(exit_block);
  17712. const g = exit_block.owningGraph();
  17713. const block_exit = g.insertNode(g.createLoad(name, type)).output();
  17714. exit_block.registerOutput(block_exit);
  17715. insert.dispose();
  17716. }
  17717. addNodeOutput(n, type, name) {
  17718. const out = n.addOutput().setType(type);
  17719. if (torch._C.meaningfulName(name)) {
  17720. out.setDebugName(name);
  17721. }
  17722. const g = n.owningGraph();
  17723. g.createStore(name, out).insertAfter(n);
  17724. }
  17725. addNodeInput(n, type, name) {
  17726. const g = n.owningGraph();
  17727. const inp = g.createLoad(name, type).insertBefore(n).output();
  17728. n.addInput(inp);
  17729. }
  17730. addIfLoadStores(n) {
  17731. const [true_block, false_block] = n.blocks();
  17732. const true_vars = this.addControlFlowLoadStores(true_block);
  17733. const false_vars = this.addControlFlowLoadStores(false_block);
  17734. const mutated_variables = new Set();
  17735. for (const v of true_vars.definedVariables()) {
  17736. if (false_vars.findInAnyFrame(v)) {
  17737. mutated_variables.add(v);
  17738. }
  17739. }
  17740. for (const v of false_vars.definedVariables()) {
  17741. if (true_vars.findInAnyFrame(v)) {
  17742. mutated_variables.add(v);
  17743. }
  17744. }
  17745. for (const x of mutated_variables) {
  17746. const true_type = true_vars.findInAnyFrame(x);
  17747. const false_type = false_vars.findInAnyFrame(x);
  17748. const unified = torch._C.unifyTypes(true_type, false_type, /*default_to_union=*/true);
  17749. this.addBlockOutput(true_block, true_type, x);
  17750. this.addBlockOutput(false_block, false_type, x);
  17751. this.addNodeOutput(n, unified, x);
  17752. }
  17753. }
  17754. addLoopLoadStores(n) {
  17755. const [body_block] = n.blocks();
  17756. const loop_vars = this.addControlFlowLoadStores(body_block);
  17757. for (const name of loop_vars.definedVariables()) {
  17758. const parent_type = this.environment_stack.findInAnyFrame(name);
  17759. if (!parent_type) {
  17760. continue;
  17761. }
  17762. const block_type = loop_vars.findInThisFrame(name);
  17763. const unified_type = torch._C.unifyTypes(parent_type, block_type);
  17764. this.addNodeInput(n, parent_type, name);
  17765. this.addBlockInput(body_block, unified_type, name);
  17766. this.addBlockOutput(body_block, block_type, name);
  17767. this.addNodeOutput(n, unified_type, name);
  17768. }
  17769. }
  17770. addControlFlowLoadStores(block) {
  17771. this.pushFrame(block);
  17772. for (const n of block.nodes()) {
  17773. switch (n.kind()) {
  17774. case 'prim::If': {
  17775. this.addIfLoadStores(n);
  17776. break;
  17777. }
  17778. case 'prim::Loop': {
  17779. this.addLoopLoadStores(n);
  17780. break;
  17781. }
  17782. case 'prim::Closure': {
  17783. for (const b of n.blocks()) {
  17784. this.addControlFlowLoadStores(b);
  17785. }
  17786. break;
  17787. }
  17788. case 'prim::Store': {
  17789. this.environment_stack.setVar(n.s('name'), n.input().type());
  17790. break;
  17791. }
  17792. case 'prim::ComprehensionScope': {
  17793. this.addControlFlowLoadStores(n.blocks().at(0));
  17794. break;
  17795. }
  17796. default: {
  17797. break;
  17798. }
  17799. }
  17800. }
  17801. return this.popFrame();
  17802. }
  17803. run(graph) {
  17804. this.addControlFlowLoadStores(graph.block());
  17805. }
  17806. });
  17807. this.registerType('torch._C.LoopContinuations', class {
  17808. constructor() {
  17809. this._graph = null;
  17810. this._false_val = null;
  17811. this._curr_loop = null;
  17812. }
  17813. assignExitContinuations(block) {
  17814. for (const n of block.nodes()) {
  17815. switch (n.kind()) {
  17816. case 'prim::If': {
  17817. this.assignExitContinuations(n.blocks().at(0));
  17818. this.assignExitContinuations(n.blocks().at(1));
  17819. break;
  17820. }
  17821. case 'prim::Closure': {
  17822. const closure_block = new torch._C.LoopContinuations();
  17823. closure_block.run(n.blocks().at(0));
  17824. break;
  17825. }
  17826. case 'prim::Loop': {
  17827. const prev_loop = this._curr_loop;
  17828. this._curr_loop = n;
  17829. this.assignExitContinuations(n.blocks().at(0));
  17830. this._curr_loop = prev_loop;
  17831. break;
  17832. }
  17833. case 'prim::ContinueStmt': {
  17834. const loop_continuation = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17835. const header_block = loop_continuation.addBlock();
  17836. const [, pre_header] = this._curr_loop.blocks();
  17837. header_block.cloneFrom(pre_header, (v) => v);
  17838. this.InlineBlockBeforeNode(n, header_block);
  17839. loop_continuation.addInput(header_block.outputs()[0]);
  17840. loop_continuation.eraseBlock(0);
  17841. this.addLoopCarriedOutputs(loop_continuation);
  17842. n.destroy();
  17843. break;
  17844. }
  17845. case 'prim::BreakStmt': {
  17846. const loop_exit = this._graph.create('prim::LoopContinuation', 0).insertAfter(n);
  17847. loop_exit.addInput(this._false_val);
  17848. this.addLoopCarriedOutputs(loop_exit);
  17849. n.destroy();
  17850. break;
  17851. }
  17852. default: {
  17853. break;
  17854. }
  17855. }
  17856. }
  17857. }
  17858. run(...args) {
  17859. if (args.length === 1 && args[0] instanceof torch.Graph) {
  17860. const [graph] = args;
  17861. this.run(graph.block());
  17862. } else if (args.length === 1 && args[0] instanceof torch.Block) {
  17863. const [b] = args;
  17864. {
  17865. this._graph = b.owningGraph();
  17866. const guard = new torch._C.WithInsertPoint(b.nodes().front());
  17867. this._false_val = this._graph.insertConstant(false);
  17868. guard.dispose();
  17869. }
  17870. this.assignExitContinuations(b);
  17871. } else {
  17872. throw new python.Error('Not implemented.');
  17873. }
  17874. }
  17875. });
  17876. this.registerType('torch._C.LoopView', class {
  17877. constructor(node) {
  17878. torch._C.AT_ASSERT(node.kind() === 'prim::Loop' || node.kind() === 'onnx::Loop');
  17879. this._node = node;
  17880. }
  17881. bodyBlock() {
  17882. return this._node.blocks().at(0);
  17883. }
  17884. nextCond() {
  17885. return this.bodyBlock().outputs()[0];
  17886. }
  17887. carriedOutputs() {
  17888. return this._node.outputs();
  17889. }
  17890. bodyCarriedInputs() {
  17891. return this.bodyBlock().inputs().slice(1);
  17892. }
  17893. bodyCarriedOutputs() {
  17894. return this.bodyBlock().outputs().slice(1);
  17895. }
  17896. });
  17897. this.registerType('torch._C.WithLoopStatus', class {
  17898. constructor(to_ir, new_status) {
  17899. this._to_ir = to_ir;
  17900. this._prev = this._to_ir._loop_status;
  17901. this._to_ir._loop_status = new_status;
  17902. }
  17903. dispose() {
  17904. this._to_ir._loop_status = this._prev;
  17905. }
  17906. });
  17907. this.registerFunction('torch._C.InlineBlockBeforeNode', (before_node, block) => {
  17908. for (const block_node of block.nodes()) {
  17909. block_node.moveBefore(before_node);
  17910. }
  17911. });
  17912. this.registerFunction('torch._C.inlineLoopCondition', (...args) => {
  17913. if (args.length === 1 && args[0] instanceof torch.Block) {
  17914. const [block] = args;
  17915. for (const n of block.nodes()) {
  17916. for (const b of n.blocks()) {
  17917. torch._C.inlineLoopCondition(b);
  17918. }
  17919. if (n.kind() === 'prim::Loop') {
  17920. torch._C.inlineLoopCondition(n);
  17921. }
  17922. }
  17923. } else if (args.length === 1 && args[0] instanceof torch.Node) {
  17924. const [n] = args;
  17925. const [body_block, pre_header] = n.blocks();
  17926. const temp_block = n.addBlock();
  17927. temp_block.cloneFrom(pre_header, (v) => v);
  17928. torch._C.InlineBlockBeforeNode(n, temp_block);
  17929. n.insertInput(1, temp_block.outputs()[0]);
  17930. n.eraseBlock(2);
  17931. torch._C.InlineBlockBeforeNode(body_block.return_node(), pre_header);
  17932. body_block.return_node().insertInput(0, pre_header.outputs()[0]);
  17933. n.eraseBlock(1);
  17934. } else {
  17935. throw new python.Error('Not implemented.');
  17936. }
  17937. });
  17938. this.registerFunction('torch._C.InlineLoopCondition', (graph) => {
  17939. torch._C.inlineLoopCondition(graph.block());
  17940. });
  17941. this.registerType('torch._C.EraseLoadStores', class {
  17942. pushFrame(b) {
  17943. this.environment_stack = new torch._C.ValueEnvironment(b, this.environment_stack);
  17944. }
  17945. popFrame() {
  17946. const old_frame = this.environment_stack;
  17947. this.environment_stack = this.environment_stack.next;
  17948. return old_frame;
  17949. }
  17950. eraseBlockLoadStores(block) {
  17951. this.pushFrame(block);
  17952. for (const n of block.nodes()) {
  17953. switch (n.kind()) {
  17954. case 'prim::Store': {
  17955. this.environment_stack.setVar(n.s('name'), n.input());
  17956. n.destroy();
  17957. break;
  17958. }
  17959. case 'prim::Load': {
  17960. const name = n.s('name');
  17961. const value = this.environment_stack.findInAnyFrame(name);
  17962. torch._C.TORCH_INTERNAL_ASSERT(value);
  17963. n.output().replaceAllUsesWith(value);
  17964. n.destroy();
  17965. break;
  17966. }
  17967. case 'prim::ComprehensionScope': {
  17968. const [body] = n.blocks();
  17969. this.eraseBlockLoadStores(body);
  17970. for (const body_node of body.nodes()) {
  17971. body_node.moveBefore(n);
  17972. }
  17973. n.destroy();
  17974. break;
  17975. }
  17976. default: {
  17977. for (const b of n.blocks()) {
  17978. this.eraseBlockLoadStores(b);
  17979. }
  17980. break;
  17981. }
  17982. }
  17983. }
  17984. this.popFrame();
  17985. }
  17986. run(graph) {
  17987. this.eraseBlockLoadStores(graph.block());
  17988. }
  17989. });
  17990. this.registerFunction('torch._C.convertEnterExitNodesToWithBlocks', (/* graph */) => {
  17991. });
  17992. this.registerFunction('torch._C.inlineConsecutiveIfs', (/* graph */) => {
  17993. });
  17994. this.registerType('torch._C.ExitPair', class {
  17995. constructor(exit_v, exit_val_ref) {
  17996. const exit_vals = [];
  17997. for (const v of exit_val_ref) {
  17998. exit_vals.push(v);
  17999. }
  18000. if (exit_v.type() !== torch.BoolType.get()) {
  18001. throw new python.Error('Invalid exit value type.');
  18002. }
  18003. this.first = exit_v;
  18004. this.second = exit_vals;
  18005. }
  18006. hasExited() {
  18007. return this.first;
  18008. }
  18009. exitValues() {
  18010. return this.second;
  18011. }
  18012. });
  18013. this.registerType('torch._C.ExitTransformer', class {
  18014. constructor(graph) {
  18015. this._graph = graph;
  18016. this._target_block = null;
  18017. this._unit_values = new Map();
  18018. const guard = new torch._C.WithInsertPoint(this._graph.block().nodes().front());
  18019. this._true_val = this._graph.insertConstant(true);
  18020. this._false_val = this._graph.insertConstant(false);
  18021. this._throws_val = this.getUnitValue(torch.BoolType.get());
  18022. guard.dispose();
  18023. }
  18024. getUnitValue(type) {
  18025. const maybe_val = this._unit_values.get(type);
  18026. if (maybe_val) {
  18027. return maybe_val;
  18028. }
  18029. const unit = this._graph.createUninitialized(type).insertAfter(this._graph.param_node()).output();
  18030. this._unit_values.set(type, unit);
  18031. return unit;
  18032. }
  18033. transformReturnStmts() {
  18034. this._current_exit_kind = 'prim::ReturnStmt';
  18035. this.transformExits(this._graph.block());
  18036. }
  18037. transformLoopContinuations() {
  18038. this._current_exit_kind = 'prim::LoopContinuation';
  18039. this.transformExits(this._graph.block());
  18040. }
  18041. destroyNodeAfterExit(n) {
  18042. for (const output of n.outputs()) {
  18043. if (output.uses().length > 0) {
  18044. output.replaceAllUsesWith(this.getUnitValue(output.type()));
  18045. }
  18046. }
  18047. n.destroy();
  18048. }
  18049. deleteAfterExitNodes(block, iter) {
  18050. const nodes = block.nodes();
  18051. if (iter === nodes.end()) {
  18052. return;
  18053. }
  18054. const insert = new torch._C.WithInsertPoint(block.nodes().front());
  18055. for (const it of Array.from(nodes).reverse()) {
  18056. if (it === iter) {
  18057. break;
  18058. }
  18059. if (it !== block.return_node()) {
  18060. this.destroyNodeAfterExit(it);
  18061. }
  18062. }
  18063. this.destroyNodeAfterExit(iter);
  18064. insert.dispose();
  18065. }
  18066. updateTargetBlock(block) {
  18067. if (torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Loop' && this._current_exit_kind === 'prim::LoopContinuation') {
  18068. this._target_block = block;
  18069. } else if (torch._C.ExitTransformer.isGraphOrClosureBlock(block) && this._current_exit_kind === 'prim::ReturnStmt') {
  18070. this._target_block = block;
  18071. }
  18072. }
  18073. transformLoop(node) {
  18074. const loop = new torch._C.LoopView(node);
  18075. const body = loop.bodyBlock();
  18076. const exit_pair = this.transformExits(body);
  18077. if (this.getExitStatus(exit_pair) === 'WONT' || this.getExitStatus(exit_pair) === 'THROWS') {
  18078. return this.constructWontExitPair();
  18079. }
  18080. const insert = new torch._C.WithInsertPoint(body);
  18081. const new_if = this._graph.insertNode(this._graph.create('prim::If', 0));
  18082. new_if.addInput(exit_pair.hasExited());
  18083. new_if.addBlock().registerOutput(this._false_val);
  18084. new_if.addBlock().registerOutput(loop.nextCond());
  18085. const new_condition = new_if.addOutput().setType(torch.BoolType.get());
  18086. loop.bodyBlock().eraseOutput(0);
  18087. loop.bodyBlock().insertOutput(0, new_condition);
  18088. node.addInput(this._false_val);
  18089. body.addInput().setType(torch.BoolType.get());
  18090. body.registerOutput(exit_pair.hasExited());
  18091. const new_has_exited = node.addOutput().setType(torch.BoolType.get());
  18092. for (const exit_value of exit_pair.exitValues()) {
  18093. const typ = exit_value.type();
  18094. node.addInput(this.getUnitValue(typ));
  18095. node.addOutput().setType(typ);
  18096. body.addInput().setType(typ);
  18097. body.registerOutput(exit_value);
  18098. }
  18099. const exit_vals = node.outputs().slice(node.outputs().length - exit_pair.exitValues().size());
  18100. const result = new torch._C.ExitPair(new_has_exited, exit_vals);
  18101. insert.dispose();
  18102. return result;
  18103. }
  18104. calcIfExitStatus(then_status, else_status) {
  18105. if (then_status === 'THROWS') {
  18106. return else_status;
  18107. } else if (else_status === 'THROWS') {
  18108. return then_status;
  18109. }
  18110. if (then_status === 'WONT' && else_status === 'WONT') {
  18111. return 'WONT';
  18112. }
  18113. if (then_status === 'WILL' && else_status === 'WILL') {
  18114. return 'WILL';
  18115. }
  18116. return 'MIGHT';
  18117. }
  18118. transformIf(node) {
  18119. const [then_block, else_block] = node.blocks();
  18120. let then_pair = this.transformExits(then_block);
  18121. let else_pair = this.transformExits(else_block);
  18122. const then_status = this.getExitStatus(then_pair);
  18123. const else_status = this.getExitStatus(else_pair);
  18124. const if_status = this.calcIfExitStatus(then_status, else_status);
  18125. if (if_status === 'THROWS') {
  18126. return this.constructThrowsExitPair();
  18127. }
  18128. if (if_status === 'WONT') {
  18129. return this.constructWontExitPair();
  18130. }
  18131. if (then_status === 'WONT' || then_status === 'THROWS') {
  18132. const exit_vals = this.matchValuesWithUnitialized(else_pair.exitValues());
  18133. then_pair = new torch._C.ExitPair(then_pair.hasExited(), exit_vals);
  18134. } else if (else_status === 'WONT' || else_status === 'THROWS') {
  18135. const exit_vals = this.matchValuesWithUnitialized(then_pair.exitValues());
  18136. else_pair = new torch._C.ExitPair(else_pair.hasExited(), exit_vals);
  18137. }
  18138. let has_exited = null;
  18139. if (if_status === 'WILL') {
  18140. has_exited = this._true_val;
  18141. } else {
  18142. this.addIfOutputs(node, [then_pair.hasExited()], [else_pair.hasExited()]);
  18143. has_exited = node.outputs().at(node.outputs().length - 1);
  18144. }
  18145. this.addIfOutputs(node, then_pair.exitValues(), else_pair.exitValues());
  18146. const num_exit_vals = then_pair.exitValues().size();
  18147. const exit_vals = node.outputs().slice(node.outputs().length - num_exit_vals);
  18148. return new torch._C.ExitPair(has_exited, exit_vals);
  18149. }
  18150. transformExits(block) {
  18151. const prev_target_block = this._target_block;
  18152. this.updateTargetBlock(block);
  18153. let exit_pair = this.constructWontExitPair();
  18154. for (const node of block.nodes()) {
  18155. const it = node.next;
  18156. switch (node.kind()) {
  18157. case 'prim::RaiseException': {
  18158. exit_pair = this.constructThrowsExitPair();
  18159. break;
  18160. }
  18161. case 'prim::ReturnStmt':
  18162. case 'prim::LoopContinuation': {
  18163. if (node.kind() === this._current_exit_kind) {
  18164. exit_pair = this.constructWillExitPair(node.inputs());
  18165. node.destroy();
  18166. }
  18167. break;
  18168. }
  18169. case 'prim::If': {
  18170. exit_pair = this.transformIf(node);
  18171. break;
  18172. }
  18173. case 'prim::With': {
  18174. exit_pair = this.transformWith(node);
  18175. break;
  18176. }
  18177. case 'prim::Closure': {
  18178. this.transformExits(node.blocks().at(0));
  18179. break;
  18180. }
  18181. case 'prim::Loop': {
  18182. exit_pair = this.transformLoop(node);
  18183. break;
  18184. }
  18185. default: {
  18186. break;
  18187. }
  18188. }
  18189. const status = this.getExitStatus(exit_pair);
  18190. if (status === 'WILL' || status === 'THROWS') {
  18191. this.deleteAfterExitNodes(block, it);
  18192. break;
  18193. }
  18194. if (status === 'MIGHT') {
  18195. throw new python.Error('Not implemented.');
  18196. // const nodes = block.nodes();
  18197. // if (node === nodes[nodes.length - 1]) {
  18198. // exit_pair = this.guardBlockNodes(block, exit_pair, it);
  18199. // }
  18200. // break;
  18201. }
  18202. }
  18203. if (this._target_block === block) {
  18204. if (this.getExitStatus(exit_pair) === 'MIGHT') {
  18205. const new_if = this._graph.create('prim::If', 0).insertBefore(block.return_node());
  18206. new_if.addBlock();
  18207. new_if.addBlock();
  18208. new_if.addInput(exit_pair.hasExited());
  18209. torch._C.ExistTransformer.addIfOutputs(new_if, exit_pair.exitValues(), block.outputs());
  18210. torch._C.ExistTransformer.replaceBlockOutputs(block, new_if.soutputs());
  18211. } else if (this.getExitStatus(exit_pair) === 'WILL') {
  18212. torch._C.ExitTransformer.replaceBlockOutputs(block, exit_pair.exitValues());
  18213. }
  18214. exit_pair = this.constructWontExitPair();
  18215. }
  18216. this._target_block = prev_target_block;
  18217. return exit_pair;
  18218. }
  18219. constructThrowsExitPair() {
  18220. return new torch._C.ExitPair(this._throws_val, []);
  18221. }
  18222. constructWontExitPair() {
  18223. return new torch._C.ExitPair(this._false_val, []);
  18224. }
  18225. constructWillExitPair(exit_val_ref) {
  18226. return new torch._C.ExitPair(this._true_val, exit_val_ref);
  18227. }
  18228. getExitStatus(exit_pair) {
  18229. const exit_v = exit_pair.hasExited();
  18230. if (exit_v === this._true_val) {
  18231. return 'WILL';
  18232. } else if (exit_v === this._false_val) {
  18233. return 'WONT';
  18234. } else if (exit_v === this._throws_val) {
  18235. return 'THROWS';
  18236. }
  18237. return 'MIGHT';
  18238. }
  18239. static owningNodeKind(block) {
  18240. if (block.owningNode()) {
  18241. return block.owningNode().kind();
  18242. }
  18243. return null;
  18244. }
  18245. static isGraphOrClosureBlock(block) {
  18246. return block.owningNode() === null || torch._C.ExitTransformer.owningNodeKind(block) === 'prim::Closure';
  18247. }
  18248. static removeOutputs(b) {
  18249. while (b.outputs().length > 0) {
  18250. b.eraseOutput(0);
  18251. }
  18252. }
  18253. static registerBlockOutputs(b, outs) {
  18254. for (const out of outs) {
  18255. b.registerOutput(out);
  18256. }
  18257. }
  18258. static replaceBlockOutputs(b, outs) {
  18259. torch._C.ExitTransformer.removeOutputs(b);
  18260. torch._C.ExitTransformer.registerBlockOutputs(b, outs);
  18261. }
  18262. });
  18263. this.registerFunction('torch._C.convertWithBlocksToEnterExitNodes', (/* graph */) => {
  18264. });
  18265. this.registerFunction('torch._C.TransformExits', (graph) => {
  18266. torch._C.convertEnterExitNodesToWithBlocks(graph);
  18267. const e_loop = new torch._C.ExitTransformer(graph);
  18268. e_loop.transformLoopContinuations();
  18269. const e_ret = new torch._C.ExitTransformer(graph);
  18270. e_ret.transformReturnStmts();
  18271. torch._C.inlineConsecutiveIfs(graph.block());
  18272. torch._C.convertWithBlocksToEnterExitNodes(graph);
  18273. });
  18274. this.registerFunction('torch._C.normalizeRSub', (iter) => {
  18275. if (iter.kind() === 'aten::rsub' && iter.schema() && iter.schema().overload === 'Tensor') {
  18276. const args = iter.inputs();
  18277. const newSub = iter.replaceWithNewSymbol('aten::sub');
  18278. newSub.replaceInput(0, args[1]);
  18279. newSub.replaceInput(1, args[0]);
  18280. iter.destroyCurrent();
  18281. return true;
  18282. }
  18283. return false;
  18284. });
  18285. this.registerFunction('torch._C.normalizeOpAliases', (/* iter */) => {
  18286. });
  18287. this.registerFunction('torch._C.normalizeIsBool', (iter) => {
  18288. const args = iter.inputs();
  18289. if (args.length === 2 && args[0].type() === torch.BoolType.get() && args[1].type() === torch.BoolType.get()) {
  18290. if (iter.kind() === 'aten::__is__') {
  18291. iter.replaceWithNewSymbol('aten::eq');
  18292. iter.destroyCurrent();
  18293. return true;
  18294. }
  18295. if (iter.kind() === 'aten::__isnot__') {
  18296. iter.replaceWithNewSymbol('aten::ne');
  18297. iter.destroyCurrent();
  18298. return true;
  18299. }
  18300. }
  18301. return false;
  18302. });
  18303. this.registerFunction('torch._C.NormalizeOps', (block) => {
  18304. for (const it of block.nodes()) {
  18305. for (const sub of it.blocks()) {
  18306. torch._C.NormalizeOps(sub);
  18307. }
  18308. if (torch._C.normalizeRSub(it)) {
  18309. continue;
  18310. }
  18311. if (torch._C.normalizeOpAliases(it)) {
  18312. continue;
  18313. }
  18314. if (torch._C.normalizeIsBool(it)) {
  18315. continue;
  18316. }
  18317. }
  18318. });
  18319. this.registerFunction('torch._C.getInlineEverythingMode', () => {
  18320. return false;
  18321. });
  18322. this.registerFunction('torch._C.runCleanupPasses', (to_clean) => {
  18323. /*
  18324. torch._C.liftClosures(to_clean);
  18325. torch._C.inlineForkedClosures(to_clean);
  18326. */
  18327. if (torch._C.getInlineEverythingMode()) {
  18328. torch._C.Inline(to_clean);
  18329. }
  18330. /*
  18331. torch._C.eraseListLiterals(to_clean);
  18332. */
  18333. torch._C.LowerSimpleTuples(to_clean);
  18334. torch._C.ConstantPropagationImmutableTypes(to_clean);
  18335. torch._C.ConstantPooling(to_clean);
  18336. /*
  18337. torch._C.CanonicalizeOutputs(to_clean);
  18338. torch._C.AnnotateWarns(to_clean);
  18339. */
  18340. });
  18341. this.registerType('torch.jit._script.ScriptModule', class extends torch.nn.modules.module.Module {});
  18342. this.registerType('torch.jit._trace.TracedModule', class extends torch.jit._script.ScriptModule {});
  18343. this.registerType('torch.jit._trace.TopLevelTracedModule', class extends torch.jit._trace.TracedModule {});
  18344. this.registerType('torch.jit._script.RecursiveScriptModule', class extends torch.jit._script.ScriptModule {
  18345. constructor(cpp_module) {
  18346. super();
  18347. this._initializing = true;
  18348. this._c = cpp_module;
  18349. }
  18350. static _construct(cpp_module, init_fn) {
  18351. const script_module = new torch.jit._script.RecursiveScriptModule(cpp_module);
  18352. init_fn(script_module);
  18353. torch.jit._script.RecursiveScriptModule._finalize_scriptmodule(script_module);
  18354. return script_module;
  18355. }
  18356. static _finalize_scriptmodule(script_module) {
  18357. script_module._parameters = new torch.ParameterDict(script_module._c).items();
  18358. script_module._buffers = new torch.BufferDict(script_module._c).items();
  18359. // script_module._modules = OrderedModuleDict(script_module._c, script_module._modules)
  18360. script_module._initializing = false;
  18361. }
  18362. get graph() {
  18363. // return this._c._get_method('forward').graph;
  18364. return this._c.graph;
  18365. }
  18366. get code_with_constants() {
  18367. // return this.forward.code_with_constants;
  18368. return this._c.code_with_constants;
  18369. }
  18370. __setattr__(name, value) {
  18371. if (this._initializing) {
  18372. super.__setattr__(name, value);
  18373. } else if (this._modules.has(name)) {
  18374. this._modules.set(name, value);
  18375. } else if (this._c.hasattr(name)) {
  18376. this._c.setattr(name, value);
  18377. } else {
  18378. //
  18379. }
  18380. }
  18381. __getattr__(name) {
  18382. if (this._initializing) {
  18383. return super.__getattr__(name);
  18384. }
  18385. if (this._modules.has(name)) {
  18386. return this._modules.get(name);
  18387. }
  18388. if (this._c.hasattr(name)) {
  18389. return this._c.getattr(name);
  18390. }
  18391. if (this._c._has_method(name)) {
  18392. //
  18393. }
  18394. return super.__getattr__(name);
  18395. }
  18396. });
  18397. torch.jit.ScriptModule = torch.jit._script.ScriptModule;
  18398. torch.jit.RecursiveScriptModule = torch.jit._script.RecursiveScriptModule;
  18399. torch.jit.TopLevelTracedModule = torch.jit._trace.TopLevelTracedModule;
  18400. torch.CompilationUnit = torch.jit.CompilationUnit;
  18401. torch._C.CompilationUnit = torch.jit.CompilationUnit;
  18402. torch._C.ScriptModule = torch.ScriptModule;
  18403. torch._C.ClassType = torch.ClassType;
  18404. this.registerType('torch._C.FlatBuffersLoader', class {
  18405. constructor(cu) {
  18406. this._cu = cu;
  18407. const torch = cu.execution.__import__('torch');
  18408. this._torch = torch;
  18409. const dtypes = Array.from(new Set(Object.values(torch).filter((obj) => obj instanceof torch.dtype)));
  18410. this._dtypes = new Map(dtypes.map((dtype) => [dtype.scalar_type(), dtype]));
  18411. this._ivalue_parsers = new Map();
  18412. this._ivalue_parsers.set(torch.mobile.serialization.Int, (ivalue) => ivalue.val.int_val);
  18413. this._ivalue_parsers.set(torch.mobile.serialization.Bool, (ivalue) => ivalue.val.bool_val);
  18414. this._ivalue_parsers.set(torch.mobile.serialization.Double, (ivalue) => ivalue.val.double_val);
  18415. this._ivalue_parsers.set(torch.mobile.serialization.TensorMetadata, (ivalue) => this.parseTensor(ivalue));
  18416. this._ivalue_parsers.set(torch.mobile.serialization.Object, (ivalue) => this.parseObject(ivalue));
  18417. }
  18418. parseModule(module) {
  18419. this._module = module;
  18420. this._all_functions = new Map();
  18421. this._all_ivalues = new Array(module.ivalues.length);
  18422. this._all_types = new Array(module.object_types.length);
  18423. const mobile_ivalue_size = module.mobile_ivalue_size ? module.mobile_ivalue_size : module.ivalues.length;
  18424. for (let i = 0; i < mobile_ivalue_size; i++) {
  18425. this.parseAndPopulate(i, module.ivalues[i]);
  18426. }
  18427. const m = this._all_ivalues[module.state_obj];
  18428. for (const [name, value] of this._all_functions) {
  18429. const class_index = module.ivalues[name].val.class_type;
  18430. const class_type = this._all_types[class_index];
  18431. if (value) {
  18432. class_type.addMethod(value);
  18433. }
  18434. }
  18435. m._min_operator_version = module.operator_version;
  18436. m._bytecode_version = module.bytecode_version;
  18437. return m;
  18438. }
  18439. parseAndPopulate(i, ivalue) {
  18440. if (ivalue.val instanceof torch.mobile.serialization.Function) {
  18441. this._all_functions.set(i, this.parseFunction(ivalue.val));
  18442. } else {
  18443. this._all_ivalues[i] = this.parseIValue(ivalue);
  18444. }
  18445. }
  18446. parseFunction(/* val */) {
  18447. return null;
  18448. }
  18449. parseIValue(ivalue) {
  18450. if (ivalue.val) {
  18451. const callback = this._ivalue_parsers.get(ivalue.val.constructor);
  18452. return callback(ivalue);
  18453. }
  18454. return null;
  18455. }
  18456. parseTensor(ivalue) {
  18457. return this.parseTensorFromMetadata(ivalue.val);
  18458. }
  18459. parseTensorFromMetadata(metadata) {
  18460. if (metadata.quantized_schema) {
  18461. throw new torch.Error('Quantized schema not implemented.');
  18462. }
  18463. const index = metadata.storage_location_index;
  18464. const data = this._module.storage_data[index].data;
  18465. const dtype = this._dtypes.get(metadata.scalar_type);
  18466. const size = data.length / dtype.itemsize();
  18467. const storage = new torch.storage.TypedStorage(size, dtype);
  18468. storage._set_cdata(data);
  18469. const tensor = new torch.Tensor();
  18470. const shape = Array.from(metadata.sizes);
  18471. const stride = Array.from(metadata.strides);
  18472. tensor.__setstate__([storage, metadata.storage_offset, shape, stride]);
  18473. return tensor;
  18474. }
  18475. parseObject(ivalue) {
  18476. const object = ivalue.val;
  18477. const obj_type = this._module.object_types[object.type_index];
  18478. const cls = this.getOrCreateClassTypeForObject(object);
  18479. switch (obj_type.type) {
  18480. case torch.mobile.serialization.TypeType.CLASS_WITH_FIELD: {
  18481. const torch = this._torch;
  18482. const obj = torch.ScriptObject.create(cls);
  18483. for (let i = 0; i < object.attrs.length; i++) {
  18484. const attr_name = obj_type.attr_names[i];
  18485. const val = this._all_ivalues[object.attrs[i]];
  18486. obj.__setattr__(attr_name, val);
  18487. }
  18488. return obj;
  18489. }
  18490. case torch.mobile.serialization.TypeType.CUSTOM_CLASS:
  18491. case torch.mobile.serialization.TypeType.CLASS_WITH_SETSTATE:
  18492. default: {
  18493. throw new python.Error(`Unknown object type type '${obj_type.type}'.`);
  18494. }
  18495. }
  18496. }
  18497. getOrCreateClassTypeForObject(object) {
  18498. let cls = this._all_types[object.type_index];
  18499. const obj_type = this._module.object_types[object.type_index];
  18500. if (!cls) {
  18501. const name = obj_type.type_name;
  18502. if (name.startsWith('__torch__') || name.startsWith('torch.jit')) {
  18503. cls = this._cu.get_class(new torch._C.QualifiedName(name));
  18504. if (!cls) {
  18505. const torch = this._torch;
  18506. cls = torch.ClassType.create(name, this._cu, true);
  18507. this._cu.register_type(cls);
  18508. }
  18509. } else {
  18510. // cls = c10::parseType(qn_str).cast<ClassType>();
  18511. }
  18512. this._all_types[object.type_index] = cls;
  18513. if (obj_type.type === torch.mobile.serialization.TypeType.CLASS_WITH_FIELD) {
  18514. for (let i = 0; i < object.attrs.length; i++) {
  18515. // const val = this._all_ivalues[object.attrs[i]];
  18516. cls.addAttribute(obj_type.attr_names[i] /*, null val.type(c10::DynamicType) */);
  18517. }
  18518. }
  18519. }
  18520. return cls;
  18521. }
  18522. });
  18523. this.registerType('torch.export.UnflattenedModule', class extends torch.nn.modules.module.Module {
  18524. constructor(export_module, flat_args_adapter) {
  18525. super();
  18526. const export_graph = copy.deepcopy(export_module.graph);
  18527. self.graph_signature = copy.deepcopy(export_module.graph_signature);
  18528. this.graph = torch.fx.Graph();
  18529. this.graph.owning_module = this;
  18530. this.module_call_graph = copy.deepcopy(export_module.module_call_graph);
  18531. this.flat_args_adapter = flat_args_adapter;
  18532. this.adapted = false;
  18533. // this._run_with_interpreter = RUN_WITH_INTERPRETER
  18534. this._inplace_buffer_mutations(export_graph, this.graph_signature);
  18535. }
  18536. });
  18537. this.registerType('torch.export.graph_signature.ExportGraphSignature', class {
  18538. constructor(input_specs, output_specs) {
  18539. this.input_specs = input_specs;
  18540. this.output_specs = output_specs;
  18541. }
  18542. get user_inputs() {
  18543. const user_inputs = [];
  18544. for (const s of this.input_specs) {
  18545. if (s.kind !== torch.export.graph_signature.InputKind.USER_INPUT) {
  18546. continue;
  18547. }
  18548. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18549. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18550. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18551. user_inputs.push(s.arg.name);
  18552. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18553. user_inputs.push(s.arg.value);
  18554. } else {
  18555. throw new python.Error(`Unsupported user input '${s.arg}'.`);
  18556. }
  18557. }
  18558. return user_inputs;
  18559. }
  18560. get user_outputs() {
  18561. const user_outputs = [];
  18562. for (const s of this.output_specs) {
  18563. if (s.kind !== torch.export.graph_signature.OutputKind.USER_OUTPUT) {
  18564. continue;
  18565. }
  18566. if (s.arg instanceof torch.export.graph_signature.TensorArgument ||
  18567. s.arg instanceof torch.export.graph_signature.SymIntArgument ||
  18568. s.arg instanceof torch.export.graph_signature.CustomObjArgument) {
  18569. user_outputs.push(s.arg.name);
  18570. } else if (s.arg instanceof torch.export.graph_signature.ConstantArgument) {
  18571. user_outputs.push(s.arg.value);
  18572. } else {
  18573. throw new python.Error(`Unsupported user output '${s.arg}'.`);
  18574. }
  18575. }
  18576. return user_outputs;
  18577. }
  18578. get inputs_to_parameters() {
  18579. return new Map(this.input_specs
  18580. .filter((s) => s.kind === torch.export.graph_signature.InputKind.PARAMETER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18581. .map((s) => [s.arg.name, s.target]));
  18582. }
  18583. get inputs_to_buffers() {
  18584. return new Map(this.input_specs
  18585. .filter((s) => s.kind === torch.export.graph_signature.InputKind.BUFFER && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18586. .map((s) => [s.arg.name, s.target]));
  18587. }
  18588. get inputs_to_lifted_tensor_constants() {
  18589. return new Map(this.input_specs
  18590. .filter((s) => s.kind === torch.export.graph_signature.InputKind.CONSTANT_TENSOR && s.arg instanceof torch.export.graph_signature.TensorArgument && typeof s.target === 'string')
  18591. .map((s) => [s.arg.name, s.target]));
  18592. }
  18593. });
  18594. torch.export.graph_signature.InputKind = {
  18595. USER_INPUT: 0,
  18596. PARAMETER: 1,
  18597. BUFFER: 2,
  18598. CONSTANT_TENSOR: 3,
  18599. CUSTOM_OBJ: 4,
  18600. TOKEN: 5
  18601. };
  18602. this.registerType('torch.export.graph_signature.InputSpec', class {
  18603. constructor(kind, arg, target, persistent) {
  18604. this.kind = kind;
  18605. this.arg = arg;
  18606. this.target = target;
  18607. this.persistent = persistent || null;
  18608. }
  18609. });
  18610. torch.export.graph_signature.OutputKind = {
  18611. USER_OUTPUT: 0,
  18612. LOSS_OUTPUT: 1,
  18613. BUFFER_MUTATION: 2,
  18614. GRADIENT_TO_PARAMETER: 3,
  18615. GRADIENT_TO_USER_INPUT: 4,
  18616. USER_INPUT_MUTATION: 5,
  18617. TOKEN: 6
  18618. };
  18619. this.registerType('torch.export.graph_signature.OutputSpec', class {
  18620. constructor(kind, arg, target) {
  18621. this.kind = kind;
  18622. this.arg = arg;
  18623. this.target = target;
  18624. }
  18625. });
  18626. this.registerType('torch.export.graph_signature.ConstantArgument', class {
  18627. constructor(name, value) {
  18628. this.name = name;
  18629. this.value = value; // Union[int, float, bool, str, None]
  18630. }
  18631. });
  18632. this.registerType('torch.export.graph_signature.TensorArgument', class {
  18633. constructor(name) {
  18634. this.name = name;
  18635. }
  18636. });
  18637. this.registerType('torch.export.graph_signature.SymIntArgument', class {
  18638. constructor(name) {
  18639. this.name = name;
  18640. }
  18641. });
  18642. this.registerType('torch.export.graph_signature.CustomObjArgument', class {
  18643. constructor(name, class_fqn, fake_val) {
  18644. this.name = name;
  18645. this.class_fqn = class_fqn;
  18646. this.fake_val = fake_val;
  18647. }
  18648. });
  18649. this.registerType('torch.export.exported_program.ExportedProgram', class {
  18650. constructor(root, graph, graph_signature, state_dict, range_constraints, module_call_graph, example_inputs, verifier, tensor_constants, constants) {
  18651. // graph._codegen = torch.fx.graph.CodeGen()
  18652. this._graph_module = this._create_graph_module_for_export(root, graph);
  18653. if (root instanceof torch.fx.GraphModule) {
  18654. // this._graph_module.meta.update(root.meta);
  18655. }
  18656. this._graph_signature = graph_signature;
  18657. this._state_dict = state_dict;
  18658. this._range_constraints = range_constraints;
  18659. this._module_call_graph = module_call_graph;
  18660. this._example_inputs = example_inputs;
  18661. this._constants = tensor_constants || constants || {};
  18662. }
  18663. _create_graph_module_for_export(root, graph) {
  18664. let gm = null;
  18665. try {
  18666. gm = new torch.fx.GraphModule(root, graph);
  18667. } catch {
  18668. const gm = new torch.fx.GraphModule(root, torch.fx.Graph());
  18669. gm._graph = graph;
  18670. }
  18671. return gm;
  18672. }
  18673. get graph_module() {
  18674. return this._graph_module;
  18675. }
  18676. get graph() {
  18677. return this._graph_module.graph;
  18678. }
  18679. get graph_signature() {
  18680. return this._graph_signature;
  18681. }
  18682. get state_dict() {
  18683. return this._state_dict;
  18684. }
  18685. get constants() {
  18686. return this._constants;
  18687. }
  18688. });
  18689. this.registerType('torch.export.exported_program.ModuleCallEntry', class {});
  18690. this.registerType('torch.export.exported_program.ModuleCallSignature', class {});
  18691. this.registerFunction('torch.export.exported_program._create_graph_module_for_export', (root, graph) => {
  18692. return new torch.fx.graph_module.GraphModule(root, graph);
  18693. });
  18694. this.registerFunction('torch.export.unflatten', (module, flat_args_adapter) => {
  18695. module = torch.export._remove_effect_tokens(module);
  18696. return new torch.export.UnflattenedModule(module, flat_args_adapter);
  18697. });
  18698. this.registerFunction('torch._export.exported_program._create_graph_module_for_export', (root, graph) => {
  18699. return new torch.fx.graph_module.GraphModule(root, graph);
  18700. });
  18701. this.registerType('torch._export.serde.serialize.SerializedArtifact', class {
  18702. constructor(exported_program, state_dict, constants, example_inputs) {
  18703. this.exported_program = exported_program;
  18704. this.state_dict = state_dict;
  18705. this.constants = constants;
  18706. this.example_inputs = example_inputs;
  18707. }
  18708. });
  18709. torch._export.serde.serialize._SYM_OPS = new Set([
  18710. operator.eq, operator.ne, operator.le, operator.ge, operator.lt, operator.gt,
  18711. operator.neg, operator.pos, operator.and_, operator.or_,
  18712. math.trunc, torch.sym_not,
  18713. operator.mul, operator.add, operator.sub, operator.floordiv, operator.mod, operator.pow,
  18714. torch.sym_int, torch.sym_float, torch.sym_ite, torch.sym_max, torch.sym_min, torch.sym_sqrt,
  18715. operator.truediv, operator.and_
  18716. ]);
  18717. this.registerType('torch._export.serde.union._Union', class {
  18718. constructor(obj) {
  18719. if (obj.$type) {
  18720. this.type = obj.$type;
  18721. this[obj.$type] = obj.$value;
  18722. delete obj.$type;
  18723. delete obj.$value;
  18724. } else if (obj.type) {
  18725. this.type = obj.type;
  18726. const entries = Object.entries(obj).filter(([key]) => key !== 'type');
  18727. this[obj.type] = Object.fromEntries(entries);
  18728. } else {
  18729. let entries = Object.entries(obj);
  18730. if (entries.length > 1) {
  18731. entries = entries.filter(([, value]) => value !== null);
  18732. }
  18733. if (entries.length !== 1) {
  18734. throw new python.Error(`Invalid union type '${entries.map(([key]) => key).join(',')}'.`);
  18735. }
  18736. const [entry] = entries;
  18737. const [type, value] = entry;
  18738. this.type = type;
  18739. this[type] = value;
  18740. }
  18741. }
  18742. get value() {
  18743. return this[this.type];
  18744. }
  18745. });
  18746. this.registerType('torch._export.serde.schema.NamedArgument', class {
  18747. constructor(obj) {
  18748. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18749. this.name = obj.name;
  18750. }
  18751. });
  18752. this.registerType('torch._export.serde.schema.Argument', class extends torch._export.serde.union._Union {
  18753. constructor(obj) {
  18754. super(obj);
  18755. switch (this.type) {
  18756. case 'as_int':
  18757. case 'as_ints':
  18758. case 'as_float':
  18759. case 'as_floats':
  18760. case 'as_bool':
  18761. case 'as_bools':
  18762. case 'as_string':
  18763. case 'as_strings':
  18764. case 'as_scalar_type':
  18765. case 'as_device':
  18766. case 'as_memory_format':
  18767. case 'as_layout':
  18768. break;
  18769. case 'as_none':
  18770. this.as_none = null;
  18771. break;
  18772. case 'as_tensor':
  18773. this.as_tensor = new torch._export.serde.schema.TensorArgument(this.as_tensor);
  18774. break;
  18775. case 'as_tensors':
  18776. this.as_tensors = this.as_tensors.map((item) => new torch._export.serde.schema.TensorArgument(item));
  18777. break;
  18778. case 'as_graph':
  18779. this.as_graph = new torch._export.serde.schema.GraphArgument(this.as_graph);
  18780. break;
  18781. case 'as_sym_int':
  18782. this.as_sym_int = new torch._export.serde.schema.SymIntArgument(this.as_sym_int);
  18783. break;
  18784. case 'as_sym_ints':
  18785. this.as_sym_ints = this.as_sym_ints.map((item) => new torch._export.serde.schema.SymIntArgument(item));
  18786. break;
  18787. case 'as_sym_bool':
  18788. this.as_sym_bool = new torch._export.serde.schema.SymBoolArgument(this.as_sym_bool);
  18789. break;
  18790. case 'as_sym_bools':
  18791. this.as_sym_bools = this.as_sym_bools.map((item) => new torch._export.serde.schema.SymBoolArgument(item));
  18792. break;
  18793. case 'as_sym_float':
  18794. this.as_sym_float = new torch._export.serde.schema.SymFloatArgument(this.as_sym_float);
  18795. break;
  18796. case 'as_sym_floats':
  18797. this.as_sym_floats = this.as_sym_float.map((item) => new torch._export.serde.schema.SymFloatArgument(item));
  18798. break;
  18799. case 'as_optional_tensors':
  18800. this.as_optional_tensors = this.as_optional_tensors.map((item) => new torch._export.serde.schema.OptionalTensorArgument(item));
  18801. break;
  18802. case 'as_custom_obj':
  18803. this.as_custom_obj = new torch._export.serde.schema.CustomObjArgument(this.as_custom_obj);
  18804. break;
  18805. // case 'as_graph': GraphArgument
  18806. default:
  18807. throw new python.Error(`Unsupported argument '${this.type}'.`);
  18808. }
  18809. }
  18810. });
  18811. this.registerType('torch._export.serde.schema.Node', class {
  18812. constructor(obj) {
  18813. this.target = obj.target;
  18814. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.NamedArgument(input));
  18815. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18816. this.metadata = new Map(Object.entries(obj.metadata));
  18817. }
  18818. });
  18819. torch._export.serde.schema.ScalarType = {
  18820. UNKNOWN: 0,
  18821. BYTE: 1,
  18822. CHAR: 2,
  18823. SHORT: 3,
  18824. INT: 4,
  18825. LONG: 5,
  18826. HALF: 6,
  18827. FLOAT: 7,
  18828. DOUBLE: 8,
  18829. COMPLEXHALF: 9,
  18830. COMPLEXFLOAT: 10,
  18831. COMPLEXDOUBLE: 11,
  18832. BOOL: 12,
  18833. BFLOAT16: 13,
  18834. UINT16: 28,
  18835. FLOAT8E4M3FN: 29,
  18836. FLOAT8E5M2: 30,
  18837. FLOAT8E4M3FNUZ: 31,
  18838. FLOAT8E5M2FNUZ: 32,
  18839. };
  18840. torch._export.serde.schema.Layout = {
  18841. Unknown: 0,
  18842. SparseCoo: 1,
  18843. SparseCsr: 2,
  18844. SparseCsc: 3,
  18845. SparseBsr: 4,
  18846. SparseBsc: 5,
  18847. _mkldnn: 6,
  18848. Strided: 7
  18849. };
  18850. torch._export.serde.schema.MemoryFormat = {
  18851. Unknown: 0,
  18852. ContiguousFormat: 1,
  18853. ChannelsLast: 2,
  18854. ChannelsLast3d: 3,
  18855. PreserveFormat: 4,
  18856. };
  18857. this.registerType('torch._export.serde.schema.Device', class {
  18858. constructor(obj) {
  18859. Object.assign(this, { ...obj });
  18860. }
  18861. });
  18862. this.registerType('torch._export.serde.schema.TensorMeta', class {
  18863. constructor(obj) {
  18864. obj = obj.meta || obj;
  18865. this.dtype = obj.dtype;
  18866. this.sizes = obj.sizes.map((size) => new torch._export.serde.schema.SymInt(size));
  18867. this.requires_grad = obj.requires_grad;
  18868. this.device = obj.device;
  18869. this.strides = obj.strides.map((stride) => new torch._export.serde.schema.SymInt(stride));
  18870. this.storage_offset = new torch._export.serde.schema.SymInt(Number.isInteger(obj.storage_offset) ? { as_int: obj.storage_offset } : obj.storage_offset);
  18871. this.layout = obj.layout;
  18872. }
  18873. });
  18874. this.registerType('torch._export.serde.schema.Graph', class {
  18875. constructor(obj) {
  18876. this.inputs = obj.inputs.map((input) => new torch._export.serde.schema.Argument(input));
  18877. this.outputs = obj.outputs.map((output) => new torch._export.serde.schema.Argument(output));
  18878. this.nodes = obj.nodes.map((node) => new torch._export.serde.schema.Node(node));
  18879. this.tensor_values = new Map(Object.entries(obj.tensor_values).map(([key, value]) => [key, new torch._export.serde.schema.TensorMeta(value)]));
  18880. this.sym_int_values = new Map(Object.entries(obj.sym_int_values).map(([key, value]) => [key, new torch._export.serde.schema.SymInt(value)]));
  18881. this.sym_bool_values = new Map(Object.entries(obj.sym_bool_values).map(([key, value]) => [key, new torch._export.serde.schema.SymBool(value)]));
  18882. this.is_single_tensor_return = obj.is_single_tensor_return;
  18883. this.custom_obj_values = new Map(Object.entries(obj.custom_obj_values || {}).map(([key, value]) => [key, new torch._export.serde.schema.CustomObjArgument(value)]));
  18884. if (obj.contants) {
  18885. // this.constants = new Map(Object.entries(serialized_graph.constants).map(([k, v]) => [k, torch.load(v)]));
  18886. // graph_signature -> input_specs -> tensor_constant
  18887. }
  18888. }
  18889. });
  18890. this.registerType('torch._export.serde.schema.ModuleCallSignature', class {
  18891. constructor(obj) {
  18892. Object.assign(this, { ...obj });
  18893. this.inputs = this.inputs.map((item) => new torch._export.serde.schema.Argument(item));
  18894. this.outputs = this.outputs.map((item) => new torch._export.serde.schema.Argument(item));
  18895. }
  18896. });
  18897. this.registerType('torch._export.serde.schema.ModuleCallEntry', class {
  18898. constructor(obj) {
  18899. Object.assign(this, { ...obj });
  18900. this.signature = this.signature ? new torch._export.serde.schema.ModuleCallSignature(this.signature) : null;
  18901. }
  18902. });
  18903. this.registerType('torch._export.serde.schema.GraphModule', class {
  18904. constructor(obj) {
  18905. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  18906. this.signature = new torch._export.serde.schema.GraphSignature(obj.signature);
  18907. this.module_call_graph = obj.module_call_graph.map((item) => new torch._export.serde.schema.ModuleCallEntry(item));
  18908. this.metadata = new Map(Object.entries(obj.metadata || {}));
  18909. }
  18910. });
  18911. this.registerType('torch._export.serde.schema.ExportedProgram', class {
  18912. constructor(obj) {
  18913. Object.assign(this, { ...obj });
  18914. this.graph_module = new torch._export.serde.schema.GraphModule(obj.graph_module);
  18915. }
  18916. });
  18917. this.registerType('torch._export.serde.schema.SymExprHint', class extends torch._export.serde.union._Union {});
  18918. this.registerType('torch._export.serde.schema.SymExpr', class {
  18919. constructor(obj) {
  18920. this.expr_str = obj.expr_str;
  18921. this.hint = obj.hint ? new torch._export.serde.schema.SymExprHint(obj.hint) : null;
  18922. }
  18923. });
  18924. this.registerType('torch._export.serde.schema.SymInt', class extends torch._export.serde.union._Union {
  18925. constructor(obj) {
  18926. super(obj);
  18927. if (this.type === 'as_int') {
  18928. // continue
  18929. } else if (this.type === 'as_expr') {
  18930. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18931. } else {
  18932. throw new python.Error(`Unsupported symbolic int '${this.type}'.`);
  18933. }
  18934. }
  18935. });
  18936. this.registerType('torch._export.serde.schema.SymBool', class extends torch._export.serde.union._Union {
  18937. constructor(obj) {
  18938. super(obj);
  18939. if (this.type === 'as_bool') {
  18940. // continue
  18941. } else if (this.type === 'as_expr') {
  18942. this.as_expr = new torch._export.serde.schema.SymExpr(this.as_expr);
  18943. } else {
  18944. throw new python.Error(`Unsupported symbolic bool '${this.type}'.`);
  18945. }
  18946. }
  18947. });
  18948. this.registerType('torch._export.serde.schema.SymIntArgument', class extends torch._export.serde.union._Union {
  18949. constructor(obj) {
  18950. super(obj);
  18951. Object.assign(this, { ...obj });
  18952. }
  18953. });
  18954. this.registerType('torch._export.serde.schema.SymFloatArgument', class extends torch._export.serde.union._Union {
  18955. constructor(obj) {
  18956. super(obj);
  18957. Object.assign(this, { ...obj });
  18958. }
  18959. });
  18960. this.registerType('torch._export.serde.schema.SymBoolArgument', class extends torch._export.serde.union._Union {
  18961. constructor(obj) {
  18962. super(obj);
  18963. Object.assign(this, { ...obj });
  18964. }
  18965. });
  18966. this.registerType('torch._export.serde.schema.CustomObjArgument', class {
  18967. constructor(obj) {
  18968. Object.assign(this, { ...obj });
  18969. }
  18970. });
  18971. this.registerType('torch._export.serde.schema.GraphSignature', class {
  18972. constructor(obj) {
  18973. this.input_specs = [];
  18974. if (Array.isArray(obj.input_specs)) {
  18975. this.input_specs = obj.input_specs.map((input_spec) => new torch._export.serde.schema.InputSpec(input_spec));
  18976. }
  18977. if (Array.isArray(obj.user_inputs)) {
  18978. for (const user_input of obj.user_inputs) {
  18979. this.input_specs.push(new torch._export.serde.schema.InputSpec({ user_input: { arg: { as_string: user_input } } }));
  18980. }
  18981. }
  18982. if (obj.inputs_to_parameters) {
  18983. for (const [input, parameter_name] of Object.entries(obj.inputs_to_parameters)) {
  18984. this.input_specs.push(new torch._export.serde.schema.InputSpec({ parameter: { arg: { name: input }, parameter_name } }));
  18985. }
  18986. }
  18987. this.output_specs = [];
  18988. if (Array.isArray(obj.output_specs)) {
  18989. this.output_specs = obj.output_specs.map((output_spec) => new torch._export.serde.schema.OutputSpec(output_spec));
  18990. }
  18991. }
  18992. });
  18993. this.registerType('torch._export.serde.schema.UserInputSpec', class {
  18994. constructor(obj) {
  18995. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  18996. }
  18997. });
  18998. this.registerType('torch._export.serde.schema.InputToParameterSpec', class {
  18999. constructor(obj) {
  19000. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19001. this.parameter_name = obj.parameter_name;
  19002. }
  19003. });
  19004. this.registerType('torch._export.serde.schema.InputToBufferSpec', class {
  19005. constructor(obj) {
  19006. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19007. this.buffer_name = obj.buffer_name;
  19008. }
  19009. });
  19010. this.registerType('torch._export.serde.schema.InputToTensorConstantSpec', class {
  19011. constructor(obj) {
  19012. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19013. this.tensor_constant_name = obj.tensor_constant_name;
  19014. }
  19015. });
  19016. this.registerType('torch._export.serde.schema.InputToConstantInputSpec', class {
  19017. constructor(obj) {
  19018. this.name = obj.name;
  19019. this.value = new torch._export.serde.schema.ConstantValue(obj.value);
  19020. }
  19021. });
  19022. this.registerType('torch._export.serde.schema.ConstantValue', class extends torch._export.serde.union._Union {
  19023. constructor(obj) {
  19024. super(obj);
  19025. if (this.type === 'as_int' || this.type === 'as_float' || this.type === 'as_bool' || this.type === 'as_string' || this.type === 'as_strings') {
  19026. // continue
  19027. } else if (this.type === 'as_none') {
  19028. this.as_none = null;
  19029. } else {
  19030. throw new python.Error(`Unsupported constant value type '${this.type}'.`);
  19031. }
  19032. }
  19033. });
  19034. this.registerType('torch._export.serde.schema.InputSpec', class extends torch._export.serde.union._Union {
  19035. constructor(obj) {
  19036. super(obj);
  19037. if (this.type === 'user_input') {
  19038. this.user_input = new torch._export.serde.schema.UserInputSpec(this.user_input);
  19039. } else if (this.type === 'parameter') {
  19040. this.parameter = new torch._export.serde.schema.InputToParameterSpec(this.parameter);
  19041. } else if (this.type === 'buffer') {
  19042. this.buffer = new torch._export.serde.schema.InputToBufferSpec(this.buffer);
  19043. } else if (this.type === 'tensor_constant') {
  19044. this.tensor_constant = new torch._export.serde.schema.InputToTensorConstantSpec(this.tensor_constant);
  19045. } else if (this.type === 'constant_input') {
  19046. this.constant_input = new torch._export.serde.schema.InputToConstantInputSpec(this.constant_input);
  19047. } else {
  19048. throw new python.Error(`Unsupported input spec type '${this.type}'.`);
  19049. }
  19050. /*
  19051. custom_obj: InputToCustomObjSpec
  19052. token: InputTokenSpec
  19053. */
  19054. }
  19055. });
  19056. this.registerType('torch._export.serde.schema.UserOutputSpec', class {
  19057. constructor(obj) {
  19058. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19059. }
  19060. });
  19061. this.registerType('torch._export.serde.schema.BufferMutationSpec', class {
  19062. constructor(obj) {
  19063. this.arg = new torch._export.serde.schema.TensorArgument(obj.arg);
  19064. this.buffer_name = obj.buffer_name;
  19065. }
  19066. });
  19067. this.registerType('torch._export.serde.schema.GradientToParameterSpec', class {
  19068. constructor(obj) {
  19069. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19070. this.parameter_name = obj.parameter_name;
  19071. }
  19072. });
  19073. this.registerType('torch._export.serde.schema.GradientToUserInputSpec', class {
  19074. constructor(obj) {
  19075. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19076. this.user_input_name = obj.user_input_name;
  19077. }
  19078. });
  19079. this.registerType('torch._export.serde.schema.UserInputMutationSpec', class {
  19080. constructor(obj) {
  19081. this.arg = new torch._export.serde.schema.Argument(obj.arg);
  19082. this.user_input_name = obj.user_input_name;
  19083. }
  19084. });
  19085. this.registerType('torch._export.serde.schema.OutputTokenSpec', class {
  19086. constructor(obj) {
  19087. this.arg = new torch._export.serde.schema.TokenArgument(obj.arg);
  19088. }
  19089. });
  19090. this.registerType('torch._export.serde.schema.OutputSpec', class extends torch._export.serde.union._Union {
  19091. constructor(obj) {
  19092. super(obj);
  19093. if (this.type === 'user_output') {
  19094. this.user_output = new torch._export.serde.schema.UserOutputSpec(this.user_output);
  19095. } else if (this.type === 'loss_output') {
  19096. this.loss_output = new torch._export.serde.schema.LossOutputSpec(this.loss_output);
  19097. } else if (this.type === 'buffer_mutation') {
  19098. this.buffer_mutation = new torch._export.serde.schema.BufferMutationSpec(this.buffer_mutation);
  19099. } else if (this.type === 'gradient_to_parameter') {
  19100. this.gradient_to_parameter = new torch._export.serde.schema.GradientToParameterSpec(this.gradient_to_parameter);
  19101. } else if (this.type === 'gradient_to_user_input') {
  19102. this.gradient_to_user_input = new torch._export.serde.schema.GradientToUserInputSpec(this.gradient_to_user_input);
  19103. } else if (this.type === 'user_input_mutation') {
  19104. this.user_input_mutation = new torch._export.serde.schema.UserInputMutationSpec(this.user_input_mutation);
  19105. } else if (this.type === 'token') {
  19106. this.token = new torch._export.serde.schema.OutputTokenSpec(this.token);
  19107. }
  19108. }
  19109. });
  19110. this.registerType('torch._export.serde.schema.TensorArgument', class {
  19111. constructor(obj) {
  19112. this.name = obj.name;
  19113. }
  19114. });
  19115. this.registerType('torch._export.serde.schema.TokenArgument', class {
  19116. constructor(obj) {
  19117. this.name = obj.name;
  19118. }
  19119. });
  19120. this.registerType('torch._export.serde.schema.GraphArgument', class {
  19121. constructor(obj) {
  19122. this.name = obj.name;
  19123. this.graph = new torch._export.serde.schema.Graph(obj.graph);
  19124. }
  19125. });
  19126. this.registerType('torch._export.serde.schema.OptionalTensorArgument', class extends torch._export.serde.union._Union {
  19127. constructor(obj) {
  19128. super(obj);
  19129. if (this.type === 'as_tensor') {
  19130. this.as_tensor = new torch._export.serde.schema.TensorArgument({ name: this.as_tensor });
  19131. } else if (this.type === 'as_none') {
  19132. this.as_none = null;
  19133. } else {
  19134. throw new python.Error(`Unsupported optional tensor argument '${this.type}'.`);
  19135. }
  19136. }
  19137. });
  19138. this.registerFunction('torch.export.pt2_archive._package._load_state_dict', (f, model_name) => {
  19139. const legacy_file = `data/weights/${model_name}.pt`;
  19140. if (f.has(legacy_file)) {
  19141. return f.get(legacy_file);
  19142. }
  19143. const weights_config_file = `data/weights/${model_name}_weights_config.json`;
  19144. if (!f.has(weights_config_file)) {
  19145. return null;
  19146. }
  19147. const weights_config = f.get(weights_config_file);
  19148. const state_dict_file_map = torch.export.pt2_archive._package._build_file_map(f, weights_config, 'data/weights/');
  19149. const state_dict = new builtins.dict();
  19150. for (const [weight_fqn, payload_meta] of Object.entries(weights_config.config)) {
  19151. if (payload_meta.use_pickle) {
  19152. const weight_bytes = f.get(`data/weights/${payload_meta.path_name}`);
  19153. const weight_tensor = torch.load(weight_bytes);
  19154. state_dict.set(weight_fqn, weight_tensor);
  19155. } else {
  19156. const tensor_meta = payload_meta.tensor_meta;
  19157. const tensor = state_dict_file_map.get(payload_meta.path_name);
  19158. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19159. const strides = tensor_meta.strides.map((s) => s.as_int);
  19160. const storage_offset = tensor_meta.storage_offset.as_int;
  19161. const weight_tensor = new torch.Tensor();
  19162. weight_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19163. weight_tensor.requires_grad = tensor_meta.requires_grad || false;
  19164. if (payload_meta.is_param) {
  19165. state_dict.set(weight_fqn, new torch.nn.parameter.Parameter(weight_tensor, tensor_meta.requires_grad));
  19166. } else {
  19167. state_dict.set(weight_fqn, weight_tensor);
  19168. }
  19169. }
  19170. }
  19171. return state_dict;
  19172. });
  19173. this.registerFunction('torch.export.pt2_archive._package._load_constants', (f, model_name) => {
  19174. const legacy_file = `data/constants/${model_name}.pt`;
  19175. if (f.has(legacy_file)) {
  19176. const entries = f.get(legacy_file);
  19177. return new builtins.dict(entries);
  19178. }
  19179. const constants_config_file = `data/constants/${model_name}_constants_config.json`;
  19180. if (!f.has(constants_config_file)) {
  19181. return null;
  19182. }
  19183. const constants_config = f.get(constants_config_file);
  19184. const constant_file_map = torch.export.pt2_archive._package._build_file_map(f, constants_config, 'data/constants/');
  19185. const constants = new builtins.dict();
  19186. for (const [constant_fqn, payload_meta] of Object.entries(constants_config.config)) {
  19187. const path_name = payload_meta.path_name;
  19188. if (path_name.startsWith('tensor_')) {
  19189. if (payload_meta.use_pickle) {
  19190. const constant_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19191. const constant_tensor = torch.load(constant_bytes);
  19192. constants.set(constant_fqn, constant_tensor);
  19193. } else {
  19194. const tensor_meta = payload_meta.tensor_meta;
  19195. const tensor = constant_file_map.get(payload_meta.path_name);
  19196. const sizes = tensor_meta.sizes.map((s) => s.as_int);
  19197. const strides = tensor_meta.strides.map((s) => s.as_int);
  19198. const storage_offset = tensor_meta.storage_offset.as_int;
  19199. const constant_tensor = new torch.Tensor();
  19200. constant_tensor.__setstate__([tensor.storage(), storage_offset, sizes, strides]);
  19201. constants.set(constant_fqn, constant_tensor);
  19202. }
  19203. } else if (payload_meta.path_name.startsWith('custom_obj_')) {
  19204. const custom_obj_bytes = f.get(`data/constants/${payload_meta.path_name}`);
  19205. const custom_obj = torch._C._pickle_load_obj(custom_obj_bytes);
  19206. constants.set(constant_fqn, custom_obj);
  19207. }
  19208. }
  19209. return constants;
  19210. });
  19211. this.registerFunction('torch._export.serde.serialize.deserialize_scalar_type', (st) => {
  19212. if (!torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.has(st)) {
  19213. throw new python.Error(`Unsupported scalar type '${st}'.`);
  19214. }
  19215. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE.get(st);
  19216. });
  19217. this.registerFunction('torch.export.pt2_archive._package._build_file_map', (archive_reader, config, base_dir) => {
  19218. const file_map = new builtins.dict();
  19219. for (const payload_meta of Object.values(config.config)) {
  19220. if (payload_meta.use_pickle) {
  19221. continue;
  19222. }
  19223. if (file_map.has(payload_meta.path_name)) {
  19224. continue;
  19225. }
  19226. const tensor_bytes = archive_reader.get(`${base_dir}${payload_meta.path_name}`);
  19227. const tensor = torch.export.pt2_archive._package._create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta);
  19228. file_map.set(payload_meta.path_name, tensor);
  19229. }
  19230. return file_map;
  19231. });
  19232. this.registerFunction('torch.export.pt2_archive._package._create_flat_tensor_from_bytes', (tensor_bytes, tensor_meta) => {
  19233. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19234. const itemsize = dtype.itemsize();
  19235. const num_elements = tensor_bytes.length / itemsize;
  19236. const storage = new torch.storage.TypedStorage(num_elements, dtype);
  19237. storage._set_cdata(tensor_bytes);
  19238. const tensor = new torch.Tensor();
  19239. tensor.__setstate__([storage, 0, [num_elements], [1]]);
  19240. tensor.requires_grad = tensor_meta.requires_grad || false;
  19241. return tensor;
  19242. });
  19243. this.registerFunction('torch.export.pt2_archive._package.load_pt2', (f, expected_opset_version) => {
  19244. const exported_programs = new Map();
  19245. for (const name of f.keys()) {
  19246. const match = name.match(/^models\/([^/]+)\.json$/);
  19247. if (match) {
  19248. const [, model_name] = match;
  19249. const serialized_exported_program = f.get(`models/${model_name}.json`);
  19250. const serialized_state_dict = torch.export.pt2_archive._package._load_state_dict(f, model_name);
  19251. const serialized_constants = torch.export.pt2_archive._package._load_constants(f, model_name);
  19252. const serialized_example_inputs = f.get(`data/sample_inputs/${model_name}.pt`, 'zip');
  19253. const artifact = new torch._export.serde.serialize.SerializedArtifact(serialized_exported_program, serialized_state_dict, serialized_constants, serialized_example_inputs);
  19254. const exported_program = torch._export.serde.serialize.deserialize(artifact, expected_opset_version);
  19255. exported_programs.set(model_name, exported_program);
  19256. }
  19257. }
  19258. return { exported_programs };
  19259. });
  19260. this.registerFunction('torch._export.serde.serialize._dict_to_dataclass', (cls, data) => {
  19261. if (data === null) {
  19262. return data;
  19263. }
  19264. if (cls) {
  19265. return new cls(data);
  19266. }
  19267. throw new python.Error(`Unsupported data class '${cls.__name__}'.`);
  19268. });
  19269. this.registerFunction('torch._export.serde.serialize.deserialize', (artifact, expected_opset_version) => {
  19270. const serialized_exported_program = torch._export.serde.serialize._dict_to_dataclass(torch._export.serde.schema.ExportedProgram, artifact.exported_program);
  19271. return new torch._export.serde.serialize.ExportedProgramDeserializer(expected_opset_version).deserialize(serialized_exported_program, artifact.state_dict, artifact.constants, artifact.example_inputs);
  19272. });
  19273. this.registerType('torch._export.serde.serialize.ExportedProgramDeserializer', class {
  19274. constructor(expected_opset_version) {
  19275. this.expected_opset_version = expected_opset_version;
  19276. }
  19277. deserialize(exported_program, state_dict, constants, example_inputs) {
  19278. const symbol_name_to_range = new Map(Object.entries(exported_program.range_constraints));
  19279. /*
  19280. symbol_name_to_range = {
  19281. k: symbolic_shapes.ValueRanges(_int_to_sympy_int(v.min_val), _int_to_sympy_int(v.max_val))
  19282. for k, v in exported_program.range_constraints.items()
  19283. }
  19284. */
  19285. const deserializer = new torch._export.serde.serialize.GraphModuleDeserializer();
  19286. const res = deserializer.deserialize(
  19287. exported_program.graph_module,
  19288. state_dict,
  19289. constants,
  19290. example_inputs,
  19291. symbol_name_to_range);
  19292. const range_constraints = null;
  19293. /*
  19294. range_constraints = self.deserialize_range_constraints(
  19295. symbol_name_to_range, res.names_to_symbols,
  19296. )
  19297. model_opset_version: Optional[Dict[str, int]] = serialized_artifact.exported_program.opset_version
  19298. self._validate_model_opset_version(model_opset_version)
  19299. upgrader = GraphModuleOpUpgrader(self.expected_opset_version, model_opset_version)
  19300. */
  19301. return new torch.export.exported_program.ExportedProgram(
  19302. res.graph_module, res.graph_module.graph, res.signature,
  19303. res.state_dict, range_constraints, res.module_call_graph, res.example_inputs,
  19304. null, // verifier=load_verifier(serialized_artifact.exported_program.dialect),
  19305. res.constants);
  19306. // return upgrader.upgrade(exported_program)
  19307. }
  19308. });
  19309. this.registerFunction('torch._export.serde.serialize.deserialize_torch_artifact', (serialized) => {
  19310. if (serialized instanceof builtins.dict || serialized instanceof builtins.tuple) {
  19311. return serialized;
  19312. }
  19313. if (serialized === null || serialized.length === 0) {
  19314. return new builtins.dict();
  19315. }
  19316. const artifact = torch.load(serialized);
  19317. return artifact;
  19318. });
  19319. this.registerType('torch._export.serde.serialize.GraphModuleDeserializer', class {
  19320. constructor() {
  19321. this.serialized_name_to_node = new builtins.dict();
  19322. this.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19323. this.graph = new torch.fx.Graph();
  19324. this.module = new torch.nn.Module();
  19325. }
  19326. save_graph_module() {
  19327. const Context = class {
  19328. constructor(self) {
  19329. this.self = self;
  19330. }
  19331. __enter__() {
  19332. this.saved = [
  19333. this.self.graph,
  19334. this.self.module,
  19335. this.self.serialized_name_to_node,
  19336. this.self.serialized_name_to_meta,
  19337. this.self.unbacked_symbols,
  19338. ];
  19339. this.self.graph = new torch.fx.graph.Graph();
  19340. this.self.module = new torch.nn.modules.module.Module();
  19341. this.self.serialized_name_to_node = new builtins.dict();
  19342. this.self.serialized_name_to_meta = new builtins.dict(); // torch._export.serde.serialize.LazyMap
  19343. this.self.unbacked_symbols = new Set();
  19344. }
  19345. __exit__(/* exc_type, exc_value, traceback */) {
  19346. const self = this.self;
  19347. [self.graph, self.module, self.serialized_name_to_node, self.serialized_name_to_meta, self.unbacked_symbols] = this.saved;
  19348. }
  19349. };
  19350. return new Context(this);
  19351. }
  19352. deserialize_graph_output(output) {
  19353. if (output.type === 'as_tensor') {
  19354. return this.serialized_name_to_node.get(output.as_tensor.name);
  19355. } else if (output.type === 'as_sym_int') {
  19356. return this.serialized_name_to_node.get(output.as_sym_int.as_name);
  19357. } else if (output.type === 'as_sym_bool') {
  19358. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19359. } else if (output.type === 'as_int') {
  19360. return this.serialized_name_to_node.get(output.as_int.as_name);
  19361. } else if (output.type === 'as_none') {
  19362. return this.serialized_name_to_node.get(output.as_sym_bool.as_name);
  19363. }
  19364. throw new python.Error(`Unsupported graph node ${output.type}.`);
  19365. }
  19366. deserialize_graph(serialized_graph) {
  19367. for (const [name, tensor_value] of serialized_graph.tensor_values) {
  19368. const meta_val = this.deserialize_tensor_meta(tensor_value.meta || tensor_value, this.fake_tensor_mode);
  19369. this.serialized_name_to_meta.set(name, meta_val);
  19370. }
  19371. for (const [name, sym_int_value] of serialized_graph.sym_int_values) {
  19372. this.serialized_name_to_meta.set(name, this.deserialize_sym_int(sym_int_value));
  19373. }
  19374. for (const [name, sym_bool_value] of serialized_graph.sym_bool_values) {
  19375. this.serialized_name_to_meta.set(name, this.deserialize_sym_bool(sym_bool_value));
  19376. }
  19377. for (const [name, script_obj_meta] of serialized_graph.custom_obj_values) {
  19378. this.serialized_name_to_meta.set(name, this.deserialize_script_obj_meta(script_obj_meta));
  19379. }
  19380. for (let i = 0; i < serialized_graph.inputs.length; i++) {
  19381. const input = serialized_graph.inputs[i];
  19382. if (input.type === 'as_tensor' || input.type === 'as_sym_int' || input.type === 'as_custom_obj') {
  19383. const node_name = input.value.name;
  19384. const placeholder_node = this.graph.placeholder(node_name);
  19385. placeholder_node.name = node_name;
  19386. this.sync_fx_node(node_name, placeholder_node);
  19387. } else if (input.type === 'as_int' || input.type === 'as_float' || input.type === 'as_bool' || input.type === 'as_none' || input.type === 'as_string') {
  19388. const node_name = this.signature.input_specs[i].arg.name;
  19389. const placeholder_node = this.graph.placeholder(node_name);
  19390. placeholder_node.meta.set('val', this.deserialize_input(input));
  19391. } else {
  19392. throw new python.Error(`Invalid input ${input.type}.`);
  19393. }
  19394. }
  19395. for (const serialized_node of serialized_graph.nodes) {
  19396. const target = this.deserialize_operator(serialized_node.target);
  19397. this.deserialize_node(serialized_node, target);
  19398. }
  19399. let outputs = [];
  19400. for (const output of serialized_graph.outputs) {
  19401. outputs.push(this.deserialize_graph_output(output));
  19402. }
  19403. if (serialized_graph.is_single_tensor_return) {
  19404. [outputs] = outputs;
  19405. } else {
  19406. outputs = new builtins.tuple(outputs);
  19407. }
  19408. const output_node = this.graph.output(outputs);
  19409. if (serialized_graph.is_single_tensor_return) {
  19410. output_node.meta.set('val', output_node.args[0].meta.get('val'));
  19411. } else {
  19412. /* output_node.meta['val'] = tuple(
  19413. arg.meta['val'] if isinstance(arg, torch.fx.Node) else arg
  19414. for arg in output_node.args[0]
  19415. ) */
  19416. }
  19417. return self.graph;
  19418. }
  19419. deserialize_operator(serialized_target) {
  19420. let module = null;
  19421. let serialized_target_names = null;
  19422. if (serialized_target.startsWith('_operator')) {
  19423. module = operator;
  19424. serialized_target_names = serialized_target.split('.').slice(1);
  19425. } else if (serialized_target.startsWith('torch')) {
  19426. module = torch;
  19427. serialized_target_names = serialized_target.split('.').slice(1);
  19428. } else if (serialized_target.startsWith('#')) {
  19429. return self.deserialize_extension_operator(serialized_target);
  19430. } else {
  19431. return serialized_target;
  19432. }
  19433. let target = module;
  19434. for (const name of serialized_target_names) {
  19435. target = builtins.getattr(target, name);
  19436. if (!target) {
  19437. return serialized_target;
  19438. }
  19439. }
  19440. return target;
  19441. }
  19442. deserialize_node(serialized_node, target) {
  19443. let fx_node = null;
  19444. if (torch._export.serde.serialize._SYM_OPS.has(target)) {
  19445. const name = serialized_node.outputs[0].value.as_name;
  19446. const args = this.deserialize_sym_op_inputs(serialized_node.inputs);
  19447. fx_node = this.graph.create_node('call_function', target, args, null, name);
  19448. this.deserialize_sym_op_outputs(serialized_node, fx_node);
  19449. } else if (builtins.isinstance(target, torch._ops.HigherOrderOperator)) {
  19450. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19451. const metadata = this.deserialize_metadata(serialized_node.metadata);
  19452. for (const x of [...args, ...kwargs.values()]) {
  19453. if (builtins.isinstance(x, torch.fx.Node) && x.op === 'get_attr') {
  19454. x.meta.update(metadata);
  19455. }
  19456. }
  19457. const name = serialized_node.outputs.length === 1 &&
  19458. builtins.hasattr(serialized_node.outputs[0], 'as_tensor') &&
  19459. builtins.getattr(serialized_node, 'is_hop_single_tensor_return', true) ?
  19460. serialized_node.outputs[0].as_tensor.name : null;
  19461. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19462. this.deserialize_outputs(serialized_node, fx_node);
  19463. fx_node.meta.update(metadata);
  19464. } else if (builtins.isinstance(target, torch._ops.OpOverload)) {
  19465. const name = this._is_single_tensor_return(target) ? serialized_node.outputs[0].as_tensor.name : null;
  19466. const [args, kwargs] = this.deserialize_inputs(target, serialized_node);
  19467. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19468. this.deserialize_outputs(serialized_node, fx_node);
  19469. } else if (typeof target === 'string') {
  19470. // Handle unresolved operators
  19471. execution.emit('resolve', target);
  19472. if (target.match(/^torch\.ops\.(aten|prim|quantized)\./)) {
  19473. throw new python.Error(`Unsupported node target type '${target}'.`);
  19474. }
  19475. const [args, kwargs] = this.deserialize_hoo_inputs(serialized_node.inputs);
  19476. const name = serialized_node.outputs.length === 1 && builtins.hasattr(serialized_node.outputs[0], 'as_tensor') ? serialized_node.outputs[0].as_tensor.name : null;
  19477. fx_node = this.graph.create_node('call_function', target, args, kwargs, name);
  19478. this.deserialize_outputs(serialized_node, fx_node);
  19479. } else {
  19480. throw new python.Error(`Unsupported node target type '${target}'.`);
  19481. }
  19482. fx_node.meta.update(this.deserialize_metadata(serialized_node.metadata));
  19483. if (fx_node.op !== 'placeholder' && fx_node.op !== 'output' && !fx_node.meta.has('nn_module_stack')) {
  19484. fx_node.meta.set('nn_module_stack', new builtins.dict());
  19485. }
  19486. }
  19487. deserialize_input_spec(i) {
  19488. if (i.type === 'user_input') {
  19489. return new torch.export.graph_signature.InputSpec(
  19490. torch.export.graph_signature.InputKind.USER_INPUT,
  19491. this.deserialize_argument_spec(i.user_input.arg),
  19492. null);
  19493. } else if (i.type === 'parameter') {
  19494. return new torch.export.graph_signature.InputSpec(
  19495. torch.export.graph_signature.InputKind.PARAMETER,
  19496. new torch.export.graph_signature.TensorArgument(i.parameter.arg.name),
  19497. i.parameter.parameter_name,
  19498. );
  19499. } else if (i.type === 'buffer') {
  19500. return new torch.export.graph_signature.InputSpec(
  19501. torch.export.graph_signature.InputKind.BUFFER,
  19502. new torch.export.graph_signature.TensorArgument(i.buffer.arg.name),
  19503. i.buffer.buffer_name,
  19504. i.buffer.persistent,
  19505. );
  19506. } else if (i.type === 'tensor_constant') {
  19507. return new torch.export.graph_signature.InputSpec(
  19508. torch.export.graph_signature.InputKind.CONSTANT_TENSOR,
  19509. new torch.export.graph_signature.TensorArgument(i.tensor_constant.arg.name),
  19510. i.tensor_constant.tensor_constant_name);
  19511. } else if (i.type === 'custom_obj') {
  19512. return new torch.export.graph_signature.InputSpec(
  19513. torch.export.graph_signature.InputKind.CUSTOM_OBJ,
  19514. new torch.export.graph_signature.CustomObjArgument(i.custom_obj.arg.name, i.custom_obj.arg.class_fqn),
  19515. i.custom_obj.custom_obj_name);
  19516. } else if (i.type === 'token') {
  19517. return new torch.export.graph_signature.InputSpec(
  19518. torch.export.graph_signature.InputKind.TOKEN,
  19519. new torch.export.graph_signature.TokenArgument(i.token.arg.name),
  19520. null);
  19521. } else if (i.type === 'constant_input') {
  19522. return new torch.export.graph_signature.InputSpec(
  19523. torch.export.graph_signature.InputKind.USER_INPUT,
  19524. new torch.export.graph_signature.ConstantArgument(i.constant_input.name, this.deserialize_constant_input(i.constant_input.value)),
  19525. null);
  19526. }
  19527. throw new python.Error(`Unknown input spec ${i}`);
  19528. }
  19529. deserialize_constant_input(inp) {
  19530. if (inp.type === 'as_int') {
  19531. return inp.as_int;
  19532. } else if (inp.type === 'as_float') {
  19533. return inp.as_float;
  19534. } else if (inp.type === 'as_string') {
  19535. return inp.as_string;
  19536. } else if (inp.type === 'as_bool') {
  19537. return inp.as_bool;
  19538. } else if (inp.type === 'as_none') {
  19539. return null;
  19540. }
  19541. throw new python.Error(`Unhandled constant argument ${inp} to deserialize.`);
  19542. }
  19543. deserialize_output_spec(o) {
  19544. if (o.type === 'user_output') {
  19545. return new torch.export.graph_signature.OutputSpec(
  19546. torch.export.graph_signature.OutputKind.USER_OUTPUT,
  19547. this.deserialize_argument_spec(o.user_output.arg),
  19548. null);
  19549. } else if (o.type === 'loss_output') {
  19550. return new torch.export.graph_signature.OutputSpec(
  19551. torch.export.graph_signature.OutputKind.LOSS_OUTPUT,
  19552. new torch.export.graph_signature.TensorArgument(o.loss_output.arg.name),
  19553. null);
  19554. } else if (o.type === 'buffer_mutation') {
  19555. return new torch.export.graph_signature.OutputSpec(
  19556. torch.export.graph_signature.OutputKind.BUFFER_MUTATION,
  19557. new torch.export.graph_signature.TensorArgument(o.buffer_mutation.arg.name),
  19558. o.buffer_mutation.buffer_name);
  19559. } else if (o.type === 'gradient_to_parameter') {
  19560. return new torch.export.graph_signature.OutputSpec(
  19561. torch.export.graph_signature.OutputKind.GRADIENT_TO_PARAMETER,
  19562. new torch.export.graph_signature.TensorArgument(o.gradient_to_parameter.arg.name),
  19563. o.gradient_to_parameter.parameter_name);
  19564. } else if (o.type === 'gradient_to_user_input') {
  19565. return new torch.export.graph_signature.OutputSpec(
  19566. torch.export.graph_signature.OutputKind.GRADIENT_TO_USER_INPUT,
  19567. new torch.export.graph_signature.TensorArgument(o.gradient_to_user_input.arg.name),
  19568. o.gradient_to_user_input.user_input_name);
  19569. } else if (o.type === 'user_input_mutation') {
  19570. return new torch.export.graph_signature.OutputSpec(
  19571. torch.export.graph_signature.OutputKind.USER_INPUT_MUTATION,
  19572. new torch.export.graph_signature.TensorArgument(o.user_input_mutation.arg.name),
  19573. o.user_input_mutation.user_input_name);
  19574. } else if (o.type === 'token') {
  19575. return new torch.export.graph_signature.OutputSpec(
  19576. torch.export.graph_signature.OutputKind.TOKEN,
  19577. new torch.export.graph_signature.TokenArgument(o.token.arg.name),
  19578. null);
  19579. }
  19580. throw new python.Error(`Unknown output spec ${o}.`);
  19581. }
  19582. deserialize_signature(sig) {
  19583. return new torch.export.graph_signature.ExportGraphSignature(
  19584. sig.input_specs.map((i) => this.deserialize_input_spec(i)),
  19585. sig.output_specs.map((o) => this.deserialize_output_spec(o)));
  19586. }
  19587. deserialize(serialized_graph_module, serialized_state_dict, constants, example_inputs, symbol_name_to_range) {
  19588. this.shape_env = new torch.fx.experimental.symbolic_shapes.ShapeEnv(/* assume_static_by_default = True */);
  19589. this.fake_tensor_mode = new torch._subclasses.fake_tensor.FakeTensorMode(false, true, this.shape_env);
  19590. this.sympy_functions = new Map([
  19591. ['FloorDiv', torch.utils._sympy.functions.FloorDiv],
  19592. ['ModularIndexing', torch.utils._sympy.functions.ModularIndexing],
  19593. ['Where', torch.utils._sympy.functions.Where],
  19594. ['PythonMod', torch.utils._sympy.functions.PythonMod],
  19595. ['Mod', torch.utils._sympy.functions.Mod],
  19596. ['CleanDiv', torch.utils._sympy.functions.CleanDiv],
  19597. ['CeilToInt', torch.utils._sympy.functions.CeilToInt],
  19598. ['FloorToInt', torch.utils._sympy.functions.FloorToInt],
  19599. ['CeilDiv', torch.utils._sympy.functions.CeilDiv],
  19600. ['LShift', torch.utils._sympy.functions.LShift],
  19601. ['RShift', torch.utils._sympy.functions.RShift],
  19602. ['PowByNatural', torch.utils._sympy.functions.PowByNatural],
  19603. ['FloatPow', torch.utils._sympy.functions.FloatPow],
  19604. ['FloatTrueDiv', torch.utils._sympy.functions.FloatTrueDiv],
  19605. ['IntTrueDiv', torch.utils._sympy.functions.IntTrueDiv],
  19606. ['IsNonOverlappingAndDenseIndicator', torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator],
  19607. ['TruncToFloat', torch.utils._sympy.functions.TruncToFloat],
  19608. ['TruncToInt', torch.utils._sympy.functions.TruncToInt],
  19609. ['RoundToInt', torch.utils._sympy.functions.RoundToInt],
  19610. ['RoundDecimal', torch.utils._sympy.functions.RoundDecimal],
  19611. ['ToFloat', torch.utils._sympy.functions.ToFloat],
  19612. ['Identity', torch.utils._sympy.functions.Identity],
  19613. ]);
  19614. this.symbol_name_to_symbol = new Map();
  19615. this.constants = torch._export.serde.serialize.deserialize_torch_artifact(constants);
  19616. this.signature = this.deserialize_signature(serialized_graph_module.signature);
  19617. this.symbol_name_to_range = symbol_name_to_range || new Map();
  19618. /*
  19619. if symbol_name_to_range:
  19620. for k, vr in symbol_name_to_range.items():
  19621. lower = int(vr.lower)
  19622. if vr.upper >= 2: # max is >= 2, not sym bool range
  19623. lower = max(2, lower)
  19624. this.symbol_name_to_range[k] = symbolic_shapes.ValueRanges(_int_to_sympy_int(lower), vr.upper)
  19625. */
  19626. this.example_inputs = null;
  19627. if (example_inputs) {
  19628. this.example_inputs = torch._export.serde.serialize.deserialize_torch_artifact(example_inputs);
  19629. }
  19630. this.deserialize_graph(serialized_graph_module.graph);
  19631. const module_call_graph = null; // this.deserialize_module_call_graph(serialized_graph_module.module_call_graph)
  19632. return {
  19633. graph_module: torch._export.exported_program._create_graph_module_for_export(this.module, this.graph),
  19634. signature: this.signature,
  19635. module_call_graph,
  19636. names_to_symbols: this.symbol_name_to_symbol,
  19637. state_dict: torch._export.serde.serialize.deserialize_torch_artifact(serialized_state_dict),
  19638. constants: this.constants,
  19639. example_inputs: this.example_inputs,
  19640. };
  19641. }
  19642. sync_fx_node(name, fx_node) {
  19643. if (this.serialized_name_to_node.has(name)) {
  19644. throw new python.Error(`Node ${name} has already been deserialized before.`);
  19645. }
  19646. this.serialized_name_to_node.set(name, fx_node);
  19647. fx_node.meta.set('val', this.serialized_name_to_meta.get(name));
  19648. }
  19649. deserialize_sym_op_inputs(inputs) {
  19650. return inputs.map((input) => this.deserialize_input(input.arg));
  19651. }
  19652. deserialize_inputs(target, serialized_node) {
  19653. const schema_args = this._get_schema_from_target(target).arguments;
  19654. const actual_args = new Map(serialized_node.inputs.map((input) => [input.name, this.deserialize_input(input.arg)]));
  19655. const args = new builtins.list();
  19656. const kwargs = new builtins.dict();
  19657. for (const schema_arg of schema_args) {
  19658. const is_positional = !schema_arg.has_default_value() && !schema_arg.kwarg_only;
  19659. if (is_positional) {
  19660. args.push(actual_args.get(schema_arg.name));
  19661. } else if (actual_args.has(schema_arg.name)) {
  19662. kwargs.set(schema_arg.name, actual_args.get(schema_arg.name));
  19663. }
  19664. }
  19665. return [args, kwargs];
  19666. }
  19667. deserialize_hoo_inputs(inputs) {
  19668. const args = [];
  19669. const kwargs = new builtins.dict();
  19670. for (const input_ of inputs) {
  19671. if (input_.name === '') {
  19672. args.push(this.deserialize_input(input_.arg));
  19673. } else {
  19674. kwargs.set(input_.name, this.deserialize_input(input_.arg));
  19675. }
  19676. }
  19677. return [new builtins.tuple(args), kwargs];
  19678. }
  19679. deserialize_input(inp) {
  19680. const value = inp.value;
  19681. const typ_ = inp.type;
  19682. if (typ_ === 'as_none') {
  19683. return null;
  19684. } else if (typ_ === 'as_tensor') {
  19685. return this.serialized_name_to_node.get(inp.as_tensor.name);
  19686. } else if (typ_ === 'as_scalar_type') {
  19687. return torch._export.serde.serialize.deserialize_scalar_type(inp.as_scalar_type);
  19688. } else if (typ_ === 'as_memory_format') {
  19689. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format];
  19690. } else if (typ_ === 'as_layout') {
  19691. return torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout];
  19692. } else if (typ_ === 'as_graph') {
  19693. const context = this.save_graph_module();
  19694. context.__enter__();
  19695. this.deserialize_graph(value.graph);
  19696. const submodule = torch.export.exported_program._create_graph_module_for_export(this.module, this.graph);
  19697. context.__exit__(null, null, null);
  19698. this.module.register_module(value.name, submodule);
  19699. return this.graph.create_node('get_attr', value.name, null, null, value.name);
  19700. } else if (typ_ === 'as_device') {
  19701. return this.deserialize_device(inp.as_device);
  19702. } else if (typ_ === 'as_int') {
  19703. return inp.as_int;
  19704. } else if (typ_ === 'as_float') {
  19705. return inp.as_float;
  19706. } else if (typ_ === 'as_bool') {
  19707. return inp.as_bool;
  19708. } else if (typ_ === 'as_string') {
  19709. return inp.as_string;
  19710. } else if (typ_ === 'as_sym_int') {
  19711. return this.deserialize_sym_argument(inp.as_sym_int);
  19712. } else if (typ_ === 'as_sym_float') {
  19713. return this.deserialize_sym_argument(inp.as_sym_float);
  19714. } else if (typ_ === 'as_sym_bool') {
  19715. return this.deserialize_sym_argument(inp.as_sym_bool);
  19716. } else if (Array.isArray(value)) {
  19717. if (value.length === 0) {
  19718. return [];
  19719. } else if (typ_ === 'as_tensors') {
  19720. const result = [];
  19721. for (const arg of value) {
  19722. result.push(this.serialized_name_to_node.get(arg.name));
  19723. }
  19724. return result;
  19725. } else if (typ_ === 'as_ints' || typ_ === 'as_floats' || typ_ === 'as_bools' || typ_ === 'as_strings') {
  19726. return Array.from(value);
  19727. } else if (typ_ === 'as_sym_ints' || typ_ === 'as_sym_bools') {
  19728. return value.map((arg) => this.deserialize_sym_argument(arg));
  19729. } else if (typ_ === 'as_optional_tensors') {
  19730. const deserialize_optional_tensor_args = (a) => {
  19731. if (a.type === 'as_none') {
  19732. return null;
  19733. } else if (a.type === 'as_tensor') {
  19734. return this.serialized_name_to_node.get(a.value.name);
  19735. }
  19736. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19737. };
  19738. return value.map((item) => deserialize_optional_tensor_args(item));
  19739. }
  19740. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19741. } else if (typ_ === 'as_custom_obj') {
  19742. if (this.serialized_name_to_node.has(inp.as_custom_obj.name)) {
  19743. return this.serialized_name_to_node.get(inp.as_custom_obj.name);
  19744. }
  19745. return this.constants[inp.as_custom_obj.name];
  19746. } else if (typ_ === 'as_operator') {
  19747. return this.deserialize_operator(inp.as_operator);
  19748. }
  19749. throw new python.Error(`Unsupported argument '${typ_}'.`);
  19750. }
  19751. deserialize_sym_argument(sym_arg) {
  19752. if (sym_arg instanceof torch._export.serde.schema.SymIntArgument) {
  19753. if (sym_arg.type === 'as_int') {
  19754. return sym_arg.as_int;
  19755. } else if (sym_arg.type === 'as_name') {
  19756. return this.serialized_name_to_node.get(sym_arg.as_name);
  19757. }
  19758. } else if (sym_arg instanceof torch._export.serde.schema.SymFloatArgument) {
  19759. if (sym_arg.type === 'as_float') {
  19760. return sym_arg.as_float;
  19761. } else if (sym_arg.type === 'as_name') {
  19762. return this.serialized_name_to_node.get(sym_arg.as_name);
  19763. }
  19764. } else if (sym_arg instanceof torch._export.serde.schema.SymBoolArgument) {
  19765. if (sym_arg.type === 'as_bool') {
  19766. return sym_arg.as_bool;
  19767. } else if (sym_arg.type === 'as_name') {
  19768. return this.serialized_name_to_node.get(sym_arg.as_name);
  19769. }
  19770. }
  19771. throw new python.Error(`Unsupported symbolic argument type '${sym_arg.type}`);
  19772. }
  19773. deserialize_sym_op_outputs(serialized_node, fx_node) {
  19774. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19775. }
  19776. deserialize_outputs(serialized_node, fx_node) {
  19777. if (serialized_node.outputs.length === 0) {
  19778. return;
  19779. }
  19780. if (serialized_node.outputs.length === 1 &&
  19781. serialized_node.outputs[0].type === 'as_tensor') {
  19782. this.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node);
  19783. return;
  19784. } else if (serialized_node.outputs.length === 1 &&
  19785. (serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymIntArgument ||
  19786. serialized_node.outputs[0].value instanceof torch._export.serde.schema.SymBoolArgument)) {
  19787. this.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node);
  19788. return;
  19789. }
  19790. this.deserialize_multiple_outputs(serialized_node, fx_node);
  19791. }
  19792. deserialize_multiple_outputs(serialized_node, fx_node) {
  19793. const deserialized_metadata = this.deserialize_metadata(serialized_node.metadata);
  19794. const generate_getitem = (meta_val, fx_node, arg, idx) => {
  19795. let name = '';
  19796. if (arg instanceof torch._export.serde.schema.TensorArgument) {
  19797. name = arg.name;
  19798. } else if (arg instanceof torch._export.serde.schema.SymIntArgument) {
  19799. name = arg.as_name;
  19800. } else {
  19801. throw new python.Error(`Unsupported argument type '${arg}'.`);
  19802. }
  19803. const individual_output = this.graph.create_node(
  19804. 'call_function',
  19805. operator.getitem,
  19806. new builtins.tuple([fx_node, idx]),
  19807. null,
  19808. name,
  19809. );
  19810. this.sync_fx_node(name, individual_output);
  19811. meta_val.push(this.serialized_name_to_meta.get(name));
  19812. individual_output.meta.update(deserialized_metadata);
  19813. };
  19814. const generate_getitems = (meta_val, fx_node, args) => {
  19815. for (let idx = 0; idx < args.length; idx++) {
  19816. let arg = args[idx];
  19817. if (arg instanceof torch._export.serde.schema.Argument) {
  19818. arg = arg.value;
  19819. }
  19820. if (arg instanceof torch._export.serde.schema.TensorArgument || arg instanceof torch._export.serde.schema.SymIntArgument) {
  19821. generate_getitem(meta_val, fx_node, arg, idx);
  19822. } else if (Array.isArray(arg)) { // arg instanceof (list, tuple))
  19823. const list_output = this.graph.create_node(
  19824. 'call_function',
  19825. operator.getitem,
  19826. (fx_node, idx),
  19827. );
  19828. meta_val.push([]);
  19829. generate_getitems(meta_val[meta_val.length - 1], list_output, arg);
  19830. list_output.meta.update(deserialized_metadata);
  19831. list_output.meta.set('val', meta_val[meta_val.length - 1]);
  19832. } else {
  19833. throw new python.Error(`Unsupported node output type: '${arg}'.`);
  19834. }
  19835. }
  19836. };
  19837. const meta_val = [];
  19838. if (serialized_node.outputs.length === 1) {
  19839. // assert isinstance(serialized_node.outputs[0].value, list)
  19840. // assert isinstance(serialized_node.outputs[0].value[0], TensorArgument)
  19841. generate_getitems(meta_val, fx_node, serialized_node.outputs[0].as_tensors);
  19842. } else {
  19843. generate_getitems(meta_val, fx_node, serialized_node.outputs);
  19844. }
  19845. fx_node.meta.set('val', new builtins.tuple(meta_val));
  19846. this.serialized_name_to_node.set(fx_node.name, fx_node);
  19847. }
  19848. deserialize_metadata(metadata) {
  19849. const ret = new builtins.dict();
  19850. const stack_trace = metadata.get('stack_trace');
  19851. if (stack_trace) {
  19852. ret.set('stack_trace', stack_trace);
  19853. }
  19854. const deserialize_meta_func = (serialized_target) => {
  19855. let module = null;
  19856. let serialized_target_names = [];
  19857. if (serialized_target.startsWith('torch.nn')) {
  19858. module = torch.nn;
  19859. serialized_target_names = serialized_target.split('.').slice(1);
  19860. } else if (serialized_target.startsWith('torch')) {
  19861. module = torch;
  19862. serialized_target_names = serialized_target.split('.').slice(1);
  19863. } else {
  19864. return this.deserialize_operator(serialized_target);
  19865. }
  19866. let target = module;
  19867. for (const name of serialized_target_names) {
  19868. if (!builtins.hasattr(target, name)) {
  19869. return serialized_target;
  19870. }
  19871. target = builtins.getattr(target, name);
  19872. }
  19873. return target;
  19874. };
  19875. const nn_module_stack_str = metadata.get('nn_module_stack');
  19876. if (nn_module_stack_str) {
  19877. const import_nn_module_stack = (key, path, ty) => {
  19878. return [key, [path, ty]];
  19879. };
  19880. const nn_module_stack = new Map(nn_module_stack_str.split(';').map((item) => import_nn_module_stack(...item.split(','))));
  19881. ret.set('nn_module_stack', nn_module_stack);
  19882. }
  19883. const source_fn_st_str = metadata.get('source_fn_stack');
  19884. if (source_fn_st_str) {
  19885. const source_fn_st = [];
  19886. for (const source_fn_str of source_fn_st_str.split(';')) {
  19887. const [name, target_str] = source_fn_str.split(',');
  19888. source_fn_st.push([name, deserialize_meta_func(target_str)]);
  19889. }
  19890. ret.set('source_fn_stack', source_fn_st);
  19891. }
  19892. const torch_fn = metadata.get('torch_fn');
  19893. if (torch_fn) {
  19894. ret.set('torch_fn', new builtins.tuple(torch_fn.split(';')));
  19895. }
  19896. const custom_str = metadata.get('custom');
  19897. if (custom_str) {
  19898. ret.set('custom', JSON.parse(custom_str));
  19899. }
  19900. return ret;
  19901. }
  19902. deserialize_argument_spec(x) {
  19903. if (x.type === 'as_tensor') {
  19904. return new torch.export.graph_signature.TensorArgument(x.as_tensor.name);
  19905. } else if (x.type === 'as_sym_int') {
  19906. return new torch.export.graph_signature.SymIntArgument(x.as_sym_int.as_name);
  19907. } else if (x.type === 'as_custom_obj') {
  19908. return new torch.export.graph_signature.ConstantArgument(x.as_custom_obj.name, this.deserialize_input(x));
  19909. }
  19910. return new torch.export.graph_signature.ConstantArgument('', this.deserialize_input(x));
  19911. }
  19912. deserialize_tensor_meta(tensor_meta) {
  19913. try {
  19914. this.fake_tensor_mode.__enter__();
  19915. const sizes = tensor_meta.sizes.map((val) => this.deserialize_sym_int(val));
  19916. const strides = tensor_meta.strides.map((val) => this.deserialize_sym_int(val));
  19917. const device = this.deserialize_device(tensor_meta.device);
  19918. const dtype = torch._export.serde.serialize.deserialize_scalar_type(tensor_meta.dtype);
  19919. return torch.empty_strided(sizes, strides, dtype, null, device);
  19920. } finally {
  19921. this.fake_tensor_mode.__exit__(null, null, null);
  19922. }
  19923. }
  19924. deserialize_script_obj_meta(script_obj_meta) {
  19925. return new torch.export.graph_signature.CustomObjArgument(script_obj_meta.name, script_obj_meta.class_fqn);
  19926. }
  19927. _parse_sym_expr(expr_str, hint) {
  19928. const _process_sym_expr = (sym, hint) => {
  19929. if (sym.is_Integer || sym.is_Float || sym.is_Boolean) {
  19930. return sym;
  19931. }
  19932. expr_str = sym.__str__();
  19933. for (const arg of sym.args) {
  19934. this._parse_sym_expr(arg);
  19935. }
  19936. if (this.symbol_name_to_symbol.has(expr_str)) {
  19937. sym = this.symbol_name_to_symbol.get(expr_str);
  19938. } else {
  19939. this.symbol_name_to_symbol.set(expr_str, sym);
  19940. 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])) {
  19941. this.unbacked_symbols.add(sym);
  19942. }
  19943. }
  19944. if (hint !== null && !this.shape_env.var_to_val.has(sym)) {
  19945. this.shape_env.add_var_to_val(sym, hint);
  19946. }
  19947. const vr = this.symbol_name_to_range.get(expr_str);
  19948. if (vr) {
  19949. this.shape_env.constrain_symbol_range(sym, vr.lower, vr.upper);
  19950. }
  19951. if (builtins.isinstance(sym, sympy.core.symbol.Symbol)) {
  19952. this.shape_env.var_to_stack.set(sym, torch.utils._traceback.CapturedTraceback.extract(false, false, 1));
  19953. }
  19954. return sym;
  19955. };
  19956. const locals = new Map([...this.sympy_functions, ...this.symbol_name_to_symbol]);
  19957. const expr = sympy.core.sympify.sympify(expr_str, locals);
  19958. return _process_sym_expr(expr, hint);
  19959. }
  19960. deserialize_sym_int(s) {
  19961. const val = s.value;
  19962. let hint = null;
  19963. if (s.type === 'as_expr') {
  19964. if (val.hint === null) {
  19965. hint = null;
  19966. } else {
  19967. // assert val.hint.type == "as_int"
  19968. hint = val.hint.value;
  19969. }
  19970. const sym = this._parse_sym_expr(val.expr_str, hint);
  19971. return this.shape_env.create_symintnode(sym, hint);
  19972. } else if (s.type === 'as_int') {
  19973. // assert type(val) is int
  19974. return val;
  19975. }
  19976. throw new python.Error(`SymInt has invalid field type ${s.type} with value ${s.value}.`);
  19977. }
  19978. deserialize_sym_bool(s) {
  19979. const val = s.value;
  19980. let hint = null;
  19981. if (s.type === 'as_expr') {
  19982. if (val.hint === null) {
  19983. hint = null;
  19984. } else {
  19985. // assert val.hint.type == "as_bool"
  19986. hint = val.hint.value;
  19987. }
  19988. const sym = this._parse_sym_expr(val.expr_str, hint);
  19989. return this.shape_env.create_symboolnode(sym, hint);
  19990. } else if (s.type === 'as_bool') {
  19991. // assert type(val) is bool
  19992. return val;
  19993. }
  19994. throw new python.Error(`SymBool has invalid field type ${s.type} with value ${s.value}.`);
  19995. }
  19996. deserialize_device(d) {
  19997. if (d.index === null) {
  19998. return new torch.device(d.type);
  19999. }
  20000. return new torch.device(d.type, d.index);
  20001. }
  20002. _get_schema_from_target(target) {
  20003. if (target instanceof torch._ops.OpOverload) {
  20004. return target._schema;
  20005. }
  20006. throw new python.Error(`Unsupported schema '${target.name}'.`);
  20007. }
  20008. _is_single_tensor_return(target) {
  20009. const schema = this._get_schema_from_target(target);
  20010. const returns = schema.returns;
  20011. return returns.length === 1 && returns[0].real_type instanceof torch.TensorType;
  20012. }
  20013. });
  20014. this.registerType('torch._export.verifier.Verifier', class {});
  20015. this.registerType('torch._dynamo.convert_frame.CatchErrorsWrapper', class {});
  20016. this.registerType('torch._dynamo.convert_frame.ConvertFrameAssert', class {});
  20017. this.registerType('torch._dynamo.convert_frame.ConvertFrame', class {});
  20018. this.registerType('torch._dynamo.convert_frame.ConvertFrameBox', class {});
  20019. this.registerType('torch._dynamo.eval_frame._TorchDynamoContext', class {});
  20020. this.registerType('torch._dynamo.eval_frame.OptimizedModule', class extends torch.nn.modules.module.Module {
  20021. constructor(mod, dynamo_ctx) {
  20022. builtins.object.__setattr__(self, '_orig_mod', mod);
  20023. // this._super_module_initialized = false;
  20024. super();
  20025. // this._super_module_initialized = true;
  20026. this._orig_mod = mod;
  20027. this.dynamo_ctx = dynamo_ctx;
  20028. // this._initialize();
  20029. this.training = this._orig_mod.training;
  20030. }
  20031. });
  20032. this.registerType('torch._dynamo.eval_frame.OptimizeContext', class extends torch._dynamo.eval_frame._TorchDynamoContext {});
  20033. this.registerType('torch._dynamo.hooks.Hooks', class {});
  20034. this.registerType('torch._dynamo.output_graph.GraphCompileReason', class {});
  20035. this.registerType('torch._dynamo.repro.after_dynamo.WrapBackendDebug', class {});
  20036. this.registerType('torch._TorchCompileInductorWrapper', class {});
  20037. this.registerFunction('torch._inductor.compile_fx.compile_fx');
  20038. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', (meta) => {
  20039. const name = `_imported_module_${Math.floor(Math.random() * 10000)}`;
  20040. const module = new types.ModuleType(name);
  20041. execution.register('sys').modules.set(name, module);
  20042. const context = new python.Execution.Context(module, null);
  20043. execution.exec(meta.get('module_src'), context);
  20044. const obj = execution.invoke(`${name}.${meta.get('class_name')}`, []);
  20045. const state = meta.get('state');
  20046. if (state) {
  20047. if (obj.__setstate__) {
  20048. obj.__setstate__(state);
  20049. } else {
  20050. for (const [key, value] of state) {
  20051. obj[key] = value;
  20052. }
  20053. }
  20054. }
  20055. return obj;
  20056. });
  20057. this.registerFunction('torch_utils.misc.assert_shape', (/* tensor, ref_shape */) => {});
  20058. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', (/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) => {});
  20059. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', (/* x, f, up, down, padding, flip_filter, gain, impl */) => {});
  20060. this.registerFunction('torch_utils.ops.bias_act', (/* x, b, dim, act, alpha, gain, clamp, impl */) => {});
  20061. this.registerFunction('torch_utils.ops.fma.fma', (/* a, b, c */) => {});
  20062. this.registerType('torch.device', class {
  20063. constructor(type, index) {
  20064. this.type = type;
  20065. this.index = index ? index : null;
  20066. }
  20067. __str__() {
  20068. return this.index === null ? this.type : `${this.type}:${this.index}`;
  20069. }
  20070. toString() {
  20071. const index = this.index === null ? '' : `, index=${this.index}`;
  20072. return `device(type='${this.type}'${index})`;
  20073. }
  20074. });
  20075. this.registerType('torch.memory_format', class {
  20076. constructor(name) {
  20077. this.name = name;
  20078. }
  20079. __str__() {
  20080. return `torch.${this.name}`;
  20081. }
  20082. toString() {
  20083. return this.__str__();
  20084. }
  20085. });
  20086. this.registerType('torch.dtype', class {
  20087. constructor(scalar_type, name, itemsize) {
  20088. this._scalar_type = scalar_type;
  20089. this._name = name;
  20090. this._itemsize = itemsize;
  20091. }
  20092. scalar_type() {
  20093. return this._scalar_type;
  20094. }
  20095. itemsize() {
  20096. return this._itemsize;
  20097. }
  20098. __reduce__() {
  20099. return this._name;
  20100. }
  20101. __str__() {
  20102. return `torch.${this._name}`;
  20103. }
  20104. toString() {
  20105. return this.__str__();
  20106. }
  20107. });
  20108. this.registerType('torch.layout', class {
  20109. constructor(name) {
  20110. this._name = name;
  20111. }
  20112. __str__() {
  20113. return `torch.${this._name}`;
  20114. }
  20115. toString() {
  20116. return this.__str__();
  20117. }
  20118. });
  20119. this.registerType('torch.qscheme', class {
  20120. constructor(name) {
  20121. this._name = name;
  20122. }
  20123. __str__() {
  20124. return this._name;
  20125. }
  20126. toString() {
  20127. return this.__str__();
  20128. }
  20129. });
  20130. this.registerType('torch.utils.hooks.RemovableHandle', class {
  20131. __setstate__(state) {
  20132. [this.hooks_dict_ref, this.id] = state;
  20133. this.hooks_dict_ref = this.hooks_dict_ref || new Map();
  20134. }
  20135. });
  20136. this.registerType('torch.storage._StorageBase', class {
  20137. constructor(size, dtype) {
  20138. this._size = size;
  20139. this._dtype = dtype;
  20140. this._device = null;
  20141. }
  20142. get device() {
  20143. return this._device;
  20144. }
  20145. get dtype() {
  20146. return this._dtype;
  20147. }
  20148. element_size() {
  20149. return this._dtype.element_size;
  20150. }
  20151. size() {
  20152. return this._size;
  20153. }
  20154. get data() {
  20155. return this._cdata;
  20156. }
  20157. _set_cdata(data) {
  20158. const length = this.size() * this.dtype.itemsize();
  20159. if (length !== data.length) {
  20160. throw new python.Error('Typed storage data size mismatch.');
  20161. }
  20162. this._cdata = data;
  20163. }
  20164. _set_from_file(unpickler) {
  20165. const buffer = unpickler.read(8);
  20166. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20167. if (size !== this.size()) {
  20168. throw new python.Error('Typed storage size mismatch.');
  20169. }
  20170. const itemsize = this.dtype.itemsize();
  20171. const data = unpickler.stream(itemsize * size);
  20172. this._set_cdata(data);
  20173. }
  20174. static _new_with_file(unpickler) {
  20175. const buffer = unpickler.read(8);
  20176. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20177. const storage = new this(size);
  20178. const itemsize = storage.dtype.itemsize();
  20179. const data = unpickler.stream(itemsize * size);
  20180. storage._set_cdata(data);
  20181. return storage;
  20182. }
  20183. });
  20184. this.registerType('torch.storage.UntypedStorage', class {
  20185. constructor(size) {
  20186. this._size = size;
  20187. }
  20188. _set_cdata(data) {
  20189. if (this._size !== data.length) {
  20190. throw new python.Error('Untyped storage data size mismatch.');
  20191. }
  20192. this._cdata = data;
  20193. }
  20194. });
  20195. this.registerType('torch.storage.TypedStorage', class {
  20196. constructor(...args) {
  20197. if (args.length === 0) {
  20198. this._size = 0;
  20199. } else if (args.length === 1 && Number.isInteger(args[0])) {
  20200. [this._size] = args;
  20201. } else if (args.length >= 2 && Number.isInteger(args[0]) && args[1] instanceof torch.dtype) {
  20202. if (args[3] instanceof torch.device) {
  20203. [this._size, this.dtype, , this._device] = args;
  20204. } else {
  20205. [this._size, this.dtype] = args;
  20206. }
  20207. } else {
  20208. throw new python.Error(`Unsupported TypedStorage arguments '${JSON.stringify(args)}'.`);
  20209. }
  20210. }
  20211. get device() {
  20212. return this._device;
  20213. }
  20214. get dtype() {
  20215. return this._dtype;
  20216. }
  20217. set dtype(value) {
  20218. this._dtype = value;
  20219. }
  20220. element_size() {
  20221. return this._dtype.element_size;
  20222. }
  20223. size() {
  20224. return this._size;
  20225. }
  20226. get data() {
  20227. return this._cdata;
  20228. }
  20229. _set_cdata(data) {
  20230. const length = this.size() * this.dtype.itemsize();
  20231. if (length !== data.length) {
  20232. throw new python.Error('Storage data size mismatch.');
  20233. }
  20234. this._cdata = data;
  20235. }
  20236. _set_from_file(unpickler) {
  20237. const buffer = unpickler.read(8);
  20238. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20239. if (size !== this.size()) {
  20240. throw new python.Error('Storage size mismatch.');
  20241. }
  20242. const itemsize = this.dtype.itemsize();
  20243. const data = unpickler.stream(itemsize * size);
  20244. this._set_cdata(data);
  20245. }
  20246. static _new_with_file(unpickler) {
  20247. const buffer = unpickler.read(8);
  20248. const size = buffer.reverse().reduce((a, b) => (a * 256) + b, 0);
  20249. const storage = new this(size);
  20250. const itemsize = storage.dtype.itemsize();
  20251. const data = unpickler.stream(itemsize * size);
  20252. storage._set_cdata(data);
  20253. return storage;
  20254. }
  20255. });
  20256. this.registerType('torch.storage._LegacyStorage', class extends torch.storage.TypedStorage {
  20257. });
  20258. this.registerType('torch.BoolStorage', class extends torch.storage._LegacyStorage {
  20259. constructor(...args) {
  20260. // eslint-disable-next-line no-constructor-return
  20261. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BoolStorage.dtype);
  20262. }
  20263. });
  20264. this.registerType('torch.ByteStorage', class extends torch.storage._LegacyStorage {
  20265. constructor(...args) {
  20266. // eslint-disable-next-line no-constructor-return
  20267. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ByteStorage.dtype);
  20268. }
  20269. });
  20270. this.registerType('torch.CharStorage', class extends torch.storage._LegacyStorage {
  20271. constructor(...args) {
  20272. // eslint-disable-next-line no-constructor-return
  20273. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.CharStorage.dtype);
  20274. }
  20275. });
  20276. this.registerType('torch.ShortStorage', class extends torch.storage._LegacyStorage {
  20277. constructor(...args) {
  20278. // eslint-disable-next-line no-constructor-return
  20279. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ShortStorage.dtype);
  20280. }
  20281. });
  20282. this.registerType('torch.IntStorage', class extends torch.storage._LegacyStorage {
  20283. constructor(...args) {
  20284. // eslint-disable-next-line no-constructor-return
  20285. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.IntStorage.dtype);
  20286. }
  20287. });
  20288. this.registerType('torch.LongStorage', class extends torch.storage._LegacyStorage {
  20289. constructor(...args) {
  20290. // eslint-disable-next-line no-constructor-return
  20291. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.LongStorage.dtype);
  20292. }
  20293. });
  20294. this.registerType('torch.HalfStorage', class extends torch.storage._LegacyStorage {
  20295. constructor(...args) {
  20296. // eslint-disable-next-line no-constructor-return
  20297. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.HalfStorage.dtype);
  20298. }
  20299. });
  20300. this.registerType('torch.FloatStorage', class extends torch.storage._LegacyStorage {
  20301. constructor(...args) {
  20302. // eslint-disable-next-line no-constructor-return
  20303. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.FloatStorage.dtype);
  20304. }
  20305. });
  20306. this.registerType('torch.DoubleStorage', class extends torch.storage._LegacyStorage {
  20307. constructor(...args) {
  20308. // eslint-disable-next-line no-constructor-return
  20309. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.DoubleStorage.dtype);
  20310. }
  20311. });
  20312. this.registerType('torch.ComplexHalfStorage', class extends torch.storage._LegacyStorage {
  20313. constructor(...args) {
  20314. // eslint-disable-next-line no-constructor-return
  20315. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexHalfStorage.dtype);
  20316. }
  20317. });
  20318. this.registerType('torch.ComplexFloatStorage', class extends torch.storage._LegacyStorage {
  20319. constructor(...args) {
  20320. // eslint-disable-next-line no-constructor-return
  20321. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexFloatStorage.dtype);
  20322. }
  20323. });
  20324. this.registerType('torch.ComplexDoubleStorage', class extends torch.storage._LegacyStorage {
  20325. constructor(...args) {
  20326. // eslint-disable-next-line no-constructor-return
  20327. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.ComplexDoubleStorage.dtype);
  20328. }
  20329. });
  20330. this.registerType('torch.QInt8Storage', class extends torch.storage._LegacyStorage {
  20331. constructor(...args) {
  20332. // eslint-disable-next-line no-constructor-return
  20333. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20334. }
  20335. });
  20336. this.registerType('torch.QUInt8Storage', class extends torch.storage._LegacyStorage {
  20337. constructor(...args) {
  20338. // eslint-disable-next-line no-constructor-return
  20339. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt8Storage.dtype);
  20340. }
  20341. });
  20342. this.registerType('torch.QInt32Storage', class extends torch.storage._LegacyStorage {
  20343. constructor(...args) {
  20344. // eslint-disable-next-line no-constructor-return
  20345. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QInt32Storage.dtype);
  20346. }
  20347. });
  20348. this.registerType('torch.BFloat16Storage', class extends torch.storage._LegacyStorage {
  20349. constructor(...args) {
  20350. // eslint-disable-next-line no-constructor-return
  20351. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.BFloat16Storage.dtype);
  20352. }
  20353. });
  20354. this.registerType('torch.QUInt4x2Storage', class extends torch.storage._LegacyStorage {
  20355. constructor(...args) {
  20356. // eslint-disable-next-line no-constructor-return
  20357. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt4x2Storage.dtype);
  20358. }
  20359. });
  20360. this.registerType('torch.QUInt2x4Storage', class extends torch.storage._LegacyStorage {
  20361. constructor(...args) {
  20362. // eslint-disable-next-line no-constructor-return
  20363. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.QUInt2x4Storage.dtype);
  20364. }
  20365. });
  20366. this.registerType('torch.UInt16Storage', class extends torch.storage._LegacyStorage {
  20367. constructor(...args) {
  20368. // eslint-disable-next-line
  20369. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt16Storage.dtype);
  20370. }
  20371. });
  20372. this.registerType('torch.UInt32Storage', class extends torch.storage._LegacyStorage {
  20373. constructor(...args) {
  20374. // eslint-disable-next-line no-constructor-return
  20375. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt32Storage.dtype);
  20376. }
  20377. });
  20378. this.registerType('torch.UInt64Storage', class extends torch.storage._LegacyStorage {
  20379. constructor(...args) {
  20380. // eslint-disable-next-line no-constructor-return
  20381. return new torch.storage.TypedStorage(args.length > 0 ? args[0] : 0, torch.UInt64Storage.dtype);
  20382. }
  20383. });
  20384. this.registerType('torch.Size', class extends Array {
  20385. constructor(size) {
  20386. super(size.length);
  20387. for (let i = 0; i < size.length; i++) {
  20388. this[i] = size[i];
  20389. }
  20390. }
  20391. __len__() {
  20392. return this.length;
  20393. }
  20394. });
  20395. this.registerType('torch._C.TensorMeta', class {
  20396. });
  20397. this.registerType('torch._C.TensorBase', class extends torch._C.TensorMeta {
  20398. });
  20399. this.registerType('torch.Tensor', class extends torch._C.TensorBase {
  20400. constructor(storage, shape, dtype, layout, device, requires_grad) {
  20401. super();
  20402. if (storage) {
  20403. this._storage = storage;
  20404. }
  20405. if (shape !== null && shape !== undefined) {
  20406. this._shape = shape;
  20407. }
  20408. if (dtype) {
  20409. this._dtype = dtype;
  20410. }
  20411. this._layout = layout || torch.strided;
  20412. if (device) {
  20413. this._device = device;
  20414. }
  20415. if (requires_grad !== undefined) {
  20416. this.requires_grad = requires_grad;
  20417. }
  20418. }
  20419. clone() {
  20420. const tensor = new torch.Tensor(this._storage, this._shape, this._dtype, this._layout, this._device, this.requires_grad);
  20421. tensor._storage_offset = this._storage_offset;
  20422. tensor._stride = this._stride;
  20423. tensor._values = this._values;
  20424. tensor._indices = this._indices;
  20425. tensor.__quantized__ = this.__quantized__;
  20426. tensor.__nested__ = this.__nested__;
  20427. tensor.data = this.data;
  20428. tensor._backward_hooks = this._backward_hooks;
  20429. return tensor;
  20430. }
  20431. get device() {
  20432. if (this._device !== undefined) {
  20433. return this._device;
  20434. }
  20435. return this.storage().device;
  20436. }
  20437. get dtype() {
  20438. if (this._dtype !== undefined) {
  20439. return this._dtype;
  20440. }
  20441. if (this._layout === torch.sparse_coo) {
  20442. return this._values.dtype;
  20443. }
  20444. return this.storage().dtype;
  20445. }
  20446. get shape() {
  20447. return this._shape;
  20448. }
  20449. get layout() {
  20450. return this._layout;
  20451. }
  20452. get values() {
  20453. if (this._layout === torch.sparse_coo) {
  20454. return this._values;
  20455. }
  20456. throw new python.Error(`Unsupported values in layout'${this._layout.__str__()}'.`);
  20457. }
  20458. get indices() {
  20459. if (this._layout === torch.sparse_coo) {
  20460. return this._indices;
  20461. }
  20462. throw new python.Error(`Unsupported indices in layout'${this._indices.__str__()}'.`);
  20463. }
  20464. get is_quantized() {
  20465. return this.__quantized__ === true;
  20466. }
  20467. get is_nested() {
  20468. return this.__nested__ === true;
  20469. }
  20470. get is_sparse() {
  20471. return this.layout !== torch.strided;
  20472. }
  20473. size() {
  20474. return this._shape;
  20475. }
  20476. storage() {
  20477. return this._storage;
  20478. }
  20479. storage_offset() {
  20480. return this._storage_offset;
  20481. }
  20482. stride() {
  20483. return this._stride;
  20484. }
  20485. resize_(shape) {
  20486. this._shape = shape;
  20487. }
  20488. __len__() {
  20489. return this._shape[0];
  20490. }
  20491. __setstate__(state) {
  20492. switch (state.length) {
  20493. case 3:
  20494. break;
  20495. case 4:
  20496. [this._storage, this._storage_offset, this._shape, this._stride] = state;
  20497. break;
  20498. case 5:
  20499. [this.data, ,this._backward_hooks, this.requires_grad] = state;
  20500. break;
  20501. default:
  20502. throw new python.Error(`Unsupported tensor state length '${state.length}'.`);
  20503. }
  20504. }
  20505. set_(source, storage_offset, size, stride) {
  20506. this._storage = source;
  20507. this._storage_offset = storage_offset;
  20508. this._shape = size;
  20509. this._stride = stride;
  20510. }
  20511. __bool__() {
  20512. return true;
  20513. }
  20514. __int__() {
  20515. const storage = this.storage();
  20516. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  20517. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20518. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20519. return view.getBigInt64(0, true);
  20520. }
  20521. return NaN;
  20522. }
  20523. __float__() {
  20524. const storage = this.storage();
  20525. if (storage && storage.dtype.__reduce__() === 'float32') {
  20526. if (storage.size() !== undefined && storage.data.length === 4) {
  20527. const buffer = storage.data.peek ? storage.data.peek() : storage.data;
  20528. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  20529. return view.getFloat32(0, true);
  20530. }
  20531. }
  20532. return NaN;
  20533. }
  20534. __str__() {
  20535. return 'tensor(...)';
  20536. }
  20537. static _make_wrapper_subclass(cls, size, stride, dtype, storage_offset, layout, device, requires_grad) {
  20538. const t = new torch.Tensor(null, size, dtype, layout, device, requires_grad);
  20539. t.__setstate__([null, storage_offset, size, stride]);
  20540. return t;
  20541. }
  20542. });
  20543. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  20544. constructor(data, requires_grad) {
  20545. super();
  20546. this.data = data || new torch.Tensor([]);
  20547. this.requires_grad = requires_grad === undefined ? true : requires_grad;
  20548. }
  20549. });
  20550. this.registerType('torch._subclasses.fake_tensor.FakeTensor', class extends torch.Tensor {
  20551. });
  20552. this.registerType('torch._subclasses.fake_tensor.FakeTensorMode', class extends torch.utils._python_dispatch.TorchDispatchMode {
  20553. constructor(allow_fallback_kernels, allow_non_fake_inputs, shape_env) {
  20554. super();
  20555. this.allow_fallback_kernels = allow_fallback_kernels;
  20556. this.allow_non_fake_inputs = allow_non_fake_inputs;
  20557. this.shape_env = shape_env;
  20558. this.enter_stack = [];
  20559. this._mode_key = 0; // torch._C._TorchDispatchModeKey.FAKE
  20560. }
  20561. __enter__() {
  20562. const prev_only_lift_cpu_tensors = null;
  20563. const maybe_prev_fake_mode = torch._C._unset_dispatch_mode(this._mode_key);
  20564. if (this === maybe_prev_fake_mode) {
  20565. torch._C._set_dispatch_mode(this);
  20566. this.enter_stack.push([false, null, prev_only_lift_cpu_tensors]);
  20567. } else {
  20568. this.enter_stack.push([true, maybe_prev_fake_mode, prev_only_lift_cpu_tensors]);
  20569. return super.__enter__();
  20570. }
  20571. return this;
  20572. }
  20573. __exit__(exc_type, exc_value, traceback) {
  20574. const [live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors] = this.enter_stack.pop();
  20575. if (live) {
  20576. super.__exit__(exc_type, exc_value, traceback);
  20577. if (maybe_prev_fake_mode !== null) {
  20578. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20579. }
  20580. if (maybe_prev_only_lift_cpu_tensors !== null) {
  20581. torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors);
  20582. }
  20583. torch._C._set_dispatch_mode(maybe_prev_fake_mode);
  20584. }
  20585. }
  20586. });
  20587. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch.nn.parameter.Parameter {
  20588. constructor(requires_grad /*, device, dtype */) {
  20589. super(undefined, requires_grad);
  20590. }
  20591. });
  20592. this.registerType('torch.nn.parameter.UninitializedBuffer', class extends torch.Tensor {});
  20593. this.registerType('torch.BoolTensor', class extends torch.Tensor {
  20594. constructor(...args) {
  20595. // eslint-disable-next-line no-constructor-return
  20596. return new torch.Tensor(...args);
  20597. }
  20598. });
  20599. this.registerType('torch.ByteTensor', class extends torch.Tensor {
  20600. constructor(...args) {
  20601. // eslint-disable-next-line no-constructor-return
  20602. return new torch.Tensor(...args);
  20603. }
  20604. });
  20605. this.registerType('torch.CharTensor', class extends torch.Tensor {
  20606. constructor(...args) {
  20607. // eslint-disable-next-line no-constructor-return
  20608. return new torch.Tensor(...args);
  20609. }
  20610. });
  20611. this.registerType('torch.ShortTensor', class extends torch.Tensor {
  20612. constructor(...args) {
  20613. // eslint-disable-next-line no-constructor-return
  20614. return new torch.Tensor(...args);
  20615. }
  20616. });
  20617. this.registerType('torch.IntTensor', class extends torch.Tensor {
  20618. constructor(...args) {
  20619. // eslint-disable-next-line no-constructor-return
  20620. return new torch.Tensor(...args);
  20621. }
  20622. });
  20623. this.registerType('torch.LongTensor', class extends torch.Tensor {
  20624. constructor(...args) {
  20625. // eslint-disable-next-line no-constructor-return
  20626. return new torch.Tensor(...args);
  20627. }
  20628. });
  20629. this.registerType('torch.HalfTensor', class extends torch.Tensor {
  20630. constructor(...args) {
  20631. // eslint-disable-next-line no-constructor-return
  20632. return new torch.Tensor(...args);
  20633. }
  20634. });
  20635. this.registerType('torch.FloatTensor', class extends torch.Tensor {
  20636. constructor(...args) {
  20637. // eslint-disable-next-line no-constructor-return
  20638. return new torch.Tensor(...args);
  20639. }
  20640. });
  20641. this.registerType('torch.DoubleTensor', class extends torch.Tensor {
  20642. constructor(...args) {
  20643. // eslint-disable-next-line no-constructor-return
  20644. return new torch.Tensor(...args);
  20645. }
  20646. });
  20647. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {
  20648. constructor(...args) {
  20649. // eslint-disable-next-line no-constructor-return
  20650. return new torch.Tensor(...args);
  20651. }
  20652. });
  20653. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {
  20654. constructor(...args) {
  20655. // eslint-disable-next-line no-constructor-return
  20656. return new torch.Tensor(...args);
  20657. }
  20658. });
  20659. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {
  20660. constructor(...args) {
  20661. // eslint-disable-next-line no-constructor-return
  20662. return new torch.Tensor(...args);
  20663. }
  20664. });
  20665. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {
  20666. constructor(...args) {
  20667. // eslint-disable-next-line no-constructor-return
  20668. return new torch.Tensor(...args);
  20669. }
  20670. });
  20671. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {
  20672. constructor(...args) {
  20673. // eslint-disable-next-line no-constructor-return
  20674. return new torch.Tensor(...args);
  20675. }
  20676. });
  20677. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {
  20678. constructor(...args) {
  20679. // eslint-disable-next-line no-constructor-return
  20680. return new torch.Tensor(...args);
  20681. }
  20682. });
  20683. this.registerType('torch.cuda._CudaLegacyStorage', class extends torch.storage._LegacyStorage {});
  20684. this.registerType('torch.cuda.FloatStorage', class extends torch.cuda._CudaLegacyStorage {});
  20685. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {
  20686. constructor(...args) {
  20687. // eslint-disable-next-line no-constructor-return
  20688. return new torch.Tensor(...args);
  20689. }
  20690. });
  20691. this.registerType('torch.cuda.DoubleStorage', class extends torch.cuda._CudaLegacyStorage {});
  20692. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {
  20693. constructor(...args) {
  20694. // eslint-disable-next-line no-constructor-return
  20695. return new torch.Tensor(...args);
  20696. }
  20697. });
  20698. this.registerType('torch.cuda.amp.grad_scaler.GradScaler', class {});
  20699. this.registerType('torchao.utils.TorchAOBaseTensor', class extends torch.Tensor {
  20700. constructor(...args) {
  20701. // eslint-disable-next-line no-constructor-return
  20702. return new torch.Tensor(...args);
  20703. }
  20704. });
  20705. this.registerType('torchao.dtypes.affine_quantized_tensor.AffineQuantizedTensor', class extends torchao.utils.TorchAOBaseTensor {});
  20706. this.registerType('torchao.dtypes.utils.Layout', class {});
  20707. this.registerType('torchao.dtypes.uintx.plain_layout.PlainAQTTensorImpl', class {});
  20708. this.registerType('torchao.dtypes.floatx.float8_layout.Float8Layout', class extends torchao.dtypes.utils.Layout {});
  20709. this.registerType('torchao.dtypes.utils.AQTTensorImpl', class extends torchao.utils.TorchAOBaseTensor {});
  20710. this.registerType('torchao.dtypes.utils.PlainLayout', class extends torchao.dtypes.utils.Layout {});
  20711. this.registerType('torchao.dtypes.floatx.float8_layout.Float8AQTTensorImpl', class extends torchao.dtypes.utils.AQTTensorImpl {});
  20712. this.registerType('torchao.quantization.quant_primitives.ZeroPointDomain', class extends this.enum.Enum {});
  20713. this.registerFunction('torch.cuda.amp.grad_scaler._refresh_per_optimizer_state');
  20714. this.registerType('torch.SymBool', class {
  20715. constructor(node) {
  20716. this.node = node;
  20717. }
  20718. });
  20719. this.registerType('torch.SymInt', class {
  20720. constructor(node) {
  20721. this.node = node;
  20722. }
  20723. toString() {
  20724. return this.node.__str__();
  20725. }
  20726. });
  20727. this.register('torch.nn').Module = this.register('torch.nn.modules.module').Module;
  20728. this.register('torch.optim').Adam = this.register('torch.optim.adam').Adam;
  20729. this.register('torch.nn').ReLU = this.register('torch.nn.modules.activation').ReLU;
  20730. this.register('sklearn.utils').Bunch = this.register('sklearn.utils._bunch').Bunch;
  20731. /* eslint-disable no-multi-assign */
  20732. // https://github.com/pytorch/pytorch/blob/main/c10/core/ScalarType.h
  20733. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype(0, 'uint8', 1);
  20734. torch.int8 = torch.CharStorage.dtype = new torch.dtype(1, 'int8', 1);
  20735. torch.int16 = torch.ShortStorage.dtype = new torch.dtype(2, 'int16', 2);
  20736. torch.int32 = torch.IntStorage.dtype = new torch.dtype(3, 'int32', 4);
  20737. torch.int64 = torch.LongStorage.dtype = new torch.dtype(4, 'int64', 8);
  20738. torch.float16 = torch.HalfStorage.dtype = new torch.dtype(5, 'float16', 2);
  20739. torch.float32 = torch.FloatStorage.dtype = new torch.dtype(6, 'float32', 4);
  20740. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype(7, 'float64', 8);
  20741. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype(8, 'complex<float16>', 4);
  20742. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype(9, 'complex<float32>', 8);
  20743. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype(10, 'complex<float64>', 16);
  20744. torch.bool = torch.BoolStorage.dtype = new torch.dtype(11, 'boolean', 1);
  20745. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype(12, 'qint8', 1);
  20746. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype(13, 'quint8', 1);
  20747. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype(14, 'qint32', 4);
  20748. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype(15, 'bfloat16', 2);
  20749. torch.quint4x2 = torch.QUInt4x2Storage.dtype = new torch.dtype(16, 'quint4x2', 1);
  20750. torch.quint2x4 = torch.QUInt2x4Storage.dtype = new torch.dtype(17, 'quint2x4');
  20751. torch.bits1x8 = new torch.dtype(18, 'bits1x8');
  20752. torch.bits2x4 = new torch.dtype(19, 'bits2x4');
  20753. torch.bits4x2 = new torch.dtype(20, 'bits4x2');
  20754. torch.bits8 = new torch.dtype(21, 'bits8');
  20755. torch.bits16 = new torch.dtype(22, 'bits16');
  20756. torch.float8_e5m2 = new torch.dtype(23, 'float8_e5m2', 1);
  20757. torch.float8_e5m2fnuz = new torch.dtype(24, 'float8_e5m2fnuz', 1);
  20758. torch.float8_e4m3fn = new torch.dtype(25, 'float8_e4m3fn', 1);
  20759. torch.float8_e4m3fnuz = new torch.dtype(26, 'float8_e4m3fnuz', 1);
  20760. torch.uint16 = torch.UInt16Storage.dtype = new torch.dtype(27, 'uint16', 2);
  20761. torch.uint32 = torch.UInt32Storage.dtype = new torch.dtype(28, 'uint32', 4);
  20762. torch.uint64 = torch.UInt64Storage.dtype = new torch.dtype(29, 'uint64', 8);
  20763. torch._export.serde.serialize._SERIALIZE_TO_TORCH_DTYPE = new Map([
  20764. ['uint8', 'BYTE'],
  20765. ['int8', 'CHAR'], ['int16', 'SHORT'], ['int32', 'INT'], ['int64', 'LONG'],
  20766. ['float16', 'HALF'], ['float32', 'FLOAT'], ['float64', 'DOUBLE'],
  20767. ['complex32', 'COMPLEXHALF'], ['complex64', 'COMPLEXFLOAT'], ['complex128', 'COMPLEXDOUBLE'],
  20768. ['bool', 'BOOL'], ['bfloat16', 'BFLOAT16'], ['uint16', 'UINT16'],
  20769. ['float8_e4m3fn','FLOAT8E4M3FN'], ['float8_e5m2','FLOAT8E5M2'], ['float8_e4m3fnuz','FLOAT8E4M3FNUZ'], ['float8_e5m2fnuz','FLOAT8E5M2FNUZ']
  20770. ].map(([key, value]) => [torch._export.serde.schema.ScalarType[value], torch[key]]));
  20771. torch.contiguous_format = new torch.memory_format('contiguous_format');
  20772. torch.channels_last = new torch.memory_format('channels_last');
  20773. torch.channels_last_3d = new torch.memory_format('channels_last_3d');
  20774. torch.preserve_format = new torch.memory_format('preserve_format');
  20775. torch._export.serde.serialize._SERIALIZE_TO_TORCH_MEMORY_FORMAT = Object.fromEntries([
  20776. ['contiguous_format', 'ContiguousFormat'],
  20777. ['channels_last', 'ChannelsLast'],
  20778. ['channels_last_3d', 'ChannelsLast3d'],
  20779. ['preserve_format', 'PreserveFormat']
  20780. ].map(([key, value]) => [torch._export.serde.schema.MemoryFormat[value], torch[key]]));
  20781. /* eslint-enable no-multi-assign */
  20782. torch.strided = new torch.layout('strided');
  20783. torch.sparse_coo = new torch.layout('sparse_coo');
  20784. torch.sparse_csr = new torch.layout('sparse_csr');
  20785. torch.sparse_csc = new torch.layout('sparse_csc');
  20786. torch.sparse_bsr = new torch.layout('sparse_bsr');
  20787. torch.sparse_bsc = new torch.layout('sparse_bsc');
  20788. torch._mkldnn = new torch.layout('_mkldnn');
  20789. torch._export.serde.serialize._SERIALIZE_TO_TORCH_LAYOUT = Object.fromEntries([
  20790. ['sparse_coo', 'SparseCoo'],
  20791. ['sparse_csr', 'SparseCsr'],
  20792. ['sparse_csc', 'SparseCsc'],
  20793. ['sparse_bsr', 'SparseBsr'],
  20794. ['sparse_bsc', 'SparseBsc'],
  20795. ['_mkldnn', '_mkldnn'],
  20796. ['strided', 'Strided'],
  20797. ].map(([key, value]) => [torch._export.serde.schema.Layout[value], torch[key]]));
  20798. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  20799. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  20800. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  20801. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  20802. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  20803. torch.inf = this.register('math').inf;
  20804. this.registerFunction('fastcore.basics._using_attr');
  20805. this.registerFunction('fastcore.imports.noop');
  20806. this.registerType('fastcore.basics.fastuple', class {});
  20807. this.registerType('fastcore.basics.GetAttr', class {});
  20808. this.registerType('fastcore.dispatch._TypeDict', class {});
  20809. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  20810. this.registerType('fastcore.foundation.L', class {});
  20811. this.registerType('fastcore.transform.Pipeline', class extends builtins.object {});
  20812. this.registerType('fastcore.transform.Transform', class extends builtins.object {});
  20813. this.registerType('fastcore.transform.DisplayedTransform', class extends fastcore.transform.Transform {});
  20814. this.registerType('fastcore.transform.ItemTransform', class extends fastcore.transform.Transform {});
  20815. this.registerType('fastai.basic_train.Learner', class {});
  20816. this.registerType('fastai.basic_train.Recorder', class {});
  20817. this.registerFunction('fastai.torch_core._fa_rebuild_tensor', (cls, ...args) => {
  20818. const tensor = torch._utils._rebuild_tensor_v2(...args);
  20819. return self.invoke(cls, [tensor]);
  20820. });
  20821. this.registerFunction('fastai.torch_core.trainable_params');
  20822. this.registerFunction('fastai.torch_core._rebuild_from_type', (func, type, args, dict) => {
  20823. const tensor = self.invoke(type, [func(...args)]);
  20824. Object.assign(tensor, dict);
  20825. return tensor;
  20826. });
  20827. this.registerType('fastai.torch_core.Module', class extends torch.nn.modules.module.Module {});
  20828. this.registerType('fastai.torch_core.TensorBase', class extends torch.Tensor {
  20829. constructor(x) {
  20830. super();
  20831. Object.assign(this, x);
  20832. }
  20833. });
  20834. this.registerType('fastai.torch_core.TensorCategory', class extends fastai.torch_core.TensorBase {});
  20835. this.registerType('fastai.torch_core.TensorImageBase', class extends fastai.torch_core.TensorBase {});
  20836. this.registerType('fastai.torch_core.TensorImage', class extends fastai.torch_core.TensorImageBase {});
  20837. this.registerType('fastai.torch_core.TensorMask', class extends fastai.torch_core.TensorImageBase {});
  20838. this.registerType('fastai.torch_core.TensorMultiCategory', class extends fastai.torch_core.TensorCategory {});
  20839. this.registerFunction('fastai.torch_core.uniform');
  20840. this.registerType('fastai.callback.core.Callback', class extends fastcore.basics.GetAttr {});
  20841. this.registerType('fastai.callback.core.TrainEvalCallback', class extends fastai.callback.core.Callback {});
  20842. this.registerType('fastai.callback.fp16.AMPMode', class extends this.enum.Enum {});
  20843. this.registerType('fastai.callback.fp16.MixedPrecision', class {});
  20844. this.registerFunction('fastai.callback.hook._hook_inner');
  20845. this.registerType('fastai.callback.hook.Hook', class extends builtins.object {});
  20846. this.registerType('fastai.callback.hook.Hooks', class extends builtins.object {});
  20847. this.registerType('fastai.callback.mixup.MixHandler', class extends fastai.callback.core.Callback {});
  20848. this.registerType('fastai.callback.mixup.CutMix', class extends fastai.callback.mixup.MixHandler {});
  20849. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  20850. this.registerType('fastai.callback.progress.ShowGraphCallback', class {});
  20851. this.registerType('fastai.callback.tracker.EarlyStoppingCallback', class {});
  20852. this.registerType('fastai.callback.tracker.TrackerCallback', class {});
  20853. this.registerType('fastai.callback.tracker.SaveModelCallback', class extends fastai.callback.tracker.TrackerCallback {});
  20854. this.registerType('fastai.data.core.DataLoaders', class extends fastcore.basics.GetAttr {});
  20855. this.registerType('fastai.data.core.Datasets', class {});
  20856. this.registerType('fastai.data.load.DataLoader', class extends fastcore.basics.GetAttr {});
  20857. this.registerType('fastai.data.core.FilteredBase', class {});
  20858. this.registerType('fastai.data.core.TfmdDL', class extends fastai.data.load.DataLoader {});
  20859. this.registerType('fastai.data.core.TfmdLists', class {});
  20860. this.registerType('fastai.data.load._FakeLoader', class {});
  20861. this.registerFunction('fastai.data.load._wif');
  20862. this.registerType('fastai.data.transforms.Categorize', class {});
  20863. this.registerType('fastai.data.transforms.Category', class {});
  20864. this.registerType('fastai.data.transforms.CategoryMap', class {});
  20865. this.registerType('fastai.data.transforms.ColReader', class {});
  20866. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  20867. this.registerType('fastai.data.transforms.MultiCategorize', class {});
  20868. this.registerType('fastai.data.transforms.Normalize', class {});
  20869. this.registerType('fastai.data.transforms.parent_label', class {});
  20870. this.registerType('fastai.data.transforms.OneHotEncode', class {});
  20871. this.registerType('fastai.data.transforms.RegressionSetup', class {});
  20872. this.registerType('fastai.data.transforms.ToTensor', class {});
  20873. this.registerType('fastai.data_block.CategoryList', class {});
  20874. this.registerType('fastai.data_block.CategoryProcessor', class {});
  20875. this.registerType('fastai.imports.noop', class {});
  20876. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  20877. this.registerType('fastai.layers.ConvLayer', class {});
  20878. this.registerType('fastai.layers.Embedding', class {});
  20879. this.registerType('fastai.layers.Flatten', class {});
  20880. this.registerType('fastai.layers.FlattenedLoss', class {});
  20881. this.registerType('fastai.layers.LinBnDrop', class {});
  20882. this.registerType('fastai.layers.MergeLayer', class {});
  20883. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  20884. this.registerType('fastai.layers.ResBlock', class {});
  20885. this.registerType('fastai.layers.SelfAttention', class {});
  20886. this.registerType('fastai.layers.SigmoidRange', class {});
  20887. this.registerType('fastai.layers.TimeDistributed', class {});
  20888. this.registerType('fastai.layers.ToTensorBase', class {});
  20889. this.registerType('fastai.learner._ConstantFunc', class {});
  20890. this.registerType('fastai.learner.Metric', class {});
  20891. this.registerType('fastai.learner.AvgLoss', class extends fastai.learner.Metric {});
  20892. this.registerType('fastai.learner.AvgMetric', class extends fastai.learner.Metric {});
  20893. this.registerType('fastai.learner.AvgSmoothLoss', class extends fastai.learner.Metric {});
  20894. this.registerType('fastai.learner.CastToTensor', class extends fastai.callback.core.Callback {});
  20895. this.registerType('fastai.learner.Dice', class extends fastai.learner.Metric {});
  20896. this.registerType('fastai.learner.Learner', class extends fastcore.basics.GetAttr {});
  20897. this.registerType('fastai.learner.Recorder', class {});
  20898. this.registerType('fastai.losses.BaseLoss', class {});
  20899. this.registerType('fastai.losses.BCEWithLogitsLossFlat', class {});
  20900. this.registerType('fastai.losses.CrossEntropyLossFlat', class extends fastai.losses.BaseLoss {});
  20901. this.registerType('fastai.losses.FocalLoss', class extends fastai.torch_core.Module {});
  20902. this.registerType('fastai.losses.FocalLossFlat', class extends fastai.losses.BaseLoss {});
  20903. this.registerType('fastai.losses.LabelSmoothingCrossEntropy', class extends fastai.torch_core.Module {});
  20904. this.registerType('fastai.metrics.AccumMetric', class extends fastai.learner.Metric {});
  20905. this.registerType('fastai.metrics.Dice', class {});
  20906. this.registerType('fastai.metrics.JaccardCoeff', class {});
  20907. this.registerFunction('fastai.metrics._rmse');
  20908. this.registerFunction('fastai.metrics.accuracy');
  20909. this.registerFunction('fastai.metrics.accuracy_multi');
  20910. this.registerFunction('fastai.metrics.foreground_acc');
  20911. this.registerFunction('fastai.metrics.mse');
  20912. this.registerFunction('fastai.metrics.error_rate');
  20913. this.registerType('fastai.optimizer._BaseOptimizer', class {});
  20914. this.registerType('fastai.optimizer.Optimizer', class extends fastai.optimizer._BaseOptimizer {});
  20915. this.registerFunction('fastai.optimizer.Adam');
  20916. this.registerFunction('fastai.optimizer.adam_step');
  20917. this.registerFunction('fastai.optimizer.average_grad');
  20918. this.registerFunction('fastai.optimizer.average_sqr_grad');
  20919. this.registerFunction('fastai.optimizer.RAdam');
  20920. this.registerFunction('fastai.optimizer.step_stat');
  20921. this.registerFunction('fastai.optimizer.weight_decay');
  20922. this.registerType('fastai.tabular.core.Categorify', class {});
  20923. this.registerType('fastai.tabular.core.FillMissing', class {});
  20924. this.registerType('fastai.tabular.core.FillStrategy', class {});
  20925. this.registerType('fastai.tabular.core.ReadTabBatch', class extends fastcore.transform.ItemTransform {});
  20926. this.registerType('fastai.tabular.core.TabDataLoader', class extends fastai.data.core.TfmdDL {});
  20927. this.registerType('fastai.tabular.data.TabularDataLoaders', class extends fastai.data.core.DataLoaders {});
  20928. this.registerType('fastai.tabular.core.Tabular', class {});
  20929. this.registerType('fastai.tabular.core.TabularPandas', class extends fastai.tabular.core.Tabular {});
  20930. this.registerType('fastai.tabular.core.TabWeightedDL', class {});
  20931. this.registerType('fastai.tabular.learner.TabularLearner', class extends fastai.learner.Learner {});
  20932. this.registerType('fastai.tabular.model.TabularModel', class {});
  20933. this.registerFunction('fastai.vision.augment.aug_transforms');
  20934. this.registerFunction('fastai.vision.augment.dihedral_mat');
  20935. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  20936. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  20937. this.registerType('fastai.vision.augment._WarpCoord', class {});
  20938. this.registerType('fastai.vision.augment.RandTransform', class extends fastcore.transform.DisplayedTransform {});
  20939. this.registerType('fastai.vision.augment.AffineCoordTfm', class extends fastai.vision.augment.RandTransform {});
  20940. this.registerType('fastai.vision.augment.Brightness', class {});
  20941. this.registerType('fastai.vision.augment.flip_mat', class {});
  20942. this.registerType('fastai.vision.augment.Flip', class {});
  20943. this.registerType('fastai.vision.augment.RandomResizedCrop', class {});
  20944. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  20945. this.registerType('fastai.vision.augment.Resize', class {});
  20946. this.registerType('fastai.vision.augment.rotate_mat', class {});
  20947. this.registerFunction('fastai.vision.augment.TensorImage.lighting');
  20948. this.registerType('fastai.vision.augment.Warp', class extends fastai.vision.augment.AffineCoordTfm {});
  20949. this.registerType('fastai.vision.augment.zoom_mat', class {});
  20950. this.registerType('fastai.vision.core.PILImage', class {});
  20951. this.registerType('fastai.vision.core.PILMask', class {});
  20952. this.registerType('fastai.vision.core.AddMaskCodes', class {});
  20953. this.registerType('fastai.vision.data.ImageList', class {});
  20954. this.registerType('fastai.vision.data.ImageItemList', class {});
  20955. this.registerType('fastai.vision.image.Image', class {});
  20956. this.registerType('fastai.vision.image.RandTransform', class {});
  20957. this.registerType('fastai.vision.image.TfmCrop', class {});
  20958. this.registerFunction('fastai.vision.learner._resnet_split');
  20959. this.registerFunction('fastai.vision.learner.default_split');
  20960. this.registerFunction('fastai.vision.learner.default_split');
  20961. this.registerType('fastai.vision.learner.TimmBody', class {});
  20962. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  20963. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  20964. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  20965. this.registerType('fastai.vision.models.xresnet.XResNet', class {});
  20966. this.registerFunction('fastai.vision.transform._crop_pad');
  20967. }
  20968. exec(code , context) {
  20969. const ast = this.ast;
  20970. const program = ast.parse(code, '', null, null);
  20971. if (!program) {
  20972. throw new python.Error("Module '?' parse error.");
  20973. }
  20974. this.block(program.body, context);
  20975. }
  20976. debug(/* file */) {
  20977. }
  20978. source(file) {
  20979. if (this._sources.has(file)) {
  20980. return this._sources.get(file);
  20981. }
  20982. return null;
  20983. }
  20984. read(file) {
  20985. const buffer = this.source(file);
  20986. if (buffer) {
  20987. const debug = this.debug(file);
  20988. return this.parse(file, buffer, debug);
  20989. }
  20990. return null;
  20991. }
  20992. parse(filename, buffer, debug) {
  20993. const ast = this.ast;
  20994. const source = this._utf8Decoder.decode(buffer);
  20995. const program = ast.parse(source, filename, null, debug);
  20996. if (!program) {
  20997. throw new python.Error(`Module '${filename}' parse error.`);
  20998. }
  20999. return program;
  21000. }
  21001. import(name, current, level) {
  21002. if (level) {
  21003. let bits = current.split('.');
  21004. if (bits.length < level) {
  21005. throw new python.Error('Invalid relative import beyond top-level package.');
  21006. }
  21007. bits = bits.slice(0, bits.length - level);
  21008. const base = bits.join('.');
  21009. name = name ? [base, name].join('.') : base;
  21010. }
  21011. const index = name.lastIndexOf('.');
  21012. let parent = null;
  21013. let child = null;
  21014. if (index > 0) {
  21015. parent = name.substring(0, index);
  21016. child = name.substring(index + 1);
  21017. this.import(parent);
  21018. }
  21019. if (!this._modules.has(name)) {
  21020. const module = this._registry.get(name) || new this.builtins.module(name);
  21021. module.__package__ = name;
  21022. this._modules.set(name, module);
  21023. const path = name.split('.').join('/');
  21024. module.__path__ = [path];
  21025. const file = `${path}.py`;
  21026. const program = this.read(file);
  21027. if (program) {
  21028. module.__file__ = file;
  21029. for (const [name, value] of Object.entries(this.builtins)) {
  21030. switch (name) {
  21031. case '__class__':
  21032. case '__package__':
  21033. case '__module__':
  21034. case '__name__':
  21035. case '__path__':
  21036. case '__file__':
  21037. break;
  21038. default:
  21039. module[name] = value;
  21040. break;
  21041. }
  21042. }
  21043. const context = new python.Execution.Context(module, null);
  21044. if (name !== 'builtins') {
  21045. context.set('__builtins__', this._modules.get('builtins'));
  21046. }
  21047. this.block(program.body, context);
  21048. }
  21049. if (parent) {
  21050. const parent_module = this._modules.get(parent);
  21051. parent_module[child] = module;
  21052. }
  21053. }
  21054. return this._modules.get(name);
  21055. }
  21056. __import__(name, globals, locals, fromlist, level) {
  21057. let module = null;
  21058. level = level || 0;
  21059. if (level === 0) {
  21060. module = this.import(name);
  21061. } else {
  21062. globals = globals || {};
  21063. let current = globals.__package__;
  21064. if (!current) {
  21065. const spec = globals.__spec__;
  21066. if (spec) {
  21067. current = spec.parent;
  21068. } else {
  21069. const name = globals.__name__;
  21070. const bits = name.split('.');
  21071. bits.pop();
  21072. current = bits.join('.');
  21073. }
  21074. }
  21075. module = this.import(name, current, level);
  21076. }
  21077. if (!fromlist) {
  21078. if (level === 0) {
  21079. return this.import(name.split('.')[0]);
  21080. } else if (name) {
  21081. throw new python.Error(`Unsupported relative import '${name}'.`);
  21082. // cut_off = len(name) - len(name.partition('.')[0])
  21083. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  21084. }
  21085. } else if (module.__path__) {
  21086. const handle_fromlist = (module, fromlist, recursive) => {
  21087. for (const name of fromlist) {
  21088. if (name === '*') {
  21089. if (!recursive && module.__all__) {
  21090. handle_fromlist(module, module.__all__, true);
  21091. }
  21092. } else if (!module[name]) {
  21093. this.import(`${module.__name__}.${name}`);
  21094. }
  21095. }
  21096. return module;
  21097. };
  21098. handle_fromlist(module, fromlist);
  21099. }
  21100. return module;
  21101. }
  21102. module(name) {
  21103. return this._modules.get(name);
  21104. }
  21105. resolve(name) {
  21106. const index = name.lastIndexOf('.');
  21107. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  21108. const moduleName = index === -1 ? '' : name.substring(0, index);
  21109. const module = this.import(moduleName);
  21110. let type = module ? module[memberName] : null;
  21111. if (!type) {
  21112. if (!this._unresolved.has(name)) {
  21113. const moduleName = name.split('.').shift();
  21114. if (this._registry.has(moduleName) && moduleName !== '__main__' && moduleName !== '__torch__') {
  21115. this.emit('resolve', name);
  21116. }
  21117. const type = this._createType(name, class {});
  21118. this._unresolved.set(name, type);
  21119. }
  21120. type = this._unresolved.get(name);
  21121. }
  21122. return type;
  21123. }
  21124. invoke(target, args) {
  21125. const builtins = this.builtins;
  21126. if (typeof target === 'string') {
  21127. target = this.resolve(target);
  21128. }
  21129. if (target) {
  21130. if (target.__class__ === builtins.type) {
  21131. if (target.prototype && target.prototype.__class__ === target) {
  21132. return Reflect.construct(target, args);
  21133. }
  21134. const obj = Object.create(target);
  21135. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21136. obj.__init__(...args);
  21137. }
  21138. return obj;
  21139. } else if (target.__class__ === builtins.function) {
  21140. if (target.__call__) {
  21141. return target.__call__(args);
  21142. }
  21143. return target(...args);
  21144. }
  21145. }
  21146. throw new python.Error('Unsupported invoke target.');
  21147. }
  21148. call(target, name, args, keywords, context) {
  21149. const builtins = this.builtins;
  21150. const callTarget = this.target(target, context);
  21151. const callArguments = args.map((arg) => this.expression(arg, context));
  21152. if (!callTarget || (name !== null && !callTarget[name])) {
  21153. if (name === '__new__' && callArguments.length === 1 && callArguments[0] === callTarget) {
  21154. name = null;
  21155. callArguments.shift();
  21156. } else {
  21157. const targetName = `${this.identifier(target)}.${name}`;
  21158. throw new python.Error(`Unknown function '${targetName}'.`);
  21159. }
  21160. }
  21161. const func = name ? callTarget[name] : callTarget;
  21162. if (func.__class__ === builtins.type) {
  21163. if (func.prototype && func.prototype.__class__ === func) {
  21164. return Reflect.construct(func, callArguments);
  21165. }
  21166. const obj = Object.create(func);
  21167. obj.__class__ = func;
  21168. if (obj.__init__ && typeof obj.__init__ === 'function') {
  21169. obj.__init__(...args);
  21170. }
  21171. return obj;
  21172. }
  21173. if (func.__class__ === builtins.function) {
  21174. if (func.__call__) {
  21175. return func.__call__(callArguments);
  21176. }
  21177. }
  21178. if (func.__class__ === builtins.method) {
  21179. if (func.__call__) {
  21180. return func.__call__([callTarget].concat(callArguments));
  21181. }
  21182. }
  21183. if (typeof func === 'function') {
  21184. return func.apply(callTarget, callArguments);
  21185. }
  21186. throw new python.Error('Unsupported call expression.');
  21187. }
  21188. apply(method, args, context) {
  21189. const locals = Array.prototype.slice.call(args);
  21190. context = new python.Execution.Context(context.globals, {});
  21191. args = method.args.posonlyargs.concat(method.args.args);
  21192. const default_pos = args.length - method.args.defaults.length;
  21193. for (let i = 0; i < method.args.args.length; i++) {
  21194. const arg = method.args.args[i];
  21195. let value = null;
  21196. if (locals.length > 0) {
  21197. value = locals.shift();
  21198. } else if (i >= default_pos) {
  21199. value = this.expression(method.args.defaults[i - default_pos], context);
  21200. } else {
  21201. throw new python.Error('Missing required positional argument.');
  21202. }
  21203. context.set(arg.arg, value);
  21204. }
  21205. return this.block(method.body, context);
  21206. }
  21207. block(statements, context) {
  21208. statements = Array.prototype.slice.call(statements);
  21209. while (statements.length > 0) {
  21210. const stmt = statements.shift();
  21211. const value = this.statement(stmt, context);
  21212. if (value !== undefined) {
  21213. return value;
  21214. }
  21215. }
  21216. return undefined;
  21217. }
  21218. statement(stmt, context) {
  21219. const ast = this.ast;
  21220. const builtins = this.builtins;
  21221. if (stmt instanceof ast.Pass) {
  21222. // pass
  21223. } else if (stmt instanceof ast.Constant) {
  21224. // pass
  21225. } else if (stmt instanceof ast.Return) {
  21226. return this.expression(stmt.value, context);
  21227. } else if (stmt instanceof ast.FunctionDef) {
  21228. const module = context.get('__name__');
  21229. /* eslint-disable consistent-this */
  21230. const self = this;
  21231. /* eslint-enable consistent-this */
  21232. const parent = context.get('__class__');
  21233. const type = (parent === builtins.module) ? builtins.function : builtins.method;
  21234. const func = {
  21235. __class__: type,
  21236. __globals__: context,
  21237. __module__: module,
  21238. __name__: stmt.name,
  21239. __code__: stmt,
  21240. __call__(args) {
  21241. return self.apply(this.__code__, args, this.__globals__);
  21242. }
  21243. };
  21244. context.set(stmt.name, func);
  21245. } else if (stmt instanceof ast.ClassDef) {
  21246. const bases = stmt.bases.map((base) => this.base(base, context));
  21247. if (bases.length > 1) {
  21248. throw new python.Error(`Unsupported multiple bases for class '${stmt.name}'.`);
  21249. }
  21250. const base = bases.length === 1 ? bases[0] : null;
  21251. const name = `${context.get('__name__')}.${stmt.name}`;
  21252. const value = this._createType(name, base ? class extends base {} : class {});
  21253. value.__bases__ = bases;
  21254. context.set(stmt.name, value);
  21255. this.block(stmt.body, new python.Execution.Context(context.globals, value.prototype));
  21256. } else if (stmt instanceof ast.AnnAssign) {
  21257. const target = this.identifier(stmt.target, context);
  21258. context.set(target, stmt.value ? this.expression(stmt.value, context) : undefined);
  21259. } else if (stmt instanceof ast.Assign) {
  21260. this.expression(stmt, context);
  21261. } else if (stmt instanceof ast.If) {
  21262. const test = this.expression(stmt.test, context);
  21263. if (test === true || test) {
  21264. const value = this.block(stmt.body, context);
  21265. if (value !== undefined) {
  21266. return value;
  21267. }
  21268. } else if (test === false) {
  21269. if (stmt.orelse) {
  21270. const value = this.block(stmt.orelse, context);
  21271. if (value !== undefined) {
  21272. return value;
  21273. }
  21274. }
  21275. } else {
  21276. throw new python.Error('Unsupported condition.');
  21277. }
  21278. } else if (stmt instanceof ast.For) {
  21279. if (stmt.target instanceof ast.Name && stmt.iter instanceof ast.Tuple === false) {
  21280. const range = this.expression(stmt.iter, context);
  21281. const variable = stmt.target;
  21282. for (const current of range) {
  21283. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current } }, context);
  21284. const value = this.block(stmt.body.statements, context);
  21285. if (value !== undefined) {
  21286. return value;
  21287. }
  21288. }
  21289. } else {
  21290. throw new python.Error("Unsupported 'for' statement.");
  21291. }
  21292. } else if (stmt instanceof ast.While) {
  21293. const test = this.expression(stmt.test, context);
  21294. if (test) {
  21295. const value = this.block(stmt.body.statements, context);
  21296. if (value !== undefined) {
  21297. return value;
  21298. }
  21299. }
  21300. } else if (stmt instanceof ast.With) {
  21301. const items = [];
  21302. for (const item of stmt.items) {
  21303. items.push(this.expression(item.context_expr, context));
  21304. }
  21305. for (const item of items) {
  21306. if (item.__enter__ && item.__enter__.__call__) {
  21307. item.__enter__.__call__([item]);
  21308. }
  21309. }
  21310. const value = this.block(stmt.body, context);
  21311. for (const item of items) {
  21312. if (item.__exit__ && item.__exit__.__call__) {
  21313. item.__exit__.__call__([item]);
  21314. }
  21315. }
  21316. if (value !== undefined) {
  21317. return value;
  21318. }
  21319. } else if (stmt instanceof ast.Expr) {
  21320. this.expression(stmt.value, context);
  21321. } else if (stmt instanceof ast.Import) {
  21322. for (const alias of stmt.names) {
  21323. let module = this.__import__(alias.name, context);
  21324. if (alias.asname) {
  21325. const bits = alias.name.split('.').reverse();
  21326. bits.pop();
  21327. while (bits.length > 0) {
  21328. module = module[bits.pop()];
  21329. }
  21330. context.set(alias.asname, module);
  21331. } else {
  21332. context.set(alias.name.split('.')[0], module);
  21333. }
  21334. }
  21335. } else if (stmt instanceof ast.ImportFrom) {
  21336. const fromlist = stmt.names.map((name) => name.name);
  21337. const module = this.__import__(stmt.module, context.globals, context.locals, fromlist, stmt.level);
  21338. for (const entry of stmt.names) {
  21339. const name = entry.name;
  21340. const asname = entry.asname ? entry.asname : null;
  21341. if (!module[name]) {
  21342. throw new python.Error(`Cannot import '${name}' from '${stmt.module}'.`);
  21343. }
  21344. context.set(asname ? asname : name, module[name]);
  21345. }
  21346. } else {
  21347. throw new python.Error(`Unsupported statement '${stmt.__class__.__name__}'.`);
  21348. }
  21349. return undefined;
  21350. }
  21351. expression(expr, context) {
  21352. const ast = this.ast;
  21353. const builtins = this.builtins;
  21354. const typing = this.typing;
  21355. const self = context.get('self');
  21356. switch (expr.__class__.__name__) {
  21357. case 'Assign': {
  21358. const [target] = expr.targets;
  21359. if (target instanceof ast.Name) {
  21360. const value = this.expression(expr.value, context);
  21361. context.set(target.id, value);
  21362. return undefined;
  21363. } else if (target instanceof ast.Subscript) {
  21364. if (target.value instanceof ast.Name &&
  21365. target.slice instanceof ast.List &&
  21366. target.slice.elts.length === 1) {
  21367. const index = this.expression(target.slice.elts[0], context);
  21368. const id = target.value.id;
  21369. if (id === '__annotations__') {
  21370. context.set(id, context.get(id) || {});
  21371. }
  21372. const obj = context.get(id);
  21373. const value = this.expression(expr.value, context);
  21374. if (obj instanceof Map) {
  21375. obj.set(index, value);
  21376. } else {
  21377. obj[index] = value;
  21378. }
  21379. return undefined;
  21380. }
  21381. } else if (target instanceof ast.Attribute) {
  21382. const obj = this.expression(target.value, context);
  21383. const value = this.expression(expr.value, context);
  21384. obj[target.attr] = value;
  21385. return undefined;
  21386. } else if (target instanceof ast.Tuple) {
  21387. context.target.push(target.elts);
  21388. const value = this.expression(expr.value, context);
  21389. context.target.pop();
  21390. if (target.elts.every((elt) => elt instanceof ast.Name)) {
  21391. if (target.elts.length < value.length) {
  21392. throw new python.Error(`ValueError: too many values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21393. }
  21394. if (target.elts.length > value.length) {
  21395. throw new python.Error(`ValueError: not enough values to unpack (expected ${target.value.length}, actual ${value.length}).`);
  21396. }
  21397. for (let i = 0; i < value.length; i++) {
  21398. context.set(target.elts[i].id, value[i]);
  21399. }
  21400. return undefined;
  21401. }
  21402. }
  21403. break;
  21404. }
  21405. case 'List': {
  21406. return expr.elts.map((expr) => this.expression(expr, context));
  21407. }
  21408. case 'Constant': {
  21409. return expr.value;
  21410. }
  21411. case 'Subscript': {
  21412. if (expr.value instanceof ast.Name && expr.slice instanceof ast.Tuple === false) {
  21413. const id = expr.value.id;
  21414. if (context.get(id)) {
  21415. const index = this.expression(expr.slice, context);
  21416. const target = context.get(id);
  21417. if (target instanceof Map) {
  21418. return target.get(index);
  21419. }
  21420. return target[index < 0 ? target.length + index : index];
  21421. }
  21422. }
  21423. const value = this.expression(expr.value, context);
  21424. if (value && expr.slice instanceof ast.List &&
  21425. (value.__class__ === typing._TupleType ||
  21426. value.__class__ === typing._SpecialGenericAlias ||
  21427. value.__class__ === typing._SpecialForm)) {
  21428. const type = { ...value };
  21429. type.__args__ = expr.slice.elts.map((arg) => this.expression(arg, context));
  21430. return type;
  21431. }
  21432. if (expr.slice instanceof ast.List && expr.slice.elts.length === 1) {
  21433. const index = this.expression(expr.slice.elts[0], context);
  21434. if (value instanceof Map) {
  21435. return value.get(index);
  21436. }
  21437. return value[index < 0 ? value.length + index : index];
  21438. }
  21439. break;
  21440. }
  21441. case 'Attribute': {
  21442. const value = this.target(expr.value, context);
  21443. return value[expr.attr];
  21444. }
  21445. case 'Call': {
  21446. const func = expr.func;
  21447. if (func instanceof ast.Attribute) {
  21448. return this.call(func.value, func.attr, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21449. }
  21450. return this.call(func, null, expr.args, expr.keywords, context, expr.range ? expr.range() : null);
  21451. }
  21452. case 'Name': {
  21453. const id = expr.id;
  21454. if (id === 'self') {
  21455. return self;
  21456. }
  21457. const type = (value) => {
  21458. return value &&
  21459. (value.__class__ === builtins.type ||
  21460. value.__class__ === typing._TupleType ||
  21461. value.__class__ === typing._SpecialGenericAlias ||
  21462. value.__class__ === typing._SpecialForm);
  21463. };
  21464. const builtin = builtins[id];
  21465. if (type(builtin)) {
  21466. return builtin;
  21467. }
  21468. const value = context.get(id);
  21469. if (value === undefined) {
  21470. const value = typing[id];
  21471. if (type(value)) {
  21472. return value;
  21473. }
  21474. }
  21475. return value;
  21476. }
  21477. case 'Tuple': {
  21478. return expr.elts.map((expr) => this.expression(expr, context));
  21479. }
  21480. case 'Dict': {
  21481. const dict = {};
  21482. for (let i = 0; i < expr.keys.length; i++) {
  21483. const key = this.expression(expr.keys[i], context);
  21484. const value = this.expression(expr.values[i], context);
  21485. dict[key] = value;
  21486. }
  21487. return dict;
  21488. }
  21489. case 'UnaryOp': {
  21490. if (expr.op instanceof ast.USub) {
  21491. return -this.expression(expr.operand, context);
  21492. }
  21493. throw new python.Error(`Unsupported unary expression '${expr.op}'.`);
  21494. }
  21495. case 'binary': {
  21496. switch (expr.op) {
  21497. case '==': {
  21498. return this.expression(expr.left, context) === this.expression(expr.right, context);
  21499. }
  21500. default: {
  21501. throw new python.Error(`Unsupported binary expression '${expr.op}'.`);
  21502. }
  21503. }
  21504. }
  21505. default: {
  21506. throw new python.Error(`Unsupported expression '${expr.type}'.`);
  21507. }
  21508. }
  21509. return undefined;
  21510. }
  21511. base(expr, context) {
  21512. return this.expression(expr, context);
  21513. }
  21514. identifier(expr) {
  21515. const ast = this.ast;
  21516. if (expr instanceof ast.Name) {
  21517. return expr.id;
  21518. }
  21519. if (expr instanceof ast.Attribute) {
  21520. return `${this.identifier(expr.value)}.${expr.attr}`;
  21521. }
  21522. return null;
  21523. }
  21524. target(expr, context) {
  21525. const ast = this.ast;
  21526. let current = expr;
  21527. let path = [];
  21528. for (;;) {
  21529. if (current instanceof ast.Attribute) {
  21530. path.push(current.attr);
  21531. current = current.value;
  21532. } else if (current instanceof ast.Name && current.id !== 'self' && current.id !== 'CONSTANTS') {
  21533. path.push(current.id);
  21534. break;
  21535. } else {
  21536. path = null;
  21537. break;
  21538. }
  21539. }
  21540. if (path) {
  21541. let target = null;
  21542. for (let i = path.length - 1; i >= 0; i--) {
  21543. const name = path[i];
  21544. if (target) {
  21545. target = target.__getattr__ ? target.__getattr__(name) : target[name];
  21546. } else {
  21547. target = context.get(name);
  21548. }
  21549. if (!target) {
  21550. break;
  21551. }
  21552. }
  21553. if (!target) {
  21554. path.reverse();
  21555. const name = path.join('.');
  21556. const file = `${path.join('/')}.py`;
  21557. if (this._sources.has(file)) {
  21558. target = this.import(name);
  21559. } else {
  21560. target = this.resolve(name);
  21561. }
  21562. }
  21563. return target;
  21564. }
  21565. return this.expression(expr, context);
  21566. }
  21567. add(name, source) {
  21568. this._sources.set(name, source);
  21569. }
  21570. on(event, listener) {
  21571. const value = this._events.get(event) || [];
  21572. value.push(listener);
  21573. this._events.set(event, value);
  21574. }
  21575. emit(event, ...args) {
  21576. if (this._events.has(event)) {
  21577. for (const callback of this._events.get(event)) {
  21578. callback(this, ...args);
  21579. }
  21580. }
  21581. }
  21582. register(name, value) {
  21583. if (!this._registry.has(name)) {
  21584. value = value || new (this._registry.get('builtins').module)(name);
  21585. this._registry.set(name, value);
  21586. let current = name;
  21587. for (;;) {
  21588. const index = current.lastIndexOf('.');
  21589. if (index === -1) {
  21590. break;
  21591. }
  21592. const child = current.substring(index + 1);
  21593. current = current.substring(0, index);
  21594. if (!value.__module__) {
  21595. value.__module__ = current;
  21596. }
  21597. const parent = this.register(current);
  21598. parent[child] = value;
  21599. value = parent;
  21600. }
  21601. }
  21602. return this._registry.get(name);
  21603. }
  21604. registerFunction(name, value) {
  21605. const builtins = this.builtins;
  21606. const index = name.lastIndexOf('.');
  21607. if (!value) {
  21608. value = () => {
  21609. throw new python.Error(`'${name}' is not implemented.`);
  21610. };
  21611. }
  21612. value.__class__ = builtins.function;
  21613. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21614. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21615. const module = this.register(value.__module__);
  21616. if (module[name]) {
  21617. throw new python.Error(`Function '${name}' is already registered.`);
  21618. }
  21619. module[value.__name__] = value;
  21620. return value;
  21621. }
  21622. registerOperator(name, value) {
  21623. this._operators.set(name, value);
  21624. }
  21625. _createType(name, value) {
  21626. const builtins = this.builtins;
  21627. const index = name.lastIndexOf('.');
  21628. value.__class__ = builtins.type;
  21629. value.__name__ = index === -1 ? name : name.substring(index + 1);
  21630. value.__module__ = index === -1 ? '' : name.substring(0, index);
  21631. value.prototype.__class__ = value;
  21632. return value;
  21633. }
  21634. registerType(name, value) {
  21635. value = this._createType(name, value);
  21636. const parts = name.split('.');
  21637. const memberName = parts.pop();
  21638. const moduleName = parts.join('.');
  21639. const module = this.register(moduleName);
  21640. if (module[memberName]) {
  21641. throw new python.Error(`Class '${memberName}' is already registered.`);
  21642. }
  21643. module[memberName] = value;
  21644. return value;
  21645. }
  21646. };
  21647. python.Execution.Context = class {
  21648. constructor(globals, locals) {
  21649. this.globals = globals;
  21650. this.locals = locals;
  21651. }
  21652. set(name, value) {
  21653. if (this.locals) {
  21654. this.locals[name] = value;
  21655. } else {
  21656. this.globals[name] = value;
  21657. }
  21658. }
  21659. get(name) {
  21660. if (this.locals && name in this.locals) {
  21661. return this.locals[name];
  21662. }
  21663. if (name in this.globals) {
  21664. return this.globals[name];
  21665. }
  21666. return undefined;
  21667. }
  21668. get target() {
  21669. this._target = this._target || [];
  21670. return this._target;
  21671. }
  21672. };
  21673. python.BinaryReader = class {
  21674. constructor(buffer) {
  21675. this._buffer = buffer;
  21676. this._length = buffer.length;
  21677. this._position = 0;
  21678. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  21679. this._utf8Decoder = new TextDecoder('utf-8');
  21680. this._asciiDecoder = new TextDecoder('ascii');
  21681. }
  21682. get position() {
  21683. return this._position;
  21684. }
  21685. get length() {
  21686. return this._length;
  21687. }
  21688. seek(position) {
  21689. this._position = position >= 0 ? position : this._length + position;
  21690. if (this._position > this._buffer.length) {
  21691. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21692. }
  21693. }
  21694. skip(offset) {
  21695. this._position += offset;
  21696. if (this._position > this._buffer.length) {
  21697. throw new python.Error(`Expected ${this._position - this._buffer.length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21698. }
  21699. }
  21700. stream(length) {
  21701. const buffer = this.read(length);
  21702. return new python.BinaryReader(buffer);
  21703. }
  21704. peek(length) {
  21705. const position = this._position;
  21706. length = length === undefined ? this._length - this._position : length;
  21707. this.skip(length);
  21708. const end = this._position;
  21709. this.skip(-length);
  21710. if (position === 0 && length === this._length) {
  21711. return this._buffer;
  21712. }
  21713. return this._buffer.subarray(position, end);
  21714. }
  21715. read(length) {
  21716. const position = this._position;
  21717. length = length === undefined ? this._length - this._position : length;
  21718. this.skip(length);
  21719. if (position === 0 && length === this._length) {
  21720. return this._buffer;
  21721. }
  21722. return this._buffer.subarray(position, this._position);
  21723. }
  21724. byte() {
  21725. const position = this._position;
  21726. this.skip(1);
  21727. return this._view.getUint8(position);
  21728. }
  21729. uint16() {
  21730. const position = this._position;
  21731. this.skip(2);
  21732. return this._view.getUint16(position, true);
  21733. }
  21734. int32() {
  21735. const position = this._position;
  21736. this.skip(4);
  21737. return this._view.getInt32(position, true);
  21738. }
  21739. uint32() {
  21740. const position = this._position;
  21741. this.skip(4);
  21742. return this._view.getUint32(position, true);
  21743. }
  21744. int64() {
  21745. const position = this._position;
  21746. this.skip(8);
  21747. return this._view.getBigInt64(position, true);
  21748. }
  21749. float64() {
  21750. const position = this._position;
  21751. this.skip(8);
  21752. return this._view.getFloat64(position, false);
  21753. }
  21754. string(size, encoding) {
  21755. const data = this.read(size);
  21756. return (encoding === 'utf-8') ?
  21757. this._utf8Decoder.decode(data) :
  21758. this._asciiDecoder.decode(data);
  21759. }
  21760. line() {
  21761. const index = this._buffer.indexOf(0x0A, this._position);
  21762. if (index === -1) {
  21763. throw new python.Error('Could not find end of line.');
  21764. }
  21765. const size = index - this._position;
  21766. const text = this.string(size, 'ascii');
  21767. this.skip(1);
  21768. return text;
  21769. }
  21770. };
  21771. python.StreamReader = class {
  21772. constructor(stream) {
  21773. this._stream = stream;
  21774. this._length = stream.length;
  21775. this._position = 0;
  21776. this._utf8Decoder = new TextDecoder('utf-8');
  21777. this._asciiDecoder = new TextDecoder('ascii');
  21778. }
  21779. get position() {
  21780. return this._position;
  21781. }
  21782. get length() {
  21783. return this._length;
  21784. }
  21785. seek(position) {
  21786. this._stream.seek(position);
  21787. this._position = this._stream.position;
  21788. }
  21789. skip(offset) {
  21790. this._position += offset;
  21791. if (this._position > this._length) {
  21792. throw new python.Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21793. }
  21794. }
  21795. stream(length) {
  21796. this._stream.seek(this._position);
  21797. this.skip(length);
  21798. return this._stream.stream(length);
  21799. }
  21800. peek(length) {
  21801. this._stream.seek(this._position);
  21802. return this._stream.peek(length);
  21803. }
  21804. read(length) {
  21805. this._stream.seek(this._position);
  21806. this.skip(length);
  21807. return this._stream.read(length);
  21808. }
  21809. byte() {
  21810. const position = this._fill(1);
  21811. return this._view.getUint8(position);
  21812. }
  21813. uint16() {
  21814. const position = this._fill(2);
  21815. return this._view.getUint16(position, true);
  21816. }
  21817. int32() {
  21818. const position = this._fill(4);
  21819. return this._view.getInt32(position, true);
  21820. }
  21821. uint32() {
  21822. const position = this._fill(4);
  21823. return this._view.getUint32(position, true);
  21824. }
  21825. int64() {
  21826. const position = this._fill(8);
  21827. return this._view.getBigInt64(position, true);
  21828. }
  21829. float64() {
  21830. const position = this._fill(8);
  21831. return this._view.getFloat64(position, false);
  21832. }
  21833. string(size, encoding) {
  21834. const data = this.read(size);
  21835. return (encoding === 'utf-8') ?
  21836. this._utf8Decoder.decode(data) :
  21837. this._asciiDecoder.decode(data);
  21838. }
  21839. line() {
  21840. let position = this._fill(0);
  21841. let index = this._buffer.indexOf(0x0A, position);
  21842. if (index === -1) {
  21843. const size = Math.min(0x20000000, this._stream.length - this._position);
  21844. this._fill(size);
  21845. this.skip(-size);
  21846. position = this._fill(0);
  21847. index = this._buffer.indexOf(0x0A, position);
  21848. if (index === -1) {
  21849. throw new python.Error('Could not find end of line.');
  21850. }
  21851. }
  21852. const size = index - position;
  21853. const text = this.string(size, 'ascii');
  21854. this.skip(1);
  21855. return text;
  21856. }
  21857. _fill(length) {
  21858. if (this._position + length > this._length) {
  21859. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  21860. }
  21861. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  21862. this._offset = this._position;
  21863. this._stream.seek(this._offset);
  21864. const size = Math.max(length, Math.min(0x10000000, this._length - this._offset));
  21865. this._buffer = this._stream.read(size);
  21866. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  21867. }
  21868. const position = this._position;
  21869. this._position += length;
  21870. return position - this._offset;
  21871. }
  21872. };
  21873. python.Error = class extends Error {
  21874. constructor(message) {
  21875. super(message);
  21876. this.name = 'Python Error';
  21877. }
  21878. };
  21879. export const Execution = python.Execution;